1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements type-related semantic analysis.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/ASTStructuralEquivalence.h"
18#include "clang/AST/CXXInheritance.h"
19#include "clang/AST/Decl.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprObjC.h"
24#include "clang/AST/LocInfoType.h"
25#include "clang/AST/Type.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/AST/TypeLocVisitor.h"
28#include "clang/Basic/LangOptions.h"
29#include "clang/Basic/SourceLocation.h"
30#include "clang/Basic/Specifiers.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/Preprocessor.h"
33#include "clang/Sema/DeclSpec.h"
34#include "clang/Sema/DelayedDiagnostic.h"
35#include "clang/Sema/Lookup.h"
36#include "clang/Sema/ParsedAttr.h"
37#include "clang/Sema/ParsedTemplate.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaCUDA.h"
40#include "clang/Sema/SemaHLSL.h"
41#include "clang/Sema/SemaObjC.h"
42#include "clang/Sema/SemaOpenMP.h"
43#include "clang/Sema/Template.h"
44#include "llvm/ADT/ArrayRef.h"
45#include "llvm/ADT/STLForwardCompat.h"
46#include "llvm/ADT/StringExtras.h"
47#include "llvm/IR/DerivedTypes.h"
48#include "llvm/Support/ErrorHandling.h"
49#include "llvm/TargetParser/RISCVTargetParser.h"
50#include <bitset>
51#include <optional>
52
53using namespace clang;
54
55enum TypeDiagSelector {
56 TDS_Function,
57 TDS_Pointer,
58 TDS_ObjCObjOrBlock
59};
60
61/// isOmittedBlockReturnType - Return true if this declarator is missing a
62/// return type because this is a omitted return type on a block literal.
63static bool isOmittedBlockReturnType(const Declarator &D) {
64 if (D.getContext() != DeclaratorContext::BlockLiteral ||
65 D.getDeclSpec().hasTypeSpecifier())
66 return false;
67
68 if (D.getNumTypeObjects() == 0)
69 return true; // ^{ ... }
70
71 if (D.getNumTypeObjects() == 1 &&
72 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Function)
73 return true; // ^(int X, float Y) { ... }
74
75 return false;
76}
77
78/// diagnoseBadTypeAttribute - Diagnoses a type attribute which
79/// doesn't apply to the given type.
80static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
81 QualType type) {
82 TypeDiagSelector WhichType;
83 bool useExpansionLoc = true;
84 switch (attr.getKind()) {
85 case ParsedAttr::AT_ObjCGC:
86 WhichType = TDS_Pointer;
87 break;
88 case ParsedAttr::AT_ObjCOwnership:
89 WhichType = TDS_ObjCObjOrBlock;
90 break;
91 default:
92 // Assume everything else was a function attribute.
93 WhichType = TDS_Function;
94 useExpansionLoc = false;
95 break;
96 }
97
98 SourceLocation loc = attr.getLoc();
99 StringRef name = attr.getAttrName()->getName();
100
101 // The GC attributes are usually written with macros; special-case them.
102 IdentifierInfo *II =
103 attr.isArgIdent(Arg: 0) ? attr.getArgAsIdent(Arg: 0)->getIdentifierInfo() : nullptr;
104 if (useExpansionLoc && loc.isMacroID() && II) {
105 if (II->isStr(Str: "strong")) {
106 if (S.findMacroSpelling(loc, name: "__strong")) name = "__strong";
107 } else if (II->isStr(Str: "weak")) {
108 if (S.findMacroSpelling(loc, name: "__weak")) name = "__weak";
109 }
110 }
111
112 S.Diag(Loc: loc, DiagID: attr.isRegularKeywordAttribute()
113 ? diag::err_type_attribute_wrong_type
114 : diag::warn_type_attribute_wrong_type)
115 << name << WhichType << type;
116}
117
118// objc_gc applies to Objective-C pointers or, otherwise, to the
119// smallest available pointer type (i.e. 'void*' in 'void**').
120#define OBJC_POINTER_TYPE_ATTRS_CASELIST \
121 case ParsedAttr::AT_ObjCGC: \
122 case ParsedAttr::AT_ObjCOwnership
123
124// Calling convention attributes.
125#define CALLING_CONV_ATTRS_CASELIST \
126 case ParsedAttr::AT_CDecl: \
127 case ParsedAttr::AT_FastCall: \
128 case ParsedAttr::AT_StdCall: \
129 case ParsedAttr::AT_ThisCall: \
130 case ParsedAttr::AT_RegCall: \
131 case ParsedAttr::AT_Pascal: \
132 case ParsedAttr::AT_SwiftCall: \
133 case ParsedAttr::AT_SwiftAsyncCall: \
134 case ParsedAttr::AT_VectorCall: \
135 case ParsedAttr::AT_AArch64VectorPcs: \
136 case ParsedAttr::AT_AArch64SVEPcs: \
137 case ParsedAttr::AT_MSABI: \
138 case ParsedAttr::AT_SysVABI: \
139 case ParsedAttr::AT_Pcs: \
140 case ParsedAttr::AT_IntelOclBicc: \
141 case ParsedAttr::AT_PreserveMost: \
142 case ParsedAttr::AT_PreserveAll: \
143 case ParsedAttr::AT_M68kRTD: \
144 case ParsedAttr::AT_PreserveNone: \
145 case ParsedAttr::AT_RISCVVectorCC: \
146 case ParsedAttr::AT_RISCVVLSCC
147
148// Function type attributes.
149#define FUNCTION_TYPE_ATTRS_CASELIST \
150 case ParsedAttr::AT_NSReturnsRetained: \
151 case ParsedAttr::AT_NoReturn: \
152 case ParsedAttr::AT_NonBlocking: \
153 case ParsedAttr::AT_NonAllocating: \
154 case ParsedAttr::AT_Blocking: \
155 case ParsedAttr::AT_Allocating: \
156 case ParsedAttr::AT_Regparm: \
157 case ParsedAttr::AT_CFIUncheckedCallee: \
158 case ParsedAttr::AT_CFISalt: \
159 case ParsedAttr::AT_CmseNSCall: \
160 case ParsedAttr::AT_ArmStreaming: \
161 case ParsedAttr::AT_ArmStreamingCompatible: \
162 case ParsedAttr::AT_ArmPreserves: \
163 case ParsedAttr::AT_ArmIn: \
164 case ParsedAttr::AT_ArmOut: \
165 case ParsedAttr::AT_ArmInOut: \
166 case ParsedAttr::AT_ArmAgnostic: \
167 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
168 case ParsedAttr::AT_AnyX86NoCfCheck: \
169 CALLING_CONV_ATTRS_CASELIST
170
171// Microsoft-specific type qualifiers.
172#define MS_TYPE_ATTRS_CASELIST \
173 case ParsedAttr::AT_Ptr32: \
174 case ParsedAttr::AT_Ptr64: \
175 case ParsedAttr::AT_SPtr: \
176 case ParsedAttr::AT_UPtr
177
178// Nullability qualifiers.
179#define NULLABILITY_TYPE_ATTRS_CASELIST \
180 case ParsedAttr::AT_TypeNonNull: \
181 case ParsedAttr::AT_TypeNullable: \
182 case ParsedAttr::AT_TypeNullableResult: \
183 case ParsedAttr::AT_TypeNullUnspecified
184
185namespace {
186 /// An object which stores processing state for the entire
187 /// GetTypeForDeclarator process.
188 class TypeProcessingState {
189 Sema &sema;
190
191 /// The declarator being processed.
192 Declarator &declarator;
193
194 /// The index of the declarator chunk we're currently processing.
195 /// May be the total number of valid chunks, indicating the
196 /// DeclSpec.
197 unsigned chunkIndex;
198
199 /// The original set of attributes on the DeclSpec.
200 SmallVector<ParsedAttr *, 2> savedAttrs;
201
202 /// A list of attributes to diagnose the uselessness of when the
203 /// processing is complete.
204 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
205
206 /// Attributes corresponding to AttributedTypeLocs that we have not yet
207 /// populated.
208 // FIXME: The two-phase mechanism by which we construct Types and fill
209 // their TypeLocs makes it hard to correctly assign these. We keep the
210 // attributes in creation order as an attempt to make them line up
211 // properly.
212 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
213 SmallVector<TypeAttrPair, 8> AttrsForTypes;
214 bool AttrsForTypesSorted = true;
215
216 /// MacroQualifiedTypes mapping to macro expansion locations that will be
217 /// stored in a MacroQualifiedTypeLoc.
218 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
219
220 /// Flag to indicate we parsed a noderef attribute. This is used for
221 /// validating that noderef was used on a pointer or array.
222 bool parsedNoDeref;
223
224 // Flag to indicate that we already parsed a HLSL parameter modifier
225 // attribute. This prevents double-mutating the type.
226 bool ParsedHLSLParamMod;
227
228 public:
229 TypeProcessingState(Sema &sema, Declarator &declarator)
230 : sema(sema), declarator(declarator),
231 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false),
232 ParsedHLSLParamMod(false) {}
233
234 Sema &getSema() const {
235 return sema;
236 }
237
238 Declarator &getDeclarator() const {
239 return declarator;
240 }
241
242 bool isProcessingDeclSpec() const {
243 return chunkIndex == declarator.getNumTypeObjects();
244 }
245
246 unsigned getCurrentChunkIndex() const {
247 return chunkIndex;
248 }
249
250 void setCurrentChunkIndex(unsigned idx) {
251 assert(idx <= declarator.getNumTypeObjects());
252 chunkIndex = idx;
253 }
254
255 ParsedAttributesView &getCurrentAttributes() const {
256 if (isProcessingDeclSpec())
257 return getMutableDeclSpec().getAttributes();
258 return declarator.getTypeObject(i: chunkIndex).getAttrs();
259 }
260
261 /// Save the current set of attributes on the DeclSpec.
262 void saveDeclSpecAttrs() {
263 // Don't try to save them multiple times.
264 if (!savedAttrs.empty())
265 return;
266
267 DeclSpec &spec = getMutableDeclSpec();
268 llvm::append_range(C&: savedAttrs,
269 R: llvm::make_pointer_range(Range&: spec.getAttributes()));
270 }
271
272 /// Record that we had nowhere to put the given type attribute.
273 /// We will diagnose such attributes later.
274 void addIgnoredTypeAttr(ParsedAttr &attr) {
275 ignoredTypeAttrs.push_back(Elt: &attr);
276 }
277
278 /// Diagnose all the ignored type attributes, given that the
279 /// declarator worked out to the given type.
280 void diagnoseIgnoredTypeAttrs(QualType type) const {
281 for (auto *Attr : ignoredTypeAttrs)
282 diagnoseBadTypeAttribute(S&: getSema(), attr: *Attr, type);
283 }
284
285 /// Get an attributed type for the given attribute, and remember the Attr
286 /// object so that we can attach it to the AttributedTypeLoc.
287 QualType getAttributedType(Attr *A, QualType ModifiedType,
288 QualType EquivType) {
289 QualType T =
290 sema.Context.getAttributedType(attr: A, modifiedType: ModifiedType, equivalentType: EquivType);
291 AttrsForTypes.push_back(Elt: {cast<AttributedType>(Val: T.getTypePtr()), A});
292 AttrsForTypesSorted = false;
293 return T;
294 }
295
296 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
297 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
298 QualType WrappedType) {
299 return sema.Context.getBTFTagAttributedType(BTFAttr, Wrapped: WrappedType);
300 }
301
302 /// Get a OverflowBehaviorType type for the overflow_behavior type
303 /// attribute.
304 QualType
305 getOverflowBehaviorType(OverflowBehaviorType::OverflowBehaviorKind Kind,
306 QualType UnderlyingType) {
307 return sema.Context.getOverflowBehaviorType(Kind, Wrapped: UnderlyingType);
308 }
309
310 /// Completely replace the \c auto in \p TypeWithAuto by
311 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
312 /// necessary.
313 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
314 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
315 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
316 // Attributed type still should be an attributed type after replacement.
317 auto *NewAttrTy = cast<AttributedType>(Val: T.getTypePtr());
318 for (TypeAttrPair &A : AttrsForTypes) {
319 if (A.first == AttrTy)
320 A.first = NewAttrTy;
321 }
322 AttrsForTypesSorted = false;
323 }
324 return T;
325 }
326
327 /// Extract and remove the Attr* for a given attributed type.
328 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
329 if (!AttrsForTypesSorted) {
330 llvm::stable_sort(Range&: AttrsForTypes, C: llvm::less_first());
331 AttrsForTypesSorted = true;
332 }
333
334 // FIXME: This is quadratic if we have lots of reuses of the same
335 // attributed type.
336 for (auto It = llvm::partition_point(
337 Range&: AttrsForTypes,
338 P: [=](const TypeAttrPair &A) { return A.first < AT; });
339 It != AttrsForTypes.end() && It->first == AT; ++It) {
340 if (It->second) {
341 const Attr *Result = It->second;
342 It->second = nullptr;
343 return Result;
344 }
345 }
346
347 // The AttributedType can be inherited from another declarator, for
348 // example when __typeof__ reuses a type built for a different
349 // declaration, in which case there is no entry for it in this
350 // TypeProcessingState. Return null in that case.
351 return nullptr;
352 }
353
354 SourceLocation
355 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
356 auto FoundLoc = LocsForMacros.find(Val: MQT);
357 assert(FoundLoc != LocsForMacros.end() &&
358 "Unable to find macro expansion location for MacroQualifedType");
359 return FoundLoc->second;
360 }
361
362 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
363 SourceLocation Loc) {
364 LocsForMacros[MQT] = Loc;
365 }
366
367 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
368
369 bool didParseNoDeref() const { return parsedNoDeref; }
370
371 void setParsedHLSLParamMod(bool Parsed) { ParsedHLSLParamMod = Parsed; }
372
373 bool didParseHLSLParamMod() const { return ParsedHLSLParamMod; }
374
375 ~TypeProcessingState() {
376 if (savedAttrs.empty())
377 return;
378
379 getMutableDeclSpec().getAttributes().clearListOnly();
380 for (ParsedAttr *AL : savedAttrs)
381 getMutableDeclSpec().getAttributes().addAtEnd(newAttr: AL);
382 }
383
384 private:
385 DeclSpec &getMutableDeclSpec() const {
386 return const_cast<DeclSpec&>(declarator.getDeclSpec());
387 }
388 };
389} // end anonymous namespace
390
391static void moveAttrFromListToList(ParsedAttr &attr,
392 ParsedAttributesView &fromList,
393 ParsedAttributesView &toList) {
394 fromList.remove(ToBeRemoved: &attr);
395 toList.addAtEnd(newAttr: &attr);
396}
397
398/// The location of a type attribute.
399enum TypeAttrLocation {
400 /// The attribute is in the decl-specifier-seq.
401 TAL_DeclSpec,
402 /// The attribute is part of a DeclaratorChunk.
403 TAL_DeclChunk,
404 /// The attribute is immediately after the declaration's name.
405 TAL_DeclName
406};
407
408static void
409processTypeAttrs(TypeProcessingState &state, QualType &type,
410 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
411 CUDAFunctionTarget CFT = CUDAFunctionTarget::HostDevice);
412
413static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
414 QualType &type, CUDAFunctionTarget CFT);
415
416static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
417 ParsedAttr &attr, QualType &type);
418
419static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
420 QualType &type);
421
422static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
423 ParsedAttr &attr, QualType &type);
424
425static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
426 ParsedAttr &attr, QualType &type) {
427 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
428 return handleObjCGCTypeAttr(state, attr, type);
429 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
430 return handleObjCOwnershipTypeAttr(state, attr, type);
431}
432
433/// Given the index of a declarator chunk, check whether that chunk
434/// directly specifies the return type of a function and, if so, find
435/// an appropriate place for it.
436///
437/// \param i - a notional index which the search will start
438/// immediately inside
439///
440/// \param onlyBlockPointers Whether we should only look into block
441/// pointer types (vs. all pointer types).
442static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
443 unsigned i,
444 bool onlyBlockPointers) {
445 assert(i <= declarator.getNumTypeObjects());
446
447 DeclaratorChunk *result = nullptr;
448
449 // First, look inwards past parens for a function declarator.
450 for (; i != 0; --i) {
451 DeclaratorChunk &fnChunk = declarator.getTypeObject(i: i-1);
452 switch (fnChunk.Kind) {
453 case DeclaratorChunk::Paren:
454 continue;
455
456 // If we find anything except a function, bail out.
457 case DeclaratorChunk::Pointer:
458 case DeclaratorChunk::BlockPointer:
459 case DeclaratorChunk::Array:
460 case DeclaratorChunk::Reference:
461 case DeclaratorChunk::MemberPointer:
462 case DeclaratorChunk::Pipe:
463 return result;
464
465 // If we do find a function declarator, scan inwards from that,
466 // looking for a (block-)pointer declarator.
467 case DeclaratorChunk::Function:
468 for (--i; i != 0; --i) {
469 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i: i-1);
470 switch (ptrChunk.Kind) {
471 case DeclaratorChunk::Paren:
472 case DeclaratorChunk::Array:
473 case DeclaratorChunk::Function:
474 case DeclaratorChunk::Reference:
475 case DeclaratorChunk::Pipe:
476 continue;
477
478 case DeclaratorChunk::MemberPointer:
479 case DeclaratorChunk::Pointer:
480 if (onlyBlockPointers)
481 continue;
482
483 [[fallthrough]];
484
485 case DeclaratorChunk::BlockPointer:
486 result = &ptrChunk;
487 goto continue_outer;
488 }
489 llvm_unreachable("bad declarator chunk kind");
490 }
491
492 // If we run out of declarators doing that, we're done.
493 return result;
494 }
495 llvm_unreachable("bad declarator chunk kind");
496
497 // Okay, reconsider from our new point.
498 continue_outer: ;
499 }
500
501 // Ran out of chunks, bail out.
502 return result;
503}
504
505/// Given that an objc_gc attribute was written somewhere on a
506/// declaration *other* than on the declarator itself (for which, use
507/// distributeObjCPointerTypeAttrFromDeclarator), and given that it
508/// didn't apply in whatever position it was written in, try to move
509/// it to a more appropriate position.
510static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
511 ParsedAttr &attr, QualType type) {
512 Declarator &declarator = state.getDeclarator();
513
514 // Move it to the outermost normal or block pointer declarator.
515 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
516 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
517 switch (chunk.Kind) {
518 case DeclaratorChunk::Pointer:
519 case DeclaratorChunk::BlockPointer: {
520 // But don't move an ARC ownership attribute to the return type
521 // of a block.
522 DeclaratorChunk *destChunk = nullptr;
523 if (state.isProcessingDeclSpec() &&
524 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
525 destChunk = maybeMovePastReturnType(declarator, i: i - 1,
526 /*onlyBlockPointers=*/true);
527 if (!destChunk) destChunk = &chunk;
528
529 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
530 toList&: destChunk->getAttrs());
531 return;
532 }
533
534 case DeclaratorChunk::Paren:
535 case DeclaratorChunk::Array:
536 continue;
537
538 // We may be starting at the return type of a block.
539 case DeclaratorChunk::Function:
540 if (state.isProcessingDeclSpec() &&
541 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
542 if (DeclaratorChunk *dest = maybeMovePastReturnType(
543 declarator, i,
544 /*onlyBlockPointers=*/true)) {
545 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
546 toList&: dest->getAttrs());
547 return;
548 }
549 }
550 goto error;
551
552 // Don't walk through these.
553 case DeclaratorChunk::Reference:
554 case DeclaratorChunk::MemberPointer:
555 case DeclaratorChunk::Pipe:
556 goto error;
557 }
558 }
559 error:
560
561 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
562}
563
564/// Distribute an objc_gc type attribute that was written on the
565/// declarator.
566static void distributeObjCPointerTypeAttrFromDeclarator(
567 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
568 Declarator &declarator = state.getDeclarator();
569
570 // objc_gc goes on the innermost pointer to something that's not a
571 // pointer.
572 unsigned innermost = -1U;
573 bool considerDeclSpec = true;
574 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
575 DeclaratorChunk &chunk = declarator.getTypeObject(i);
576 switch (chunk.Kind) {
577 case DeclaratorChunk::Pointer:
578 case DeclaratorChunk::BlockPointer:
579 innermost = i;
580 continue;
581
582 case DeclaratorChunk::Reference:
583 case DeclaratorChunk::MemberPointer:
584 case DeclaratorChunk::Paren:
585 case DeclaratorChunk::Array:
586 case DeclaratorChunk::Pipe:
587 continue;
588
589 case DeclaratorChunk::Function:
590 considerDeclSpec = false;
591 goto done;
592 }
593 }
594 done:
595
596 // That might actually be the decl spec if we weren't blocked by
597 // anything in the declarator.
598 if (considerDeclSpec) {
599 if (handleObjCPointerTypeAttr(state, attr, type&: declSpecType)) {
600 // Splice the attribute into the decl spec. Prevents the
601 // attribute from being applied multiple times and gives
602 // the source-location-filler something to work with.
603 state.saveDeclSpecAttrs();
604 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
605 Other&: declarator.getAttributes(), PA: &attr);
606 return;
607 }
608 }
609
610 // Otherwise, if we found an appropriate chunk, splice the attribute
611 // into it.
612 if (innermost != -1U) {
613 moveAttrFromListToList(attr, fromList&: declarator.getAttributes(),
614 toList&: declarator.getTypeObject(i: innermost).getAttrs());
615 return;
616 }
617
618 // Otherwise, diagnose when we're done building the type.
619 declarator.getAttributes().remove(ToBeRemoved: &attr);
620 state.addIgnoredTypeAttr(attr);
621}
622
623/// A function type attribute was written somewhere in a declaration
624/// *other* than on the declarator itself or in the decl spec. Given
625/// that it didn't apply in whatever position it was written in, try
626/// to move it to a more appropriate position.
627static void distributeFunctionTypeAttr(TypeProcessingState &state,
628 ParsedAttr &attr, QualType type) {
629 Declarator &declarator = state.getDeclarator();
630
631 // Try to push the attribute from the return type of a function to
632 // the function itself.
633 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
634 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
635 switch (chunk.Kind) {
636 case DeclaratorChunk::Function:
637 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
638 toList&: chunk.getAttrs());
639 return;
640
641 case DeclaratorChunk::Paren:
642 case DeclaratorChunk::Pointer:
643 case DeclaratorChunk::BlockPointer:
644 case DeclaratorChunk::Array:
645 case DeclaratorChunk::Reference:
646 case DeclaratorChunk::MemberPointer:
647 case DeclaratorChunk::Pipe:
648 continue;
649 }
650 }
651
652 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
653}
654
655/// Try to distribute a function type attribute to the innermost
656/// function chunk or type. Returns true if the attribute was
657/// distributed, false if no location was found.
658static bool distributeFunctionTypeAttrToInnermost(
659 TypeProcessingState &state, ParsedAttr &attr,
660 ParsedAttributesView &attrList, QualType &declSpecType,
661 CUDAFunctionTarget CFT) {
662 Declarator &declarator = state.getDeclarator();
663
664 // Put it on the innermost function chunk, if there is one.
665 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
666 DeclaratorChunk &chunk = declarator.getTypeObject(i);
667 if (chunk.Kind != DeclaratorChunk::Function) continue;
668
669 moveAttrFromListToList(attr, fromList&: attrList, toList&: chunk.getAttrs());
670 return true;
671 }
672
673 return handleFunctionTypeAttr(state, attr, type&: declSpecType, CFT);
674}
675
676/// A function type attribute was written in the decl spec. Try to
677/// apply it somewhere.
678static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
679 ParsedAttr &attr,
680 QualType &declSpecType,
681 CUDAFunctionTarget CFT) {
682 state.saveDeclSpecAttrs();
683
684 // Try to distribute to the innermost.
685 if (distributeFunctionTypeAttrToInnermost(
686 state, attr, attrList&: state.getCurrentAttributes(), declSpecType, CFT))
687 return;
688
689 // If that failed, diagnose the bad attribute when the declarator is
690 // fully built.
691 state.addIgnoredTypeAttr(attr);
692}
693
694/// A function type attribute was written on the declarator or declaration.
695/// Try to apply it somewhere.
696/// `Attrs` is the attribute list containing the declaration (either of the
697/// declarator or the declaration).
698static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
699 ParsedAttr &attr,
700 QualType &declSpecType,
701 CUDAFunctionTarget CFT) {
702 Declarator &declarator = state.getDeclarator();
703
704 // Try to distribute to the innermost.
705 if (distributeFunctionTypeAttrToInnermost(
706 state, attr, attrList&: declarator.getAttributes(), declSpecType, CFT))
707 return;
708
709 // If that failed, diagnose the bad attribute when the declarator is
710 // fully built.
711 declarator.getAttributes().remove(ToBeRemoved: &attr);
712 state.addIgnoredTypeAttr(attr);
713}
714
715/// Given that there are attributes written on the declarator or declaration
716/// itself, try to distribute any type attributes to the appropriate
717/// declarator chunk.
718///
719/// These are attributes like the following:
720/// int f ATTR;
721/// int (f ATTR)();
722/// but not necessarily this:
723/// int f() ATTR;
724///
725/// `Attrs` is the attribute list containing the declaration (either of the
726/// declarator or the declaration).
727static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
728 QualType &declSpecType,
729 CUDAFunctionTarget CFT) {
730 // The called functions in this loop actually remove things from the current
731 // list, so iterating over the existing list isn't possible. Instead, make a
732 // non-owning copy and iterate over that.
733 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
734 for (ParsedAttr &attr : AttrsCopy) {
735 // Do not distribute [[]] attributes. They have strict rules for what
736 // they appertain to.
737 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
738 continue;
739
740 switch (attr.getKind()) {
741 OBJC_POINTER_TYPE_ATTRS_CASELIST:
742 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
743 break;
744
745 FUNCTION_TYPE_ATTRS_CASELIST:
746 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
747 break;
748
749 MS_TYPE_ATTRS_CASELIST:
750 // Microsoft type attributes cannot go after the declarator-id.
751 continue;
752
753 NULLABILITY_TYPE_ATTRS_CASELIST:
754 // Nullability specifiers cannot go after the declarator-id.
755
756 // Objective-C __kindof does not get distributed.
757 case ParsedAttr::AT_ObjCKindOf:
758 continue;
759
760 default:
761 break;
762 }
763 }
764}
765
766/// Add a synthetic '()' to a block-literal declarator if it is
767/// required, given the return type.
768static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
769 QualType declSpecType) {
770 Declarator &declarator = state.getDeclarator();
771
772 // First, check whether the declarator would produce a function,
773 // i.e. whether the innermost semantic chunk is a function.
774 if (declarator.isFunctionDeclarator()) {
775 // If so, make that declarator a prototyped declarator.
776 declarator.getFunctionTypeInfo().hasPrototype = true;
777 return;
778 }
779
780 // If there are any type objects, the type as written won't name a
781 // function, regardless of the decl spec type. This is because a
782 // block signature declarator is always an abstract-declarator, and
783 // abstract-declarators can't just be parentheses chunks. Therefore
784 // we need to build a function chunk unless there are no type
785 // objects and the decl spec type is a function.
786 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
787 return;
788
789 // Note that there *are* cases with invalid declarators where
790 // declarators consist solely of parentheses. In general, these
791 // occur only in failed efforts to make function declarators, so
792 // faking up the function chunk is still the right thing to do.
793
794 // Otherwise, we need to fake up a function declarator.
795 SourceLocation loc = declarator.getBeginLoc();
796
797 // ...and *prepend* it to the declarator.
798 SourceLocation NoLoc;
799 declarator.AddInnermostTypeInfo(TI: DeclaratorChunk::getFunction(
800 /*HasProto=*/true,
801 /*IsAmbiguous=*/false,
802 /*LParenLoc=*/NoLoc,
803 /*ArgInfo=*/Params: nullptr,
804 /*NumParams=*/0,
805 /*EllipsisLoc=*/NoLoc,
806 /*RParenLoc=*/NoLoc,
807 /*RefQualifierIsLvalueRef=*/true,
808 /*RefQualifierLoc=*/NoLoc,
809 /*MutableLoc=*/NoLoc, ESpecType: EST_None,
810 /*ESpecRange=*/SourceRange(),
811 /*Exceptions=*/nullptr,
812 /*ExceptionRanges=*/nullptr,
813 /*NumExceptions=*/0,
814 /*NoexceptExpr=*/nullptr,
815 /*ExceptionSpecTokens=*/nullptr,
816 /*DeclsInPrototype=*/{}, LocalRangeBegin: loc, LocalRangeEnd: loc, TheDeclarator&: declarator));
817
818 // For consistency, make sure the state still has us as processing
819 // the decl spec.
820 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
821 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
822}
823
824static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
825 unsigned &TypeQuals,
826 QualType TypeSoFar,
827 unsigned RemoveTQs,
828 unsigned DiagID) {
829 // If this occurs outside a template instantiation, warn the user about
830 // it; they probably didn't mean to specify a redundant qualifier.
831 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
832 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
833 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
834 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
835 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
836 if (!(RemoveTQs & Qual.first))
837 continue;
838
839 if (!S.inTemplateInstantiation()) {
840 if (TypeQuals & Qual.first)
841 S.Diag(Loc: Qual.second, DiagID)
842 << DeclSpec::getSpecifierName(Q: Qual.first) << TypeSoFar
843 << FixItHint::CreateRemoval(RemoveRange: Qual.second);
844 }
845
846 TypeQuals &= ~Qual.first;
847 }
848}
849
850/// Return true if this is omitted block return type. Also check type
851/// attributes and type qualifiers when returning true.
852static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
853 QualType Result) {
854 if (!isOmittedBlockReturnType(D: declarator))
855 return false;
856
857 // Warn if we see type attributes for omitted return type on a block literal.
858 SmallVector<ParsedAttr *, 2> ToBeRemoved;
859 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
860 if (AL.isInvalid() || !AL.isTypeAttr())
861 continue;
862 S.Diag(Loc: AL.getLoc(),
863 DiagID: diag::warn_block_literal_attributes_on_omitted_return_type)
864 << AL;
865 ToBeRemoved.push_back(Elt: &AL);
866 }
867 // Remove bad attributes from the list.
868 for (ParsedAttr *AL : ToBeRemoved)
869 declarator.getMutableDeclSpec().getAttributes().remove(ToBeRemoved: AL);
870
871 // Warn if we see type qualifiers for omitted return type on a block literal.
872 const DeclSpec &DS = declarator.getDeclSpec();
873 unsigned TypeQuals = DS.getTypeQualifiers();
874 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, TypeSoFar: Result, RemoveTQs: (unsigned)-1,
875 DiagID: diag::warn_block_literal_qualifiers_on_omitted_return_type);
876 declarator.getMutableDeclSpec().ClearTypeQualifiers();
877
878 return true;
879}
880
881static OpenCLAccessAttr::Spelling
882getImageAccess(const ParsedAttributesView &Attrs) {
883 for (const ParsedAttr &AL : Attrs)
884 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
885 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
886 return OpenCLAccessAttr::Keyword_read_only;
887}
888
889static UnaryTransformType::UTTKind
890TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
891 switch (SwitchTST) {
892#define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
893 case TST_##Trait: \
894 return UnaryTransformType::Enum;
895#include "clang/Basic/BuiltinTraits.inc"
896 default:
897 llvm_unreachable("attempted to parse a non-unary transform builtin");
898 }
899}
900
901/// Convert the specified declspec to the appropriate type
902/// object.
903/// \param state Specifies the declarator containing the declaration specifier
904/// to be converted, along with other associated processing state.
905/// \returns The type described by the declaration specifiers. This function
906/// never returns null.
907static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
908 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
909 // checking.
910
911 Sema &S = state.getSema();
912 Declarator &declarator = state.getDeclarator();
913 DeclSpec &DS = declarator.getMutableDeclSpec();
914 SourceLocation DeclLoc = declarator.getIdentifierLoc();
915 if (DeclLoc.isInvalid())
916 DeclLoc = DS.getBeginLoc();
917
918 ASTContext &Context = S.Context;
919
920 QualType Result;
921 switch (DS.getTypeSpecType()) {
922 case DeclSpec::TST_void:
923 Result = Context.VoidTy;
924 break;
925 case DeclSpec::TST_char:
926 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
927 Result = Context.CharTy;
928 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
929 Result = Context.SignedCharTy;
930 else {
931 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
932 "Unknown TSS value");
933 Result = Context.UnsignedCharTy;
934 }
935 break;
936 case DeclSpec::TST_wchar:
937 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
938 Result = Context.WCharTy;
939 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
940 S.Diag(Loc: DS.getTypeSpecSignLoc(), DiagID: diag::ext_wchar_t_sign_spec)
941 << DS.getSpecifierName(T: DS.getTypeSpecType(),
942 Policy: Context.getPrintingPolicy());
943 Result = Context.getSignedWCharType();
944 } else {
945 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
946 "Unknown TSS value");
947 S.Diag(Loc: DS.getTypeSpecSignLoc(), DiagID: diag::ext_wchar_t_sign_spec)
948 << DS.getSpecifierName(T: DS.getTypeSpecType(),
949 Policy: Context.getPrintingPolicy());
950 Result = Context.getUnsignedWCharType();
951 }
952 break;
953 case DeclSpec::TST_char8:
954 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
955 "Unknown TSS value");
956 Result = Context.Char8Ty;
957 break;
958 case DeclSpec::TST_char16:
959 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
960 "Unknown TSS value");
961 Result = Context.Char16Ty;
962 break;
963 case DeclSpec::TST_char32:
964 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
965 "Unknown TSS value");
966 Result = Context.Char32Ty;
967 break;
968 case DeclSpec::TST_unspecified:
969 // If this is a missing declspec in a block literal return context, then it
970 // is inferred from the return statements inside the block.
971 // The declspec is always missing in a lambda expr context; it is either
972 // specified with a trailing return type or inferred.
973 if (S.getLangOpts().CPlusPlus14 &&
974 declarator.getContext() == DeclaratorContext::LambdaExpr) {
975 // In C++1y, a lambda's implicit return type is 'auto'.
976 Result = Context.getAutoDeductType();
977 break;
978 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
979 checkOmittedBlockReturnType(S, declarator,
980 Result: Context.DependentTy)) {
981 Result = Context.DependentTy;
982 break;
983 }
984
985 // Unspecified typespec defaults to int in C90. However, the C90 grammar
986 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
987 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
988 // Note that the one exception to this is function definitions, which are
989 // allowed to be completely missing a declspec. This is handled in the
990 // parser already though by it pretending to have seen an 'int' in this
991 // case.
992 if (S.getLangOpts().isImplicitIntRequired()) {
993 // Only emit the diagnostic for the first declarator in a DeclGroup, as
994 // the warning is always implied for all subsequent declarators, and the
995 // fix must only be applied exactly once as well.
996 if (declarator.isFirstDeclarator()) {
997 S.Diag(Loc: DeclLoc, DiagID: diag::warn_missing_type_specifier)
998 << DS.getSourceRange()
999 << FixItHint::CreateInsertion(InsertionLoc: DS.getBeginLoc(), Code: "int ");
1000 }
1001 } else if (!DS.hasTypeSpecifier()) {
1002 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1003 // "At least one type specifier shall be given in the declaration
1004 // specifiers in each declaration, and in the specifier-qualifier list
1005 // in each struct declaration and type name."
1006 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1007 if (declarator.isFirstDeclarator()) {
1008 S.Diag(Loc: DeclLoc, DiagID: diag::err_missing_type_specifier)
1009 << DS.getSourceRange();
1010 }
1011
1012 // When this occurs, often something is very broken with the value
1013 // being declared, poison it as invalid so we don't get chains of
1014 // errors.
1015 declarator.setInvalidType(true);
1016 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1017 DS.isTypeSpecPipe()) {
1018 if (declarator.isFirstDeclarator()) {
1019 S.Diag(Loc: DeclLoc, DiagID: diag::err_missing_actual_pipe_type)
1020 << DS.getSourceRange();
1021 }
1022 declarator.setInvalidType(true);
1023 } else if (declarator.isFirstDeclarator()) {
1024 assert(S.getLangOpts().isImplicitIntAllowed() &&
1025 "implicit int is disabled?");
1026 S.Diag(Loc: DeclLoc, DiagID: diag::ext_missing_type_specifier)
1027 << DS.getSourceRange()
1028 << FixItHint::CreateInsertion(InsertionLoc: DS.getBeginLoc(), Code: "int ");
1029 }
1030 }
1031
1032 [[fallthrough]];
1033 case DeclSpec::TST_int: {
1034 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1035 switch (DS.getTypeSpecWidth()) {
1036 case TypeSpecifierWidth::Unspecified:
1037 Result = Context.IntTy;
1038 break;
1039 case TypeSpecifierWidth::Short:
1040 Result = Context.ShortTy;
1041 break;
1042 case TypeSpecifierWidth::Long:
1043 Result = Context.LongTy;
1044 break;
1045 case TypeSpecifierWidth::LongLong:
1046 Result = Context.LongLongTy;
1047
1048 if (S.getLangOpts().OpenCL) {
1049 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1050 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::warn_opencl_longlong);
1051 } else if (!S.getLangOpts().C99) {
1052 // 'long long' is a C99 or C++11 feature.
1053 if (S.getLangOpts().CPlusPlus)
1054 S.Diag(Loc: DS.getTypeSpecWidthLoc(),
1055 DiagID: S.getLangOpts().CPlusPlus11 ?
1056 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1057 else
1058 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::ext_c99_longlong);
1059 }
1060 break;
1061 }
1062 } else {
1063 switch (DS.getTypeSpecWidth()) {
1064 case TypeSpecifierWidth::Unspecified:
1065 Result = Context.UnsignedIntTy;
1066 break;
1067 case TypeSpecifierWidth::Short:
1068 Result = Context.UnsignedShortTy;
1069 break;
1070 case TypeSpecifierWidth::Long:
1071 Result = Context.UnsignedLongTy;
1072 break;
1073 case TypeSpecifierWidth::LongLong:
1074 Result = Context.UnsignedLongLongTy;
1075
1076 if (S.getLangOpts().OpenCL) {
1077 // OpenCL v3.0 s6.3.4: 'long long' is a reserved data type.
1078 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::warn_opencl_longlong);
1079 } else if (!S.getLangOpts().C99) {
1080 // 'long long' is a C99 or C++11 feature.
1081 if (S.getLangOpts().CPlusPlus)
1082 S.Diag(Loc: DS.getTypeSpecWidthLoc(),
1083 DiagID: S.getLangOpts().CPlusPlus11 ?
1084 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1085 else
1086 S.Diag(Loc: DS.getTypeSpecWidthLoc(), DiagID: diag::ext_c99_longlong);
1087 }
1088 break;
1089 }
1090 }
1091 break;
1092 }
1093 case DeclSpec::TST_bitint: {
1094 if (!S.Context.getTargetInfo().hasBitIntType())
1095 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "_BitInt";
1096 Result =
1097 S.BuildBitIntType(IsUnsigned: DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1098 BitWidth: DS.getRepAsExpr(), Loc: DS.getBeginLoc());
1099 if (Result.isNull()) {
1100 Result = Context.IntTy;
1101 declarator.setInvalidType(true);
1102 }
1103 break;
1104 }
1105 case DeclSpec::TST_accum: {
1106 switch (DS.getTypeSpecWidth()) {
1107 case TypeSpecifierWidth::Short:
1108 Result = Context.ShortAccumTy;
1109 break;
1110 case TypeSpecifierWidth::Unspecified:
1111 Result = Context.AccumTy;
1112 break;
1113 case TypeSpecifierWidth::Long:
1114 Result = Context.LongAccumTy;
1115 break;
1116 case TypeSpecifierWidth::LongLong:
1117 llvm_unreachable("Unable to specify long long as _Accum width");
1118 }
1119
1120 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1121 Result = Context.getCorrespondingUnsignedType(T: Result);
1122
1123 if (DS.isTypeSpecSat())
1124 Result = Context.getCorrespondingSaturatedType(Ty: Result);
1125
1126 break;
1127 }
1128 case DeclSpec::TST_fract: {
1129 switch (DS.getTypeSpecWidth()) {
1130 case TypeSpecifierWidth::Short:
1131 Result = Context.ShortFractTy;
1132 break;
1133 case TypeSpecifierWidth::Unspecified:
1134 Result = Context.FractTy;
1135 break;
1136 case TypeSpecifierWidth::Long:
1137 Result = Context.LongFractTy;
1138 break;
1139 case TypeSpecifierWidth::LongLong:
1140 llvm_unreachable("Unable to specify long long as _Fract width");
1141 }
1142
1143 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1144 Result = Context.getCorrespondingUnsignedType(T: Result);
1145
1146 if (DS.isTypeSpecSat())
1147 Result = Context.getCorrespondingSaturatedType(Ty: Result);
1148
1149 break;
1150 }
1151 case DeclSpec::TST_int128:
1152 if (!S.Context.getTargetInfo().hasInt128Type() &&
1153 !(S.getLangOpts().isTargetDevice()))
1154 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1155 << "__int128";
1156 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1157 Result = Context.UnsignedInt128Ty;
1158 else
1159 Result = Context.Int128Ty;
1160 break;
1161 case DeclSpec::TST_float16:
1162 // CUDA host and device may have different _Float16 support, therefore
1163 // do not diagnose _Float16 usage to avoid false alarm.
1164 // ToDo: more precise diagnostics for CUDA.
1165 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1166 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1167 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1168 << "_Float16";
1169 Result = Context.Float16Ty;
1170 break;
1171 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1172 case DeclSpec::TST_BFloat16:
1173 if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1174 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1175 !S.getLangOpts().SYCLIsDevice)
1176 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "__bf16";
1177 Result = Context.BFloat16Ty;
1178 break;
1179 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1180 case DeclSpec::TST_double:
1181 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1182 Result = Context.LongDoubleTy;
1183 else
1184 Result = Context.DoubleTy;
1185 if (S.getLangOpts().OpenCL) {
1186 if (!S.getOpenCLOptions().isSupported(Ext: "cl_khr_fp64", LO: S.getLangOpts()))
1187 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1188 << 0 << Result
1189 << (S.getLangOpts().getOpenCLCompatibleVersion() >= 300
1190 ? "cl_khr_fp64 and __opencl_c_fp64"
1191 : "cl_khr_fp64");
1192 else if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp64", LO: S.getLangOpts()))
1193 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::ext_opencl_double_without_pragma);
1194 }
1195 break;
1196 case DeclSpec::TST_float128:
1197 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1198 !S.getLangOpts().isTargetDevice())
1199 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported)
1200 << "__float128";
1201 Result = Context.Float128Ty;
1202 break;
1203 case DeclSpec::TST_ibm128:
1204 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1205 !S.getLangOpts().SYCLIsDevice &&
1206 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1207 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_type_unsupported) << "__ibm128";
1208 Result = Context.Ibm128Ty;
1209 break;
1210 case DeclSpec::TST_bool:
1211 Result = Context.BoolTy; // _Bool or bool
1212 break;
1213 case DeclSpec::TST_decimal32: // _Decimal32
1214 case DeclSpec::TST_decimal64: // _Decimal64
1215 case DeclSpec::TST_decimal128: // _Decimal128
1216 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decimal_unsupported);
1217 Result = Context.IntTy;
1218 declarator.setInvalidType(true);
1219 break;
1220 case DeclSpec::TST_class:
1221 case DeclSpec::TST_enum:
1222 case DeclSpec::TST_union:
1223 case DeclSpec::TST_struct:
1224 case DeclSpec::TST_interface: {
1225 TagDecl *D = dyn_cast_or_null<TagDecl>(Val: DS.getRepAsDecl());
1226 if (!D) {
1227 // This can happen in C++ with ambiguous lookups.
1228 Result = Context.IntTy;
1229 declarator.setInvalidType(true);
1230 break;
1231 }
1232
1233 // If the type is deprecated or unavailable, diagnose it.
1234 S.DiagnoseUseOfDecl(D, Locs: DS.getTypeSpecTypeNameLoc());
1235
1236 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1237 DS.getTypeSpecComplex() == 0 &&
1238 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1239 "No qualifiers on tag names!");
1240
1241 ElaboratedTypeKeyword Keyword =
1242 KeywordHelpers::getKeywordForTypeSpec(TypeSpec: DS.getTypeSpecType());
1243 // TypeQuals handled by caller.
1244 Result = Context.getTagType(Keyword, Qualifier: DS.getTypeSpecScope().getScopeRep(), TD: D,
1245 OwnsTag: DS.isTypeSpecOwned());
1246 break;
1247 }
1248 case DeclSpec::TST_typename: {
1249 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1250 DS.getTypeSpecComplex() == 0 &&
1251 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1252 "Can't handle qualifiers on typedef names yet!");
1253 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1254 if (Result.isNull()) {
1255 declarator.setInvalidType(true);
1256 }
1257
1258 // TypeQuals handled by caller.
1259 break;
1260 }
1261 case DeclSpec::TST_typeof_unqualType:
1262 case DeclSpec::TST_typeofType:
1263 // FIXME: Preserve type source info.
1264 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1265 assert(!Result.isNull() && "Didn't get a type for typeof?");
1266 if (!Result->isDependentType())
1267 if (const auto *TT = Result->getAs<TagType>())
1268 S.DiagnoseUseOfDecl(D: TT->getDecl(), Locs: DS.getTypeSpecTypeLoc());
1269 // TypeQuals handled by caller.
1270 Result = Context.getTypeOfType(
1271 QT: Result, Kind: DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1272 ? TypeOfKind::Unqualified
1273 : TypeOfKind::Qualified);
1274 break;
1275 case DeclSpec::TST_typeof_unqualExpr:
1276 case DeclSpec::TST_typeofExpr: {
1277 Expr *E = DS.getRepAsExpr();
1278 assert(E && "Didn't get an expression for typeof?");
1279 // TypeQuals handled by caller.
1280 Result = S.BuildTypeofExprType(E, Kind: DS.getTypeSpecType() ==
1281 DeclSpec::TST_typeof_unqualExpr
1282 ? TypeOfKind::Unqualified
1283 : TypeOfKind::Qualified);
1284 if (Result.isNull()) {
1285 Result = Context.IntTy;
1286 declarator.setInvalidType(true);
1287 }
1288 break;
1289 }
1290 case DeclSpec::TST_decltype: {
1291 Expr *E = DS.getRepAsExpr();
1292 assert(E && "Didn't get an expression for decltype?");
1293 // TypeQuals handled by caller.
1294 Result = S.BuildDecltypeType(E);
1295 if (Result.isNull()) {
1296 Result = Context.IntTy;
1297 declarator.setInvalidType(true);
1298 }
1299 break;
1300 }
1301 case DeclSpec::TST_typename_pack_indexing: {
1302 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1303 if (Result.isNull()) {
1304 declarator.setInvalidType(true);
1305 Result = Context.IntTy;
1306 }
1307 break;
1308 }
1309
1310#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1311#include "clang/Basic/BuiltinTraits.inc"
1312 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1313 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1314 Result = S.BuildUnaryTransformType(
1315 BaseType: Result, UKind: TSTToUnaryTransformType(SwitchTST: DS.getTypeSpecType()),
1316 Loc: DS.getTypeSpecTypeLoc());
1317 if (Result.isNull()) {
1318 Result = Context.IntTy;
1319 declarator.setInvalidType(true);
1320 }
1321 break;
1322
1323 case DeclSpec::TST_auto:
1324 case DeclSpec::TST_decltype_auto: {
1325 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1326 ? AutoTypeKeyword::DecltypeAuto
1327 : AutoTypeKeyword::Auto;
1328
1329 TemplateName TypeConstraintConcept;
1330 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1331 if (DS.isConstrainedAuto()) {
1332 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1333 TypeConstraintConcept = TemplateId->Template.get();
1334 TemplateArgumentListInfo TemplateArgsInfo;
1335 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1336 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1337 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1338 TemplateId->NumArgs);
1339 S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
1340 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1341 TemplateArgs.push_back(Elt: ArgLoc.getArgument());
1342 } else {
1343 declarator.setInvalidType(true);
1344 }
1345 }
1346 Result = S.Context.getAutoType(DK: DeducedKind::Undeduced, DeducedAsType: QualType(), Keyword: AutoKW,
1347 TypeConstraintConcept, TypeConstraintArgs: TemplateArgs);
1348 break;
1349 }
1350
1351 case DeclSpec::TST_auto_type:
1352 Result = Context.getAutoType(DK: DeducedKind::Undeduced, DeducedAsType: QualType(),
1353 Keyword: AutoTypeKeyword::GNUAutoType);
1354 break;
1355
1356 case DeclSpec::TST_unknown_anytype:
1357 Result = Context.UnknownAnyTy;
1358 break;
1359
1360 case DeclSpec::TST_atomic:
1361 Result = S.GetTypeFromParser(Ty: DS.getRepAsType());
1362 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1363 Result = S.BuildAtomicType(T: Result, Loc: DS.getTypeSpecTypeLoc());
1364 if (Result.isNull()) {
1365 Result = Context.IntTy;
1366 declarator.setInvalidType(true);
1367 }
1368 break;
1369
1370#define GENERIC_IMAGE_TYPE(ImgType, Id) \
1371 case DeclSpec::TST_##ImgType##_t: \
1372 switch (getImageAccess(DS.getAttributes())) { \
1373 case OpenCLAccessAttr::Keyword_write_only: \
1374 Result = Context.Id##WOTy; \
1375 break; \
1376 case OpenCLAccessAttr::Keyword_read_write: \
1377 Result = Context.Id##RWTy; \
1378 break; \
1379 case OpenCLAccessAttr::Keyword_read_only: \
1380 Result = Context.Id##ROTy; \
1381 break; \
1382 case OpenCLAccessAttr::SpellingNotCalculated: \
1383 llvm_unreachable("Spelling not yet calculated"); \
1384 } \
1385 break;
1386#include "clang/Basic/OpenCLImageTypes.def"
1387
1388#define HLSL_INTANGIBLE_TYPE(Name, Id, SingletonId) \
1389 case DeclSpec::TST_##Name: \
1390 Result = Context.SingletonId; \
1391 break;
1392#include "clang/Basic/HLSLIntangibleTypes.def"
1393
1394#define HLSL_PACKED_TYPE(Name, Id, SingletonId) \
1395 case DeclSpec::TST_##Name: \
1396 Result = Context.SingletonId; \
1397 break;
1398#include "clang/Basic/HLSLPackedTypes.def"
1399
1400 case DeclSpec::TST_error:
1401 Result = Context.IntTy;
1402 declarator.setInvalidType(true);
1403 break;
1404 }
1405
1406 // FIXME: we want resulting declarations to be marked invalid, but claiming
1407 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1408 // a null type.
1409 if (Result->containsErrors())
1410 declarator.setInvalidType();
1411
1412 if (S.getLangOpts().OpenCL) {
1413 const auto &OpenCLOptions = S.getOpenCLOptions();
1414 bool IsOpenCLC30Compatible =
1415 S.getLangOpts().getOpenCLCompatibleVersion() >= 300;
1416 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1417 // support.
1418 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1419 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1420 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1421 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1422 // only when the optional feature is supported
1423 if ((Result->isImageType() || Result->isSamplerT()) &&
1424 (IsOpenCLC30Compatible &&
1425 !OpenCLOptions.isSupported(Ext: "__opencl_c_images", LO: S.getLangOpts()))) {
1426 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1427 << 0 << Result << "__opencl_c_images";
1428 declarator.setInvalidType();
1429 } else if (Result->isOCLImage3dWOType() &&
1430 !OpenCLOptions.isSupported(Ext: "cl_khr_3d_image_writes",
1431 LO: S.getLangOpts())) {
1432 S.Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_opencl_requires_extension)
1433 << 0 << Result
1434 << (IsOpenCLC30Compatible
1435 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1436 : "cl_khr_3d_image_writes");
1437 declarator.setInvalidType();
1438 }
1439 }
1440
1441 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1442 DS.getTypeSpecType() == DeclSpec::TST_fract;
1443
1444 // Only fixed point types can be saturated
1445 if (DS.isTypeSpecSat() && !IsFixedPointType)
1446 S.Diag(Loc: DS.getTypeSpecSatLoc(), DiagID: diag::err_invalid_saturation_spec)
1447 << DS.getSpecifierName(T: DS.getTypeSpecType(),
1448 Policy: Context.getPrintingPolicy());
1449
1450 // Handle complex types.
1451 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1452 if (S.getLangOpts().Freestanding)
1453 S.Diag(Loc: DS.getTypeSpecComplexLoc(), DiagID: diag::ext_freestanding_complex);
1454 Result = Context.getComplexType(T: Result);
1455 } else if (DS.isTypeAltiVecVector()) {
1456 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(T: Result));
1457 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1458 VectorKind VecKind = VectorKind::AltiVecVector;
1459 if (DS.isTypeAltiVecPixel())
1460 VecKind = VectorKind::AltiVecPixel;
1461 else if (DS.isTypeAltiVecBool())
1462 VecKind = VectorKind::AltiVecBool;
1463 Result = Context.getVectorType(VectorType: Result, NumElts: 128/typeSize, VecKind);
1464 }
1465
1466 // _Imaginary was a feature of C99 through C23 but was never supported in
1467 // Clang. The feature was removed in C2y, but we retain the unsupported
1468 // diagnostic for an improved user experience.
1469 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1470 S.Diag(Loc: DS.getTypeSpecComplexLoc(), DiagID: diag::err_imaginary_not_supported);
1471
1472 // Before we process any type attributes, synthesize a block literal
1473 // function declarator if necessary.
1474 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1475 maybeSynthesizeBlockSignature(state, declSpecType: Result);
1476
1477 // Apply any type attributes from the decl spec. This may cause the
1478 // list of type attributes to be temporarily saved while the type
1479 // attributes are pushed around.
1480 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1481 if (!DS.isTypeSpecPipe()) {
1482 // We also apply declaration attributes that "slide" to the decl spec.
1483 // Ordering can be important for attributes. The decalaration attributes
1484 // come syntactically before the decl spec attributes, so we process them
1485 // in that order.
1486 ParsedAttributesView SlidingAttrs;
1487 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1488 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1489 SlidingAttrs.addAtEnd(newAttr: &AL);
1490
1491 // For standard syntax attributes, which would normally appertain to the
1492 // declaration here, suggest moving them to the type instead. But only
1493 // do this for our own vendor attributes; moving other vendors'
1494 // attributes might hurt portability.
1495 // There's one special case that we need to deal with here: The
1496 // `MatrixType` attribute may only be used in a typedef declaration. If
1497 // it's being used anywhere else, don't output the warning as
1498 // ProcessDeclAttributes() will output an error anyway.
1499 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1500 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1501 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1502 S.Diag(Loc: AL.getLoc(), DiagID: diag::warn_type_attribute_deprecated_on_decl)
1503 << AL;
1504 }
1505 }
1506 }
1507 // During this call to processTypeAttrs(),
1508 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1509 // reference to the DeclSpec attributes, rather than the declaration
1510 // attributes. However, this doesn't matter, as getCurrentAttributes()
1511 // is only called when distributing attributes from one attribute list
1512 // to another. Declaration attributes are always C++11 attributes, and these
1513 // are never distributed.
1514 processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: SlidingAttrs);
1515 processTypeAttrs(state, type&: Result, TAL: TAL_DeclSpec, attrs: DS.getAttributes());
1516 }
1517
1518 // Apply const/volatile/restrict qualifiers to T.
1519 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1520 // Warn about CV qualifiers on function types.
1521 // C99 6.7.3p8:
1522 // If the specification of a function type includes any type qualifiers,
1523 // the behavior is undefined.
1524 // C2y changed this behavior to be implementation-defined. Clang defines
1525 // the behavior in all cases to ignore the qualifier, as in C++.
1526 // C++11 [dcl.fct]p7:
1527 // The effect of a cv-qualifier-seq in a function declarator is not the
1528 // same as adding cv-qualification on top of the function type. In the
1529 // latter case, the cv-qualifiers are ignored.
1530 if (Result->isFunctionType()) {
1531 unsigned DiagId = diag::warn_typecheck_function_qualifiers_ignored;
1532 if (!S.getLangOpts().CPlusPlus && !S.getLangOpts().C2y)
1533 DiagId = diag::ext_typecheck_function_qualifiers_unspecified;
1534 diagnoseAndRemoveTypeQualifiers(
1535 S, DS, TypeQuals, TypeSoFar: Result, RemoveTQs: DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1536 DiagID: DiagId);
1537 // No diagnostic for 'restrict' or '_Atomic' applied to a
1538 // function type; we'll diagnose those later, in BuildQualifiedType.
1539 }
1540
1541 // C++11 [dcl.ref]p1:
1542 // Cv-qualified references are ill-formed except when the
1543 // cv-qualifiers are introduced through the use of a typedef-name
1544 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1545 //
1546 // There don't appear to be any other contexts in which a cv-qualified
1547 // reference type could be formed, so the 'ill-formed' clause here appears
1548 // to never happen.
1549 if (TypeQuals && Result->isReferenceType()) {
1550 diagnoseAndRemoveTypeQualifiers(
1551 S, DS, TypeQuals, TypeSoFar: Result,
1552 RemoveTQs: DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1553 DiagID: diag::warn_typecheck_reference_qualifiers);
1554 }
1555
1556 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1557 // than once in the same specifier-list or qualifier-list, either directly
1558 // or via one or more typedefs."
1559 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1560 && TypeQuals & Result.getCVRQualifiers()) {
1561 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1562 S.Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::ext_duplicate_declspec)
1563 << "const";
1564 }
1565
1566 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1567 S.Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::ext_duplicate_declspec)
1568 << "volatile";
1569 }
1570
1571 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1572 // produce a warning in this case.
1573 }
1574
1575 QualType Qualified = S.BuildQualifiedType(T: Result, Loc: DeclLoc, CVRA: TypeQuals, DS: &DS);
1576
1577 // If adding qualifiers fails, just use the unqualified type.
1578 if (Qualified.isNull())
1579 declarator.setInvalidType(true);
1580 else
1581 Result = Qualified;
1582 }
1583
1584 // Check for __ob_wrap and __ob_trap
1585 if (DS.isOverflowBehaviorSpecified() &&
1586 S.getLangOpts().OverflowBehaviorTypes) {
1587 if (Result->isAtomicType()) {
1588 SourceLocation Loc = DS.getOverflowBehaviorLoc();
1589 StringRef SpecifierName =
1590 DeclSpec::getSpecifierName(S: DS.getOverflowBehaviorState());
1591 S.Diag(Loc, DiagID: diag::err_overflow_behavior_atomic_type)
1592 << SpecifierName << Result.getAsString() << 1;
1593 } else if (!Result->isIntegerType()) {
1594 SourceLocation Loc = DS.getOverflowBehaviorLoc();
1595 StringRef SpecifierName =
1596 DeclSpec::getSpecifierName(S: DS.getOverflowBehaviorState());
1597 S.Diag(Loc, DiagID: diag::err_overflow_behavior_non_integer_type)
1598 << SpecifierName << Result.getAsString() << 1;
1599 } else {
1600 OverflowBehaviorType::OverflowBehaviorKind Kind =
1601 DS.isWrapSpecified()
1602 ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
1603 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
1604 Result = state.getOverflowBehaviorType(Kind, UnderlyingType: Result);
1605 }
1606 }
1607
1608 if (S.getLangOpts().HLSL)
1609 Result = S.HLSL().ProcessResourceTypeAttributes(Wrapped: Result);
1610
1611 assert(!Result.isNull() && "This function should not return a null type");
1612 return Result;
1613}
1614
1615static std::string getPrintableNameForEntity(DeclarationName Entity) {
1616 if (Entity)
1617 return Entity.getAsString();
1618
1619 return "type name";
1620}
1621
1622QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1623 Qualifiers Qs, const DeclSpec *DS) {
1624 if (T.isNull())
1625 return QualType();
1626
1627 // Ignore any attempt to form a cv-qualified reference.
1628 if (T->isReferenceType()) {
1629 Qs.removeConst();
1630 Qs.removeVolatile();
1631 }
1632
1633 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1634 // object or incomplete types shall not be restrict-qualified."
1635 if (Qs.hasRestrict()) {
1636 unsigned DiagID = 0;
1637 QualType EltTy = Context.getBaseElementType(QT: T);
1638
1639 if (EltTy->isAnyPointerType() || EltTy->isReferenceType() ||
1640 EltTy->isMemberPointerType()) {
1641
1642 if (const auto *PTy = EltTy->getAs<MemberPointerType>())
1643 EltTy = PTy->getPointeeType();
1644 else
1645 EltTy = EltTy->getPointeeType();
1646
1647 // If we have a pointer or reference, the pointee must have an object
1648 // incomplete type.
1649 if (!EltTy->isIncompleteOrObjectType())
1650 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1651
1652 } else if (!T->isDependentType() && !isa<AutoType>(Val: T)) {
1653 // For an inferred type, we may not have seen the initializer yet and so
1654 // have no idea whether the underlying type is a pointer type or not.
1655 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1656 EltTy = T;
1657 }
1658
1659 Loc = DS ? DS->getRestrictSpecLoc() : Loc;
1660 if (DiagID) {
1661 Diag(Loc, DiagID) << EltTy;
1662 Qs.removeRestrict();
1663 } else {
1664 if (T->isArrayType())
1665 DiagCompat(Loc, CompatDiagId: diag_compat::restrict_on_array_of_pointers);
1666 }
1667 }
1668
1669 return Context.getQualifiedType(T, Qs);
1670}
1671
1672QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1673 unsigned CVRAU, const DeclSpec *DS) {
1674 if (T.isNull())
1675 return QualType();
1676
1677 // Ignore any attempt to form a cv-qualified reference.
1678 if (T->isReferenceType())
1679 CVRAU &=
1680 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1681
1682 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1683 // TQ_unaligned;
1684 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1685
1686 // C11 6.7.3/5:
1687 // If the same qualifier appears more than once in the same
1688 // specifier-qualifier-list, either directly or via one or more typedefs,
1689 // the behavior is the same as if it appeared only once.
1690 //
1691 // It's not specified what happens when the _Atomic qualifier is applied to
1692 // a type specified with the _Atomic specifier, but we assume that this
1693 // should be treated as if the _Atomic qualifier appeared multiple times.
1694 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1695 // C11 6.7.3/5:
1696 // If other qualifiers appear along with the _Atomic qualifier in a
1697 // specifier-qualifier-list, the resulting type is the so-qualified
1698 // atomic type.
1699 //
1700 // Don't need to worry about array types here, since _Atomic can't be
1701 // applied to such types.
1702 SplitQualType Split = T.getSplitUnqualifiedType();
1703 T = BuildAtomicType(T: QualType(Split.Ty, 0),
1704 Loc: DS ? DS->getAtomicSpecLoc() : Loc);
1705 if (T.isNull())
1706 return T;
1707 Split.Quals.addCVRQualifiers(mask: CVR);
1708 return BuildQualifiedType(T, Loc, Qs: Split.Quals);
1709 }
1710
1711 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1712 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1713 return BuildQualifiedType(T, Loc, Qs: Q, DS);
1714}
1715
1716QualType Sema::BuildParenType(QualType T) {
1717 return Context.getParenType(NamedType: T);
1718}
1719
1720/// Given that we're building a pointer or reference to the given
1721static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1722 SourceLocation loc,
1723 bool isReference) {
1724 // Bail out if retention is unrequired or already specified.
1725 if (!type->isObjCLifetimeType() ||
1726 type.getObjCLifetime() != Qualifiers::OCL_None)
1727 return type;
1728
1729 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1730
1731 // If the object type is const-qualified, we can safely use
1732 // __unsafe_unretained. This is safe (because there are no read
1733 // barriers), and it'll be safe to coerce anything but __weak* to
1734 // the resulting type.
1735 if (type.isConstQualified()) {
1736 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1737
1738 // Otherwise, check whether the static type does not require
1739 // retaining. This currently only triggers for Class (possibly
1740 // protocol-qualifed, and arrays thereof).
1741 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1742 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1743
1744 // If we are in an unevaluated context, like sizeof, skip adding a
1745 // qualification.
1746 } else if (S.isUnevaluatedContext()) {
1747 return type;
1748
1749 // If that failed, give an error and recover using __strong. __strong
1750 // is the option most likely to prevent spurious second-order diagnostics,
1751 // like when binding a reference to a field.
1752 } else {
1753 // These types can show up in private ivars in system headers, so
1754 // we need this to not be an error in those cases. Instead we
1755 // want to delay.
1756 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1757 S.DelayedDiagnostics.add(
1758 diag: sema::DelayedDiagnostic::makeForbiddenType(loc,
1759 diagnostic: diag::err_arc_indirect_no_ownership, type, argument: isReference));
1760 } else {
1761 S.Diag(Loc: loc, DiagID: diag::err_arc_indirect_no_ownership) << type << isReference;
1762 }
1763 implicitLifetime = Qualifiers::OCL_Strong;
1764 }
1765 assert(implicitLifetime && "didn't infer any lifetime!");
1766
1767 Qualifiers qs;
1768 qs.addObjCLifetime(type: implicitLifetime);
1769 return S.Context.getQualifiedType(T: type, Qs: qs);
1770}
1771
1772static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1773 std::string Quals = FnTy->getMethodQuals().getAsString();
1774
1775 switch (FnTy->getRefQualifier()) {
1776 case RQ_None:
1777 break;
1778
1779 case RQ_LValue:
1780 if (!Quals.empty())
1781 Quals += ' ';
1782 Quals += '&';
1783 break;
1784
1785 case RQ_RValue:
1786 if (!Quals.empty())
1787 Quals += ' ';
1788 Quals += "&&";
1789 break;
1790 }
1791
1792 return Quals;
1793}
1794
1795namespace {
1796/// Kinds of declarator that cannot contain a qualified function type.
1797///
1798/// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1799/// a function type with a cv-qualifier or a ref-qualifier can only appear
1800/// at the topmost level of a type.
1801///
1802/// Parens and member pointers are permitted. We don't diagnose array and
1803/// function declarators, because they don't allow function types at all.
1804///
1805/// The values of this enum are used in diagnostics.
1806enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1807} // end anonymous namespace
1808
1809/// Check whether the type T is a qualified function type, and if it is,
1810/// diagnose that it cannot be contained within the given kind of declarator.
1811static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1812 QualifiedFunctionKind QFK) {
1813 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1814 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1815 if (!FPT ||
1816 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1817 return false;
1818
1819 S.Diag(Loc, DiagID: diag::err_compound_qualified_function_type)
1820 << QFK << isa<FunctionType>(Val: T.IgnoreParens()) << T
1821 << getFunctionQualifiersAsString(FnTy: FPT);
1822 return true;
1823}
1824
1825bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
1826 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1827 if (!FPT ||
1828 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
1829 return false;
1830
1831 Diag(Loc, DiagID: diag::err_qualified_function_typeid)
1832 << T << getFunctionQualifiersAsString(FnTy: FPT);
1833 return true;
1834}
1835
1836// Helper to deduce addr space of a pointee type in OpenCL mode.
1837static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
1838 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
1839 !PointeeType->isSamplerT() &&
1840 !PointeeType.hasAddressSpace())
1841 PointeeType = S.getASTContext().getAddrSpaceQualType(
1842 T: PointeeType, AddressSpace: S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
1843 return PointeeType;
1844}
1845
1846QualType Sema::BuildPointerType(QualType T,
1847 SourceLocation Loc, DeclarationName Entity) {
1848 if (T->isReferenceType()) {
1849 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1850 Diag(Loc, DiagID: diag::err_illegal_decl_pointer_to_reference)
1851 << getPrintableNameForEntity(Entity) << T;
1852 return QualType();
1853 }
1854
1855 if (T->isFunctionType() && getLangOpts().OpenCL &&
1856 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
1857 LO: getLangOpts())) {
1858 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*pointer*/ 0;
1859 return QualType();
1860 }
1861
1862 if (getLangOpts().HLSL && Loc.isValid()) {
1863 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 0;
1864 return QualType();
1865 }
1866
1867 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Pointer))
1868 return QualType();
1869
1870 if (T->isObjCObjectType())
1871 return Context.getObjCObjectPointerType(OIT: T);
1872
1873 // In ARC, it is forbidden to build pointers to unqualified pointers.
1874 if (getLangOpts().ObjCAutoRefCount)
1875 T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: false);
1876
1877 if (getLangOpts().OpenCL)
1878 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
1879
1880 // In WebAssembly, pointers to reference types and pointers to tables are
1881 // illegal.
1882 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
1883 if (T.isWebAssemblyReferenceType()) {
1884 Diag(Loc, DiagID: diag::err_wasm_reference_pr) << 0;
1885 return QualType();
1886 }
1887
1888 // We need to desugar the type here in case T is a ParenType.
1889 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
1890 Diag(Loc, DiagID: diag::err_wasm_table_pr) << 0;
1891 return QualType();
1892 }
1893 }
1894
1895 // Build the pointer type.
1896 return Context.getPointerType(T);
1897}
1898
1899QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1900 SourceLocation Loc,
1901 DeclarationName Entity) {
1902 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1903 "Unresolved overloaded function type");
1904
1905 // C++0x [dcl.ref]p6:
1906 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1907 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1908 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1909 // the type "lvalue reference to T", while an attempt to create the type
1910 // "rvalue reference to cv TR" creates the type TR.
1911 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1912
1913 // C++ [dcl.ref]p4: There shall be no references to references.
1914 //
1915 // According to C++ DR 106, references to references are only
1916 // diagnosed when they are written directly (e.g., "int & &"),
1917 // but not when they happen via a typedef:
1918 //
1919 // typedef int& intref;
1920 // typedef intref& intref2;
1921 //
1922 // Parser::ParseDeclaratorInternal diagnoses the case where
1923 // references are written directly; here, we handle the
1924 // collapsing of references-to-references as described in C++0x.
1925 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1926
1927 // C++ [dcl.ref]p1:
1928 // A declarator that specifies the type "reference to cv void"
1929 // is ill-formed.
1930 if (T->isVoidType()) {
1931 Diag(Loc, DiagID: diag::err_reference_to_void);
1932 return QualType();
1933 }
1934
1935 if (getLangOpts().HLSL && Loc.isValid()) {
1936 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 1;
1937 return QualType();
1938 }
1939
1940 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_Reference))
1941 return QualType();
1942
1943 if (T->isFunctionType() && getLangOpts().OpenCL &&
1944 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
1945 LO: getLangOpts())) {
1946 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*reference*/ 1;
1947 return QualType();
1948 }
1949
1950 // In ARC, it is forbidden to build references to unqualified pointers.
1951 if (getLangOpts().ObjCAutoRefCount)
1952 T = inferARCLifetimeForPointee(S&: *this, type: T, loc: Loc, /*reference*/ isReference: true);
1953
1954 if (getLangOpts().OpenCL)
1955 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
1956
1957 // In WebAssembly, references to reference types and tables are illegal.
1958 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
1959 T.isWebAssemblyReferenceType()) {
1960 Diag(Loc, DiagID: diag::err_wasm_reference_pr) << 1;
1961 return QualType();
1962 }
1963 if (T->isWebAssemblyTableType()) {
1964 Diag(Loc, DiagID: diag::err_wasm_table_pr) << 1;
1965 return QualType();
1966 }
1967
1968 // Handle restrict on references.
1969 if (LValueRef)
1970 return Context.getLValueReferenceType(T, SpelledAsLValue);
1971 return Context.getRValueReferenceType(T);
1972}
1973
1974static bool checkOpenCLPipePacketType(Sema &S, QualType T, SourceLocation Loc) {
1975 if (T->isPointerType())
1976 return S.Diag(Loc, DiagID: diag::err_invalid_pipe_packet_type)
1977 << /*pointer*/ 0 << T;
1978 if (T->isReferenceType())
1979 return S.Diag(Loc, DiagID: diag::err_invalid_pipe_packet_type)
1980 << /*reference*/ 1 << T;
1981 if (T->isBlockPointerType())
1982 return S.Diag(Loc, DiagID: diag::err_invalid_pipe_packet_type)
1983 << /*block pointer*/ 2 << T;
1984 if (!T->isObjectType())
1985 return S.Diag(Loc, DiagID: diag::err_invalid_pipe_packet_type)
1986 << /*non-object*/ 3 << T;
1987 if (!T->isDependentType() && !S.isCompleteType(Loc, T))
1988 return S.Diag(Loc, DiagID: diag::err_invalid_pipe_packet_type)
1989 << /*incomplete*/ 4 << T;
1990
1991 return false;
1992}
1993
1994QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1995 if (checkOpenCLPipePacketType(S&: *this, T, Loc))
1996 return QualType();
1997 return Context.getReadPipeType(T);
1998}
1999
2000QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2001 if (checkOpenCLPipePacketType(S&: *this, T, Loc))
2002 return QualType();
2003 return Context.getWritePipeType(T);
2004}
2005
2006QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2007 SourceLocation Loc) {
2008 if (BitWidth->isInstantiationDependent())
2009 return Context.getDependentBitIntType(Unsigned: IsUnsigned, BitsExpr: BitWidth);
2010
2011 llvm::APSInt Bits(32);
2012 ExprResult ICE = VerifyIntegerConstantExpression(
2013 E: BitWidth, Result: &Bits, /*FIXME*/ CanFold: AllowFoldKind::Allow);
2014
2015 if (ICE.isInvalid())
2016 return QualType();
2017
2018 size_t NumBits = Bits.getZExtValue();
2019 if (!IsUnsigned && NumBits < 2) {
2020 Diag(Loc, DiagID: diag::err_bit_int_bad_size) << 0;
2021 return QualType();
2022 }
2023
2024 if (IsUnsigned && NumBits < 1) {
2025 Diag(Loc, DiagID: diag::err_bit_int_bad_size) << 1;
2026 return QualType();
2027 }
2028
2029 const TargetInfo &TI = getASTContext().getTargetInfo();
2030 if (NumBits > TI.getMaxBitIntWidth()) {
2031 Diag(Loc, DiagID: diag::err_bit_int_max_size)
2032 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2033 return QualType();
2034 }
2035
2036 return Context.getBitIntType(Unsigned: IsUnsigned, NumBits);
2037}
2038
2039/// Check whether the specified array bound can be evaluated using the relevant
2040/// language rules. If so, returns the possibly-converted expression and sets
2041/// SizeVal to the size. If not, but the expression might be a VLA bound,
2042/// returns ExprResult(). Otherwise, produces a diagnostic and returns
2043/// ExprError().
2044static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2045 llvm::APSInt &SizeVal, unsigned VLADiag,
2046 bool VLAIsError) {
2047 if (S.getLangOpts().CPlusPlus14 &&
2048 (VLAIsError ||
2049 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2050 // C++14 [dcl.array]p1:
2051 // The constant-expression shall be a converted constant expression of
2052 // type std::size_t.
2053 //
2054 // Don't apply this rule if we might be forming a VLA: in that case, we
2055 // allow non-constant expressions and constant-folding. We only need to use
2056 // the converted constant expression rules (to properly convert the source)
2057 // when the source expression is of class type.
2058 return S.CheckConvertedConstantExpression(
2059 From: ArraySize, T: S.Context.getSizeType(), Value&: SizeVal, CCE: CCEKind::ArrayBound);
2060 }
2061
2062 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2063 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2064 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2065 public:
2066 unsigned VLADiag;
2067 bool VLAIsError;
2068 bool IsVLA = false;
2069
2070 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2071 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2072
2073 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2074 QualType T) override {
2075 return S.Diag(Loc, DiagID: diag::err_array_size_non_int) << T;
2076 }
2077
2078 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2079 SourceLocation Loc) override {
2080 IsVLA = !VLAIsError;
2081 return S.Diag(Loc, DiagID: VLADiag);
2082 }
2083
2084 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2085 SourceLocation Loc) override {
2086 return S.Diag(Loc, DiagID: diag::ext_vla_folded_to_constant);
2087 }
2088 } Diagnoser(VLADiag, VLAIsError);
2089
2090 ExprResult R =
2091 S.VerifyIntegerConstantExpression(E: ArraySize, Result: &SizeVal, Diagnoser);
2092 if (Diagnoser.IsVLA)
2093 return ExprResult();
2094 return R;
2095}
2096
2097bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2098 EltTy = Context.getBaseElementType(QT: EltTy);
2099 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2100 EltTy->isUndeducedType())
2101 return true;
2102
2103 CharUnits Size = Context.getTypeSizeInChars(T: EltTy);
2104 CharUnits Alignment = Context.getTypeAlignInChars(T: EltTy);
2105
2106 if (Size.isMultipleOf(N: Alignment))
2107 return true;
2108
2109 Diag(Loc, DiagID: diag::err_array_element_alignment)
2110 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2111 return false;
2112}
2113
2114bool Sema::checkArrayTooLarge(QualType ElementType,
2115 const llvm::APSInt &NumElements,
2116 SourceLocation Loc, SourceRange Range) {
2117 unsigned ActiveSizeBits = NumElements.getActiveBits();
2118 if (!ElementType->isDependentType() && !ElementType->isIncompleteType() &&
2119 !ElementType->isUndeducedType() && ElementType->isConstantSizeType())
2120 ActiveSizeBits =
2121 std::max(a: ActiveSizeBits, b: ConstantArrayType::getNumAddressingBits(
2122 Context, ElementType, NumElements));
2123 if (ActiveSizeBits <= ConstantArrayType::getMaxSizeBits(Context))
2124 return false;
2125
2126 Diag(Loc, DiagID: diag::err_array_too_large)
2127 << toString(I: NumElements, Radix: 10, Signed: NumElements.isSigned(),
2128 /*formatAsCLiteral=*/false, /*UpperCase=*/false,
2129 /*InsertSeparators=*/true)
2130 << Range;
2131 return true;
2132}
2133
2134QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
2135 Expr *ArraySize, unsigned Quals,
2136 SourceRange Brackets, DeclarationName Entity) {
2137 // ArrayType stores only the CVR qualifiers; __unaligned and _Atomic are
2138 // dropped.
2139 unsigned IndexTypeQuals = Quals & Qualifiers::CVRMask;
2140
2141 SourceLocation Loc = Brackets.getBegin();
2142 if (getLangOpts().CPlusPlus) {
2143 // C++ [dcl.array]p1:
2144 // T is called the array element type; this type shall not be a reference
2145 // type, the (possibly cv-qualified) type void, a function type or an
2146 // abstract class type.
2147 //
2148 // C++ [dcl.array]p3:
2149 // When several "array of" specifications are adjacent, [...] only the
2150 // first of the constant expressions that specify the bounds of the arrays
2151 // may be omitted.
2152 //
2153 // Note: function types are handled in the common path with C.
2154 if (T->isReferenceType()) {
2155 Diag(Loc, DiagID: diag::err_illegal_decl_array_of_references)
2156 << getPrintableNameForEntity(Entity) << T;
2157 return QualType();
2158 }
2159
2160 if (T->isVoidType() || T->isIncompleteArrayType()) {
2161 Diag(Loc, DiagID: diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2162 return QualType();
2163 }
2164
2165 if (RequireNonAbstractType(Loc: Brackets.getBegin(), T,
2166 DiagID: diag::err_array_of_abstract_type))
2167 return QualType();
2168
2169 // Mentioning a member pointer type for an array type causes us to lock in
2170 // an inheritance model, even if it's inside an unused typedef.
2171 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2172 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2173 if (!MPTy->getQualifier().isDependent())
2174 (void)isCompleteType(Loc, T);
2175
2176 } else {
2177 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2178 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2179 if (!T.isWebAssemblyReferenceType() &&
2180 RequireCompleteSizedType(Loc, T,
2181 DiagID: diag::err_array_incomplete_or_sizeless_type))
2182 return QualType();
2183 }
2184
2185 // Multi-dimensional arrays of WebAssembly references are not allowed.
2186 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2187 const auto *ATy = dyn_cast<ArrayType>(Val&: T);
2188 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2189 Diag(Loc, DiagID: diag::err_wasm_reftype_multidimensional_array);
2190 return QualType();
2191 }
2192 }
2193
2194 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2195 Diag(Loc, DiagID: diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2196 return QualType();
2197 }
2198
2199 if (T->isFunctionType()) {
2200 Diag(Loc, DiagID: diag::err_illegal_decl_array_of_functions)
2201 << getPrintableNameForEntity(Entity) << T;
2202 return QualType();
2203 }
2204
2205 if (const auto *RD = T->getAsRecordDecl()) {
2206 // If the element type is a struct or union that contains a variadic
2207 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2208 if (RD->hasFlexibleArrayMember())
2209 Diag(Loc, DiagID: diag::ext_flexible_array_in_array) << T;
2210 } else if (T->isObjCObjectType()) {
2211 Diag(Loc, DiagID: diag::err_objc_array_of_interfaces) << T;
2212 return QualType();
2213 }
2214
2215 if (!checkArrayElementAlignment(EltTy: T, Loc))
2216 return QualType();
2217
2218 // Do placeholder conversions on the array size expression.
2219 if (ArraySize && ArraySize->hasPlaceholderType()) {
2220 ExprResult Result = CheckPlaceholderExpr(E: ArraySize);
2221 if (Result.isInvalid()) return QualType();
2222 ArraySize = Result.get();
2223 }
2224
2225 // Do lvalue-to-rvalue conversions on the array size expression.
2226 if (ArraySize && !ArraySize->isPRValue()) {
2227 ExprResult Result = DefaultLvalueConversion(E: ArraySize);
2228 if (Result.isInvalid())
2229 return QualType();
2230
2231 ArraySize = Result.get();
2232 }
2233
2234 // C99 6.7.5.2p1: The size expression shall have integer type.
2235 // C++11 allows contextual conversions to such types.
2236 if (!getLangOpts().CPlusPlus11 &&
2237 ArraySize && !ArraySize->isTypeDependent() &&
2238 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2239 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_array_size_non_int)
2240 << ArraySize->getType() << ArraySize->getSourceRange();
2241 return QualType();
2242 }
2243
2244 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2245 if (!ArraySize)
2246 return false;
2247
2248 // If the array size expression is a conditional expression whose branches
2249 // are both integer constant expressions, one negative and one positive,
2250 // then it's assumed to be like an old-style static assertion. e.g.,
2251 // int old_style_assert[expr ? 1 : -1];
2252 // We will accept any integer constant expressions instead of assuming the
2253 // values 1 and -1 are always used.
2254 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2255 Val: ArraySize->IgnoreParenImpCasts())) {
2256 std::optional<llvm::APSInt> LHS =
2257 CondExpr->getLHS()->getIntegerConstantExpr(Ctx: Context);
2258 std::optional<llvm::APSInt> RHS =
2259 CondExpr->getRHS()->getIntegerConstantExpr(Ctx: Context);
2260 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2261 }
2262 return false;
2263 };
2264
2265 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2266 unsigned VLADiag;
2267 bool VLAIsError;
2268 if (getLangOpts().OpenCL) {
2269 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2270 VLADiag = diag::err_opencl_vla;
2271 VLAIsError = true;
2272 } else if (getLangOpts().C99) {
2273 VLADiag = diag::warn_vla_used;
2274 VLAIsError = false;
2275 } else if (isSFINAEContext()) {
2276 VLADiag = diag::err_vla_in_sfinae;
2277 VLAIsError = true;
2278 } else if (getLangOpts().OpenMP && OpenMP().isInOpenMPTaskUntiedContext()) {
2279 VLADiag = diag::err_openmp_vla_in_task_untied;
2280 VLAIsError = true;
2281 } else if (getLangOpts().CPlusPlus) {
2282 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2283 VLADiag = getLangOpts().GNUMode
2284 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2285 : diag::ext_vla_cxx_static_assert;
2286 else
2287 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2288 : diag::ext_vla_cxx;
2289 VLAIsError = false;
2290 } else {
2291 VLADiag = diag::ext_vla;
2292 VLAIsError = false;
2293 }
2294
2295 llvm::APSInt ConstVal(Context.getTypeSize(T: Context.getSizeType()));
2296 if (!ArraySize) {
2297 if (ASM == ArraySizeModifier::Star) {
2298 Diag(Loc, DiagID: VLADiag);
2299 if (VLAIsError)
2300 return QualType();
2301
2302 T = Context.getVariableArrayType(EltTy: T, NumElts: nullptr, ASM, IndexTypeQuals);
2303 } else {
2304 T = Context.getIncompleteArrayType(EltTy: T, ASM, IndexTypeQuals);
2305 }
2306 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2307 T = Context.getDependentSizedArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals);
2308 } else {
2309 ExprResult R =
2310 checkArraySize(S&: *this, ArraySize, SizeVal&: ConstVal, VLADiag, VLAIsError);
2311 if (R.isInvalid())
2312 return QualType();
2313
2314 if (!R.isUsable()) {
2315 // C99: an array with a non-ICE size is a VLA. We accept any expression
2316 // that we can fold to a non-zero positive value as a non-VLA as an
2317 // extension.
2318 T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals);
2319 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2320 !T->isConstantSizeType()) {
2321 // C99: an array with an element type that has a non-constant-size is a
2322 // VLA.
2323 // FIXME: Add a note to explain why this isn't a VLA.
2324 Diag(Loc, DiagID: VLADiag);
2325 if (VLAIsError)
2326 return QualType();
2327 T = Context.getVariableArrayType(EltTy: T, NumElts: ArraySize, ASM, IndexTypeQuals);
2328 } else {
2329 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2330 // have a value greater than zero.
2331 // In C++, this follows from narrowing conversions being disallowed.
2332 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2333 if (Entity)
2334 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_decl_negative_array_size)
2335 << getPrintableNameForEntity(Entity)
2336 << ArraySize->getSourceRange();
2337 else
2338 Diag(Loc: ArraySize->getBeginLoc(),
2339 DiagID: diag::err_typecheck_negative_array_size)
2340 << ArraySize->getSourceRange();
2341 return QualType();
2342 }
2343 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2344 if (getLangOpts().OpenCL) {
2345 Diag(Loc: ArraySize->getBeginLoc(), DiagID: diag::err_typecheck_zero_array_size)
2346 << 3 << ArraySize->getSourceRange();
2347 return QualType();
2348 }
2349
2350 // GCC accepts zero sized static arrays. We allow them when
2351 // we're not in a SFINAE context.
2352 Diag(Loc: ArraySize->getBeginLoc(),
2353 DiagID: isSFINAEContext() ? diag::err_typecheck_zero_array_size
2354 : diag::ext_typecheck_zero_array_size)
2355 << 0 << ArraySize->getSourceRange();
2356 if (isSFINAEContext())
2357 return QualType();
2358 }
2359
2360 if (checkArrayTooLarge(ElementType: T, NumElements: ConstVal, Loc: ArraySize->getBeginLoc(),
2361 Range: ArraySize->getSourceRange()))
2362 return QualType();
2363
2364 T = Context.getConstantArrayType(EltTy: T, ArySize: ConstVal, SizeExpr: ArraySize, ASM,
2365 IndexTypeQuals);
2366 }
2367 }
2368
2369 if (T->isVariableArrayType()) {
2370 if (!Context.getTargetInfo().isVLASupported()) {
2371 // CUDA device code and some other targets don't support VLAs.
2372 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2373 targetDiag(Loc,
2374 DiagID: IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2375 << (IsCUDADevice ? llvm::to_underlying(E: CUDA().CurrentTarget()) : 0);
2376 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2377 // VLAs are supported on this target, but we may need to do delayed
2378 // checking that the VLA is not being used within a coroutine.
2379 FSI->setHasVLA(Loc);
2380 }
2381 }
2382
2383 // If this is not C99, diagnose array size modifiers on non-VLAs.
2384 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2385 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2386 Diag(Loc, DiagID: getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2387 : diag::ext_c99_array_usage)
2388 << ASM;
2389 }
2390
2391 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2392 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2393 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2394 if (getLangOpts().OpenCL) {
2395 const QualType ArrType = Context.getBaseElementType(QT: T);
2396 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2397 ArrType->isSamplerT() || ArrType->isImageType()) {
2398 Diag(Loc, DiagID: diag::err_opencl_invalid_type_array) << ArrType;
2399 return QualType();
2400 }
2401 }
2402
2403 // Remember where the bound of a VLA is evaluated. Bounds in a function
2404 // prototype are evaluated in that function, which doesn't exist yet, so they
2405 // are not recorded and their uses are not diagnosed.
2406 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(T))
2407 if (CurContext->isFunctionOrMethod() &&
2408 !(getCurScope() && getCurScope()->isFunctionPrototypeScope()))
2409 if (const Expr *Size = VAT->getSizeExpr())
2410 VLASizeExprOwners.try_emplace(Key: Size, Args&: CurContext);
2411
2412 return T;
2413}
2414
2415static bool CheckBitIntElementType(Sema &S, SourceLocation AttrLoc,
2416 const BitIntType *BIT,
2417 bool ForMatrixType = false) {
2418 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2419 unsigned NumBits = BIT->getNumBits();
2420 if (!llvm::isPowerOf2_32(Value: NumBits))
2421 return S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_bitint_vector_type)
2422 << ForMatrixType;
2423 return false;
2424}
2425
2426// A bool vector is stored as an integer with one bit per element and can be
2427// formed from any vector (e.g. by the conditional operator); the size bound
2428// keeps the natural alignment within TypeInfo::Align.
2429static constexpr uint64_t MaxVectorElements = llvm::IntegerType::MAX_INT_BITS;
2430static constexpr uint64_t MaxVectorSizeInBits = 1ULL << 31;
2431
2432QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2433 SourceLocation AttrLoc) {
2434 // The base type must be integer (not Boolean or enumeration) or float, and
2435 // can't already be a vector.
2436 if ((!CurType->isDependentType() &&
2437 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2438 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2439 !CurType->isBitIntType()) ||
2440 CurType->isArrayType()) {
2441 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_vector_type) << CurType;
2442 return QualType();
2443 }
2444
2445 if (const auto *BIT = CurType->getAs<BitIntType>();
2446 BIT && CheckBitIntElementType(S&: *this, AttrLoc, BIT))
2447 return QualType();
2448
2449 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2450 return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc,
2451 VecKind: VectorKind::Generic);
2452
2453 std::optional<llvm::APSInt> VecSize =
2454 SizeExpr->getIntegerConstantExpr(Ctx: Context);
2455 if (!VecSize) {
2456 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2457 << "vector_size" << AANT_ArgumentIntegerConstant
2458 << SizeExpr->getSourceRange();
2459 return QualType();
2460 }
2461
2462 if (VecSize->isNegative()) {
2463 Diag(Loc: SizeExpr->getExprLoc(), DiagID: diag::err_attribute_vec_negative_size);
2464 return QualType();
2465 }
2466
2467 if (CurType->isDependentType())
2468 return Context.getDependentVectorType(VectorType: CurType, SizeExpr, AttrLoc,
2469 VecKind: VectorKind::Generic);
2470
2471 // vecSize is specified in bytes - convert to bits.
2472 if (VecSize->ugt(RHS: MaxVectorSizeInBits / 8)) {
2473 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2474 << SizeExpr->getSourceRange() << "vector";
2475 return QualType();
2476 }
2477 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2478 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(T: CurType));
2479
2480 if (VectorSizeBits == 0) {
2481 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2482 << SizeExpr->getSourceRange() << "vector";
2483 return QualType();
2484 }
2485
2486 if (!TypeSize || VectorSizeBits % TypeSize) {
2487 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_size)
2488 << SizeExpr->getSourceRange();
2489 return QualType();
2490 }
2491
2492 if (VectorSizeBits / TypeSize > MaxVectorElements) {
2493 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2494 << SizeExpr->getSourceRange() << "vector";
2495 return QualType();
2496 }
2497
2498 return Context.getVectorType(VectorType: CurType, NumElts: VectorSizeBits / TypeSize,
2499 VecKind: VectorKind::Generic);
2500}
2501
2502QualType Sema::BuildExtVectorType(QualType T, Expr *SizeExpr,
2503 SourceLocation AttrLoc) {
2504 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2505 // in conjunction with complex types (pointers, arrays, functions, etc.).
2506 //
2507 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2508 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2509 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2510 // of bool aren't allowed.
2511 //
2512 // We explicitly allow bool elements in ext_vector_type for C/C++.
2513 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2514 if ((!T->isDependentType() && !T->isIntegerType() &&
2515 !T->isRealFloatingType()) ||
2516 T->isEnumeralType() || (IsNoBoolVecLang && T->isBooleanType())) {
2517 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_vector_type) << T;
2518 return QualType();
2519 }
2520
2521 if (const auto *BIT = T->getAs<BitIntType>();
2522 BIT && CheckBitIntElementType(S&: *this, AttrLoc, BIT))
2523 return QualType();
2524
2525 if (!SizeExpr->isTypeDependent() && !SizeExpr->isValueDependent()) {
2526 std::optional<llvm::APSInt> VecSize =
2527 SizeExpr->getIntegerConstantExpr(Ctx: Context);
2528 if (!VecSize) {
2529 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2530 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2531 << SizeExpr->getSourceRange();
2532 return QualType();
2533 }
2534
2535 if (VecSize->isNegative()) {
2536 Diag(Loc: SizeExpr->getExprLoc(), DiagID: diag::err_attribute_vec_negative_size);
2537 return QualType();
2538 }
2539
2540 // Unlike gcc's vector_size attribute, the size is specified as the
2541 // number of elements, not the number of bytes.
2542 if (VecSize->ugt(RHS: MaxVectorElements)) {
2543 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2544 << SizeExpr->getSourceRange() << "vector";
2545 return QualType();
2546 }
2547 unsigned VectorSize = static_cast<unsigned>(VecSize->getZExtValue());
2548
2549 if (VectorSize == 0) {
2550 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2551 << SizeExpr->getSourceRange() << "vector";
2552 return QualType();
2553 }
2554
2555 if (!T->isDependentType() &&
2556 VectorSize * Context.getTypeSize(T) > MaxVectorSizeInBits) {
2557 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2558 << SizeExpr->getSourceRange() << "vector";
2559 return QualType();
2560 }
2561
2562 return Context.getExtVectorType(VectorType: T, NumElts: VectorSize);
2563 }
2564
2565 return Context.getDependentSizedExtVectorType(VectorType: T, SizeExpr, AttrLoc);
2566}
2567
2568QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2569 SourceLocation AttrLoc) {
2570 assert(Context.getLangOpts().MatrixTypes &&
2571 "Should never build a matrix type when it is disabled");
2572
2573 // Check element type, if it is not dependent.
2574 if (!ElementTy->isDependentType() &&
2575 !MatrixType::isValidElementType(T: ElementTy, LangOpts: getLangOpts())) {
2576 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_invalid_matrix_type) << ElementTy;
2577 return QualType();
2578 }
2579
2580 if (const auto *BIT = ElementTy->getAs<BitIntType>();
2581 BIT &&
2582 CheckBitIntElementType(S&: *this, AttrLoc, BIT, /*ForMatrixType=*/true))
2583 return QualType();
2584
2585 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2586 NumRows->isValueDependent() || NumCols->isValueDependent())
2587 return Context.getDependentSizedMatrixType(ElementType: ElementTy, RowExpr: NumRows, ColumnExpr: NumCols,
2588 AttrLoc);
2589
2590 std::optional<llvm::APSInt> ValueRows =
2591 NumRows->getIntegerConstantExpr(Ctx: Context);
2592 std::optional<llvm::APSInt> ValueColumns =
2593 NumCols->getIntegerConstantExpr(Ctx: Context);
2594
2595 auto const RowRange = NumRows->getSourceRange();
2596 auto const ColRange = NumCols->getSourceRange();
2597
2598 // Both are row and column expressions are invalid.
2599 if (!ValueRows && !ValueColumns) {
2600 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2601 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2602 << ColRange;
2603 return QualType();
2604 }
2605
2606 // Only the row expression is invalid.
2607 if (!ValueRows) {
2608 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2609 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2610 return QualType();
2611 }
2612
2613 // Only the column expression is invalid.
2614 if (!ValueColumns) {
2615 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
2616 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2617 return QualType();
2618 }
2619
2620 // Check the matrix dimensions.
2621 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2622 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2623 if (MatrixRows == 0 && MatrixColumns == 0) {
2624 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size)
2625 << "matrix" << RowRange << ColRange;
2626 return QualType();
2627 }
2628 if (MatrixRows == 0) {
2629 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size) << "matrix" << RowRange;
2630 return QualType();
2631 }
2632 if (MatrixColumns == 0) {
2633 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_zero_size) << "matrix" << ColRange;
2634 return QualType();
2635 }
2636 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension &&
2637 MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2638 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2639 << RowRange << ColRange << "matrix row and column";
2640 return QualType();
2641 }
2642 if (MatrixRows > Context.getLangOpts().MaxMatrixDimension) {
2643 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2644 << RowRange << "matrix row";
2645 return QualType();
2646 }
2647 if (MatrixColumns > Context.getLangOpts().MaxMatrixDimension) {
2648 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_size_too_large)
2649 << ColRange << "matrix column";
2650 return QualType();
2651 }
2652 return Context.getConstantMatrixType(ElementType: ElementTy, NumRows: MatrixRows, NumColumns: MatrixColumns);
2653}
2654
2655bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2656 if ((T->isArrayType() && !getLangOpts().allowArrayReturnTypes()) ||
2657 T->isFunctionType()) {
2658 Diag(Loc, DiagID: diag::err_func_returning_array_function)
2659 << T->isFunctionType() << T;
2660 return true;
2661 }
2662
2663 // Functions cannot return half FP.
2664 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2665 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2666 Diag(Loc, DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2667 FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2668 return true;
2669 }
2670
2671 // Methods cannot return interface types. All ObjC objects are
2672 // passed by reference.
2673 if (T->isObjCObjectType()) {
2674 Diag(Loc, DiagID: diag::err_object_cannot_be_passed_returned_by_value)
2675 << 0 << T << FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2676 return true;
2677 }
2678
2679 // __ptrauth is illegal on a function return type.
2680 if (T.getPointerAuth()) {
2681 Diag(Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 0;
2682 return true;
2683 }
2684
2685 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2686 T.hasNonTrivialToPrimitiveCopyCUnion())
2687 checkNonTrivialCUnion(QT: T, Loc, UseContext: NonTrivialCUnionContext::FunctionReturn,
2688 NonTrivialKind: NTCUK_Destruct | NTCUK_Copy);
2689
2690 // C++2a [dcl.fct]p12:
2691 // A volatile-qualified return type is deprecated
2692 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2693 Diag(Loc, DiagID: diag::warn_deprecated_volatile_return) << T;
2694
2695 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2696 return true;
2697 return false;
2698}
2699
2700/// Check the extended parameter information. Most of the necessary
2701/// checking should occur when applying the parameter attribute; the
2702/// only other checks required are positional restrictions.
2703static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2704 const FunctionProtoType::ExtProtoInfo &EPI,
2705 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2706 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2707
2708 bool emittedError = false;
2709 auto actualCC = EPI.ExtInfo.getCC();
2710 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2711 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2712 bool isCompatible =
2713 (required == RequiredCC::OnlySwift)
2714 ? (actualCC == CC_Swift)
2715 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2716 if (isCompatible || emittedError)
2717 return;
2718 S.Diag(Loc: getParamLoc(paramIndex), DiagID: diag::err_swift_param_attr_not_swiftcall)
2719 << getParameterABISpelling(kind: EPI.ExtParameterInfos[paramIndex].getABI())
2720 << (required == RequiredCC::OnlySwift);
2721 emittedError = true;
2722 };
2723 for (size_t paramIndex = 0, numParams = paramTypes.size();
2724 paramIndex != numParams; ++paramIndex) {
2725 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2726 // Nothing interesting to check for orindary-ABI parameters.
2727 case ParameterABI::Ordinary:
2728 case ParameterABI::HLSLOut:
2729 case ParameterABI::HLSLInOut:
2730 continue;
2731
2732 // swift_indirect_result parameters must be a prefix of the function
2733 // arguments.
2734 case ParameterABI::SwiftIndirectResult:
2735 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2736 if (paramIndex != 0 &&
2737 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2738 != ParameterABI::SwiftIndirectResult) {
2739 S.Diag(Loc: getParamLoc(paramIndex),
2740 DiagID: diag::err_swift_indirect_result_not_first);
2741 }
2742 continue;
2743
2744 case ParameterABI::SwiftContext:
2745 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2746 continue;
2747
2748 // SwiftAsyncContext is not limited to swiftasynccall functions.
2749 case ParameterABI::SwiftAsyncContext:
2750 continue;
2751
2752 // swift_error parameters must be preceded by a swift_context parameter.
2753 case ParameterABI::SwiftErrorResult:
2754 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2755 if (paramIndex == 0 ||
2756 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2757 ParameterABI::SwiftContext) {
2758 S.Diag(Loc: getParamLoc(paramIndex),
2759 DiagID: diag::err_swift_error_result_not_after_swift_context);
2760 }
2761 continue;
2762 }
2763 llvm_unreachable("bad ABI kind");
2764 }
2765}
2766
2767QualType Sema::BuildFunctionType(QualType T,
2768 MutableArrayRef<QualType> ParamTypes,
2769 SourceLocation Loc, DeclarationName Entity,
2770 const FunctionProtoType::ExtProtoInfo &EPI) {
2771 bool Invalid = false;
2772
2773 Invalid |= CheckFunctionReturnType(T, Loc);
2774
2775 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2776 // FIXME: Loc is too inprecise here, should use proper locations for args.
2777 QualType ParamType = Context.getAdjustedParameterType(T: ParamTypes[Idx]);
2778 if (ParamType->isVoidType()) {
2779 Diag(Loc, DiagID: diag::err_param_with_void_type);
2780 Invalid = true;
2781 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2782 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2783 // Disallow half FP arguments.
2784 Diag(Loc, DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2785 FixItHint::CreateInsertion(InsertionLoc: Loc, Code: "*");
2786 Invalid = true;
2787 } else if (ParamType->isWebAssemblyTableType()) {
2788 Diag(Loc, DiagID: diag::err_wasm_table_as_function_parameter);
2789 Invalid = true;
2790 } else if (ParamType.getPointerAuth()) {
2791 // __ptrauth is illegal on a function return type.
2792 Diag(Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 1;
2793 Invalid = true;
2794 }
2795
2796 // C++2a [dcl.fct]p4:
2797 // A parameter with volatile-qualified type is deprecated
2798 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2799 Diag(Loc, DiagID: diag::warn_deprecated_volatile_param) << ParamType;
2800
2801 ParamTypes[Idx] = ParamType;
2802 }
2803
2804 if (EPI.ExtParameterInfos) {
2805 checkExtParameterInfos(S&: *this, paramTypes: ParamTypes, EPI,
2806 getParamLoc: [=](unsigned i) { return Loc; });
2807 }
2808
2809 if (EPI.ExtInfo.getProducesResult()) {
2810 // This is just a warning, so we can't fail to build if we see it.
2811 ObjC().checkNSReturnsRetainedReturnType(loc: Loc, type: T);
2812 }
2813
2814 if (Invalid)
2815 return QualType();
2816
2817 return Context.getFunctionType(ResultTy: T, Args: ParamTypes, EPI);
2818}
2819
2820QualType Sema::BuildMemberPointerType(QualType T, const CXXScopeSpec &SS,
2821 CXXRecordDecl *Cls, SourceLocation Loc,
2822 DeclarationName Entity) {
2823 if (!Cls && !isDependentScopeSpecifier(SS)) {
2824 Cls = dyn_cast_or_null<CXXRecordDecl>(Val: computeDeclContext(SS));
2825 if (!Cls) {
2826 auto D =
2827 Diag(Loc: SS.getBeginLoc(), DiagID: diag::err_illegal_decl_mempointer_in_nonclass)
2828 << SS.getRange();
2829 if (const IdentifierInfo *II = Entity.getAsIdentifierInfo())
2830 D << II;
2831 else
2832 D << "member pointer";
2833 return QualType();
2834 }
2835 }
2836
2837 // Verify that we're not building a pointer to pointer to function with
2838 // exception specification.
2839 if (CheckDistantExceptionSpec(T)) {
2840 Diag(Loc, DiagID: diag::err_distant_exception_spec);
2841 return QualType();
2842 }
2843
2844 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2845 // with reference type, or "cv void."
2846 if (T->isReferenceType()) {
2847 Diag(Loc, DiagID: diag::err_illegal_decl_mempointer_to_reference)
2848 << getPrintableNameForEntity(Entity) << T;
2849 return QualType();
2850 }
2851
2852 if (T->isVoidType()) {
2853 Diag(Loc, DiagID: diag::err_illegal_decl_mempointer_to_void)
2854 << getPrintableNameForEntity(Entity);
2855 return QualType();
2856 }
2857
2858 if (T->isFunctionType() && getLangOpts().OpenCL &&
2859 !getOpenCLOptions().isAvailableOption(Ext: "__cl_clang_function_pointers",
2860 LO: getLangOpts())) {
2861 Diag(Loc, DiagID: diag::err_opencl_function_pointer) << /*pointer*/ 0;
2862 return QualType();
2863 }
2864
2865 if (getLangOpts().HLSL && Loc.isValid()) {
2866 Diag(Loc, DiagID: diag::err_hlsl_pointers_unsupported) << 0;
2867 return QualType();
2868 }
2869
2870 // Adjust the default free function calling convention to the default method
2871 // calling convention.
2872 bool IsCtorOrDtor =
2873 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2874 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2875 if (T->isFunctionType())
2876 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
2877
2878 return Context.getMemberPointerType(T, Qualifier: SS.getScopeRep(), Cls);
2879}
2880
2881QualType Sema::BuildBlockPointerType(QualType T,
2882 SourceLocation Loc,
2883 DeclarationName Entity) {
2884 if (!T->isFunctionType()) {
2885 Diag(Loc, DiagID: diag::err_nonfunction_block_type);
2886 return QualType();
2887 }
2888
2889 if (checkQualifiedFunction(S&: *this, T, Loc, QFK: QFK_BlockPointer))
2890 return QualType();
2891
2892 if (getLangOpts().OpenCL)
2893 T = deduceOpenCLPointeeAddrSpace(S&: *this, PointeeType: T);
2894
2895 return Context.getBlockPointerType(T);
2896}
2897
2898QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2899 QualType QT = Ty.get();
2900 if (QT.isNull()) {
2901 if (TInfo) *TInfo = nullptr;
2902 return QualType();
2903 }
2904
2905 TypeSourceInfo *TSI = nullptr;
2906 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(Val&: QT)) {
2907 QT = LIT->getType();
2908 TSI = LIT->getTypeSourceInfo();
2909 }
2910
2911 if (TInfo)
2912 *TInfo = TSI;
2913 return QT;
2914}
2915
2916static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2917 Qualifiers::ObjCLifetime ownership,
2918 unsigned chunkIndex);
2919
2920/// Given that this is the declaration of a parameter under ARC,
2921/// attempt to infer attributes and such for pointer-to-whatever
2922/// types.
2923static void inferARCWriteback(TypeProcessingState &state,
2924 QualType &declSpecType) {
2925 Sema &S = state.getSema();
2926 Declarator &declarator = state.getDeclarator();
2927
2928 // TODO: should we care about decl qualifiers?
2929
2930 // Check whether the declarator has the expected form. We walk
2931 // from the inside out in order to make the block logic work.
2932 unsigned outermostPointerIndex = 0;
2933 bool isBlockPointer = false;
2934 unsigned numPointers = 0;
2935 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2936 unsigned chunkIndex = i;
2937 DeclaratorChunk &chunk = declarator.getTypeObject(i: chunkIndex);
2938 switch (chunk.Kind) {
2939 case DeclaratorChunk::Paren:
2940 // Ignore parens.
2941 break;
2942
2943 case DeclaratorChunk::Reference:
2944 case DeclaratorChunk::Pointer:
2945 // Count the number of pointers. Treat references
2946 // interchangeably as pointers; if they're mis-ordered, normal
2947 // type building will discover that.
2948 outermostPointerIndex = chunkIndex;
2949 numPointers++;
2950 break;
2951
2952 case DeclaratorChunk::BlockPointer:
2953 // If we have a pointer to block pointer, that's an acceptable
2954 // indirect reference; anything else is not an application of
2955 // the rules.
2956 if (numPointers != 1) return;
2957 numPointers++;
2958 outermostPointerIndex = chunkIndex;
2959 isBlockPointer = true;
2960
2961 // We don't care about pointer structure in return values here.
2962 goto done;
2963
2964 case DeclaratorChunk::Array: // suppress if written (id[])?
2965 case DeclaratorChunk::Function:
2966 case DeclaratorChunk::MemberPointer:
2967 case DeclaratorChunk::Pipe:
2968 return;
2969 }
2970 }
2971 done:
2972
2973 // If we have *one* pointer, then we want to throw the qualifier on
2974 // the declaration-specifiers, which means that it needs to be a
2975 // retainable object type.
2976 if (numPointers == 1) {
2977 // If it's not a retainable object type, the rule doesn't apply.
2978 if (!declSpecType->isObjCRetainableType()) return;
2979
2980 // If it already has lifetime, don't do anything.
2981 if (declSpecType.getObjCLifetime()) return;
2982
2983 // Otherwise, modify the type in-place.
2984 Qualifiers qs;
2985
2986 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2987 qs.addObjCLifetime(type: Qualifiers::OCL_ExplicitNone);
2988 else
2989 qs.addObjCLifetime(type: Qualifiers::OCL_Autoreleasing);
2990 declSpecType = S.Context.getQualifiedType(T: declSpecType, Qs: qs);
2991
2992 // If we have *two* pointers, then we want to throw the qualifier on
2993 // the outermost pointer.
2994 } else if (numPointers == 2) {
2995 // If we don't have a block pointer, we need to check whether the
2996 // declaration-specifiers gave us something that will turn into a
2997 // retainable object pointer after we slap the first pointer on it.
2998 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2999 return;
3000
3001 // Look for an explicit lifetime attribute there.
3002 DeclaratorChunk &chunk = declarator.getTypeObject(i: outermostPointerIndex);
3003 if (chunk.Kind != DeclaratorChunk::Pointer &&
3004 chunk.Kind != DeclaratorChunk::BlockPointer)
3005 return;
3006 for (const ParsedAttr &AL : chunk.getAttrs())
3007 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3008 return;
3009
3010 transferARCOwnershipToDeclaratorChunk(state, ownership: Qualifiers::OCL_Autoreleasing,
3011 chunkIndex: outermostPointerIndex);
3012
3013 // Any other number of pointers/references does not trigger the rule.
3014 } else return;
3015
3016 // TODO: mark whether we did this inference?
3017}
3018
3019void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3020 SourceLocation FallbackLoc,
3021 SourceLocation ConstQualLoc,
3022 SourceLocation VolatileQualLoc,
3023 SourceLocation RestrictQualLoc,
3024 SourceLocation AtomicQualLoc,
3025 SourceLocation UnalignedQualLoc) {
3026 if (!Quals)
3027 return;
3028
3029 struct Qual {
3030 const char *Name;
3031 unsigned Mask;
3032 SourceLocation Loc;
3033 } const QualKinds[5] = {
3034 { .Name: "const", .Mask: DeclSpec::TQ_const, .Loc: ConstQualLoc },
3035 { .Name: "volatile", .Mask: DeclSpec::TQ_volatile, .Loc: VolatileQualLoc },
3036 { .Name: "restrict", .Mask: DeclSpec::TQ_restrict, .Loc: RestrictQualLoc },
3037 { .Name: "__unaligned", .Mask: DeclSpec::TQ_unaligned, .Loc: UnalignedQualLoc },
3038 { .Name: "_Atomic", .Mask: DeclSpec::TQ_atomic, .Loc: AtomicQualLoc }
3039 };
3040
3041 SmallString<32> QualStr;
3042 unsigned NumQuals = 0;
3043 SourceLocation Loc;
3044 FixItHint FixIts[5];
3045
3046 // Build a string naming the redundant qualifiers.
3047 for (auto &E : QualKinds) {
3048 if (Quals & E.Mask) {
3049 if (!QualStr.empty()) QualStr += ' ';
3050 QualStr += E.Name;
3051
3052 // If we have a location for the qualifier, offer a fixit.
3053 SourceLocation QualLoc = E.Loc;
3054 if (QualLoc.isValid()) {
3055 FixIts[NumQuals] = FixItHint::CreateRemoval(RemoveRange: QualLoc);
3056 if (Loc.isInvalid() ||
3057 getSourceManager().isBeforeInTranslationUnit(LHS: QualLoc, RHS: Loc))
3058 Loc = QualLoc;
3059 }
3060
3061 ++NumQuals;
3062 }
3063 }
3064
3065 Diag(Loc: Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3066 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3067}
3068
3069// Diagnose pointless type qualifiers on the return type of a function.
3070static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3071 Declarator &D,
3072 unsigned FunctionChunkIndex) {
3073 const DeclaratorChunk::FunctionTypeInfo &FTI =
3074 D.getTypeObject(i: FunctionChunkIndex).Fun;
3075 if (FTI.hasTrailingReturnType()) {
3076 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3077 Quals: RetTy.getLocalCVRQualifiers(),
3078 FallbackLoc: FTI.getTrailingReturnTypeLoc());
3079 return;
3080 }
3081
3082 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3083 End = D.getNumTypeObjects();
3084 OuterChunkIndex != End; ++OuterChunkIndex) {
3085 DeclaratorChunk &OuterChunk = D.getTypeObject(i: OuterChunkIndex);
3086 switch (OuterChunk.Kind) {
3087 case DeclaratorChunk::Paren:
3088 continue;
3089
3090 case DeclaratorChunk::Pointer: {
3091 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3092 S.diagnoseIgnoredQualifiers(
3093 DiagID: diag::warn_qual_return_type,
3094 Quals: PTI.TypeQuals,
3095 FallbackLoc: SourceLocation(),
3096 ConstQualLoc: PTI.ConstQualLoc,
3097 VolatileQualLoc: PTI.VolatileQualLoc,
3098 RestrictQualLoc: PTI.RestrictQualLoc,
3099 AtomicQualLoc: PTI.AtomicQualLoc,
3100 UnalignedQualLoc: PTI.UnalignedQualLoc);
3101 return;
3102 }
3103
3104 case DeclaratorChunk::Function:
3105 case DeclaratorChunk::BlockPointer:
3106 case DeclaratorChunk::Reference:
3107 case DeclaratorChunk::Array:
3108 case DeclaratorChunk::MemberPointer:
3109 case DeclaratorChunk::Pipe:
3110 // FIXME: We can't currently provide an accurate source location and a
3111 // fix-it hint for these.
3112 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3113 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3114 Quals: RetTy.getCVRQualifiers() | AtomicQual,
3115 FallbackLoc: D.getIdentifierLoc());
3116 return;
3117 }
3118
3119 llvm_unreachable("unknown declarator chunk kind");
3120 }
3121
3122 // If the qualifiers come from a conversion function type, don't diagnose
3123 // them -- they're not necessarily redundant, since such a conversion
3124 // operator can be explicitly called as "x.operator const int()".
3125 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3126 return;
3127
3128 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3129 // which are present there.
3130 S.diagnoseIgnoredQualifiers(DiagID: diag::warn_qual_return_type,
3131 Quals: D.getDeclSpec().getTypeQualifiers(),
3132 FallbackLoc: D.getIdentifierLoc(),
3133 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
3134 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
3135 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
3136 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc(),
3137 UnalignedQualLoc: D.getDeclSpec().getUnalignedSpecLoc());
3138}
3139
3140static std::pair<QualType, TypeSourceInfo *>
3141InventTemplateParameter(TypeProcessingState &state, QualType T,
3142 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3143 InventedTemplateParameterInfo &Info) {
3144 Sema &S = state.getSema();
3145 Declarator &D = state.getDeclarator();
3146
3147 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3148 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3149 const bool IsParameterPack = D.hasEllipsis();
3150
3151 // If auto is mentioned in a lambda parameter or abbreviated function
3152 // template context, convert it to a template parameter type.
3153
3154 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3155 // template parameter type. Template parameters are temporarily added
3156 // to the TU until the associated TemplateDecl is created.
3157 TemplateTypeParmDecl *InventedTemplateParam = TemplateTypeParmDecl::Create(
3158 C: S.Context, DC: S.Context.getTranslationUnitDecl(),
3159 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3160 /*NameLoc=*/D.getIdentifierLoc(), D: TemplateParameterDepth,
3161 P: AutoParameterPosition,
3162 Id: S.InventAbbreviatedTemplateParameterTypeName(ParamName: D.getIdentifier(),
3163 Index: AutoParameterPosition),
3164 Typename: false, ParameterPack: IsParameterPack,
3165 /*HasTypeConstraint=*/Auto->isConstrained());
3166 InventedTemplateParam->setImplicit();
3167 Info.TemplateParams.push_back(Elt: InventedTemplateParam);
3168
3169 // Attach type constraints to the new parameter.
3170 if (Auto->isConstrained()) {
3171 if (TrailingTSI) {
3172 // The 'auto' appears in a trailing return type we've already built;
3173 // extract its type constraints to attach to the template parameter.
3174 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3175 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3176 bool Invalid = false;
3177 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3178 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3179 S.DiagnoseUnexpandedParameterPack(Arg: AutoLoc.getArgLoc(i: Idx),
3180 UPPC: Sema::UPPC_TypeConstraint))
3181 Invalid = true;
3182 TAL.addArgument(Loc: AutoLoc.getArgLoc(i: Idx));
3183 }
3184
3185 if (!Invalid) {
3186 S.AttachTypeConstraint(
3187 NS: AutoLoc.getNestedNameSpecifierLoc(), NameInfo: AutoLoc.getConceptNameInfo(),
3188 NamedConcept: AutoLoc.getNamedConcept(),
3189 /*FoundDecl=*/AutoLoc.getFoundDecl(),
3190 TemplateArgs: AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3191 ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc());
3192 }
3193 } else {
3194 // The 'auto' appears in the decl-specifiers; we've not finished forming
3195 // TypeSourceInfo for it yet.
3196 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3197 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
3198 TemplateId->RAngleLoc);
3199 bool Invalid = false;
3200 if (TemplateId->LAngleLoc.isValid()) {
3201 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3202 TemplateId->NumArgs);
3203 S.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
3204
3205 if (D.getEllipsisLoc().isInvalid()) {
3206 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3207 if (S.DiagnoseUnexpandedParameterPack(Arg,
3208 UPPC: Sema::UPPC_TypeConstraint)) {
3209 Invalid = true;
3210 break;
3211 }
3212 }
3213 }
3214 }
3215 if (!Invalid) {
3216 TemplateName TN = TemplateId->Template.get();
3217 UsingShadowDecl *USD = TN.getAsUsingShadowDecl();
3218 TemplateDecl *CD = TN.getAsTemplateDecl();
3219 S.AttachTypeConstraint(
3220 NS: D.getDeclSpec().getTypeSpecScope().getWithLocInContext(Context&: S.Context),
3221 NameInfo: DeclarationNameInfo(DeclarationName(TemplateId->Name),
3222 TemplateId->TemplateNameLoc),
3223 NamedConcept: TN,
3224 /*FoundDecl=*/
3225 USD ? cast<NamedDecl>(Val: USD) : cast_if_present<NamedDecl>(Val: CD),
3226 TemplateArgs: TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3227 ConstrainedParameter: InventedTemplateParam, EllipsisLoc: D.getEllipsisLoc());
3228 }
3229 }
3230 }
3231
3232 // Replace the 'auto' in the function parameter with this invented
3233 // template type parameter.
3234 // FIXME: Retain some type sugar to indicate that this was written
3235 // as 'auto'?
3236 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3237 QualType NewT = state.ReplaceAutoType(TypeWithAuto: T, Replacement);
3238 TypeSourceInfo *NewTSI =
3239 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TypeWithAuto: TrailingTSI, Replacement)
3240 : nullptr;
3241 return {NewT, NewTSI};
3242}
3243
3244static TypeSourceInfo *
3245GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3246 QualType T, TypeSourceInfo *ReturnTypeInfo);
3247
3248static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3249 TypeSourceInfo *&ReturnTypeInfo) {
3250 Sema &SemaRef = state.getSema();
3251 Declarator &D = state.getDeclarator();
3252 QualType T;
3253 ReturnTypeInfo = nullptr;
3254
3255 // The TagDecl owned by the DeclSpec.
3256 TagDecl *OwnedTagDecl = nullptr;
3257
3258 switch (D.getName().getKind()) {
3259 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3260 case UnqualifiedIdKind::IK_OperatorFunctionId:
3261 case UnqualifiedIdKind::IK_Identifier:
3262 case UnqualifiedIdKind::IK_LiteralOperatorId:
3263 case UnqualifiedIdKind::IK_TemplateId:
3264 T = ConvertDeclSpecToType(state);
3265
3266 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3267 OwnedTagDecl = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
3268 // Owned declaration is embedded in declarator.
3269 OwnedTagDecl->setEmbeddedInDeclarator(true);
3270 }
3271 break;
3272
3273 case UnqualifiedIdKind::IK_ConstructorName:
3274 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3275 case UnqualifiedIdKind::IK_DestructorName:
3276 // Constructors and destructors don't have return types. Use
3277 // "void" instead.
3278 T = SemaRef.Context.VoidTy;
3279 processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec,
3280 attrs: D.getMutableDeclSpec().getAttributes());
3281 break;
3282
3283 case UnqualifiedIdKind::IK_DeductionGuideName:
3284 // Deduction guides have a trailing return type and no type in their
3285 // decl-specifier sequence. Use a placeholder return type for now.
3286 T = SemaRef.Context.DependentTy;
3287 break;
3288
3289 case UnqualifiedIdKind::IK_ConversionFunctionId:
3290 // The result type of a conversion function is the type that it
3291 // converts to.
3292 T = SemaRef.GetTypeFromParser(Ty: D.getName().ConversionFunctionId,
3293 TInfo: &ReturnTypeInfo);
3294 break;
3295 }
3296
3297 // Note: We don't need to distribute declaration attributes (i.e.
3298 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3299 // and those don't get distributed.
3300 distributeTypeAttrsFromDeclarator(
3301 state, declSpecType&: T, CFT: SemaRef.CUDA().IdentifyTarget(Attrs: D.getAttributes()));
3302
3303 // Find the deduced type in this type. Look in the trailing return type if we
3304 // have one, otherwise in the DeclSpec type.
3305 // FIXME: The standard wording doesn't currently describe this.
3306 DeducedType *Deduced = T->getContainedDeducedType();
3307 bool DeducedIsTrailingReturnType = false;
3308 if (Deduced && isa<AutoType>(Val: Deduced) && D.hasTrailingReturnType()) {
3309 QualType T = SemaRef.GetTypeFromParser(Ty: D.getTrailingReturnType());
3310 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3311 DeducedIsTrailingReturnType = true;
3312 }
3313
3314 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3315 if (Deduced) {
3316 AutoType *Auto = dyn_cast<AutoType>(Val: Deduced);
3317 int Error = -1;
3318
3319 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3320 // class template argument deduction)?
3321 bool IsCXXAutoType =
3322 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3323 bool IsDeducedReturnType = false;
3324
3325 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3326 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3327 AutoRange = D.getName().getSourceRange();
3328
3329 switch (D.getContext()) {
3330 case DeclaratorContext::LambdaExpr:
3331 // Declared return type of a lambda-declarator is implicit and is always
3332 // 'auto'.
3333 break;
3334 case DeclaratorContext::ObjCParameter:
3335 case DeclaratorContext::ObjCResult:
3336 Error = 0;
3337 break;
3338 case DeclaratorContext::RequiresExpr:
3339 Error = 22;
3340 break;
3341 case DeclaratorContext::Prototype:
3342 case DeclaratorContext::LambdaExprParameter: {
3343 InventedTemplateParameterInfo *Info = nullptr;
3344 if (D.getContext() == DeclaratorContext::Prototype) {
3345 // With concepts we allow 'auto' in function parameters.
3346 if (!SemaRef.getLangOpts().CPlusPlus || !Auto ||
3347 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3348 Error = 0;
3349 break;
3350 }
3351
3352 if (!SemaRef.getLangOpts().CPlusPlus20)
3353 SemaRef.DiagCompat(Loc: AutoRange.getBegin(), CompatDiagId: diag_compat::auto_param);
3354
3355 if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3356 Error = 21;
3357 break;
3358 }
3359
3360 Info = &SemaRef.InventedParameterInfos.back();
3361 } else {
3362 // In C++14, generic lambdas allow 'auto' in their parameters.
3363 if (!SemaRef.getLangOpts().CPlusPlus14 && Auto &&
3364 Auto->getKeyword() == AutoTypeKeyword::Auto) {
3365 Error = 25; // auto not allowed in lambda parameter (before C++14)
3366 break;
3367 } else if (!Auto || Auto->getKeyword() != AutoTypeKeyword::Auto) {
3368 Error = 16; // __auto_type or decltype(auto) not allowed in lambda
3369 // parameter
3370 break;
3371 }
3372 Info = SemaRef.getCurLambda();
3373 assert(Info && "No LambdaScopeInfo on the stack!");
3374 }
3375
3376 // We'll deal with inventing template parameters for 'auto' in trailing
3377 // return types when we pick up the trailing return type when processing
3378 // the function chunk.
3379 if (!DeducedIsTrailingReturnType)
3380 T = InventTemplateParameter(state, T, TrailingTSI: nullptr, Auto, Info&: *Info).first;
3381 break;
3382 }
3383 case DeclaratorContext::Member: {
3384 if (D.isStaticMember() || D.isFunctionDeclarator())
3385 break;
3386 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3387 if (isa<ObjCContainerDecl>(Val: SemaRef.CurContext)) {
3388 Error = 6; // Interface member.
3389 } else {
3390 switch (cast<TagDecl>(Val: SemaRef.CurContext)->getTagKind()) {
3391 case TagTypeKind::Enum:
3392 llvm_unreachable("unhandled tag kind");
3393 case TagTypeKind::Struct:
3394 Error = Cxx ? 1 : 2; /* Struct member */
3395 break;
3396 case TagTypeKind::Union:
3397 Error = Cxx ? 3 : 4; /* Union member */
3398 break;
3399 case TagTypeKind::Class:
3400 Error = 5; /* Class member */
3401 break;
3402 case TagTypeKind::Interface:
3403 Error = 6; /* Interface member */
3404 break;
3405 }
3406 }
3407 if (D.getDeclSpec().isFriendSpecified())
3408 Error = 20; // Friend type
3409 break;
3410 }
3411 case DeclaratorContext::CXXCatch:
3412 case DeclaratorContext::ObjCCatch:
3413 Error = 7; // Exception declaration
3414 break;
3415 case DeclaratorContext::TemplateParam:
3416 if (isa<DeducedTemplateSpecializationType>(Val: Deduced) &&
3417 !SemaRef.getLangOpts().CPlusPlus20)
3418 Error = 19; // Template parameter (until C++20)
3419 else if (!SemaRef.getLangOpts().CPlusPlus17)
3420 Error = 8; // Template parameter (until C++17)
3421 break;
3422 case DeclaratorContext::BlockLiteral:
3423 Error = 9; // Block literal
3424 break;
3425 case DeclaratorContext::TemplateArg:
3426 // Within a template argument list, a deduced template specialization
3427 // type will be reinterpreted as a template template argument.
3428 if (isa<DeducedTemplateSpecializationType>(Val: Deduced) &&
3429 !D.getNumTypeObjects() &&
3430 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3431 break;
3432 [[fallthrough]];
3433 case DeclaratorContext::TemplateTypeArg:
3434 Error = 10; // Template type argument
3435 break;
3436 case DeclaratorContext::AliasDecl:
3437 case DeclaratorContext::AliasTemplate:
3438 Error = 12; // Type alias
3439 break;
3440 case DeclaratorContext::TrailingReturn:
3441 case DeclaratorContext::TrailingReturnVar:
3442 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3443 Error = 13; // Function return type
3444 IsDeducedReturnType = true;
3445 break;
3446 case DeclaratorContext::ConversionId:
3447 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3448 Error = 14; // conversion-type-id
3449 IsDeducedReturnType = true;
3450 break;
3451 case DeclaratorContext::FunctionalCast:
3452 if (isa<DeducedTemplateSpecializationType>(Val: Deduced))
3453 break;
3454 if (IsCXXAutoType && !Auto->isDecltypeAuto())
3455 break; // auto(x)
3456 [[fallthrough]];
3457 case DeclaratorContext::TypeName:
3458 case DeclaratorContext::Association:
3459 Error = 15; // Generic
3460 break;
3461 case DeclaratorContext::File:
3462 case DeclaratorContext::Block:
3463 case DeclaratorContext::ForInit:
3464 case DeclaratorContext::SelectionInit:
3465 case DeclaratorContext::Condition:
3466 // FIXME: P0091R3 (erroneously) does not permit class template argument
3467 // deduction in conditions, for-init-statements, and other declarations
3468 // that are not simple-declarations.
3469 break;
3470 case DeclaratorContext::CXXNew:
3471 // FIXME: P0091R3 does not permit class template argument deduction here,
3472 // but we follow GCC and allow it anyway.
3473 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Val: Deduced))
3474 Error = 17; // 'new' type
3475 break;
3476 case DeclaratorContext::KNRTypeList:
3477 Error = 18; // K&R function parameter
3478 break;
3479 }
3480
3481 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3482 Error = 11;
3483
3484 // In Objective-C it is an error to use 'auto' on a function declarator
3485 // (and everywhere for '__auto_type').
3486 if (D.isFunctionDeclarator() &&
3487 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3488 Error = 13;
3489
3490 if (Error != -1) {
3491 unsigned Kind;
3492 if (Auto) {
3493 switch (Auto->getKeyword()) {
3494 case AutoTypeKeyword::Auto: Kind = 0; break;
3495 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3496 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3497 }
3498 } else {
3499 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3500 "unknown auto type");
3501 Kind = 3;
3502 }
3503
3504 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Val: Deduced);
3505 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3506
3507 SemaRef.Diag(Loc: AutoRange.getBegin(), DiagID: diag::err_auto_not_allowed)
3508 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(Name: TN)
3509 << QualType(Deduced, 0) << AutoRange;
3510 if (auto *TD = TN.getAsTemplateDecl())
3511 SemaRef.NoteTemplateLocation(Decl: *TD);
3512
3513 T = SemaRef.Context.IntTy;
3514 D.setInvalidType(true);
3515 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3516 // If there was a trailing return type, we already got
3517 // warn_cxx98_compat_trailing_return_type in the parser.
3518 // If there was a decltype(auto), we already got
3519 // warn_cxx11_compat_decltype_auto_type_specifier.
3520 unsigned DiagId = 0;
3521 if (D.getContext() == DeclaratorContext::LambdaExprParameter)
3522 DiagId = diag::warn_cxx11_compat_generic_lambda;
3523 else if (IsDeducedReturnType)
3524 DiagId = diag::warn_cxx11_compat_deduced_return_type;
3525 else if (Auto->getKeyword() == AutoTypeKeyword::Auto)
3526 DiagId = diag::warn_cxx98_compat_auto_type_specifier;
3527
3528 if (DiagId)
3529 SemaRef.Diag(Loc: AutoRange.getBegin(), DiagID: DiagId) << AutoRange;
3530 }
3531 }
3532
3533 if (SemaRef.getLangOpts().CPlusPlus &&
3534 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3535 // Check the contexts where C++ forbids the declaration of a new class
3536 // or enumeration in a type-specifier-seq.
3537 unsigned DiagID = 0;
3538 switch (D.getContext()) {
3539 case DeclaratorContext::TrailingReturn:
3540 case DeclaratorContext::TrailingReturnVar:
3541 // Class and enumeration definitions are syntactically not allowed in
3542 // trailing return types.
3543 llvm_unreachable("parser should not have allowed this");
3544 break;
3545 case DeclaratorContext::File:
3546 case DeclaratorContext::Member:
3547 case DeclaratorContext::Block:
3548 case DeclaratorContext::ForInit:
3549 case DeclaratorContext::SelectionInit:
3550 case DeclaratorContext::BlockLiteral:
3551 case DeclaratorContext::LambdaExpr:
3552 // C++11 [dcl.type]p3:
3553 // A type-specifier-seq shall not define a class or enumeration unless
3554 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3555 // the declaration of a template-declaration.
3556 case DeclaratorContext::AliasDecl:
3557 break;
3558 case DeclaratorContext::AliasTemplate:
3559 DiagID = diag::err_type_defined_in_alias_template;
3560 break;
3561 case DeclaratorContext::TypeName:
3562 case DeclaratorContext::FunctionalCast:
3563 case DeclaratorContext::ConversionId:
3564 case DeclaratorContext::TemplateParam:
3565 case DeclaratorContext::CXXNew:
3566 case DeclaratorContext::CXXCatch:
3567 case DeclaratorContext::ObjCCatch:
3568 case DeclaratorContext::TemplateArg:
3569 case DeclaratorContext::TemplateTypeArg:
3570 case DeclaratorContext::Association:
3571 DiagID = diag::err_type_defined_in_type_specifier;
3572 break;
3573 case DeclaratorContext::Prototype:
3574 case DeclaratorContext::LambdaExprParameter:
3575 case DeclaratorContext::ObjCParameter:
3576 case DeclaratorContext::ObjCResult:
3577 case DeclaratorContext::KNRTypeList:
3578 case DeclaratorContext::RequiresExpr:
3579 // C++ [dcl.fct]p6:
3580 // Types shall not be defined in return or parameter types.
3581 DiagID = diag::err_type_defined_in_param_type;
3582 break;
3583 case DeclaratorContext::Condition:
3584 // C++ 6.4p2:
3585 // The type-specifier-seq shall not contain typedef and shall not declare
3586 // a new class or enumeration.
3587 DiagID = diag::err_type_defined_in_condition;
3588 break;
3589 }
3590
3591 if (DiagID != 0) {
3592 SemaRef.Diag(Loc: OwnedTagDecl->getLocation(), DiagID)
3593 << SemaRef.Context.getCanonicalTagType(TD: OwnedTagDecl);
3594 D.setInvalidType(true);
3595 }
3596 }
3597
3598 assert(!T.isNull() && "This function should not return a null type");
3599 return T;
3600}
3601
3602/// Produce an appropriate diagnostic for an ambiguity between a function
3603/// declarator and a C++ direct-initializer.
3604static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3605 DeclaratorChunk &DeclType, QualType RT) {
3606 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3607 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3608
3609 // If the return type is void there is no ambiguity.
3610 if (RT->isVoidType())
3611 return;
3612
3613 // An initializer for a non-class type can have at most one argument.
3614 if (!RT->isRecordType() && FTI.NumParams > 1)
3615 return;
3616
3617 // An initializer for a reference must have exactly one argument.
3618 if (RT->isReferenceType() && FTI.NumParams != 1)
3619 return;
3620
3621 // Only warn if this declarator is declaring a function at block scope, and
3622 // doesn't have a storage class (such as 'extern') specified.
3623 if (!D.isFunctionDeclarator() ||
3624 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3625 !S.CurContext->isFunctionOrMethod() ||
3626 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3627 return;
3628
3629 // Inside a condition, a direct initializer is not permitted. We allow one to
3630 // be parsed in order to give better diagnostics in condition parsing.
3631 if (D.getContext() == DeclaratorContext::Condition)
3632 return;
3633
3634 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3635
3636 S.Diag(Loc: DeclType.Loc,
3637 DiagID: FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3638 : diag::warn_empty_parens_are_function_decl)
3639 << ParenRange;
3640
3641 // If the declaration looks like:
3642 // T var1,
3643 // f();
3644 // and name lookup finds a function named 'f', then the ',' was
3645 // probably intended to be a ';'.
3646 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3647 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3648 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3649 if (Comma.getFileID() != Name.getFileID() ||
3650 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3651 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3652 Sema::LookupOrdinaryName);
3653 if (S.LookupName(R&: Result, S: S.getCurScope()))
3654 S.Diag(Loc: D.getCommaLoc(), DiagID: diag::note_empty_parens_function_call)
3655 << FixItHint::CreateReplacement(RemoveRange: D.getCommaLoc(), Code: ";")
3656 << D.getIdentifier();
3657 Result.suppressDiagnostics();
3658 }
3659 }
3660
3661 if (FTI.NumParams > 0) {
3662 // For a declaration with parameters, eg. "T var(T());", suggest adding
3663 // parens around the first parameter to turn the declaration into a
3664 // variable declaration.
3665 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3666 SourceLocation B = Range.getBegin();
3667 SourceLocation E = S.getLocForEndOfToken(Loc: Range.getEnd());
3668 // FIXME: Maybe we should suggest adding braces instead of parens
3669 // in C++11 for classes that don't have an initializer_list constructor.
3670 S.Diag(Loc: B, DiagID: diag::note_additional_parens_for_variable_declaration)
3671 << FixItHint::CreateInsertion(InsertionLoc: B, Code: "(")
3672 << FixItHint::CreateInsertion(InsertionLoc: E, Code: ")");
3673 } else {
3674 // For a declaration without parameters, eg. "T var();", suggest replacing
3675 // the parens with an initializer to turn the declaration into a variable
3676 // declaration.
3677 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3678
3679 // Empty parens mean value-initialization, and no parens mean
3680 // default initialization. These are equivalent if the default
3681 // constructor is user-provided or if zero-initialization is a
3682 // no-op.
3683 if (RD && RD->hasDefinition() &&
3684 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3685 S.Diag(Loc: DeclType.Loc, DiagID: diag::note_empty_parens_default_ctor)
3686 << FixItHint::CreateRemoval(RemoveRange: ParenRange);
3687 else {
3688 std::string Init =
3689 S.getFixItZeroInitializerForType(T: RT, Loc: ParenRange.getBegin());
3690 if (Init.empty() && S.LangOpts.CPlusPlus11)
3691 Init = "{}";
3692 if (!Init.empty())
3693 S.Diag(Loc: DeclType.Loc, DiagID: diag::note_empty_parens_zero_initialize)
3694 << FixItHint::CreateReplacement(RemoveRange: ParenRange, Code: Init);
3695 }
3696 }
3697}
3698
3699/// Produce an appropriate diagnostic for a declarator with top-level
3700/// parentheses.
3701static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3702 DeclaratorChunk &Paren = D.getTypeObject(i: D.getNumTypeObjects() - 1);
3703 assert(Paren.Kind == DeclaratorChunk::Paren &&
3704 "do not have redundant top-level parentheses");
3705
3706 // This is a syntactic check; we're not interested in cases that arise
3707 // during template instantiation.
3708 if (S.inTemplateInstantiation())
3709 return;
3710
3711 // Check whether this could be intended to be a construction of a temporary
3712 // object in C++ via a function-style cast.
3713 bool CouldBeTemporaryObject =
3714 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3715 !D.isInvalidType() && D.getIdentifier() &&
3716 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3717 (T->isRecordType() || T->isDependentType()) &&
3718 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3719
3720 bool StartsWithDeclaratorId = true;
3721 for (auto &C : D.type_objects()) {
3722 switch (C.Kind) {
3723 case DeclaratorChunk::Paren:
3724 if (&C == &Paren)
3725 continue;
3726 [[fallthrough]];
3727 case DeclaratorChunk::Pointer:
3728 StartsWithDeclaratorId = false;
3729 continue;
3730
3731 case DeclaratorChunk::Array:
3732 if (!C.Arr.NumElts)
3733 CouldBeTemporaryObject = false;
3734 continue;
3735
3736 case DeclaratorChunk::Reference:
3737 // FIXME: Suppress the warning here if there is no initializer; we're
3738 // going to give an error anyway.
3739 // We assume that something like 'T (&x) = y;' is highly likely to not
3740 // be intended to be a temporary object.
3741 CouldBeTemporaryObject = false;
3742 StartsWithDeclaratorId = false;
3743 continue;
3744
3745 case DeclaratorChunk::Function:
3746 // In a new-type-id, function chunks require parentheses.
3747 if (D.getContext() == DeclaratorContext::CXXNew)
3748 return;
3749 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3750 // redundant-parens warning, but we don't know whether the function
3751 // chunk was syntactically valid as an expression here.
3752 CouldBeTemporaryObject = false;
3753 continue;
3754
3755 case DeclaratorChunk::BlockPointer:
3756 case DeclaratorChunk::MemberPointer:
3757 case DeclaratorChunk::Pipe:
3758 // These cannot appear in expressions.
3759 CouldBeTemporaryObject = false;
3760 StartsWithDeclaratorId = false;
3761 continue;
3762 }
3763 }
3764
3765 // FIXME: If there is an initializer, assume that this is not intended to be
3766 // a construction of a temporary object.
3767
3768 // Check whether the name has already been declared; if not, this is not a
3769 // function-style cast.
3770 if (CouldBeTemporaryObject) {
3771 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3772 Sema::LookupOrdinaryName);
3773 if (!S.LookupName(R&: Result, S: S.getCurScope()))
3774 CouldBeTemporaryObject = false;
3775 Result.suppressDiagnostics();
3776 }
3777
3778 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3779
3780 if (!CouldBeTemporaryObject) {
3781 // If we have A (::B), the parentheses affect the meaning of the program.
3782 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3783 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3784 // formally unambiguous.
3785 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3786 NestedNameSpecifier NNS = D.getCXXScopeSpec().getScopeRep();
3787 for (;;) {
3788 switch (NNS.getKind()) {
3789 case NestedNameSpecifier::Kind::Global:
3790 return;
3791 case NestedNameSpecifier::Kind::Type:
3792 NNS = NNS.getAsType()->getPrefix();
3793 continue;
3794 case NestedNameSpecifier::Kind::Namespace:
3795 NNS = NNS.getAsNamespaceAndPrefix().Prefix;
3796 continue;
3797 default:
3798 goto out;
3799 }
3800 }
3801 out:;
3802 }
3803
3804 S.Diag(Loc: Paren.Loc, DiagID: diag::warn_redundant_parens_around_declarator)
3805 << ParenRange << FixItHint::CreateRemoval(RemoveRange: Paren.Loc)
3806 << FixItHint::CreateRemoval(RemoveRange: Paren.EndLoc);
3807 return;
3808 }
3809
3810 S.Diag(Loc: Paren.Loc, DiagID: diag::warn_parens_disambiguated_as_variable_declaration)
3811 << ParenRange << D.getIdentifier();
3812 auto *RD = T->getAsCXXRecordDecl();
3813 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3814 S.Diag(Loc: Paren.Loc, DiagID: diag::note_raii_guard_add_name)
3815 << FixItHint::CreateInsertion(InsertionLoc: Paren.Loc, Code: " varname") << T
3816 << D.getIdentifier();
3817 // FIXME: A cast to void is probably a better suggestion in cases where it's
3818 // valid (when there is no initializer and we're not in a condition).
3819 S.Diag(Loc: D.getBeginLoc(), DiagID: diag::note_function_style_cast_add_parentheses)
3820 << FixItHint::CreateInsertion(InsertionLoc: D.getBeginLoc(), Code: "(")
3821 << FixItHint::CreateInsertion(InsertionLoc: S.getLocForEndOfToken(Loc: D.getEndLoc()), Code: ")");
3822 S.Diag(Loc: Paren.Loc, DiagID: diag::note_remove_parens_for_variable_declaration)
3823 << FixItHint::CreateRemoval(RemoveRange: Paren.Loc)
3824 << FixItHint::CreateRemoval(RemoveRange: Paren.EndLoc);
3825}
3826
3827/// Helper for figuring out the default CC for a function declarator type. If
3828/// this is the outermost chunk, then we can determine the CC from the
3829/// declarator context. If not, then this could be either a member function
3830/// type or normal function type.
3831static CallingConv getCCForDeclaratorChunk(
3832 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3833 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3834 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3835
3836 // Check for an explicit CC attribute.
3837 for (const ParsedAttr &AL : AttrList) {
3838 switch (AL.getKind()) {
3839 CALLING_CONV_ATTRS_CASELIST : {
3840 // Ignore attributes that don't validate or can't apply to the
3841 // function type. We'll diagnose the failure to apply them in
3842 // handleFunctionTypeAttr.
3843 CallingConv CC;
3844 if (!S.CheckCallingConvAttr(attr: AL, CC, /*FunctionDecl=*/FD: nullptr,
3845 CFT: S.CUDA().IdentifyTarget(Attrs: D.getAttributes())) &&
3846 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3847 return CC;
3848 }
3849 break;
3850 }
3851
3852 default:
3853 break;
3854 }
3855 }
3856
3857 bool IsCXXInstanceMethod = false;
3858
3859 if (S.getLangOpts().CPlusPlus) {
3860 // Look inwards through parentheses to see if this chunk will form a
3861 // member pointer type or if we're the declarator. Any type attributes
3862 // between here and there will override the CC we choose here.
3863 unsigned I = ChunkIndex;
3864 bool FoundNonParen = false;
3865 while (I && !FoundNonParen) {
3866 --I;
3867 if (D.getTypeObject(i: I).Kind != DeclaratorChunk::Paren)
3868 FoundNonParen = true;
3869 }
3870
3871 if (FoundNonParen) {
3872 // If we're not the declarator, we're a regular function type unless we're
3873 // in a member pointer.
3874 IsCXXInstanceMethod =
3875 D.getTypeObject(i: I).Kind == DeclaratorChunk::MemberPointer;
3876 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
3877 // This can only be a call operator for a lambda, which is an instance
3878 // method, unless explicitly specified as 'static'.
3879 IsCXXInstanceMethod =
3880 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
3881 } else {
3882 // We're the innermost decl chunk, so must be a function declarator.
3883 assert(D.isFunctionDeclarator());
3884
3885 // If we're inside a record, we're declaring a method, but it could be
3886 // explicitly or implicitly static.
3887 IsCXXInstanceMethod =
3888 D.isFirstDeclarationOfMember() &&
3889 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3890 !D.isStaticMember();
3891 }
3892 }
3893
3894 CallingConv CC = S.Context.getDefaultCallingConvention(IsVariadic: FTI.isVariadic,
3895 IsCXXMethod: IsCXXInstanceMethod);
3896
3897 if (S.getLangOpts().CUDA) {
3898 // If we're compiling CUDA/HIP code and targeting HIPSPV we need to make
3899 // sure the kernels will be marked with the right calling convention so that
3900 // they will be visible by the APIs that ingest SPIR-V. We do not do this
3901 // when targeting AMDGCNSPIRV, as it does not rely on OpenCL.
3902 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
3903 if (Triple.isSPIRV() && Triple.getVendor() != llvm::Triple::AMD) {
3904 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
3905 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
3906 CC = CC_DeviceKernel;
3907 break;
3908 }
3909 }
3910 }
3911 }
3912
3913 for (const ParsedAttr &AL : llvm::concat<ParsedAttr>(
3914 Ranges: D.getDeclSpec().getAttributes(), Ranges&: D.getAttributes(),
3915 Ranges: D.getDeclarationAttributes())) {
3916 if (AL.getKind() == ParsedAttr::AT_DeviceKernel) {
3917 CC = CC_DeviceKernel;
3918 break;
3919 }
3920 }
3921 return CC;
3922}
3923
3924namespace {
3925 /// A simple notion of pointer kinds, which matches up with the various
3926 /// pointer declarators.
3927 enum class SimplePointerKind {
3928 Pointer,
3929 BlockPointer,
3930 MemberPointer,
3931 Array,
3932 };
3933} // end anonymous namespace
3934
3935IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3936 switch (nullability) {
3937 case NullabilityKind::NonNull:
3938 if (!Ident__Nonnull)
3939 Ident__Nonnull = PP.getIdentifierInfo(Name: "_Nonnull");
3940 return Ident__Nonnull;
3941
3942 case NullabilityKind::Nullable:
3943 if (!Ident__Nullable)
3944 Ident__Nullable = PP.getIdentifierInfo(Name: "_Nullable");
3945 return Ident__Nullable;
3946
3947 case NullabilityKind::NullableResult:
3948 if (!Ident__Nullable_result)
3949 Ident__Nullable_result = PP.getIdentifierInfo(Name: "_Nullable_result");
3950 return Ident__Nullable_result;
3951
3952 case NullabilityKind::Unspecified:
3953 if (!Ident__Null_unspecified)
3954 Ident__Null_unspecified = PP.getIdentifierInfo(Name: "_Null_unspecified");
3955 return Ident__Null_unspecified;
3956 }
3957 llvm_unreachable("Unknown nullability kind.");
3958}
3959
3960/// Check whether there is a nullability attribute of any kind in the given
3961/// attribute list.
3962static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
3963 for (const ParsedAttr &AL : attrs) {
3964 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
3965 AL.getKind() == ParsedAttr::AT_TypeNullable ||
3966 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
3967 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
3968 return true;
3969 }
3970
3971 return false;
3972}
3973
3974namespace {
3975 /// Describes the kind of a pointer a declarator describes.
3976 enum class PointerDeclaratorKind {
3977 // Not a pointer.
3978 NonPointer,
3979 // Single-level pointer.
3980 SingleLevelPointer,
3981 // Multi-level pointer (of any pointer kind).
3982 MultiLevelPointer,
3983 // CFFooRef*
3984 MaybePointerToCFRef,
3985 // CFErrorRef*
3986 CFErrorRefPointer,
3987 // NSError**
3988 NSErrorPointerPointer,
3989 };
3990
3991 /// Describes a declarator chunk wrapping a pointer that marks inference as
3992 /// unexpected.
3993 // These values must be kept in sync with diagnostics.
3994 enum class PointerWrappingDeclaratorKind {
3995 /// Pointer is top-level.
3996 None = -1,
3997 /// Pointer is an array element.
3998 Array = 0,
3999 /// Pointer is the referent type of a C++ reference.
4000 Reference = 1
4001 };
4002} // end anonymous namespace
4003
4004/// Classify the given declarator, whose type-specified is \c type, based on
4005/// what kind of pointer it refers to.
4006///
4007/// This is used to determine the default nullability.
4008static PointerDeclaratorKind
4009classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4010 PointerWrappingDeclaratorKind &wrappingKind) {
4011 unsigned numNormalPointers = 0;
4012
4013 // For any dependent type, we consider it a non-pointer.
4014 if (type->isDependentType())
4015 return PointerDeclaratorKind::NonPointer;
4016
4017 // Look through the declarator chunks to identify pointers.
4018 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4019 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4020 switch (chunk.Kind) {
4021 case DeclaratorChunk::Array:
4022 if (numNormalPointers == 0)
4023 wrappingKind = PointerWrappingDeclaratorKind::Array;
4024 break;
4025
4026 case DeclaratorChunk::Function:
4027 case DeclaratorChunk::Pipe:
4028 break;
4029
4030 case DeclaratorChunk::BlockPointer:
4031 case DeclaratorChunk::MemberPointer:
4032 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4033 : PointerDeclaratorKind::SingleLevelPointer;
4034
4035 case DeclaratorChunk::Paren:
4036 break;
4037
4038 case DeclaratorChunk::Reference:
4039 if (numNormalPointers == 0)
4040 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4041 break;
4042
4043 case DeclaratorChunk::Pointer:
4044 ++numNormalPointers;
4045 if (numNormalPointers > 2)
4046 return PointerDeclaratorKind::MultiLevelPointer;
4047 break;
4048 }
4049 }
4050
4051 // Then, dig into the type specifier itself.
4052 unsigned numTypeSpecifierPointers = 0;
4053 do {
4054 // Decompose normal pointers.
4055 if (auto ptrType = type->getAs<PointerType>()) {
4056 ++numNormalPointers;
4057
4058 if (numNormalPointers > 2)
4059 return PointerDeclaratorKind::MultiLevelPointer;
4060
4061 type = ptrType->getPointeeType();
4062 ++numTypeSpecifierPointers;
4063 continue;
4064 }
4065
4066 // Decompose block pointers.
4067 if (type->getAs<BlockPointerType>()) {
4068 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4069 : PointerDeclaratorKind::SingleLevelPointer;
4070 }
4071
4072 // Decompose member pointers.
4073 if (type->getAs<MemberPointerType>()) {
4074 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4075 : PointerDeclaratorKind::SingleLevelPointer;
4076 }
4077
4078 // Look at Objective-C object pointers.
4079 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4080 ++numNormalPointers;
4081 ++numTypeSpecifierPointers;
4082
4083 // If this is NSError**, report that.
4084 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4085 if (objcClassDecl->getIdentifier() == S.ObjC().getNSErrorIdent() &&
4086 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4087 return PointerDeclaratorKind::NSErrorPointerPointer;
4088 }
4089 }
4090
4091 break;
4092 }
4093
4094 // Look at Objective-C class types.
4095 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4096 if (objcClass->getInterface()->getIdentifier() ==
4097 S.ObjC().getNSErrorIdent()) {
4098 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4099 return PointerDeclaratorKind::NSErrorPointerPointer;
4100 }
4101
4102 break;
4103 }
4104
4105 // If at this point we haven't seen a pointer, we won't see one.
4106 if (numNormalPointers == 0)
4107 return PointerDeclaratorKind::NonPointer;
4108
4109 if (auto *recordDecl = type->getAsRecordDecl()) {
4110 // If this is CFErrorRef*, report it as such.
4111 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4112 S.ObjC().isCFError(D: recordDecl)) {
4113 return PointerDeclaratorKind::CFErrorRefPointer;
4114 }
4115 break;
4116 }
4117
4118 break;
4119 } while (true);
4120
4121 switch (numNormalPointers) {
4122 case 0:
4123 return PointerDeclaratorKind::NonPointer;
4124
4125 case 1:
4126 return PointerDeclaratorKind::SingleLevelPointer;
4127
4128 case 2:
4129 return PointerDeclaratorKind::MaybePointerToCFRef;
4130
4131 default:
4132 return PointerDeclaratorKind::MultiLevelPointer;
4133 }
4134}
4135
4136static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4137 SourceLocation loc) {
4138 // If we're anywhere in a function, method, or closure context, don't perform
4139 // completeness checks.
4140 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4141 if (ctx->isFunctionOrMethod())
4142 return FileID();
4143
4144 if (ctx->isFileContext())
4145 break;
4146 }
4147
4148 // We only care about the expansion location.
4149 loc = S.SourceMgr.getExpansionLoc(Loc: loc);
4150 FileID file = S.SourceMgr.getFileID(SpellingLoc: loc);
4151 if (file.isInvalid())
4152 return FileID();
4153
4154 // Retrieve file information.
4155 bool invalid = false;
4156 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(FID: file, Invalid: &invalid);
4157 if (invalid || !sloc.isFile())
4158 return FileID();
4159
4160 // We don't want to perform completeness checks on the main file or in
4161 // system headers.
4162 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4163 if (fileInfo.getIncludeLoc().isInvalid())
4164 return FileID();
4165 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4166 S.Diags.getSuppressSystemWarnings()) {
4167 return FileID();
4168 }
4169
4170 return file;
4171}
4172
4173/// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4174/// taking into account whitespace before and after.
4175template <typename DiagBuilderT>
4176static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4177 SourceLocation PointerLoc,
4178 NullabilityKind Nullability) {
4179 assert(PointerLoc.isValid());
4180 if (PointerLoc.isMacroID())
4181 return;
4182
4183 SourceLocation FixItLoc = S.getLocForEndOfToken(Loc: PointerLoc);
4184 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4185 return;
4186
4187 const char *NextChar = S.SourceMgr.getCharacterData(SL: FixItLoc);
4188 if (!NextChar)
4189 return;
4190
4191 SmallString<32> InsertionTextBuf{" "};
4192 InsertionTextBuf += getNullabilitySpelling(kind: Nullability);
4193 InsertionTextBuf += " ";
4194 StringRef InsertionText = InsertionTextBuf.str();
4195
4196 if (isWhitespace(c: *NextChar)) {
4197 InsertionText = InsertionText.drop_back();
4198 } else if (NextChar[-1] == '[') {
4199 if (NextChar[0] == ']')
4200 InsertionText = InsertionText.drop_back().drop_front();
4201 else
4202 InsertionText = InsertionText.drop_front();
4203 } else if (!isAsciiIdentifierContinue(c: NextChar[0], /*allow dollar*/ AllowDollar: true) &&
4204 !isAsciiIdentifierContinue(c: NextChar[-1], /*allow dollar*/ AllowDollar: true)) {
4205 InsertionText = InsertionText.drop_back().drop_front();
4206 }
4207
4208 Diag << FixItHint::CreateInsertion(InsertionLoc: FixItLoc, Code: InsertionText);
4209}
4210
4211static void emitNullabilityConsistencyWarning(Sema &S,
4212 SimplePointerKind PointerKind,
4213 SourceLocation PointerLoc,
4214 SourceLocation PointerEndLoc) {
4215 assert(PointerLoc.isValid());
4216
4217 if (PointerKind == SimplePointerKind::Array) {
4218 S.Diag(Loc: PointerLoc, DiagID: diag::warn_nullability_missing_array);
4219 } else {
4220 S.Diag(Loc: PointerLoc, DiagID: diag::warn_nullability_missing)
4221 << static_cast<unsigned>(PointerKind);
4222 }
4223
4224 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4225 if (FixItLoc.isMacroID())
4226 return;
4227
4228 auto addFixIt = [&](NullabilityKind Nullability) {
4229 auto Diag = S.Diag(Loc: FixItLoc, DiagID: diag::note_nullability_fix_it);
4230 Diag << static_cast<unsigned>(Nullability);
4231 Diag << static_cast<unsigned>(PointerKind);
4232 fixItNullability(S, Diag, PointerLoc: FixItLoc, Nullability);
4233 };
4234 addFixIt(NullabilityKind::Nullable);
4235 addFixIt(NullabilityKind::NonNull);
4236}
4237
4238/// Complains about missing nullability if the file containing \p pointerLoc
4239/// has other uses of nullability (either the keywords or the \c assume_nonnull
4240/// pragma).
4241///
4242/// If the file has \e not seen other uses of nullability, this particular
4243/// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4244static void
4245checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4246 SourceLocation pointerLoc,
4247 SourceLocation pointerEndLoc = SourceLocation()) {
4248 // Determine which file we're performing consistency checking for.
4249 FileID file = getNullabilityCompletenessCheckFileID(S, loc: pointerLoc);
4250 if (file.isInvalid())
4251 return;
4252
4253 // If we haven't seen any type nullability in this file, we won't warn now
4254 // about anything.
4255 FileNullability &fileNullability = S.NullabilityMap[file];
4256 if (!fileNullability.SawTypeNullability) {
4257 // If this is the first pointer declarator in the file, and the appropriate
4258 // warning is on, record it in case we need to diagnose it retroactively.
4259 diag::kind diagKind;
4260 if (pointerKind == SimplePointerKind::Array)
4261 diagKind = diag::warn_nullability_missing_array;
4262 else
4263 diagKind = diag::warn_nullability_missing;
4264
4265 if (fileNullability.PointerLoc.isInvalid() &&
4266 !S.Context.getDiagnostics().isIgnored(DiagID: diagKind, Loc: pointerLoc)) {
4267 fileNullability.PointerLoc = pointerLoc;
4268 fileNullability.PointerEndLoc = pointerEndLoc;
4269 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4270 }
4271
4272 return;
4273 }
4274
4275 // Complain about missing nullability.
4276 emitNullabilityConsistencyWarning(S, PointerKind: pointerKind, PointerLoc: pointerLoc, PointerEndLoc: pointerEndLoc);
4277}
4278
4279/// Marks that a nullability feature has been used in the file containing
4280/// \p loc.
4281///
4282/// If this file already had pointer types in it that were missing nullability,
4283/// the first such instance is retroactively diagnosed.
4284///
4285/// \sa checkNullabilityConsistency
4286static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4287 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4288 if (file.isInvalid())
4289 return;
4290
4291 FileNullability &fileNullability = S.NullabilityMap[file];
4292 if (fileNullability.SawTypeNullability)
4293 return;
4294 fileNullability.SawTypeNullability = true;
4295
4296 // If we haven't seen any type nullability before, now we have. Retroactively
4297 // diagnose the first unannotated pointer, if there was one.
4298 if (fileNullability.PointerLoc.isInvalid())
4299 return;
4300
4301 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4302 emitNullabilityConsistencyWarning(S, PointerKind: kind, PointerLoc: fileNullability.PointerLoc,
4303 PointerEndLoc: fileNullability.PointerEndLoc);
4304}
4305
4306/// Returns true if any of the declarator chunks before \p endIndex include a
4307/// level of indirection: array, pointer, reference, or pointer-to-member.
4308///
4309/// Because declarator chunks are stored in outer-to-inner order, testing
4310/// every chunk before \p endIndex is testing all chunks that embed the current
4311/// chunk as part of their type.
4312///
4313/// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4314/// end index, in which case all chunks are tested.
4315static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4316 unsigned i = endIndex;
4317 while (i != 0) {
4318 // Walk outwards along the declarator chunks.
4319 --i;
4320 const DeclaratorChunk &DC = D.getTypeObject(i);
4321 switch (DC.Kind) {
4322 case DeclaratorChunk::Paren:
4323 break;
4324 case DeclaratorChunk::Array:
4325 case DeclaratorChunk::Pointer:
4326 case DeclaratorChunk::Reference:
4327 case DeclaratorChunk::MemberPointer:
4328 return true;
4329 case DeclaratorChunk::Function:
4330 case DeclaratorChunk::BlockPointer:
4331 case DeclaratorChunk::Pipe:
4332 // These are invalid anyway, so just ignore.
4333 break;
4334 }
4335 }
4336 return false;
4337}
4338
4339static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4340 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4341 Chunk.Kind == DeclaratorChunk::Array);
4342}
4343
4344template<typename AttrT>
4345static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4346 AL.setUsedAsTypeAttr();
4347 return ::new (Ctx) AttrT(Ctx, AL);
4348}
4349
4350static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4351 NullabilityKind NK) {
4352 switch (NK) {
4353 case NullabilityKind::NonNull:
4354 return createSimpleAttr<TypeNonNullAttr>(Ctx, AL&: Attr);
4355
4356 case NullabilityKind::Nullable:
4357 return createSimpleAttr<TypeNullableAttr>(Ctx, AL&: Attr);
4358
4359 case NullabilityKind::NullableResult:
4360 return createSimpleAttr<TypeNullableResultAttr>(Ctx, AL&: Attr);
4361
4362 case NullabilityKind::Unspecified:
4363 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, AL&: Attr);
4364 }
4365 llvm_unreachable("unknown NullabilityKind");
4366}
4367
4368// Diagnose whether this is a case with the multiple addr spaces.
4369// Returns true if this is an invalid case.
4370// ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4371// by qualifiers for two or more different address spaces."
4372static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4373 LangAS ASNew,
4374 SourceLocation AttrLoc) {
4375 if (ASOld != LangAS::Default) {
4376 if (ASOld != ASNew) {
4377 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_multiple_qualifiers);
4378 return true;
4379 }
4380 // Emit a warning if they are identical; it's likely unintended.
4381 S.Diag(Loc: AttrLoc,
4382 DiagID: diag::warn_attribute_address_multiple_identical_qualifiers);
4383 }
4384 return false;
4385}
4386
4387// Whether this is a type broadly expected to have nullability attached.
4388// These types are affected by `#pragma assume_nonnull`, and missing nullability
4389// will be diagnosed with -Wnullability-completeness.
4390static bool shouldHaveNullability(QualType T) {
4391 return T->canHaveNullability(/*ResultIfUnknown=*/false) &&
4392 // For now, do not infer/require nullability on C++ smart pointers.
4393 // It's unclear whether the pragma's behavior is useful for C++.
4394 // e.g. treating type-aliases and template-type-parameters differently
4395 // from types of declarations can be surprising.
4396 !isa<RecordType, TemplateSpecializationType>(
4397 Val: T->getCanonicalTypeInternal());
4398}
4399
4400static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4401 QualType declSpecType,
4402 TypeSourceInfo *TInfo) {
4403 // The TypeSourceInfo that this function returns will not be a null type.
4404 // If there is an error, this function will fill in a dummy type as fallback.
4405 QualType T = declSpecType;
4406 Declarator &D = state.getDeclarator();
4407 Sema &S = state.getSema();
4408 ASTContext &Context = S.Context;
4409 const LangOptions &LangOpts = S.getLangOpts();
4410
4411 // The name we're declaring, if any.
4412 DeclarationName Name;
4413 if (D.getIdentifier())
4414 Name = D.getIdentifier();
4415
4416 // Does this declaration declare a typedef-name?
4417 bool IsTypedefName =
4418 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4419 D.getContext() == DeclaratorContext::AliasDecl ||
4420 D.getContext() == DeclaratorContext::AliasTemplate;
4421
4422 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4423 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4424 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4425 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4426
4427 // If T is 'decltype(auto)', the only declarators we can have are parens
4428 // and at most one function declarator if this is a function declaration.
4429 // If T is a deduced class template specialization type, only parentheses
4430 // are allowed.
4431 if (auto *DT = T->getAs<DeducedType>(); DT && !T->containsErrors()) {
4432 const AutoType *AT = T->getAs<AutoType>();
4433 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(Val: DT);
4434 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4435 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4436 unsigned Index = E - I - 1;
4437 DeclaratorChunk &DeclChunk = D.getTypeObject(i: Index);
4438 unsigned DiagId = IsClassTemplateDeduction
4439 ? diag::err_deduced_class_template_compound_type
4440 : diag::err_decltype_auto_compound_type;
4441 unsigned DiagKind = 0;
4442 switch (DeclChunk.Kind) {
4443 case DeclaratorChunk::Paren:
4444 continue;
4445 case DeclaratorChunk::Function: {
4446 if (IsClassTemplateDeduction) {
4447 DiagKind = 3;
4448 break;
4449 }
4450 unsigned FnIndex;
4451 if (D.isFunctionDeclarationContext() &&
4452 D.isFunctionDeclarator(idx&: FnIndex) && FnIndex == Index)
4453 continue;
4454 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4455 break;
4456 }
4457 case DeclaratorChunk::Pointer:
4458 case DeclaratorChunk::BlockPointer:
4459 case DeclaratorChunk::MemberPointer:
4460 DiagKind = 0;
4461 break;
4462 case DeclaratorChunk::Reference:
4463 DiagKind = 1;
4464 break;
4465 case DeclaratorChunk::Array:
4466 DiagKind = 2;
4467 break;
4468 case DeclaratorChunk::Pipe:
4469 break;
4470 }
4471
4472 S.Diag(Loc: DeclChunk.Loc, DiagID: DiagId) << DiagKind;
4473 D.setInvalidType(true);
4474 break;
4475 }
4476 }
4477 }
4478
4479 // Determine whether we should infer _Nonnull on pointer types.
4480 NullabilityKindOrNone inferNullability = std::nullopt;
4481 bool inferNullabilityCS = false;
4482 bool inferNullabilityInnerOnly = false;
4483 bool inferNullabilityInnerOnlyComplete = false;
4484
4485 // Are we in an assume-nonnull region?
4486 bool inAssumeNonNullRegion = false;
4487 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4488 if (assumeNonNullLoc.isValid()) {
4489 inAssumeNonNullRegion = true;
4490 recordNullabilitySeen(S, loc: assumeNonNullLoc);
4491 }
4492
4493 // Whether to complain about missing nullability specifiers or not.
4494 enum {
4495 /// Never complain.
4496 CAMN_No,
4497 /// Complain on the inner pointers (but not the outermost
4498 /// pointer).
4499 CAMN_InnerPointers,
4500 /// Complain about any pointers that don't have nullability
4501 /// specified or inferred.
4502 CAMN_Yes
4503 } complainAboutMissingNullability = CAMN_No;
4504 unsigned NumPointersRemaining = 0;
4505 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4506
4507 if (IsTypedefName) {
4508 // For typedefs, we do not infer any nullability (the default),
4509 // and we only complain about missing nullability specifiers on
4510 // inner pointers.
4511 complainAboutMissingNullability = CAMN_InnerPointers;
4512
4513 if (shouldHaveNullability(T) && !T->getNullability()) {
4514 // Note that we allow but don't require nullability on dependent types.
4515 ++NumPointersRemaining;
4516 }
4517
4518 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4519 DeclaratorChunk &chunk = D.getTypeObject(i);
4520 switch (chunk.Kind) {
4521 case DeclaratorChunk::Array:
4522 case DeclaratorChunk::Function:
4523 case DeclaratorChunk::Pipe:
4524 break;
4525
4526 case DeclaratorChunk::BlockPointer:
4527 case DeclaratorChunk::MemberPointer:
4528 ++NumPointersRemaining;
4529 break;
4530
4531 case DeclaratorChunk::Paren:
4532 case DeclaratorChunk::Reference:
4533 continue;
4534
4535 case DeclaratorChunk::Pointer:
4536 ++NumPointersRemaining;
4537 continue;
4538 }
4539 }
4540 } else {
4541 bool isFunctionOrMethod = false;
4542 switch (auto context = state.getDeclarator().getContext()) {
4543 case DeclaratorContext::ObjCParameter:
4544 case DeclaratorContext::ObjCResult:
4545 case DeclaratorContext::Prototype:
4546 case DeclaratorContext::TrailingReturn:
4547 case DeclaratorContext::TrailingReturnVar:
4548 isFunctionOrMethod = true;
4549 [[fallthrough]];
4550
4551 case DeclaratorContext::Member:
4552 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4553 complainAboutMissingNullability = CAMN_No;
4554 break;
4555 }
4556
4557 // Weak properties are inferred to be nullable.
4558 if (state.getDeclarator().isObjCWeakProperty()) {
4559 // Weak properties cannot be nonnull, and should not complain about
4560 // missing nullable attributes during completeness checks.
4561 complainAboutMissingNullability = CAMN_No;
4562 if (inAssumeNonNullRegion) {
4563 inferNullability = NullabilityKind::Nullable;
4564 }
4565 break;
4566 }
4567
4568 [[fallthrough]];
4569
4570 case DeclaratorContext::File:
4571 case DeclaratorContext::KNRTypeList: {
4572 complainAboutMissingNullability = CAMN_Yes;
4573
4574 // Nullability inference depends on the type and declarator.
4575 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4576 switch (classifyPointerDeclarator(S, type: T, declarator&: D, wrappingKind)) {
4577 case PointerDeclaratorKind::NonPointer:
4578 case PointerDeclaratorKind::MultiLevelPointer:
4579 // Cannot infer nullability.
4580 break;
4581
4582 case PointerDeclaratorKind::SingleLevelPointer:
4583 // Infer _Nonnull if we are in an assumes-nonnull region.
4584 if (inAssumeNonNullRegion) {
4585 complainAboutInferringWithinChunk = wrappingKind;
4586 inferNullability = NullabilityKind::NonNull;
4587 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4588 context == DeclaratorContext::ObjCResult);
4589 }
4590 break;
4591
4592 case PointerDeclaratorKind::CFErrorRefPointer:
4593 case PointerDeclaratorKind::NSErrorPointerPointer:
4594 // Within a function or method signature, infer _Nullable at both
4595 // levels.
4596 if (isFunctionOrMethod && inAssumeNonNullRegion)
4597 inferNullability = NullabilityKind::Nullable;
4598 break;
4599
4600 case PointerDeclaratorKind::MaybePointerToCFRef:
4601 if (isFunctionOrMethod) {
4602 // On pointer-to-pointer parameters marked cf_returns_retained or
4603 // cf_returns_not_retained, if the outer pointer is explicit then
4604 // infer the inner pointer as _Nullable.
4605 auto hasCFReturnsAttr =
4606 [](const ParsedAttributesView &AttrList) -> bool {
4607 return AttrList.hasAttribute(K: ParsedAttr::AT_CFReturnsRetained) ||
4608 AttrList.hasAttribute(K: ParsedAttr::AT_CFReturnsNotRetained);
4609 };
4610 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4611 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4612 hasCFReturnsAttr(D.getAttributes()) ||
4613 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4614 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4615 inferNullability = NullabilityKind::Nullable;
4616 inferNullabilityInnerOnly = true;
4617 }
4618 }
4619 }
4620 break;
4621 }
4622 break;
4623 }
4624
4625 case DeclaratorContext::ConversionId:
4626 complainAboutMissingNullability = CAMN_Yes;
4627 break;
4628
4629 case DeclaratorContext::AliasDecl:
4630 case DeclaratorContext::AliasTemplate:
4631 case DeclaratorContext::Block:
4632 case DeclaratorContext::BlockLiteral:
4633 case DeclaratorContext::Condition:
4634 case DeclaratorContext::CXXCatch:
4635 case DeclaratorContext::CXXNew:
4636 case DeclaratorContext::ForInit:
4637 case DeclaratorContext::SelectionInit:
4638 case DeclaratorContext::LambdaExpr:
4639 case DeclaratorContext::LambdaExprParameter:
4640 case DeclaratorContext::ObjCCatch:
4641 case DeclaratorContext::TemplateParam:
4642 case DeclaratorContext::TemplateArg:
4643 case DeclaratorContext::TemplateTypeArg:
4644 case DeclaratorContext::TypeName:
4645 case DeclaratorContext::FunctionalCast:
4646 case DeclaratorContext::RequiresExpr:
4647 case DeclaratorContext::Association:
4648 // Don't infer in these contexts.
4649 break;
4650 }
4651 }
4652
4653 // Local function that returns true if its argument looks like a va_list.
4654 auto isVaList = [&S](QualType T) -> bool {
4655 auto *typedefTy = T->getAs<TypedefType>();
4656 if (!typedefTy)
4657 return false;
4658 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4659 do {
4660 if (typedefTy->getDecl() == vaListTypedef)
4661 return true;
4662 if (auto *name = typedefTy->getDecl()->getIdentifier())
4663 if (name->isStr(Str: "va_list"))
4664 return true;
4665 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4666 } while (typedefTy);
4667 return false;
4668 };
4669
4670 // Local function that checks the nullability for a given pointer declarator.
4671 // Returns true if _Nonnull was inferred.
4672 auto inferPointerNullability =
4673 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4674 SourceLocation pointerEndLoc,
4675 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4676 // We've seen a pointer.
4677 if (NumPointersRemaining > 0)
4678 --NumPointersRemaining;
4679
4680 // If a nullability attribute is present, there's nothing to do.
4681 if (hasNullabilityAttr(attrs))
4682 return nullptr;
4683
4684 // If we're supposed to infer nullability, do so now.
4685 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4686 ParsedAttr::Form form =
4687 inferNullabilityCS
4688 ? ParsedAttr::Form::ContextSensitiveKeyword()
4689 : ParsedAttr::Form::Keyword(IsAlignas: false /*IsAlignAs*/,
4690 IsRegularKeywordAttribute: false /*IsRegularKeywordAttribute*/);
4691 ParsedAttr *nullabilityAttr = Pool.create(
4692 attrName: S.getNullabilityKeyword(nullability: *inferNullability), attrRange: SourceRange(pointerLoc),
4693 scope: AttributeScopeInfo(), args: nullptr, numArgs: 0, form);
4694
4695 attrs.addAtEnd(newAttr: nullabilityAttr);
4696
4697 if (inferNullabilityCS) {
4698 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4699 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4700 }
4701
4702 if (pointerLoc.isValid() &&
4703 complainAboutInferringWithinChunk !=
4704 PointerWrappingDeclaratorKind::None) {
4705 auto Diag =
4706 S.Diag(Loc: pointerLoc, DiagID: diag::warn_nullability_inferred_on_nested_type);
4707 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4708 fixItNullability(S, Diag, PointerLoc: pointerLoc, Nullability: NullabilityKind::NonNull);
4709 }
4710
4711 if (inferNullabilityInnerOnly)
4712 inferNullabilityInnerOnlyComplete = true;
4713 return nullabilityAttr;
4714 }
4715
4716 // If we're supposed to complain about missing nullability, do so
4717 // now if it's truly missing.
4718 switch (complainAboutMissingNullability) {
4719 case CAMN_No:
4720 break;
4721
4722 case CAMN_InnerPointers:
4723 if (NumPointersRemaining == 0)
4724 break;
4725 [[fallthrough]];
4726
4727 case CAMN_Yes:
4728 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4729 }
4730 return nullptr;
4731 };
4732
4733 // If the type itself could have nullability but does not, infer pointer
4734 // nullability and perform consistency checking.
4735 if (S.CodeSynthesisContexts.empty()) {
4736 if (shouldHaveNullability(T) && !T->getNullability()) {
4737 if (isVaList(T)) {
4738 // Record that we've seen a pointer, but do nothing else.
4739 if (NumPointersRemaining > 0)
4740 --NumPointersRemaining;
4741 } else {
4742 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4743 if (T->isBlockPointerType())
4744 pointerKind = SimplePointerKind::BlockPointer;
4745 else if (T->isMemberPointerType())
4746 pointerKind = SimplePointerKind::MemberPointer;
4747
4748 if (auto *attr = inferPointerNullability(
4749 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4750 D.getDeclSpec().getEndLoc(),
4751 D.getMutableDeclSpec().getAttributes(),
4752 D.getMutableDeclSpec().getAttributePool())) {
4753 T = state.getAttributedType(
4754 A: createNullabilityAttr(Ctx&: Context, Attr&: *attr, NK: *inferNullability), ModifiedType: T, EquivType: T);
4755 }
4756 }
4757 }
4758
4759 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
4760 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
4761 !hasOuterPointerLikeChunk(D, endIndex: D.getNumTypeObjects())) {
4762 checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array,
4763 pointerLoc: D.getDeclSpec().getTypeSpecTypeLoc());
4764 }
4765 }
4766
4767 bool ExpectNoDerefChunk =
4768 state.getCurrentAttributes().hasAttribute(K: ParsedAttr::AT_NoDeref);
4769
4770 // Walk the DeclTypeInfo, building the recursive type as we go.
4771 // DeclTypeInfos are ordered from the identifier out, which is
4772 // opposite of what we want :).
4773
4774 // Track if the produced type matches the structure of the declarator.
4775 // This is used later to decide if we can fill `TypeLoc` from
4776 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
4777 // an error by replacing the type with `int`.
4778 bool AreDeclaratorChunksValid = true;
4779 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4780 unsigned chunkIndex = e - i - 1;
4781 state.setCurrentChunkIndex(chunkIndex);
4782 DeclaratorChunk &DeclType = D.getTypeObject(i: chunkIndex);
4783 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4784 switch (DeclType.Kind) {
4785 case DeclaratorChunk::Paren:
4786 if (i == 0)
4787 warnAboutRedundantParens(S, D, T);
4788 T = S.BuildParenType(T);
4789 break;
4790 case DeclaratorChunk::BlockPointer:
4791 // If blocks are disabled, emit an error.
4792 if (!LangOpts.Blocks)
4793 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_blocks_disable) << LangOpts.OpenCL;
4794
4795 // Handle pointer nullability.
4796 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4797 DeclType.EndLoc, DeclType.getAttrs(),
4798 state.getDeclarator().getAttributePool());
4799
4800 T = S.BuildBlockPointerType(T, Loc: D.getIdentifierLoc(), Entity: Name);
4801 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4802 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4803 // qualified with const.
4804 if (LangOpts.OpenCL)
4805 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4806 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Cls.TypeQuals);
4807 }
4808 break;
4809 case DeclaratorChunk::Pointer:
4810 // Verify that we're not building a pointer to pointer to function with
4811 // exception specification.
4812 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4813 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4814 D.setInvalidType(true);
4815 // Build the type anyway.
4816 }
4817
4818 // Handle pointer nullability
4819 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4820 DeclType.EndLoc, DeclType.getAttrs(),
4821 state.getDeclarator().getAttributePool());
4822
4823 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4824 T = Context.getObjCObjectPointerType(OIT: T);
4825 if (DeclType.Ptr.TypeQuals)
4826 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals);
4827 break;
4828 }
4829
4830 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4831 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4832 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4833 if (LangOpts.OpenCL) {
4834 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4835 T->isBlockPointerType()) {
4836 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_pointer_to_type) << T;
4837 D.setInvalidType(true);
4838 }
4839 }
4840
4841 T = S.BuildPointerType(T, Loc: DeclType.Loc, Entity: Name);
4842 if (DeclType.Ptr.TypeQuals)
4843 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Ptr.TypeQuals);
4844 if (DeclType.Ptr.OverflowBehaviorLoc.isValid()) {
4845 auto OBState = DeclType.Ptr.OverflowBehaviorIsWrap
4846 ? DeclSpec::OverflowBehaviorState::Wrap
4847 : DeclSpec::OverflowBehaviorState::Trap;
4848 S.Diag(Loc: DeclType.Ptr.OverflowBehaviorLoc,
4849 DiagID: diag::err_overflow_behavior_non_integer_type)
4850 << DeclSpec::getSpecifierName(S: OBState) << T.getAsString() << 1;
4851 D.setInvalidType(true);
4852 }
4853 break;
4854 case DeclaratorChunk::Reference: {
4855 // Verify that we're not building a reference to pointer to function with
4856 // exception specification.
4857 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4858 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4859 D.setInvalidType(true);
4860 // Build the type anyway.
4861 }
4862 T = S.BuildReferenceType(T, SpelledAsLValue: DeclType.Ref.LValueRef, Loc: DeclType.Loc, Entity: Name);
4863
4864 if (DeclType.Ref.HasRestrict)
4865 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: Qualifiers::Restrict);
4866 break;
4867 }
4868 case DeclaratorChunk::Array: {
4869 // Verify that we're not building an array of pointers to function with
4870 // exception specification.
4871 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4872 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_distant_exception_spec);
4873 D.setInvalidType(true);
4874 // Build the type anyway.
4875 }
4876 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4877 Expr *ArraySize = ATI.NumElts;
4878 ArraySizeModifier ASM;
4879
4880 // Microsoft property fields can have multiple sizeless array chunks
4881 // (i.e. int x[][][]). Skip all of these except one to avoid creating
4882 // bad incomplete array types.
4883 if (chunkIndex != 0 && !ArraySize &&
4884 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
4885 // This is a sizeless chunk. If the next is also, skip this one.
4886 DeclaratorChunk &NextDeclType = D.getTypeObject(i: chunkIndex - 1);
4887 if (NextDeclType.Kind == DeclaratorChunk::Array &&
4888 !NextDeclType.Arr.NumElts)
4889 break;
4890 }
4891
4892 if (ATI.isStar)
4893 ASM = ArraySizeModifier::Star;
4894 else if (ATI.hasStatic)
4895 ASM = ArraySizeModifier::Static;
4896 else
4897 ASM = ArraySizeModifier::Normal;
4898 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
4899 // FIXME: This check isn't quite right: it allows star in prototypes
4900 // for function definitions, and disallows some edge cases detailed
4901 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4902 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_star_outside_prototype);
4903 ASM = ArraySizeModifier::Normal;
4904 D.setInvalidType(true);
4905 }
4906
4907 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4908 // shall appear only in a declaration of a function parameter with an
4909 // array type, ...
4910 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
4911 if (!(D.isPrototypeContext() ||
4912 D.getContext() == DeclaratorContext::KNRTypeList)) {
4913 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_static_outside_prototype)
4914 << (ASM == ArraySizeModifier::Static ? "'static'"
4915 : "type qualifier");
4916 // Remove the 'static' and the type qualifiers.
4917 if (ASM == ArraySizeModifier::Static)
4918 ASM = ArraySizeModifier::Normal;
4919 ATI.TypeQuals = 0;
4920 D.setInvalidType(true);
4921 }
4922
4923 // C99 6.7.5.2p1: ... and then only in the outermost array type
4924 // derivation.
4925 if (hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) {
4926 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_array_static_not_outermost)
4927 << (ASM == ArraySizeModifier::Static ? "'static'"
4928 : "type qualifier");
4929 if (ASM == ArraySizeModifier::Static)
4930 ASM = ArraySizeModifier::Normal;
4931 ATI.TypeQuals = 0;
4932 D.setInvalidType(true);
4933 }
4934 }
4935
4936 // Array parameters can be marked nullable as well, although it's not
4937 // necessary if they're marked 'static'.
4938 if (complainAboutMissingNullability == CAMN_Yes &&
4939 !hasNullabilityAttr(attrs: DeclType.getAttrs()) &&
4940 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
4941 !hasOuterPointerLikeChunk(D, endIndex: chunkIndex)) {
4942 checkNullabilityConsistency(S, pointerKind: SimplePointerKind::Array, pointerLoc: DeclType.Loc);
4943 }
4944
4945 T = S.BuildArrayType(T, ASM, ArraySize, Quals: ATI.TypeQuals,
4946 Brackets: SourceRange(DeclType.Loc, DeclType.EndLoc), Entity: Name);
4947 break;
4948 }
4949 case DeclaratorChunk::Function: {
4950 // If the function declarator has a prototype (i.e. it is not () and
4951 // does not have a K&R-style identifier list), then the arguments are part
4952 // of the type, otherwise the argument list is ().
4953 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4954 IsQualifiedFunction =
4955 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
4956
4957 auto IsClassType = [&](CXXScopeSpec &SS) {
4958 // If there already was an problem with the scope, don’t issue another
4959 // error about the explicit object parameter.
4960 return SS.isInvalid() ||
4961 isa_and_present<CXXRecordDecl>(
4962 Val: S.computeDeclContext(SS, /*EnteringContext=*/true));
4963 };
4964
4965 // C++23 [dcl.fct]p6:
4966 //
4967 // An explicit-object-parameter-declaration is a parameter-declaration
4968 // with a this specifier. An explicit-object-parameter-declaration shall
4969 // appear only as the first parameter-declaration of a
4970 // parameter-declaration-list of one of:
4971 //
4972 // - a declaration of a member function or member function template
4973 // ([class.mem]), or
4974 //
4975 // - an explicit instantiation ([temp.explicit]) or explicit
4976 // specialization ([temp.expl.spec]) of a templated member function,
4977 // or
4978 //
4979 // - a lambda-declarator [expr.prim.lambda].
4980 DeclaratorContext C = D.getContext();
4981 ParmVarDecl *First =
4982 FTI.NumParams ? dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param)
4983 : nullptr;
4984
4985 bool IsFunctionDecl = D.getInnermostNonParenChunk() == &DeclType;
4986 if (First && First->isExplicitObjectParameter() &&
4987 C != DeclaratorContext::LambdaExpr &&
4988
4989 // Either not a member or nested declarator in a member.
4990 //
4991 // Note that e.g. 'static' or 'friend' declarations are accepted
4992 // here; we diagnose them later when we build the member function
4993 // because it's easier that way.
4994 (C != DeclaratorContext::Member || !IsFunctionDecl) &&
4995
4996 // Allow out-of-line definitions of member functions.
4997 !IsClassType(D.getCXXScopeSpec())) {
4998 if (IsFunctionDecl)
4999 S.Diag(Loc: First->getBeginLoc(),
5000 DiagID: diag::err_explicit_object_parameter_nonmember)
5001 << /*non-member*/ 2 << /*function*/ 0 << First->getSourceRange();
5002 else
5003 S.Diag(Loc: First->getBeginLoc(),
5004 DiagID: diag::err_explicit_object_parameter_invalid)
5005 << First->getSourceRange();
5006
5007 // Do let non-member function have explicit parameters
5008 // to not break assumptions elsewhere in the code.
5009 First->setExplicitObjectParameterLoc(SourceLocation());
5010 D.setInvalidType();
5011 AreDeclaratorChunksValid = false;
5012 }
5013
5014 // Check for auto functions and trailing return type and adjust the
5015 // return type accordingly.
5016 if (!D.isInvalidType()) {
5017 // trailing-return-type is only required if we're declaring a function,
5018 // and not, for instance, a pointer to a function.
5019 if (D.getDeclSpec().hasAutoTypeSpec() &&
5020 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5021 if (!S.getLangOpts().CPlusPlus14) {
5022 S.Diag(Loc: D.getDeclSpec().getTypeSpecTypeLoc(),
5023 DiagID: D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5024 ? diag::err_auto_missing_trailing_return
5025 : diag::err_deduced_return_type);
5026 T = Context.IntTy;
5027 D.setInvalidType(true);
5028 AreDeclaratorChunksValid = false;
5029 } else {
5030 S.Diag(Loc: D.getDeclSpec().getTypeSpecTypeLoc(),
5031 DiagID: diag::warn_cxx11_compat_deduced_return_type);
5032 }
5033 } else if (FTI.hasTrailingReturnType()) {
5034 // T must be exactly 'auto' at this point. See CWG issue 681.
5035 if (isa<ParenType>(Val: T)) {
5036 S.Diag(Loc: D.getBeginLoc(), DiagID: diag::err_trailing_return_in_parens)
5037 << T << D.getSourceRange();
5038 D.setInvalidType(true);
5039 // FIXME: recover and fill decls in `TypeLoc`s.
5040 AreDeclaratorChunksValid = false;
5041 } else if (D.getName().getKind() ==
5042 UnqualifiedIdKind::IK_DeductionGuideName) {
5043 if (T != Context.DependentTy) {
5044 S.Diag(Loc: D.getDeclSpec().getBeginLoc(),
5045 DiagID: diag::err_deduction_guide_with_complex_decl)
5046 << D.getSourceRange();
5047 D.setInvalidType(true);
5048 // FIXME: recover and fill decls in `TypeLoc`s.
5049 AreDeclaratorChunksValid = false;
5050 }
5051 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5052 (T.hasQualifiers() || !isa<AutoType>(Val: T) ||
5053 cast<AutoType>(Val&: T)->getKeyword() !=
5054 AutoTypeKeyword::Auto ||
5055 cast<AutoType>(Val&: T)->isConstrained())) {
5056 // Attach a valid source location for diagnostics on functions with
5057 // trailing return types missing 'auto'. Attempt to get the location
5058 // from the declared type; if invalid, fall back to the trailing
5059 // return type's location.
5060 SourceLocation Loc = D.getDeclSpec().getTypeSpecTypeLoc();
5061 SourceRange SR = D.getDeclSpec().getSourceRange();
5062 if (Loc.isInvalid()) {
5063 Loc = FTI.getTrailingReturnTypeLoc();
5064 SR = D.getSourceRange();
5065 }
5066 S.Diag(Loc, DiagID: diag::err_trailing_return_without_auto) << T << SR;
5067 D.setInvalidType(true);
5068 // FIXME: recover and fill decls in `TypeLoc`s.
5069 AreDeclaratorChunksValid = false;
5070 }
5071 T = S.GetTypeFromParser(Ty: FTI.getTrailingReturnType(), TInfo: &TInfo);
5072 if (T.isNull()) {
5073 // An error occurred parsing the trailing return type.
5074 T = Context.IntTy;
5075 D.setInvalidType(true);
5076 } else if (AutoType *Auto = T->getContainedAutoType()) {
5077 // If the trailing return type contains an `auto`, we may need to
5078 // invent a template parameter for it, for cases like
5079 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5080 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5081 if (D.getContext() == DeclaratorContext::Prototype)
5082 InventedParamInfo = &S.InventedParameterInfos.back();
5083 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5084 InventedParamInfo = S.getCurLambda();
5085 if (InventedParamInfo) {
5086 std::tie(args&: T, args&: TInfo) = InventTemplateParameter(
5087 state, T, TrailingTSI: TInfo, Auto, Info&: *InventedParamInfo);
5088 }
5089 }
5090 } else {
5091 // This function type is not the type of the entity being declared,
5092 // so checking the 'auto' is not the responsibility of this chunk.
5093 }
5094 }
5095
5096 // C99 6.7.5.3p1: The return type may not be a function or array type.
5097 // For conversion functions, we'll diagnose this particular error later.
5098 if (!D.isInvalidType() &&
5099 ((T->isArrayType() && !S.getLangOpts().allowArrayReturnTypes()) ||
5100 T->isFunctionType()) &&
5101 (D.getName().getKind() !=
5102 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5103 unsigned diagID = diag::err_func_returning_array_function;
5104 // Last processing chunk in block context means this function chunk
5105 // represents the block.
5106 if (chunkIndex == 0 &&
5107 D.getContext() == DeclaratorContext::BlockLiteral)
5108 diagID = diag::err_block_returning_array_function;
5109 S.Diag(Loc: DeclType.Loc, DiagID: diagID) << T->isFunctionType() << T;
5110 T = Context.IntTy;
5111 D.setInvalidType(true);
5112 AreDeclaratorChunksValid = false;
5113 }
5114
5115 // Do not allow returning half FP value.
5116 // FIXME: This really should be in BuildFunctionType.
5117 if (T->isHalfType()) {
5118 if (S.getLangOpts().OpenCL) {
5119 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
5120 LO: S.getLangOpts())) {
5121 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_invalid_return)
5122 << T << 0 /*pointer hint*/;
5123 D.setInvalidType(true);
5124 }
5125 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5126 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5127 S.Diag(Loc: D.getIdentifierLoc(),
5128 DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5129 D.setInvalidType(true);
5130 }
5131 }
5132
5133 // __ptrauth is illegal on a function return type.
5134 if (T.getPointerAuth()) {
5135 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_ptrauth_qualifier_invalid) << T << 0;
5136 }
5137
5138 if (LangOpts.OpenCL) {
5139 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5140 // function.
5141 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5142 T->isPipeType()) {
5143 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_invalid_return)
5144 << T << 1 /*hint off*/;
5145 D.setInvalidType(true);
5146 }
5147 // OpenCL doesn't support variadic functions and blocks
5148 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5149 // We also allow here any toolchain reserved identifiers.
5150 if (FTI.isVariadic &&
5151 !S.getOpenCLOptions().isAvailableOption(
5152 Ext: "__cl_clang_variadic_functions", LO: S.getLangOpts()) &&
5153 !(D.getIdentifier() &&
5154 ((D.getIdentifier()->getName() == "printf" &&
5155 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5156 D.getIdentifier()->getName().starts_with(Prefix: "__")))) {
5157 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_opencl_variadic_function);
5158 D.setInvalidType(true);
5159 }
5160 }
5161
5162 // Methods cannot return interface types. All ObjC objects are
5163 // passed by reference.
5164 if (T->isObjCObjectType()) {
5165 SourceLocation DiagLoc, FixitLoc;
5166 if (TInfo) {
5167 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5168 FixitLoc = S.getLocForEndOfToken(Loc: TInfo->getTypeLoc().getEndLoc());
5169 } else {
5170 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5171 FixitLoc = S.getLocForEndOfToken(Loc: D.getDeclSpec().getEndLoc());
5172 }
5173 S.Diag(Loc: DiagLoc, DiagID: diag::err_object_cannot_be_passed_returned_by_value)
5174 << 0 << T
5175 << FixItHint::CreateInsertion(InsertionLoc: FixitLoc, Code: "*");
5176
5177 T = Context.getObjCObjectPointerType(OIT: T);
5178 if (TInfo) {
5179 TypeLocBuilder TLB;
5180 TLB.pushFullCopy(L: TInfo->getTypeLoc());
5181 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5182 TLoc.setStarLoc(FixitLoc);
5183 TInfo = TLB.getTypeSourceInfo(Context, T);
5184 } else {
5185 AreDeclaratorChunksValid = false;
5186 }
5187
5188 D.setInvalidType(true);
5189 }
5190
5191 // cv-qualifiers on return types are pointless except when the type is a
5192 // class type in C++.
5193 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5194 // A dependent type or an undeduced type might later become a class
5195 // type.
5196 !(S.getLangOpts().CPlusPlus &&
5197 (T->isRecordType() || T->isDependentType() ||
5198 T->isUndeducedAutoType()))) {
5199 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5200 D.getFunctionDefinitionKind() ==
5201 FunctionDefinitionKind::Definition) {
5202 // [6.9.1/3] qualified void return is invalid on a C
5203 // function definition. Apparently ok on declarations and
5204 // in C++ though (!)
5205 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_func_returning_qualified_void) << T;
5206 } else
5207 diagnoseRedundantReturnTypeQualifiers(S, RetTy: T, D, FunctionChunkIndex: chunkIndex);
5208 }
5209
5210 // C++2a [dcl.fct]p12:
5211 // A volatile-qualified return type is deprecated
5212 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5213 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_deprecated_volatile_return) << T;
5214
5215 // Objective-C ARC ownership qualifiers are ignored on the function
5216 // return type (by type canonicalization). Complain if this attribute
5217 // was written here.
5218 if (T.getQualifiers().hasObjCLifetime()) {
5219 SourceLocation AttrLoc;
5220 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5221 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(i: chunkIndex + 1);
5222 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5223 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5224 AttrLoc = AL.getLoc();
5225 break;
5226 }
5227 }
5228 }
5229 if (AttrLoc.isInvalid()) {
5230 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5231 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5232 AttrLoc = AL.getLoc();
5233 break;
5234 }
5235 }
5236 }
5237
5238 if (AttrLoc.isValid()) {
5239 // The ownership attributes are almost always written via
5240 // the predefined
5241 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5242 if (AttrLoc.isMacroID())
5243 AttrLoc =
5244 S.SourceMgr.getImmediateExpansionRange(Loc: AttrLoc).getBegin();
5245
5246 S.Diag(Loc: AttrLoc, DiagID: diag::warn_arc_lifetime_result_type)
5247 << T.getQualifiers().getObjCLifetime();
5248 }
5249 }
5250
5251 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5252 // C++ [dcl.fct]p6:
5253 // Types shall not be defined in return or parameter types.
5254 TagDecl *Tag = cast<TagDecl>(Val: D.getDeclSpec().getRepAsDecl());
5255 S.Diag(Loc: Tag->getLocation(), DiagID: diag::err_type_defined_in_result_type)
5256 << Context.getCanonicalTagType(TD: Tag);
5257 }
5258
5259 // Exception specs are not allowed in typedefs. Complain, but add it
5260 // anyway.
5261 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5262 S.Diag(Loc: FTI.getExceptionSpecLocBeg(),
5263 DiagID: diag::err_exception_spec_in_typedef)
5264 << (D.getContext() == DeclaratorContext::AliasDecl ||
5265 D.getContext() == DeclaratorContext::AliasTemplate);
5266
5267 // If we see "T var();" or "T var(T());" at block scope, it is probably
5268 // an attempt to initialize a variable, not a function declaration.
5269 if (FTI.isAmbiguous)
5270 warnAboutAmbiguousFunction(S, D, DeclType, RT: T);
5271
5272 FunctionType::ExtInfo EI(
5273 getCCForDeclaratorChunk(S, D, AttrList: DeclType.getAttrs(), FTI, ChunkIndex: chunkIndex));
5274
5275 // OpenCL disallows functions without a prototype, but it doesn't enforce
5276 // strict prototypes as in C23 because it allows a function definition to
5277 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5278 if (!FTI.NumParams && !FTI.isVariadic &&
5279 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5280 // Simple void foo(), where the incoming T is the result type.
5281 T = Context.getFunctionNoProtoType(ResultTy: T, Info: EI);
5282 } else {
5283 // We allow a zero-parameter variadic function in C if the
5284 // function is marked with the "overloadable" attribute. Scan
5285 // for this attribute now. We also allow it in C23 per WG14 N2975.
5286 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5287 if (LangOpts.C23)
5288 S.Diag(Loc: FTI.getEllipsisLoc(),
5289 DiagID: diag::warn_c17_compat_ellipsis_only_parameter);
5290 else if (!D.getDeclarationAttributes().hasAttribute(
5291 K: ParsedAttr::AT_Overloadable) &&
5292 !D.getAttributes().hasAttribute(
5293 K: ParsedAttr::AT_Overloadable) &&
5294 !D.getDeclSpec().getAttributes().hasAttribute(
5295 K: ParsedAttr::AT_Overloadable))
5296 S.Diag(Loc: FTI.getEllipsisLoc(), DiagID: diag::err_ellipsis_first_param);
5297 }
5298
5299 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5300 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5301 // definition.
5302 S.Diag(Loc: FTI.Params[0].IdentLoc,
5303 DiagID: diag::err_ident_list_in_fn_declaration);
5304 D.setInvalidType(true);
5305 // Recover by creating a K&R-style function type, if possible.
5306 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5307 ? Context.getFunctionNoProtoType(ResultTy: T, Info: EI)
5308 : Context.IntTy;
5309 AreDeclaratorChunksValid = false;
5310 break;
5311 }
5312
5313 FunctionProtoType::ExtProtoInfo EPI;
5314 EPI.ExtInfo = EI;
5315 EPI.Variadic = FTI.isVariadic;
5316 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5317 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5318 EPI.TypeQuals.addCVRUQualifiers(
5319 mask: FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5320 : 0);
5321 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5322 : FTI.RefQualifierIsLValueRef? RQ_LValue
5323 : RQ_RValue;
5324
5325 // Otherwise, we have a function with a parameter list that is
5326 // potentially variadic.
5327 SmallVector<QualType, 16> ParamTys;
5328 ParamTys.reserve(N: FTI.NumParams);
5329
5330 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5331 ExtParameterInfos(FTI.NumParams);
5332 bool HasAnyInterestingExtParameterInfos = false;
5333
5334 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5335 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
5336 QualType ParamTy = Param->getType();
5337 assert(!ParamTy.isNull() && "Couldn't parse type?");
5338
5339 // Look for 'void'. void is allowed only as a single parameter to a
5340 // function with no other parameters (C99 6.7.5.3p10). We record
5341 // int(void) as a FunctionProtoType with an empty parameter list.
5342 if (ParamTy->isVoidType()) {
5343 // If this is something like 'float(int, void)', reject it. 'void'
5344 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5345 // have parameters of incomplete type.
5346 if (FTI.NumParams != 1 || FTI.isVariadic) {
5347 S.Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::err_void_only_param);
5348 ParamTy = Context.IntTy;
5349 Param->setType(ParamTy);
5350 } else if (FTI.Params[i].Ident) {
5351 // Reject, but continue to parse 'int(void abc)'.
5352 S.Diag(Loc: FTI.Params[i].IdentLoc, DiagID: diag::err_param_with_void_type);
5353 ParamTy = Context.IntTy;
5354 Param->setType(ParamTy);
5355 } else {
5356 // Reject, but continue to parse 'float(const void)'.
5357 if (ParamTy.hasQualifiers())
5358 S.Diag(Loc: DeclType.Loc, DiagID: diag::err_void_param_qualified);
5359
5360 for (const auto *A : Param->attrs()) {
5361 S.Diag(Loc: A->getLoc(), DiagID: diag::warn_attribute_on_void_param)
5362 << A << A->getRange();
5363 }
5364
5365 // Reject, but continue to parse 'float(this void)' as
5366 // 'float(void)'.
5367 if (Param->isExplicitObjectParameter()) {
5368 S.Diag(Loc: Param->getLocation(),
5369 DiagID: diag::err_void_explicit_object_param);
5370 Param->setExplicitObjectParameterLoc(SourceLocation());
5371 }
5372
5373 // Do not add 'void' to the list.
5374 break;
5375 }
5376 } else if (ParamTy->isHalfType()) {
5377 // Disallow half FP parameters.
5378 // FIXME: This really should be in BuildFunctionType.
5379 if (S.getLangOpts().OpenCL) {
5380 if (!S.getOpenCLOptions().isAvailableOption(Ext: "cl_khr_fp16",
5381 LO: S.getLangOpts())) {
5382 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_invalid_param)
5383 << ParamTy << 0;
5384 D.setInvalidType();
5385 Param->setInvalidDecl();
5386 }
5387 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5388 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5389 S.Diag(Loc: Param->getLocation(),
5390 DiagID: diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5391 D.setInvalidType();
5392 }
5393 } else if (!FTI.hasPrototype) {
5394 if (Context.isPromotableIntegerType(T: ParamTy)) {
5395 ParamTy = Context.getPromotedIntegerType(PromotableType: ParamTy);
5396 Param->setKNRPromoted(true);
5397 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5398 if (BTy->getKind() == BuiltinType::Float) {
5399 ParamTy = Context.DoubleTy;
5400 Param->setKNRPromoted(true);
5401 }
5402 }
5403 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5404 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5405 S.Diag(Loc: Param->getLocation(), DiagID: diag::err_opencl_invalid_param)
5406 << ParamTy << 1 /*hint off*/;
5407 D.setInvalidType();
5408 }
5409
5410 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5411 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(consumed: true);
5412 HasAnyInterestingExtParameterInfos = true;
5413 }
5414
5415 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5416 ExtParameterInfos[i] =
5417 ExtParameterInfos[i].withABI(kind: attr->getABI());
5418 HasAnyInterestingExtParameterInfos = true;
5419 }
5420
5421 if (Param->hasAttr<PassObjectSizeAttr>()) {
5422 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5423 HasAnyInterestingExtParameterInfos = true;
5424 }
5425
5426 if (Param->hasAttr<NoEscapeAttr>()) {
5427 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(NoEscape: true);
5428 HasAnyInterestingExtParameterInfos = true;
5429 }
5430
5431 ParamTys.push_back(Elt: ParamTy);
5432 }
5433
5434 if (HasAnyInterestingExtParameterInfos) {
5435 EPI.ExtParameterInfos = ExtParameterInfos.data();
5436 checkExtParameterInfos(S, paramTypes: ParamTys, EPI,
5437 getParamLoc: [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5438 }
5439
5440 SmallVector<QualType, 4> Exceptions;
5441 SmallVector<ParsedType, 2> DynamicExceptions;
5442 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5443 Expr *NoexceptExpr = nullptr;
5444
5445 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5446 // FIXME: It's rather inefficient to have to split into two vectors
5447 // here.
5448 unsigned N = FTI.getNumExceptions();
5449 DynamicExceptions.reserve(N);
5450 DynamicExceptionRanges.reserve(N);
5451 for (unsigned I = 0; I != N; ++I) {
5452 DynamicExceptions.push_back(Elt: FTI.Exceptions[I].Ty);
5453 DynamicExceptionRanges.push_back(Elt: FTI.Exceptions[I].Range);
5454 }
5455 } else if (isComputedNoexcept(ESpecType: FTI.getExceptionSpecType())) {
5456 NoexceptExpr = FTI.NoexceptExpr;
5457 }
5458
5459 S.checkExceptionSpecification(IsTopLevel: D.isFunctionDeclarationContext(),
5460 EST: FTI.getExceptionSpecType(),
5461 DynamicExceptions,
5462 DynamicExceptionRanges,
5463 NoexceptExpr,
5464 Exceptions,
5465 ESI&: EPI.ExceptionSpec);
5466
5467 // FIXME: Set address space from attrs for C++ mode here.
5468 // OpenCLCPlusPlus: A class member function has an address space.
5469 auto IsClassMember = [&]() {
5470 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5471 state.getDeclarator()
5472 .getCXXScopeSpec()
5473 .getScopeRep()
5474 .getKind() == NestedNameSpecifier::Kind::Type) ||
5475 state.getDeclarator().getContext() ==
5476 DeclaratorContext::Member ||
5477 state.getDeclarator().getContext() ==
5478 DeclaratorContext::LambdaExpr;
5479 };
5480
5481 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5482 LangAS ASIdx = LangAS::Default;
5483 // Take address space attr if any and mark as invalid to avoid adding
5484 // them later while creating QualType.
5485 if (FTI.MethodQualifiers)
5486 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5487 LangAS ASIdxNew = attr.asOpenCLLangAS();
5488 if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: ASIdx, ASNew: ASIdxNew,
5489 AttrLoc: attr.getLoc()))
5490 D.setInvalidType(true);
5491 else
5492 ASIdx = ASIdxNew;
5493 }
5494 // If a class member function's address space is not set, set it to
5495 // __generic.
5496 LangAS AS =
5497 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5498 : ASIdx);
5499 EPI.TypeQuals.addAddressSpace(space: AS);
5500 }
5501 T = Context.getFunctionType(ResultTy: T, Args: ParamTys, EPI);
5502 }
5503 break;
5504 }
5505 case DeclaratorChunk::MemberPointer: {
5506 // The scope spec must refer to a class, or be dependent.
5507 CXXScopeSpec &SS = DeclType.Mem.Scope();
5508
5509 // Handle pointer nullability.
5510 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5511 DeclType.EndLoc, DeclType.getAttrs(),
5512 state.getDeclarator().getAttributePool());
5513
5514 if (SS.isInvalid()) {
5515 // Avoid emitting extra errors if we already errored on the scope.
5516 D.setInvalidType(true);
5517 AreDeclaratorChunksValid = false;
5518 } else {
5519 T = S.BuildMemberPointerType(T, SS, /*Cls=*/nullptr, Loc: DeclType.Loc,
5520 Entity: D.getIdentifier());
5521 }
5522
5523 if (T.isNull()) {
5524 T = Context.IntTy;
5525 D.setInvalidType(true);
5526 AreDeclaratorChunksValid = false;
5527 } else if (DeclType.Mem.TypeQuals) {
5528 T = S.BuildQualifiedType(T, Loc: DeclType.Loc, CVRAU: DeclType.Mem.TypeQuals);
5529 }
5530 break;
5531 }
5532
5533 case DeclaratorChunk::Pipe: {
5534 T = S.BuildReadPipeType(T, Loc: DeclType.Loc);
5535 if (!T.isNull())
5536 processTypeAttrs(state, type&: T, TAL: TAL_DeclSpec,
5537 attrs: D.getMutableDeclSpec().getAttributes());
5538 break;
5539 }
5540 }
5541
5542 if (T.isNull()) {
5543 D.setInvalidType(true);
5544 T = Context.IntTy;
5545 AreDeclaratorChunksValid = false;
5546 }
5547
5548 // See if there are any attributes on this declarator chunk.
5549 processTypeAttrs(state, type&: T, TAL: TAL_DeclChunk, attrs: DeclType.getAttrs(),
5550 CFT: S.CUDA().IdentifyTarget(Attrs: D.getAttributes()));
5551
5552 if (DeclType.Kind != DeclaratorChunk::Paren) {
5553 if (ExpectNoDerefChunk && !IsNoDerefableChunk(Chunk: DeclType))
5554 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_noderef_on_non_pointer_or_array);
5555
5556 ExpectNoDerefChunk = state.didParseNoDeref();
5557 }
5558 }
5559
5560 if (ExpectNoDerefChunk)
5561 S.Diag(Loc: state.getDeclarator().getBeginLoc(),
5562 DiagID: diag::warn_noderef_on_non_pointer_or_array);
5563
5564 // GNU warning -Wstrict-prototypes
5565 // Warn if a function declaration or definition is without a prototype.
5566 // This warning is issued for all kinds of unprototyped function
5567 // declarations (i.e. function type typedef, function pointer etc.)
5568 // C99 6.7.5.3p14:
5569 // The empty list in a function declarator that is not part of a definition
5570 // of that function specifies that no information about the number or types
5571 // of the parameters is supplied.
5572 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5573 // function declarations whose behavior changes in C23.
5574 if (!LangOpts.requiresStrictPrototypes()) {
5575 bool IsBlock = false;
5576 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5577 switch (DeclType.Kind) {
5578 case DeclaratorChunk::BlockPointer:
5579 IsBlock = true;
5580 break;
5581 case DeclaratorChunk::Function: {
5582 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5583 // We suppress the warning when there's no LParen location, as this
5584 // indicates the declaration was an implicit declaration, which gets
5585 // warned about separately via -Wimplicit-function-declaration. We also
5586 // suppress the warning when we know the function has a prototype.
5587 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5588 FTI.getLParenLoc().isValid())
5589 S.Diag(Loc: DeclType.Loc, DiagID: diag::warn_strict_prototypes)
5590 << IsBlock
5591 << FixItHint::CreateInsertion(InsertionLoc: FTI.getRParenLoc(), Code: "void");
5592 IsBlock = false;
5593 break;
5594 }
5595 default:
5596 break;
5597 }
5598 }
5599 }
5600
5601 assert(!T.isNull() && "T must not be null after this point");
5602
5603 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5604 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5605 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5606
5607 // C++ 8.3.5p4:
5608 // A cv-qualifier-seq shall only be part of the function type
5609 // for a nonstatic member function, the function type to which a pointer
5610 // to member refers, or the top-level function type of a function typedef
5611 // declaration.
5612 //
5613 // Core issue 547 also allows cv-qualifiers on function types that are
5614 // top-level template type arguments.
5615 enum {
5616 NonMember,
5617 Member,
5618 ExplicitObjectMember,
5619 DeductionGuide
5620 } Kind = NonMember;
5621 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5622 Kind = DeductionGuide;
5623 else if (!D.getCXXScopeSpec().isSet()) {
5624 if ((D.getContext() == DeclaratorContext::Member ||
5625 D.getContext() == DeclaratorContext::LambdaExpr) &&
5626 !D.getDeclSpec().isFriendSpecified())
5627 Kind = Member;
5628 } else {
5629 DeclContext *DC = S.computeDeclContext(SS: D.getCXXScopeSpec());
5630 if (!DC || DC->isRecord())
5631 Kind = Member;
5632 }
5633
5634 if (Kind == Member) {
5635 unsigned I;
5636 if (D.isFunctionDeclarator(idx&: I)) {
5637 const DeclaratorChunk &Chunk = D.getTypeObject(i: I);
5638 if (Chunk.Fun.NumParams) {
5639 auto *P = dyn_cast_or_null<ParmVarDecl>(Val: Chunk.Fun.Params->Param);
5640 if (P && P->isExplicitObjectParameter())
5641 Kind = ExplicitObjectMember;
5642 }
5643 }
5644 }
5645
5646 // C++11 [dcl.fct]p6 (w/DR1417):
5647 // An attempt to specify a function type with a cv-qualifier-seq or a
5648 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5649 // - the function type for a non-static member function,
5650 // - the function type to which a pointer to member refers,
5651 // - the top-level function type of a function typedef declaration or
5652 // alias-declaration,
5653 // - the type-id in the default argument of a type-parameter, or
5654 // - the type-id of a template-argument for a type-parameter
5655 //
5656 // C++23 [dcl.fct]p6 (P0847R7)
5657 // ... A member-declarator with an explicit-object-parameter-declaration
5658 // shall not include a ref-qualifier or a cv-qualifier-seq and shall not be
5659 // declared static or virtual ...
5660 //
5661 // FIXME: Checking this here is insufficient. We accept-invalid on:
5662 //
5663 // template<typename T> struct S { void f(T); };
5664 // S<int() const> s;
5665 //
5666 // ... for instance.
5667 if (IsQualifiedFunction &&
5668 // Check for non-static member function and not and
5669 // explicit-object-parameter-declaration
5670 (Kind != Member || D.isExplicitObjectMemberFunction() ||
5671 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
5672 (D.getContext() == clang::DeclaratorContext::Member &&
5673 D.isStaticMember())) &&
5674 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5675 D.getContext() != DeclaratorContext::TemplateTypeArg &&
5676 D.getContext() != DeclaratorContext::TypeName) {
5677 SourceLocation Loc = D.getBeginLoc();
5678 SourceRange RemovalRange;
5679 unsigned I;
5680 if (D.isFunctionDeclarator(idx&: I)) {
5681 SmallVector<SourceLocation, 4> RemovalLocs;
5682 const DeclaratorChunk &Chunk = D.getTypeObject(i: I);
5683 assert(Chunk.Kind == DeclaratorChunk::Function);
5684
5685 if (Chunk.Fun.hasRefQualifier())
5686 RemovalLocs.push_back(Elt: Chunk.Fun.getRefQualifierLoc());
5687
5688 if (Chunk.Fun.hasMethodTypeQualifiers())
5689 Chunk.Fun.MethodQualifiers->forEachQualifier(
5690 Handle: [&](DeclSpec::TQ TypeQual, StringRef QualName,
5691 SourceLocation SL) { RemovalLocs.push_back(Elt: SL); });
5692
5693 if (!RemovalLocs.empty()) {
5694 llvm::sort(C&: RemovalLocs,
5695 Comp: BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5696 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5697 Loc = RemovalLocs.front();
5698 }
5699 }
5700
5701 S.Diag(Loc, DiagID: diag::err_invalid_qualified_function_type)
5702 << Kind << D.isFunctionDeclarator() << T
5703 << getFunctionQualifiersAsString(FnTy)
5704 << FixItHint::CreateRemoval(RemoveRange: RemovalRange);
5705
5706 // Strip the cv-qualifiers and ref-qualifiers from the type.
5707 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5708 EPI.TypeQuals.removeCVRQualifiers();
5709 EPI.RefQualifier = RQ_None;
5710
5711 T = Context.getFunctionType(ResultTy: FnTy->getReturnType(), Args: FnTy->getParamTypes(),
5712 EPI);
5713 // Rebuild any parens around the identifier in the function type.
5714 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5715 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5716 break;
5717 T = S.BuildParenType(T);
5718 }
5719 }
5720 }
5721
5722 // Apply any undistributed attributes from the declaration or declarator.
5723 ParsedAttributesView NonSlidingAttrs;
5724 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5725 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5726 NonSlidingAttrs.addAtEnd(newAttr: &AL);
5727 }
5728 }
5729 processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: NonSlidingAttrs);
5730 processTypeAttrs(state, type&: T, TAL: TAL_DeclName, attrs: D.getAttributes());
5731
5732 // Diagnose any ignored type attributes.
5733 state.diagnoseIgnoredTypeAttrs(type: T);
5734
5735 // C++0x [dcl.constexpr]p9:
5736 // A constexpr specifier used in an object declaration declares the object
5737 // as const.
5738 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5739 T->isObjectType())
5740 T.addConst();
5741
5742 // C++2a [dcl.fct]p4:
5743 // A parameter with volatile-qualified type is deprecated
5744 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5745 (D.getContext() == DeclaratorContext::Prototype ||
5746 D.getContext() == DeclaratorContext::LambdaExprParameter))
5747 S.Diag(Loc: D.getIdentifierLoc(), DiagID: diag::warn_deprecated_volatile_param) << T;
5748
5749 // If there was an ellipsis in the declarator, the declaration declares a
5750 // parameter pack whose type may be a pack expansion type.
5751 if (D.hasEllipsis()) {
5752 // C++0x [dcl.fct]p13:
5753 // A declarator-id or abstract-declarator containing an ellipsis shall
5754 // only be used in a parameter-declaration. Such a parameter-declaration
5755 // is a parameter pack (14.5.3). [...]
5756 switch (D.getContext()) {
5757 case DeclaratorContext::Prototype:
5758 case DeclaratorContext::LambdaExprParameter:
5759 case DeclaratorContext::RequiresExpr:
5760 // C++0x [dcl.fct]p13:
5761 // [...] When it is part of a parameter-declaration-clause, the
5762 // parameter pack is a function parameter pack (14.5.3). The type T
5763 // of the declarator-id of the function parameter pack shall contain
5764 // a template parameter pack; each template parameter pack in T is
5765 // expanded by the function parameter pack.
5766 //
5767 // We represent function parameter packs as function parameters whose
5768 // type is a pack expansion.
5769 if (!T->containsUnexpandedParameterPack() &&
5770 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5771 S.Diag(Loc: D.getEllipsisLoc(),
5772 DiagID: diag::err_function_parameter_pack_without_parameter_packs)
5773 << T << D.getSourceRange();
5774 D.setEllipsisLoc(SourceLocation());
5775 } else {
5776 T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt,
5777 /*ExpectPackInType=*/false);
5778 }
5779 break;
5780 case DeclaratorContext::TemplateParam:
5781 // C++0x [temp.param]p15:
5782 // If a template-parameter is a [...] is a parameter-declaration that
5783 // declares a parameter pack (8.3.5), then the template-parameter is a
5784 // template parameter pack (14.5.3).
5785 //
5786 // Note: core issue 778 clarifies that, if there are any unexpanded
5787 // parameter packs in the type of the non-type template parameter, then
5788 // it expands those parameter packs.
5789 if (T->containsUnexpandedParameterPack())
5790 T = Context.getPackExpansionType(Pattern: T, NumExpansions: std::nullopt);
5791 else
5792 S.DiagCompat(Loc: D.getEllipsisLoc(), CompatDiagId: diag_compat::variadic_templates);
5793 break;
5794
5795 case DeclaratorContext::File:
5796 case DeclaratorContext::KNRTypeList:
5797 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5798 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5799 case DeclaratorContext::TypeName:
5800 case DeclaratorContext::FunctionalCast:
5801 case DeclaratorContext::CXXNew:
5802 case DeclaratorContext::AliasDecl:
5803 case DeclaratorContext::AliasTemplate:
5804 case DeclaratorContext::Member:
5805 case DeclaratorContext::Block:
5806 case DeclaratorContext::ForInit:
5807 case DeclaratorContext::SelectionInit:
5808 case DeclaratorContext::Condition:
5809 case DeclaratorContext::CXXCatch:
5810 case DeclaratorContext::ObjCCatch:
5811 case DeclaratorContext::BlockLiteral:
5812 case DeclaratorContext::LambdaExpr:
5813 case DeclaratorContext::ConversionId:
5814 case DeclaratorContext::TrailingReturn:
5815 case DeclaratorContext::TrailingReturnVar:
5816 case DeclaratorContext::TemplateArg:
5817 case DeclaratorContext::TemplateTypeArg:
5818 case DeclaratorContext::Association:
5819 // FIXME: We may want to allow parameter packs in block-literal contexts
5820 // in the future.
5821 S.Diag(Loc: D.getEllipsisLoc(),
5822 DiagID: diag::err_ellipsis_in_declarator_not_parameter);
5823 D.setEllipsisLoc(SourceLocation());
5824 break;
5825 }
5826 }
5827
5828 assert(!T.isNull() && "T must not be null at the end of this function");
5829 if (!AreDeclaratorChunksValid)
5830 return Context.getTrivialTypeSourceInfo(T);
5831
5832 if (state.didParseHLSLParamMod() && !T->isConstantArrayType())
5833 T = S.HLSL().getInoutParameterType(Ty: T);
5834 return GetTypeSourceInfoForDeclarator(State&: state, T, ReturnTypeInfo: TInfo);
5835}
5836
5837TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D) {
5838 // Determine the type of the declarator. Not all forms of declarator
5839 // have a type.
5840
5841 TypeProcessingState state(*this, D);
5842
5843 TypeSourceInfo *ReturnTypeInfo = nullptr;
5844 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5845 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5846 inferARCWriteback(state, declSpecType&: T);
5847
5848 return GetFullTypeForDeclarator(state, declSpecType: T, TInfo: ReturnTypeInfo);
5849}
5850
5851static void transferARCOwnershipToDeclSpec(Sema &S,
5852 QualType &declSpecTy,
5853 Qualifiers::ObjCLifetime ownership) {
5854 if (declSpecTy->isObjCRetainableType() &&
5855 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5856 Qualifiers qs;
5857 qs.addObjCLifetime(type: ownership);
5858 declSpecTy = S.Context.getQualifiedType(T: declSpecTy, Qs: qs);
5859 }
5860}
5861
5862static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5863 Qualifiers::ObjCLifetime ownership,
5864 unsigned chunkIndex) {
5865 Sema &S = state.getSema();
5866 Declarator &D = state.getDeclarator();
5867
5868 // Look for an explicit lifetime attribute.
5869 DeclaratorChunk &chunk = D.getTypeObject(i: chunkIndex);
5870 if (chunk.getAttrs().hasAttribute(K: ParsedAttr::AT_ObjCOwnership))
5871 return;
5872
5873 const char *attrStr = nullptr;
5874 switch (ownership) {
5875 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5876 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5877 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5878 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5879 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5880 }
5881
5882 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5883 Arg->setIdentifierInfo(&S.Context.Idents.get(Name: attrStr));
5884
5885 ArgsUnion Args(Arg);
5886
5887 // If there wasn't one, add one (with an invalid source location
5888 // so that we don't make an AttributedType for it).
5889 ParsedAttr *attr =
5890 D.getAttributePool().create(attrName: &S.Context.Idents.get(Name: "objc_ownership"),
5891 attrRange: SourceLocation(), scope: AttributeScopeInfo(),
5892 /*args*/ &Args, numArgs: 1, form: ParsedAttr::Form::GNU());
5893 chunk.getAttrs().addAtEnd(newAttr: attr);
5894 // TODO: mark whether we did this inference?
5895}
5896
5897/// Used for transferring ownership in casts resulting in l-values.
5898static void transferARCOwnership(TypeProcessingState &state,
5899 QualType &declSpecTy,
5900 Qualifiers::ObjCLifetime ownership) {
5901 Sema &S = state.getSema();
5902 Declarator &D = state.getDeclarator();
5903
5904 int inner = -1;
5905 bool hasIndirection = false;
5906 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5907 DeclaratorChunk &chunk = D.getTypeObject(i);
5908 switch (chunk.Kind) {
5909 case DeclaratorChunk::Paren:
5910 // Ignore parens.
5911 break;
5912
5913 case DeclaratorChunk::Array:
5914 case DeclaratorChunk::Reference:
5915 case DeclaratorChunk::Pointer:
5916 if (inner != -1)
5917 hasIndirection = true;
5918 inner = i;
5919 break;
5920
5921 case DeclaratorChunk::BlockPointer:
5922 if (inner != -1)
5923 transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: i);
5924 return;
5925
5926 case DeclaratorChunk::Function:
5927 case DeclaratorChunk::MemberPointer:
5928 case DeclaratorChunk::Pipe:
5929 return;
5930 }
5931 }
5932
5933 if (inner == -1)
5934 return;
5935
5936 DeclaratorChunk &chunk = D.getTypeObject(i: inner);
5937 if (chunk.Kind == DeclaratorChunk::Pointer) {
5938 if (declSpecTy->isObjCRetainableType())
5939 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5940 if (declSpecTy->isObjCObjectType() && hasIndirection)
5941 return transferARCOwnershipToDeclaratorChunk(state, ownership, chunkIndex: inner);
5942 } else {
5943 assert(chunk.Kind == DeclaratorChunk::Array ||
5944 chunk.Kind == DeclaratorChunk::Reference);
5945 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5946 }
5947}
5948
5949TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5950 TypeProcessingState state(*this, D);
5951
5952 TypeSourceInfo *ReturnTypeInfo = nullptr;
5953 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5954
5955 if (getLangOpts().ObjC) {
5956 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(T: FromTy);
5957 if (ownership != Qualifiers::OCL_None)
5958 transferARCOwnership(state, declSpecTy, ownership);
5959 }
5960
5961 return GetFullTypeForDeclarator(state, declSpecType: declSpecTy, TInfo: ReturnTypeInfo);
5962}
5963
5964static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5965 TypeProcessingState &State) {
5966 TL.setAttr(State.takeAttrForAttributedType(AT: TL.getTypePtr()));
5967}
5968
5969static void fillHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL,
5970 TypeProcessingState &State) {
5971 HLSLAttributedResourceLocInfo LocInfo =
5972 State.getSema().HLSL().TakeLocForHLSLAttribute(RT: TL.getTypePtr());
5973 TL.setSourceRange(LocInfo.Range);
5974 TL.setContainedTypeSourceInfo(LocInfo.ContainedTyInfo);
5975}
5976
5977static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
5978 const ParsedAttributesView &Attrs) {
5979 for (const ParsedAttr &AL : Attrs) {
5980 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
5981 MTL.setAttrNameLoc(AL.getLoc());
5982 MTL.setAttrRowOperand(AL.getArgAsExpr(Arg: 0));
5983 MTL.setAttrColumnOperand(AL.getArgAsExpr(Arg: 1));
5984 MTL.setAttrOperandParensRange(SourceRange());
5985 return;
5986 }
5987 }
5988
5989 llvm_unreachable("no matrix_type attribute found at the expected location!");
5990}
5991
5992// FIXME: Also handle attributes on the decl-specifier, declarator and
5993// declaration. Matrix type locations need the same handling.
5994static void fillVectorTypeLoc(VectorTypeLoc VTL,
5995 const ParsedAttributesView &Attrs) {
5996 auto Kind = isa<ExtVectorType>(Val: VTL.getTypePtr())
5997 ? ParsedAttr::AT_ExtVectorType
5998 : ParsedAttr::AT_VectorSize;
5999 for (const ParsedAttr &AL : Attrs) {
6000 if (AL.getKind() == Kind && !AL.isInvalid() && AL.getNumArgs() == 1) {
6001 VTL.setAttrNameLoc(AL.getLoc());
6002 VTL.setSizeExpr(AL.getArgAsExpr(Arg: 0));
6003 return;
6004 }
6005 }
6006
6007 // The attribute may be on the declarator rather than this chunk, or the
6008 // vector may use a target-specific attribute. Keep the default locations
6009 // when no matching attribute is present.
6010}
6011
6012static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6013 SourceLocation Loc;
6014 switch (Chunk.Kind) {
6015 case DeclaratorChunk::Function:
6016 case DeclaratorChunk::Array:
6017 case DeclaratorChunk::Paren:
6018 case DeclaratorChunk::Pipe:
6019 llvm_unreachable("cannot be _Atomic qualified");
6020
6021 case DeclaratorChunk::Pointer:
6022 Loc = Chunk.Ptr.AtomicQualLoc;
6023 break;
6024
6025 case DeclaratorChunk::BlockPointer:
6026 case DeclaratorChunk::Reference:
6027 case DeclaratorChunk::MemberPointer:
6028 // FIXME: Provide a source location for the _Atomic keyword.
6029 break;
6030 }
6031
6032 ATL.setKWLoc(Loc);
6033 ATL.setParensRange(SourceRange());
6034}
6035
6036namespace {
6037 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6038 Sema &SemaRef;
6039 ASTContext &Context;
6040 TypeProcessingState &State;
6041 const DeclSpec &DS;
6042
6043 public:
6044 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6045 const DeclSpec &DS)
6046 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6047
6048 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6049 Visit(TyLoc: TL.getModifiedLoc());
6050 fillAttributedTypeLoc(TL, State);
6051 }
6052 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6053 Visit(TyLoc: TL.getWrappedLoc());
6054 }
6055 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6056 Visit(TyLoc: TL.getWrappedLoc());
6057 }
6058 void VisitHLSLAttributedResourceTypeLoc(HLSLAttributedResourceTypeLoc TL) {
6059 Visit(TyLoc: TL.getWrappedLoc());
6060 fillHLSLAttributedResourceTypeLoc(TL, State);
6061 }
6062 void VisitHLSLInlineSpirvTypeLoc(HLSLInlineSpirvTypeLoc TL) {}
6063 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6064 Visit(TyLoc: TL.getInnerLoc());
6065 TL.setExpansionLoc(
6066 State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr()));
6067 }
6068 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6069 Visit(TyLoc: TL.getUnqualifiedLoc());
6070 }
6071 // Allow to fill pointee's type locations, e.g.,
6072 // int __attr * __attr * __attr *p;
6073 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TyLoc: TL.getNextTypeLoc()); }
6074 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6075 if (DS.getTypeSpecType() == TST_typename) {
6076 TypeSourceInfo *TInfo = nullptr;
6077 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6078 if (TInfo) {
6079 TL.copy(other: TInfo->getTypeLoc().castAs<TypedefTypeLoc>());
6080 return;
6081 }
6082 }
6083 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6084 ? DS.getTypeSpecTypeLoc()
6085 : SourceLocation(),
6086 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6087 NameLoc: DS.getTypeSpecTypeNameLoc());
6088 }
6089 void VisitUnresolvedUsingTypeLoc(UnresolvedUsingTypeLoc TL) {
6090 if (DS.getTypeSpecType() == TST_typename) {
6091 TypeSourceInfo *TInfo = nullptr;
6092 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6093 if (TInfo) {
6094 TL.copy(other: TInfo->getTypeLoc().castAs<UnresolvedUsingTypeLoc>());
6095 return;
6096 }
6097 }
6098 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6099 ? DS.getTypeSpecTypeLoc()
6100 : SourceLocation(),
6101 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6102 NameLoc: DS.getTypeSpecTypeNameLoc());
6103 }
6104 void VisitUsingTypeLoc(UsingTypeLoc TL) {
6105 if (DS.getTypeSpecType() == TST_typename) {
6106 TypeSourceInfo *TInfo = nullptr;
6107 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6108 if (TInfo) {
6109 TL.copy(other: TInfo->getTypeLoc().castAs<UsingTypeLoc>());
6110 return;
6111 }
6112 }
6113 TL.set(ElaboratedKeywordLoc: TL.getTypePtr()->getKeyword() != ElaboratedTypeKeyword::None
6114 ? DS.getTypeSpecTypeLoc()
6115 : SourceLocation(),
6116 QualifierLoc: DS.getTypeSpecScope().getWithLocInContext(Context),
6117 NameLoc: DS.getTypeSpecTypeNameLoc());
6118 }
6119 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6120 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6121 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6122 // addition field. What we have is good enough for display of location
6123 // of 'fixit' on interface name.
6124 TL.setNameEndLoc(DS.getEndLoc());
6125 }
6126 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6127 TypeSourceInfo *RepTInfo = nullptr;
6128 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo);
6129 TL.copy(other: RepTInfo->getTypeLoc());
6130 }
6131 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6132 TypeSourceInfo *RepTInfo = nullptr;
6133 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &RepTInfo);
6134 TL.copy(other: RepTInfo->getTypeLoc());
6135 }
6136 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6137 TypeSourceInfo *TInfo = nullptr;
6138 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6139
6140 // If we got no declarator info from previous Sema routines,
6141 // just fill with the typespec loc.
6142 if (!TInfo) {
6143 TL.initialize(Context, Loc: DS.getTypeSpecTypeNameLoc());
6144 return;
6145 }
6146
6147 TypeLoc OldTL = TInfo->getTypeLoc();
6148 TL.copy(Loc: OldTL.castAs<TemplateSpecializationTypeLoc>());
6149 assert(TL.getRAngleLoc() ==
6150 OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6151 }
6152 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6153 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6154 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6155 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6156 TL.setParensRange(DS.getTypeofParensRange());
6157 }
6158 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6159 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6160 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6161 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6162 TL.setParensRange(DS.getTypeofParensRange());
6163 assert(DS.getRepAsType());
6164 TypeSourceInfo *TInfo = nullptr;
6165 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6166 TL.setUnmodifiedTInfo(TInfo);
6167 }
6168 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6169 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6170 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6171 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6172 }
6173 void VisitPackIndexingTypeLoc(PackIndexingTypeLoc TL) {
6174 assert(DS.getTypeSpecType() == DeclSpec::TST_typename_pack_indexing);
6175 TypeSourceInfo *TInfo = nullptr;
6176 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6177 TL.copy(other: TInfo->getTypeLoc());
6178 }
6179 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6180 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6181 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6182 TL.setParensRange(DS.getTypeofParensRange());
6183 assert(DS.getRepAsType());
6184 TypeSourceInfo *TInfo = nullptr;
6185 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6186 TL.setUnderlyingTInfo(TInfo);
6187 }
6188 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6189 // By default, use the source location of the type specifier.
6190 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6191 if (TL.needsExtraLocalData()) {
6192 // Set info for the written builtin specifiers.
6193 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6194 // Try to have a meaningful source location.
6195 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6196 TL.expandBuiltinRange(Range: DS.getTypeSpecSignLoc());
6197 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6198 TL.expandBuiltinRange(Range: DS.getTypeSpecWidthRange());
6199 }
6200 }
6201 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6202 assert(DS.getTypeSpecType() == TST_typename);
6203 TypeSourceInfo *TInfo = nullptr;
6204 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6205 assert(TInfo);
6206 TL.copy(Loc: TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6207 }
6208 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6209 assert(DS.getTypeSpecType() == TST_auto ||
6210 DS.getTypeSpecType() == TST_decltype_auto ||
6211 DS.getTypeSpecType() == TST_auto_type ||
6212 DS.getTypeSpecType() == TST_unspecified);
6213 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6214 if (DS.getTypeSpecType() == TST_decltype_auto)
6215 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6216 if (!DS.isConstrainedAuto())
6217 return;
6218 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6219 if (!TemplateId)
6220 return;
6221
6222 NestedNameSpecifierLoc NNS =
6223 (DS.getTypeSpecScope().isNotEmpty()
6224 ? DS.getTypeSpecScope().getWithLocInContext(Context)
6225 : NestedNameSpecifierLoc());
6226 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6227 TemplateId->RAngleLoc);
6228 if (TemplateId->NumArgs > 0) {
6229 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6230 TemplateId->NumArgs);
6231 SemaRef.translateTemplateArguments(In: TemplateArgsPtr, Out&: TemplateArgsInfo);
6232 }
6233 DeclarationNameInfo DNI = Context.getNameForTemplate(
6234 Name: TL.getTypePtr()->getTypeConstraintConcept(),
6235 NameLoc: TemplateId->TemplateNameLoc);
6236
6237 NamedDecl *FoundDecl;
6238 if (auto TN = TemplateId->Template.get();
6239 UsingShadowDecl *USD = TN.getAsUsingShadowDecl())
6240 FoundDecl = cast<NamedDecl>(Val: USD);
6241 else
6242 FoundDecl = cast_if_present<NamedDecl>(Val: TN.getAsTemplateDecl());
6243
6244 auto *CR = ConceptReference::Create(
6245 C: Context, NNS, TemplateKWLoc: TemplateId->TemplateKWLoc, ConceptNameInfo: DNI, FoundDecl,
6246 /*NamedDecl=*/NamedConcept: TL.getTypePtr()->getTypeConstraintConcept(),
6247 ArgsAsWritten: ASTTemplateArgumentListInfo::Create(C: Context, List: TemplateArgsInfo));
6248 TL.setConceptReference(CR);
6249 }
6250 void VisitDeducedTemplateSpecializationTypeLoc(
6251 DeducedTemplateSpecializationTypeLoc TL) {
6252 assert(DS.getTypeSpecType() == TST_typename);
6253 TypeSourceInfo *TInfo = nullptr;
6254 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6255 assert(TInfo);
6256 TL.copy(
6257 other: TInfo->getTypeLoc().castAs<DeducedTemplateSpecializationTypeLoc>());
6258 }
6259 void VisitTagTypeLoc(TagTypeLoc TL) {
6260 if (DS.getTypeSpecType() == TST_typename) {
6261 TypeSourceInfo *TInfo = nullptr;
6262 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6263 if (TInfo) {
6264 TL.copy(other: TInfo->getTypeLoc().castAs<TagTypeLoc>());
6265 return;
6266 }
6267 }
6268 TL.setElaboratedKeywordLoc(TL.getTypePtr()->getKeyword() !=
6269 ElaboratedTypeKeyword::None
6270 ? DS.getTypeSpecTypeLoc()
6271 : SourceLocation());
6272 TL.setQualifierLoc(DS.getTypeSpecScope().getWithLocInContext(Context));
6273 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6274 }
6275 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6276 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6277 // or an _Atomic qualifier.
6278 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6279 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6280 TL.setParensRange(DS.getTypeofParensRange());
6281
6282 TypeSourceInfo *TInfo = nullptr;
6283 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6284 assert(TInfo);
6285 TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc());
6286 } else {
6287 TL.setKWLoc(DS.getAtomicSpecLoc());
6288 // No parens, to indicate this was spelled as an _Atomic qualifier.
6289 TL.setParensRange(SourceRange());
6290 Visit(TyLoc: TL.getValueLoc());
6291 }
6292 }
6293
6294 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6295 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6296
6297 TypeSourceInfo *TInfo = nullptr;
6298 Sema::GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
6299 TL.getValueLoc().initializeFullCopy(Other: TInfo->getTypeLoc());
6300 }
6301
6302 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6303 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6304 }
6305
6306 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6307 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6308 }
6309
6310 void VisitTypeLoc(TypeLoc TL) {
6311 // FIXME: add other typespec types and change this to an assert.
6312 TL.initialize(Context, Loc: DS.getTypeSpecTypeLoc());
6313 }
6314 };
6315
6316 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6317 ASTContext &Context;
6318 TypeProcessingState &State;
6319 const DeclaratorChunk &Chunk;
6320
6321 public:
6322 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6323 const DeclaratorChunk &Chunk)
6324 : Context(Context), State(State), Chunk(Chunk) {}
6325
6326 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6327 llvm_unreachable("qualified type locs not expected here!");
6328 }
6329 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6330 llvm_unreachable("decayed type locs not expected here!");
6331 }
6332 void VisitArrayParameterTypeLoc(ArrayParameterTypeLoc TL) {
6333 llvm_unreachable("array parameter type locs not expected here!");
6334 }
6335
6336 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6337 fillAttributedTypeLoc(TL, State);
6338 }
6339 void VisitCountAttributedTypeLoc(CountAttributedTypeLoc TL) {
6340 // nothing
6341 }
6342 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6343 // nothing
6344 }
6345 void VisitOverflowBehaviorTypeLoc(OverflowBehaviorTypeLoc TL) {
6346 // nothing
6347 }
6348 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6349 // nothing
6350 }
6351 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6352 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6353 TL.setCaretLoc(Chunk.Loc);
6354 }
6355 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6356 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6357 TL.setStarLoc(Chunk.Loc);
6358 }
6359 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6360 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6361 TL.setStarLoc(Chunk.Loc);
6362 }
6363 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6364 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6365 TL.setStarLoc(Chunk.Mem.StarLoc);
6366 TL.setQualifierLoc(Chunk.Mem.Scope().getWithLocInContext(Context));
6367 }
6368 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6369 assert(Chunk.Kind == DeclaratorChunk::Reference);
6370 // 'Amp' is misleading: this might have been originally
6371 /// spelled with AmpAmp.
6372 TL.setAmpLoc(Chunk.Loc);
6373 }
6374 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6375 assert(Chunk.Kind == DeclaratorChunk::Reference);
6376 assert(!Chunk.Ref.LValueRef);
6377 TL.setAmpAmpLoc(Chunk.Loc);
6378 }
6379 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6380 assert(Chunk.Kind == DeclaratorChunk::Array);
6381 TL.setLBracketLoc(Chunk.Loc);
6382 TL.setRBracketLoc(Chunk.EndLoc);
6383 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6384 }
6385 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6386 assert(Chunk.Kind == DeclaratorChunk::Function);
6387 TL.setLocalRangeBegin(Chunk.Loc);
6388 TL.setLocalRangeEnd(Chunk.EndLoc);
6389
6390 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6391 TL.setLParenLoc(FTI.getLParenLoc());
6392 TL.setRParenLoc(FTI.getRParenLoc());
6393 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6394 ParmVarDecl *Param = cast<ParmVarDecl>(Val: FTI.Params[i].Param);
6395 TL.setParam(i: tpi++, VD: Param);
6396 }
6397 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6398 }
6399 void VisitParenTypeLoc(ParenTypeLoc TL) {
6400 assert(Chunk.Kind == DeclaratorChunk::Paren);
6401 TL.setLParenLoc(Chunk.Loc);
6402 TL.setRParenLoc(Chunk.EndLoc);
6403 }
6404 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6405 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6406 TL.setKWLoc(Chunk.Loc);
6407 }
6408 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6409 TL.setNameLoc(Chunk.Loc);
6410 }
6411 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6412 TL.setExpansionLoc(Chunk.Loc);
6413 }
6414 void VisitVectorTypeLoc(VectorTypeLoc TL) {
6415 TL.initializeLocal(Context, Loc: Chunk.Loc);
6416 fillVectorTypeLoc(VTL: TL, Attrs: Chunk.getAttrs());
6417 }
6418 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6419 TL.initializeLocal(Context, Loc: Chunk.Loc);
6420 }
6421 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6422 fillAtomicQualLoc(ATL: TL, Chunk);
6423 }
6424 void
6425 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6426 TL.initializeLocal(Context, Loc: Chunk.Loc);
6427 }
6428 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6429 fillMatrixTypeLoc(MTL: TL, Attrs: Chunk.getAttrs());
6430 }
6431
6432 void VisitTypeLoc(TypeLoc TL) {
6433 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6434 }
6435 };
6436} // end anonymous namespace
6437
6438static void fillDependentAddressSpaceTypeLoc(
6439 DependentAddressSpaceTypeLoc DASTL,
6440 ArrayRef<const ParsedAttributesView *> AttrLists) {
6441 for (const ParsedAttributesView *Attrs : AttrLists) {
6442 for (const ParsedAttr &AL : *Attrs) {
6443 // Skip invalid or malformed attributes; they did not produce a type.
6444 if (AL.getKind() != ParsedAttr::AT_AddressSpace || AL.isInvalid() ||
6445 AL.getNumArgs() != 1 || !AL.isArgExpr(Arg: 0))
6446 continue;
6447 DASTL.setAttrNameLoc(AL.getLoc());
6448 DASTL.setAttrExprOperand(AL.getArgAsExpr(Arg: 0));
6449 DASTL.setAttrOperandParensRange(SourceRange());
6450 return;
6451 }
6452 }
6453
6454 llvm_unreachable(
6455 "no address_space attribute found at the expected location!");
6456}
6457
6458/// Create and instantiate a TypeSourceInfo with type source information.
6459///
6460/// \param T QualType referring to the type as written in source code.
6461///
6462/// \param ReturnTypeInfo For declarators whose return type does not show
6463/// up in the normal place in the declaration specifiers (such as a C++
6464/// conversion function), this pointer will refer to a type source information
6465/// for that return type.
6466static TypeSourceInfo *
6467GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6468 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6469 Sema &S = State.getSema();
6470 Declarator &D = State.getDeclarator();
6471
6472 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6473 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6474
6475 // Handle parameter packs whose type is a pack expansion.
6476 if (isa<PackExpansionType>(Val: T)) {
6477 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6478 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6479 }
6480
6481 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6482 // Microsoft property fields can have multiple sizeless array chunks
6483 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6484 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6485 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6486 continue;
6487
6488 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6489 // declarator chunk.
6490 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6491 fillAtomicQualLoc(ATL, Chunk: D.getTypeObject(i));
6492 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6493 }
6494
6495 bool HasDesugaredTypeLoc = true;
6496 while (HasDesugaredTypeLoc) {
6497 switch (CurrTL.getTypeLocClass()) {
6498 case TypeLoc::MacroQualified: {
6499 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6500 TL.setExpansionLoc(
6501 State.getExpansionLocForMacroQualifiedType(MQT: TL.getTypePtr()));
6502 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6503 break;
6504 }
6505
6506 case TypeLoc::Attributed: {
6507 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6508 fillAttributedTypeLoc(TL, State);
6509 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6510 break;
6511 }
6512
6513 case TypeLoc::Adjusted:
6514 case TypeLoc::BTFTagAttributed: {
6515 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6516 break;
6517 }
6518
6519 case TypeLoc::DependentAddressSpace: {
6520 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6521 // An attribute written after the declarator-id appertains to the
6522 // declared entity, not to a chunk, so every attribute list of the
6523 // declarator has to be searched.
6524 fillDependentAddressSpaceTypeLoc(DASTL: TL, AttrLists: {&D.getTypeObject(i).getAttrs(),
6525 &D.getAttributes(),
6526 &D.getDeclSpec().getAttributes(),
6527 &D.getDeclarationAttributes()});
6528 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6529 break;
6530 }
6531
6532 default:
6533 HasDesugaredTypeLoc = false;
6534 break;
6535 }
6536 }
6537
6538 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(TyLoc: CurrTL);
6539 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6540 }
6541
6542 // If we have different source information for the return type, use
6543 // that. This really only applies to C++ conversion functions.
6544 if (ReturnTypeInfo) {
6545 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6546 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6547 memcpy(dest: CurrTL.getOpaqueData(), src: TL.getOpaqueData(), n: TL.getFullDataSize());
6548 } else {
6549 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(TyLoc: CurrTL);
6550 }
6551
6552 return TInfo;
6553}
6554
6555/// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6556ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6557 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6558 // and Sema during declaration parsing. Try deallocating/caching them when
6559 // it's appropriate, instead of allocating them and keeping them around.
6560 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(Size: sizeof(LocInfoType),
6561 Alignment: alignof(LocInfoType));
6562 new (LocT) LocInfoType(T, TInfo);
6563 assert(LocT->getTypeClass() != T->getTypeClass() &&
6564 "LocInfoType's TypeClass conflicts with an existing Type class");
6565 return ParsedType::make(P: QualType(LocT, 0));
6566}
6567
6568void LocInfoType::getAsStringInternal(std::string &Str,
6569 const PrintingPolicy &Policy) const {
6570 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6571 " was used directly instead of getting the QualType through"
6572 " GetTypeFromParser");
6573}
6574
6575TypeResult Sema::ActOnTypeName(Declarator &D) {
6576 // C99 6.7.6: Type names have no identifier. This is already validated by
6577 // the parser.
6578 assert(D.getIdentifier() == nullptr &&
6579 "Type name should have no identifier!");
6580
6581 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
6582 QualType T = TInfo->getType();
6583 if (D.isInvalidType())
6584 return true;
6585
6586 // Make sure there are no unused decl attributes on the declarator.
6587 // We don't want to do this for ObjC parameters because we're going
6588 // to apply them to the actual parameter declaration.
6589 // Likewise, we don't want to do this for alias declarations, because
6590 // we are actually going to build a declaration from this eventually.
6591 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6592 D.getContext() != DeclaratorContext::AliasDecl &&
6593 D.getContext() != DeclaratorContext::AliasTemplate)
6594 checkUnusedDeclAttributes(D);
6595
6596 if (getLangOpts().CPlusPlus) {
6597 // Check that there are no default arguments (C++ only).
6598 CheckExtraCXXDefaultArguments(D);
6599 }
6600
6601 if (AutoTypeLoc TL = TInfo->getTypeLoc().getContainedAutoTypeLoc()) {
6602 const AutoType *AT = TL.getTypePtr();
6603 CheckConstrainedAuto(AutoT: AT, Loc: TL.getConceptNameLoc());
6604 }
6605 return CreateParsedType(T, TInfo);
6606}
6607
6608//===----------------------------------------------------------------------===//
6609// Type Attribute Processing
6610//===----------------------------------------------------------------------===//
6611
6612/// Build an AddressSpace index from a constant expression and diagnose any
6613/// errors related to invalid address_spaces. Returns true on successfully
6614/// building an AddressSpace index.
6615static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6616 const Expr *AddrSpace,
6617 SourceLocation AttrLoc) {
6618 if (!AddrSpace->isValueDependent()) {
6619 std::optional<llvm::APSInt> OptAddrSpace =
6620 AddrSpace->getIntegerConstantExpr(Ctx: S.Context);
6621 if (!OptAddrSpace) {
6622 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type)
6623 << "'address_space'" << AANT_ArgumentIntegerConstant
6624 << AddrSpace->getSourceRange();
6625 return false;
6626 }
6627 llvm::APSInt &addrSpace = *OptAddrSpace;
6628
6629 // Bounds checking.
6630 if (addrSpace.isSigned()) {
6631 if (addrSpace.isNegative()) {
6632 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_space_negative)
6633 << AddrSpace->getSourceRange();
6634 return false;
6635 }
6636 addrSpace.setIsSigned(false);
6637 }
6638
6639 llvm::APSInt max(addrSpace.getBitWidth());
6640 max =
6641 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6642
6643 if (addrSpace > max) {
6644 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_space_too_high)
6645 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6646 return false;
6647 }
6648
6649 ASIdx =
6650 getLangASFromTargetAS(TargetAS: static_cast<unsigned>(addrSpace.getZExtValue()));
6651 return true;
6652 }
6653
6654 // Default value for DependentAddressSpaceTypes
6655 ASIdx = LangAS::Default;
6656 return true;
6657}
6658
6659QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6660 SourceLocation AttrLoc) {
6661 if (!AddrSpace->isValueDependent()) {
6662 if (DiagnoseMultipleAddrSpaceAttributes(S&: *this, ASOld: T.getAddressSpace(), ASNew: ASIdx,
6663 AttrLoc))
6664 return QualType();
6665
6666 return Context.getAddrSpaceQualType(T, AddressSpace: ASIdx);
6667 }
6668
6669 // A check with similar intentions as checking if a type already has an
6670 // address space except for on a dependent types, basically if the
6671 // current type is already a DependentAddressSpaceType then its already
6672 // lined up to have another address space on it and we can't have
6673 // multiple address spaces on the one pointer indirection
6674 if (T->getAs<DependentAddressSpaceType>()) {
6675 Diag(Loc: AttrLoc, DiagID: diag::err_attribute_address_multiple_qualifiers);
6676 return QualType();
6677 }
6678
6679 return Context.getDependentAddressSpaceType(PointeeType: T, AddrSpaceExpr: AddrSpace, AttrLoc);
6680}
6681
6682QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6683 SourceLocation AttrLoc) {
6684 LangAS ASIdx;
6685 if (!BuildAddressSpaceIndex(S&: *this, ASIdx, AddrSpace, AttrLoc))
6686 return QualType();
6687 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6688}
6689
6690static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6691 TypeProcessingState &State) {
6692 Sema &S = State.getSema();
6693
6694 // Ensure the argument is a string.
6695 auto *StrLiteral = dyn_cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0));
6696 if (!StrLiteral) {
6697 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
6698 << Attr << AANT_ArgumentString;
6699 Attr.setInvalid();
6700 return;
6701 }
6702
6703 ASTContext &Ctx = S.Context;
6704 StringRef BTFTypeTag = StrLiteral->getString();
6705 Type = State.getBTFTagAttributedType(
6706 BTFAttr: ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), WrappedType: Type);
6707}
6708
6709/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6710/// specified type. The attribute contains 1 argument, the id of the address
6711/// space for the type.
6712static void HandleAddressSpaceTypeAttribute(QualType &Type,
6713 const ParsedAttr &Attr,
6714 TypeProcessingState &State) {
6715 Sema &S = State.getSema();
6716
6717 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6718 // qualified by an address-space qualifier."
6719 if (Type->isFunctionType()) {
6720 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_address_function_type);
6721 Attr.setInvalid();
6722 return;
6723 }
6724
6725 LangAS ASIdx;
6726 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6727
6728 // Check the attribute arguments.
6729 if (Attr.getNumArgs() != 1) {
6730 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << Attr
6731 << 1;
6732 Attr.setInvalid();
6733 return;
6734 }
6735
6736 Expr *ASArgExpr = Attr.getArgAsExpr(Arg: 0);
6737 LangAS ASIdx;
6738 if (!BuildAddressSpaceIndex(S, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc())) {
6739 Attr.setInvalid();
6740 return;
6741 }
6742
6743 ASTContext &Ctx = S.Context;
6744 auto *ASAttr =
6745 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6746
6747 // If the expression is not value dependent (not templated), then we can
6748 // apply the address space qualifiers just to the equivalent type.
6749 // Otherwise, we make an AttributedType with the modified and equivalent
6750 // type the same, and wrap it in a DependentAddressSpaceType. When this
6751 // dependent type is resolved, the qualifier is added to the equivalent type
6752 // later.
6753 QualType T;
6754 if (!ASArgExpr->isValueDependent()) {
6755 QualType EquivType =
6756 S.BuildAddressSpaceAttr(T&: Type, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc());
6757 if (EquivType.isNull()) {
6758 Attr.setInvalid();
6759 return;
6760 }
6761 T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType);
6762 } else {
6763 T = State.getAttributedType(A: ASAttr, ModifiedType: Type, EquivType: Type);
6764 T = S.BuildAddressSpaceAttr(T, ASIdx, AddrSpace: ASArgExpr, AttrLoc: Attr.getLoc());
6765 }
6766
6767 if (!T.isNull())
6768 Type = T;
6769 else
6770 Attr.setInvalid();
6771 } else {
6772 // The keyword-based type attributes imply which address space to use.
6773 // The SYCL address space attributes are available in both SYCL host and
6774 // device compilation.
6775 ASIdx =
6776 S.getLangOpts().isSYCL() ? Attr.asSYCLLangAS() : Attr.asOpenCLLangAS();
6777 if (S.getLangOpts().HLSL)
6778 ASIdx = Attr.asHLSLLangAS();
6779
6780 if (ASIdx == LangAS::Default)
6781 llvm_unreachable("Invalid address space");
6782
6783 if (DiagnoseMultipleAddrSpaceAttributes(S, ASOld: Type.getAddressSpace(), ASNew: ASIdx,
6784 AttrLoc: Attr.getLoc())) {
6785 Attr.setInvalid();
6786 return;
6787 }
6788
6789 Type = S.Context.getAddrSpaceQualType(T: Type, AddressSpace: ASIdx);
6790 }
6791}
6792
6793static void HandleOverflowBehaviorAttr(QualType &Type, const ParsedAttr &Attr,
6794 TypeProcessingState &State) {
6795 Sema &S = State.getSema();
6796
6797 // Check for -fexperimental-overflow-behavior-types
6798 if (!S.getLangOpts().OverflowBehaviorTypes) {
6799 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_overflow_behavior_attribute_disabled)
6800 << Attr << 1;
6801 Attr.setInvalid();
6802 return;
6803 }
6804
6805 // Check the number of attribute arguments.
6806 if (Attr.getNumArgs() != 1) {
6807 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments)
6808 << Attr << 1;
6809 Attr.setInvalid();
6810 return;
6811 }
6812
6813 // Verify we aren't dealing with an atomic type
6814 if (Type->isAtomicType()) {
6815 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_overflow_behavior_atomic_type)
6816 << Attr << Type.getAsString() << 0; // 0 for attribute
6817 Attr.setInvalid();
6818 return;
6819 }
6820
6821 // Check that the underlying type is an integer type
6822 if (!Type->isIntegerType()) {
6823 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_overflow_behavior_non_integer_type)
6824 << Attr << Type.getAsString() << 0; // 0 for attribute
6825 Attr.setInvalid();
6826 return;
6827 }
6828
6829 StringRef KindName = "";
6830 IdentifierInfo *Ident = nullptr;
6831
6832 if (Attr.isArgIdent(Arg: 0)) {
6833 Ident = Attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6834 KindName = Ident->getName();
6835 }
6836
6837 // Support identifier or string argument types. Failure to provide one of
6838 // these two types results in a diagnostic that hints towards using string
6839 // arguments (either "wrap" or "trap") as this is the most common use
6840 // pattern.
6841 if (!Ident) {
6842 auto *Str = dyn_cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0));
6843 if (Str)
6844 KindName = Str->getString();
6845 else {
6846 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
6847 << Attr << AANT_ArgumentString;
6848 Attr.setInvalid();
6849 return;
6850 }
6851 }
6852
6853 OverflowBehaviorType::OverflowBehaviorKind Kind;
6854 if (KindName == "wrap") {
6855 Kind = OverflowBehaviorType::OverflowBehaviorKind::Wrap;
6856 } else if (KindName == "trap") {
6857 Kind = OverflowBehaviorType::OverflowBehaviorKind::Trap;
6858 } else {
6859 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_overflow_behavior_unknown_ident)
6860 << KindName << Attr;
6861 Attr.setInvalid();
6862 return;
6863 }
6864
6865 // Check for mixed specifier/attribute usage
6866 const DeclSpec &DS = State.getDeclarator().getDeclSpec();
6867 if (DS.isWrapSpecified() || DS.isTrapSpecified()) {
6868 // We have both specifier and attribute on the same type. If
6869 // OverflowBehaviorKinds are the same we can just warn.
6870 OverflowBehaviorType::OverflowBehaviorKind SpecifierKind =
6871 DS.isWrapSpecified() ? OverflowBehaviorType::OverflowBehaviorKind::Wrap
6872 : OverflowBehaviorType::OverflowBehaviorKind::Trap;
6873
6874 if (SpecifierKind != Kind) {
6875 StringRef SpecifierName = DS.isWrapSpecified() ? "wrap" : "trap";
6876 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_overflow_behaviors)
6877 << 1 << SpecifierName << KindName;
6878 Attr.setInvalid();
6879 return;
6880 }
6881 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_redundant_overflow_behaviors_mixed)
6882 << KindName;
6883 Attr.setInvalid();
6884 return;
6885 }
6886
6887 // Check for conflicting overflow behavior attributes
6888 if (const auto *ExistingOBT = Type->getAs<OverflowBehaviorType>()) {
6889 OverflowBehaviorType::OverflowBehaviorKind ExistingKind =
6890 ExistingOBT->getBehaviorKind();
6891 if (ExistingKind != Kind) {
6892 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_overflow_behaviors) << 0;
6893 if (Kind == OverflowBehaviorType::OverflowBehaviorKind::Trap) {
6894 Type = State.getOverflowBehaviorType(Kind,
6895 UnderlyingType: ExistingOBT->getUnderlyingType());
6896 }
6897 return;
6898 }
6899 } else {
6900 Type = State.getOverflowBehaviorType(Kind, UnderlyingType: Type);
6901 }
6902}
6903
6904/// handleObjCOwnershipTypeAttr - Process an objc_ownership
6905/// attribute on the specified type.
6906///
6907/// Returns 'true' if the attribute was handled.
6908static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6909 ParsedAttr &attr, QualType &type) {
6910 bool NonObjCPointer = false;
6911
6912 if (!type->isDependentType() && !type->isUndeducedType()) {
6913 if (const PointerType *ptr = type->getAs<PointerType>()) {
6914 QualType pointee = ptr->getPointeeType();
6915 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6916 return false;
6917 // It is important not to lose the source info that there was an attribute
6918 // applied to non-objc pointer. We will create an attributed type but
6919 // its type will be the same as the original type.
6920 NonObjCPointer = true;
6921 } else if (!type->isObjCRetainableType()) {
6922 return false;
6923 }
6924
6925 // Don't accept an ownership attribute in the declspec if it would
6926 // just be the return type of a block pointer.
6927 if (state.isProcessingDeclSpec()) {
6928 Declarator &D = state.getDeclarator();
6929 if (maybeMovePastReturnType(declarator&: D, i: D.getNumTypeObjects(),
6930 /*onlyBlockPointers=*/true))
6931 return false;
6932 }
6933 }
6934
6935 Sema &S = state.getSema();
6936 SourceLocation AttrLoc = attr.getLoc();
6937 if (AttrLoc.isMacroID())
6938 AttrLoc =
6939 S.getSourceManager().getImmediateExpansionRange(Loc: AttrLoc).getBegin();
6940
6941 if (!attr.isArgIdent(Arg: 0)) {
6942 S.Diag(Loc: AttrLoc, DiagID: diag::err_attribute_argument_type) << attr
6943 << AANT_ArgumentString;
6944 attr.setInvalid();
6945 return true;
6946 }
6947
6948 IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
6949 Qualifiers::ObjCLifetime lifetime;
6950 if (II->isStr(Str: "none"))
6951 lifetime = Qualifiers::OCL_ExplicitNone;
6952 else if (II->isStr(Str: "strong"))
6953 lifetime = Qualifiers::OCL_Strong;
6954 else if (II->isStr(Str: "weak"))
6955 lifetime = Qualifiers::OCL_Weak;
6956 else if (II->isStr(Str: "autoreleasing"))
6957 lifetime = Qualifiers::OCL_Autoreleasing;
6958 else {
6959 S.Diag(Loc: AttrLoc, DiagID: diag::warn_attribute_type_not_supported) << attr << II;
6960 attr.setInvalid();
6961 return true;
6962 }
6963
6964 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6965 // outside of ARC mode.
6966 if (!S.getLangOpts().ObjCAutoRefCount &&
6967 lifetime != Qualifiers::OCL_Weak &&
6968 lifetime != Qualifiers::OCL_ExplicitNone) {
6969 return true;
6970 }
6971
6972 SplitQualType underlyingType = type.split();
6973
6974 // Check for redundant/conflicting ownership qualifiers.
6975 if (Qualifiers::ObjCLifetime previousLifetime
6976 = type.getQualifiers().getObjCLifetime()) {
6977 // If it's written directly, that's an error.
6978 if (S.Context.hasDirectOwnershipQualifier(Ty: type)) {
6979 S.Diag(Loc: AttrLoc, DiagID: diag::err_attr_objc_ownership_redundant)
6980 << type;
6981 return true;
6982 }
6983
6984 // Otherwise, if the qualifiers actually conflict, pull sugar off
6985 // and remove the ObjCLifetime qualifiers.
6986 if (previousLifetime != lifetime) {
6987 // It's possible to have multiple local ObjCLifetime qualifiers. We
6988 // can't stop after we reach a type that is directly qualified.
6989 const Type *prevTy = nullptr;
6990 while (!prevTy || prevTy != underlyingType.Ty) {
6991 prevTy = underlyingType.Ty;
6992 underlyingType = underlyingType.getSingleStepDesugaredType();
6993 }
6994 underlyingType.Quals.removeObjCLifetime();
6995 }
6996 }
6997
6998 underlyingType.Quals.addObjCLifetime(type: lifetime);
6999
7000 if (NonObjCPointer) {
7001 StringRef name = attr.getAttrName()->getName();
7002 switch (lifetime) {
7003 case Qualifiers::OCL_None:
7004 case Qualifiers::OCL_ExplicitNone:
7005 break;
7006 case Qualifiers::OCL_Strong: name = "__strong"; break;
7007 case Qualifiers::OCL_Weak: name = "__weak"; break;
7008 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7009 }
7010 S.Diag(Loc: AttrLoc, DiagID: diag::warn_type_attribute_wrong_type) << name
7011 << TDS_ObjCObjOrBlock << type;
7012 }
7013
7014 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7015 // because having both 'T' and '__unsafe_unretained T' exist in the type
7016 // system causes unfortunate widespread consistency problems. (For example,
7017 // they're not considered compatible types, and we mangle them identicially
7018 // as template arguments.) These problems are all individually fixable,
7019 // but it's easier to just not add the qualifier and instead sniff it out
7020 // in specific places using isObjCInertUnsafeUnretainedType().
7021 //
7022 // Doing this does means we miss some trivial consistency checks that
7023 // would've triggered in ARC, but that's better than trying to solve all
7024 // the coexistence problems with __unsafe_unretained.
7025 if (!S.getLangOpts().ObjCAutoRefCount &&
7026 lifetime == Qualifiers::OCL_ExplicitNone) {
7027 type = state.getAttributedType(
7028 A: createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(Ctx&: S.Context, AL&: attr),
7029 ModifiedType: type, EquivType: type);
7030 return true;
7031 }
7032
7033 QualType origType = type;
7034 if (!NonObjCPointer)
7035 type = S.Context.getQualifiedType(split: underlyingType);
7036
7037 // If we have a valid source location for the attribute, use an
7038 // AttributedType instead.
7039 if (AttrLoc.isValid()) {
7040 type = state.getAttributedType(A: ::new (S.Context)
7041 ObjCOwnershipAttr(S.Context, attr, II),
7042 ModifiedType: origType, EquivType: type);
7043 }
7044
7045 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7046 unsigned diagnostic, QualType type) {
7047 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7048 S.DelayedDiagnostics.add(
7049 diag: sema::DelayedDiagnostic::makeForbiddenType(
7050 loc: S.getSourceManager().getExpansionLoc(Loc: loc),
7051 diagnostic, type, /*ignored*/ argument: 0));
7052 } else {
7053 S.Diag(Loc: loc, DiagID: diagnostic);
7054 }
7055 };
7056
7057 // Sometimes, __weak isn't allowed.
7058 if (lifetime == Qualifiers::OCL_Weak &&
7059 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7060
7061 // Use a specialized diagnostic if the runtime just doesn't support them.
7062 unsigned diagnostic =
7063 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7064 : diag::err_arc_weak_no_runtime);
7065
7066 // In any case, delay the diagnostic until we know what we're parsing.
7067 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7068
7069 attr.setInvalid();
7070 return true;
7071 }
7072
7073 // Forbid __weak for class objects marked as
7074 // objc_arc_weak_reference_unavailable
7075 if (lifetime == Qualifiers::OCL_Weak) {
7076 if (const ObjCObjectPointerType *ObjT =
7077 type->getAs<ObjCObjectPointerType>()) {
7078 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7079 if (Class->isArcWeakrefUnavailable()) {
7080 S.Diag(Loc: AttrLoc, DiagID: diag::err_arc_unsupported_weak_class);
7081 S.Diag(Loc: ObjT->getInterfaceDecl()->getLocation(),
7082 DiagID: diag::note_class_declared);
7083 }
7084 }
7085 }
7086 }
7087
7088 return true;
7089}
7090
7091/// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7092/// attribute on the specified type. Returns true to indicate that
7093/// the attribute was handled, false to indicate that the type does
7094/// not permit the attribute.
7095static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7096 QualType &type) {
7097 Sema &S = state.getSema();
7098
7099 // Delay if this isn't some kind of pointer.
7100 if (!type->isPointerType() &&
7101 !type->isObjCObjectPointerType() &&
7102 !type->isBlockPointerType())
7103 return false;
7104
7105 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7106 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_multiple_objc_gc);
7107 attr.setInvalid();
7108 return true;
7109 }
7110
7111 // Check the attribute arguments.
7112 if (!attr.isArgIdent(Arg: 0)) {
7113 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_argument_type)
7114 << attr << AANT_ArgumentString;
7115 attr.setInvalid();
7116 return true;
7117 }
7118 Qualifiers::GC GCAttr;
7119 if (attr.getNumArgs() > 1) {
7120 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << attr
7121 << 1;
7122 attr.setInvalid();
7123 return true;
7124 }
7125
7126 IdentifierInfo *II = attr.getArgAsIdent(Arg: 0)->getIdentifierInfo();
7127 if (II->isStr(Str: "weak"))
7128 GCAttr = Qualifiers::Weak;
7129 else if (II->isStr(Str: "strong"))
7130 GCAttr = Qualifiers::Strong;
7131 else {
7132 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_type_not_supported)
7133 << attr << II;
7134 attr.setInvalid();
7135 return true;
7136 }
7137
7138 QualType origType = type;
7139 type = S.Context.getObjCGCQualType(T: origType, gcAttr: GCAttr);
7140
7141 // Make an attributed type to preserve the source information.
7142 if (attr.getLoc().isValid())
7143 type = state.getAttributedType(
7144 A: ::new (S.Context) ObjCGCAttr(S.Context, attr, II), ModifiedType: origType, EquivType: type);
7145
7146 return true;
7147}
7148
7149namespace {
7150 /// A helper class to unwrap a type down to a function for the
7151 /// purposes of applying attributes there.
7152 ///
7153 /// Use:
7154 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7155 /// if (unwrapped.isFunctionType()) {
7156 /// const FunctionType *fn = unwrapped.get();
7157 /// // change fn somehow
7158 /// T = unwrapped.wrap(fn);
7159 /// }
7160 struct FunctionTypeUnwrapper {
7161 enum WrapKind {
7162 Desugar,
7163 Attributed,
7164 Parens,
7165 Array,
7166 Pointer,
7167 BlockPointer,
7168 Reference,
7169 MemberPointer,
7170 MacroQualified,
7171 };
7172
7173 QualType Original;
7174 const FunctionType *Fn;
7175 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7176
7177 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7178 while (true) {
7179 const Type *Ty = T.getTypePtr();
7180 if (isa<FunctionType>(Val: Ty)) {
7181 Fn = cast<FunctionType>(Val: Ty);
7182 return;
7183 } else if (isa<ParenType>(Val: Ty)) {
7184 T = cast<ParenType>(Val: Ty)->getInnerType();
7185 Stack.push_back(Elt: Parens);
7186 } else if (isa<ConstantArrayType>(Val: Ty) || isa<VariableArrayType>(Val: Ty) ||
7187 isa<IncompleteArrayType>(Val: Ty)) {
7188 T = cast<ArrayType>(Val: Ty)->getElementType();
7189 Stack.push_back(Elt: Array);
7190 } else if (isa<PointerType>(Val: Ty)) {
7191 T = cast<PointerType>(Val: Ty)->getPointeeType();
7192 Stack.push_back(Elt: Pointer);
7193 } else if (isa<BlockPointerType>(Val: Ty)) {
7194 T = cast<BlockPointerType>(Val: Ty)->getPointeeType();
7195 Stack.push_back(Elt: BlockPointer);
7196 } else if (isa<MemberPointerType>(Val: Ty)) {
7197 T = cast<MemberPointerType>(Val: Ty)->getPointeeType();
7198 Stack.push_back(Elt: MemberPointer);
7199 } else if (isa<ReferenceType>(Val: Ty)) {
7200 T = cast<ReferenceType>(Val: Ty)->getPointeeType();
7201 Stack.push_back(Elt: Reference);
7202 } else if (isa<AttributedType>(Val: Ty)) {
7203 T = cast<AttributedType>(Val: Ty)->getEquivalentType();
7204 Stack.push_back(Elt: Attributed);
7205 } else if (isa<MacroQualifiedType>(Val: Ty)) {
7206 T = cast<MacroQualifiedType>(Val: Ty)->getUnderlyingType();
7207 Stack.push_back(Elt: MacroQualified);
7208 } else {
7209 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7210 if (Ty == DTy) {
7211 Fn = nullptr;
7212 return;
7213 }
7214
7215 T = QualType(DTy, 0);
7216 Stack.push_back(Elt: Desugar);
7217 }
7218 }
7219 }
7220
7221 bool isFunctionType() const { return (Fn != nullptr); }
7222 const FunctionType *get() const { return Fn; }
7223
7224 QualType wrap(Sema &S, const FunctionType *New) {
7225 // If T wasn't modified from the unwrapped type, do nothing.
7226 if (New == get()) return Original;
7227
7228 Fn = New;
7229 return wrap(C&: S.Context, Old: Original, I: 0);
7230 }
7231
7232 private:
7233 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7234 if (I == Stack.size())
7235 return C.getQualifiedType(T: Fn, Qs: Old.getQualifiers());
7236
7237 // Build up the inner type, applying the qualifiers from the old
7238 // type to the new type.
7239 SplitQualType SplitOld = Old.split();
7240
7241 // As a special case, tail-recurse if there are no qualifiers.
7242 if (SplitOld.Quals.empty())
7243 return wrap(C, Old: SplitOld.Ty, I);
7244 return C.getQualifiedType(T: wrap(C, Old: SplitOld.Ty, I), Qs: SplitOld.Quals);
7245 }
7246
7247 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7248 if (I == Stack.size()) return QualType(Fn, 0);
7249
7250 switch (static_cast<WrapKind>(Stack[I++])) {
7251 case Desugar:
7252 // This is the point at which we potentially lose source
7253 // information.
7254 return wrap(C, Old: Old->getUnqualifiedDesugaredType(), I);
7255
7256 case Attributed:
7257 return wrap(C, Old: cast<AttributedType>(Val: Old)->getEquivalentType(), I);
7258
7259 case Parens: {
7260 QualType New = wrap(C, Old: cast<ParenType>(Val: Old)->getInnerType(), I);
7261 return C.getParenType(NamedType: New);
7262 }
7263
7264 case MacroQualified:
7265 return wrap(C, Old: cast<MacroQualifiedType>(Val: Old)->getUnderlyingType(), I);
7266
7267 case Array: {
7268 if (const auto *CAT = dyn_cast<ConstantArrayType>(Val: Old)) {
7269 QualType New = wrap(C, Old: CAT->getElementType(), I);
7270 return C.getConstantArrayType(EltTy: New, ArySize: CAT->getSize(), SizeExpr: CAT->getSizeExpr(),
7271 ASM: CAT->getSizeModifier(),
7272 IndexTypeQuals: CAT->getIndexTypeCVRQualifiers());
7273 }
7274
7275 if (const auto *VAT = dyn_cast<VariableArrayType>(Val: Old)) {
7276 QualType New = wrap(C, Old: VAT->getElementType(), I);
7277 return C.getVariableArrayType(EltTy: New, NumElts: VAT->getSizeExpr(),
7278 ASM: VAT->getSizeModifier(),
7279 IndexTypeQuals: VAT->getIndexTypeCVRQualifiers());
7280 }
7281
7282 const auto *IAT = cast<IncompleteArrayType>(Val: Old);
7283 QualType New = wrap(C, Old: IAT->getElementType(), I);
7284 return C.getIncompleteArrayType(EltTy: New, ASM: IAT->getSizeModifier(),
7285 IndexTypeQuals: IAT->getIndexTypeCVRQualifiers());
7286 }
7287
7288 case Pointer: {
7289 QualType New = wrap(C, Old: cast<PointerType>(Val: Old)->getPointeeType(), I);
7290 return C.getPointerType(T: New);
7291 }
7292
7293 case BlockPointer: {
7294 QualType New = wrap(C, Old: cast<BlockPointerType>(Val: Old)->getPointeeType(),I);
7295 return C.getBlockPointerType(T: New);
7296 }
7297
7298 case MemberPointer: {
7299 const MemberPointerType *OldMPT = cast<MemberPointerType>(Val: Old);
7300 QualType New = wrap(C, Old: OldMPT->getPointeeType(), I);
7301 return C.getMemberPointerType(T: New, Qualifier: OldMPT->getQualifier(),
7302 Cls: OldMPT->getMostRecentCXXRecordDecl());
7303 }
7304
7305 case Reference: {
7306 const ReferenceType *OldRef = cast<ReferenceType>(Val: Old);
7307 QualType New = wrap(C, Old: OldRef->getPointeeType(), I);
7308 if (isa<LValueReferenceType>(Val: OldRef))
7309 return C.getLValueReferenceType(T: New, SpelledAsLValue: OldRef->isSpelledAsLValue());
7310 else
7311 return C.getRValueReferenceType(T: New);
7312 }
7313 }
7314
7315 llvm_unreachable("unknown wrapping kind");
7316 }
7317 };
7318} // end anonymous namespace
7319
7320static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7321 ParsedAttr &PAttr, QualType &Type) {
7322 Sema &S = State.getSema();
7323
7324 Attr *A;
7325 switch (PAttr.getKind()) {
7326 default: llvm_unreachable("Unknown attribute kind");
7327 case ParsedAttr::AT_Ptr32:
7328 A = createSimpleAttr<Ptr32Attr>(Ctx&: S.Context, AL&: PAttr);
7329 break;
7330 case ParsedAttr::AT_Ptr64:
7331 A = createSimpleAttr<Ptr64Attr>(Ctx&: S.Context, AL&: PAttr);
7332 break;
7333 case ParsedAttr::AT_SPtr:
7334 A = createSimpleAttr<SPtrAttr>(Ctx&: S.Context, AL&: PAttr);
7335 break;
7336 case ParsedAttr::AT_UPtr:
7337 A = createSimpleAttr<UPtrAttr>(Ctx&: S.Context, AL&: PAttr);
7338 break;
7339 }
7340
7341 std::bitset<attr::LastAttr> Attrs;
7342 QualType Desugared = Type;
7343 for (;;) {
7344 if (const TypedefType *TT = dyn_cast<TypedefType>(Val&: Desugared)) {
7345 Desugared = TT->desugar();
7346 continue;
7347 }
7348 const AttributedType *AT = dyn_cast<AttributedType>(Val&: Desugared);
7349 if (!AT)
7350 break;
7351 Attrs[AT->getAttrKind()] = true;
7352 Desugared = AT->getModifiedType();
7353 }
7354
7355 // You cannot specify duplicate type attributes, so if the attribute has
7356 // already been applied, flag it.
7357 attr::Kind NewAttrKind = A->getKind();
7358 if (Attrs[NewAttrKind]) {
7359 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::warn_duplicate_attribute_exact) << PAttr;
7360 return true;
7361 }
7362 Attrs[NewAttrKind] = true;
7363
7364 // You cannot have both __sptr and __uptr on the same type, nor can you
7365 // have __ptr32 and __ptr64.
7366 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7367 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
7368 << "'__ptr32'"
7369 << "'__ptr64'" << /*isRegularKeyword=*/0;
7370 return true;
7371 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7372 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
7373 << "'__sptr'"
7374 << "'__uptr'" << /*isRegularKeyword=*/0;
7375 return true;
7376 }
7377
7378 // Check the raw (i.e., desugared) Canonical type to see if it
7379 // is a pointer type.
7380 if (!isa<PointerType>(Val: Desugared)) {
7381 // Pointer type qualifiers can only operate on pointer types, but not
7382 // pointer-to-member types.
7383 if (Type->isMemberPointerType())
7384 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_no_member_pointers) << PAttr;
7385 else
7386 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_pointers_only) << PAttr << 0;
7387 return true;
7388 }
7389
7390 // Add address space to type based on its attributes.
7391 LangAS ASIdx = LangAS::Default;
7392 uint64_t PtrWidth =
7393 S.Context.getTargetInfo().getPointerWidth(AddrSpace: LangAS::Default);
7394 if (PtrWidth == 32) {
7395 if (Attrs[attr::Ptr64])
7396 ASIdx = LangAS::ptr64;
7397 else if (Attrs[attr::UPtr])
7398 ASIdx = LangAS::ptr32_uptr;
7399 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7400 if (S.Context.getTargetInfo().getTriple().isOSzOS() || Attrs[attr::UPtr])
7401 ASIdx = LangAS::ptr32_uptr;
7402 else
7403 ASIdx = LangAS::ptr32_sptr;
7404 }
7405
7406 QualType Pointee = Type->getPointeeType();
7407 if (ASIdx != LangAS::Default)
7408 Pointee = S.Context.getAddrSpaceQualType(
7409 T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx);
7410
7411 QualType Equivalent = S.Context.getQualifiedType(
7412 T: S.Context.getPointerType(T: Pointee), Qs: Type.getQualifiers());
7413 Type = State.getAttributedType(A, ModifiedType: Type, EquivType: Equivalent);
7414 return false;
7415}
7416
7417static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7418 QualType &QT, ParsedAttr &PAttr) {
7419 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7420
7421 Sema &S = State.getSema();
7422 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(Ctx&: S.Context, AL&: PAttr);
7423
7424 std::bitset<attr::LastAttr> Attrs;
7425 attr::Kind NewAttrKind = A->getKind();
7426 const auto *AT = dyn_cast<AttributedType>(Val&: QT);
7427 while (AT) {
7428 Attrs[AT->getAttrKind()] = true;
7429 AT = dyn_cast<AttributedType>(Val: AT->getModifiedType());
7430 }
7431
7432 // You cannot specify duplicate type attributes, so if the attribute has
7433 // already been applied, flag it.
7434 if (Attrs[NewAttrKind]) {
7435 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::warn_duplicate_attribute_exact) << PAttr;
7436 return true;
7437 }
7438
7439 // Check that the type is a function pointer type.
7440 QualType Desugared = QT.getDesugaredType(Context: S.Context);
7441 const auto *Ptr = dyn_cast<PointerType>(Val&: Desugared);
7442 if (!Ptr || !Ptr->getPointeeType()->isFunctionType()) {
7443 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_attribute_webassembly_funcref);
7444 return true;
7445 }
7446
7447 // Add address space to type based on its attributes.
7448 LangAS ASIdx = LangAS::wasm_funcref;
7449 QualType Pointee = QT->getPointeeType();
7450 Pointee = S.Context.getAddrSpaceQualType(
7451 T: S.Context.removeAddrSpaceQualType(T: Pointee), AddressSpace: ASIdx);
7452
7453 QualType Equivalent = S.Context.getQualifiedType(
7454 T: S.Context.getPointerType(T: Pointee), Qs: QT.getQualifiers());
7455 QT = State.getAttributedType(A, ModifiedType: QT, EquivType: Equivalent);
7456 return false;
7457}
7458
7459static void HandleSwiftAttr(TypeProcessingState &State, TypeAttrLocation TAL,
7460 QualType &QT, ParsedAttr &PAttr) {
7461 if (TAL == TAL_DeclName)
7462 return;
7463
7464 Sema &S = State.getSema();
7465 auto &D = State.getDeclarator();
7466
7467 // If the attribute appears in declaration specifiers
7468 // it should be handled as a declaration attribute,
7469 // unless it's associated with a type or a function
7470 // prototype (i.e. appears on a parameter or result type).
7471 if (State.isProcessingDeclSpec()) {
7472 if (!(D.isPrototypeContext() ||
7473 D.getContext() == DeclaratorContext::TypeName))
7474 return;
7475
7476 if (auto *chunk = D.getInnermostNonParenChunk()) {
7477 moveAttrFromListToList(attr&: PAttr, fromList&: State.getCurrentAttributes(),
7478 toList&: const_cast<DeclaratorChunk *>(chunk)->getAttrs());
7479 return;
7480 }
7481 }
7482
7483 StringRef Str;
7484 if (!S.checkStringLiteralArgumentAttr(Attr: PAttr, ArgNum: 0, Str)) {
7485 PAttr.setInvalid();
7486 return;
7487 }
7488
7489 // If the attribute as attached to a paren move it closer to
7490 // the declarator. This can happen in block declarations when
7491 // an attribute is placed before `^` i.e. `(__attribute__((...)) ^)`.
7492 //
7493 // Note that it's actually invalid to use GNU style attributes
7494 // in a block but such cases are currently handled gracefully
7495 // but the parser and behavior should be consistent between
7496 // cases when attribute appears before/after block's result
7497 // type and inside (^).
7498 if (TAL == TAL_DeclChunk) {
7499 auto chunkIdx = State.getCurrentChunkIndex();
7500 if (chunkIdx >= 1 &&
7501 D.getTypeObject(i: chunkIdx).Kind == DeclaratorChunk::Paren) {
7502 moveAttrFromListToList(attr&: PAttr, fromList&: State.getCurrentAttributes(),
7503 toList&: D.getTypeObject(i: chunkIdx - 1).getAttrs());
7504 return;
7505 }
7506 }
7507
7508 auto *A = ::new (S.Context) SwiftAttrAttr(S.Context, PAttr, Str);
7509 QT = State.getAttributedType(A, ModifiedType: QT, EquivType: QT);
7510 PAttr.setUsedAsTypeAttr();
7511}
7512
7513/// Rebuild an attributed type without the nullability attribute on it.
7514static QualType rebuildAttributedTypeWithoutNullability(ASTContext &Ctx,
7515 QualType Type) {
7516 auto Attributed = dyn_cast<AttributedType>(Val: Type.getTypePtr());
7517 if (!Attributed)
7518 return Type;
7519
7520 // Skip the nullability attribute; we're done.
7521 if (Attributed->getImmediateNullability())
7522 return Attributed->getModifiedType();
7523
7524 // Build the modified type.
7525 QualType Modified = rebuildAttributedTypeWithoutNullability(
7526 Ctx, Type: Attributed->getModifiedType());
7527 assert(Modified.getTypePtr() != Attributed->getModifiedType().getTypePtr());
7528 return Ctx.getAttributedType(attrKind: Attributed->getAttrKind(), modifiedType: Modified,
7529 equivalentType: Attributed->getEquivalentType(),
7530 attr: Attributed->getAttr());
7531}
7532
7533/// Map a nullability attribute kind to a nullability kind.
7534static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7535 switch (kind) {
7536 case ParsedAttr::AT_TypeNonNull:
7537 return NullabilityKind::NonNull;
7538
7539 case ParsedAttr::AT_TypeNullable:
7540 return NullabilityKind::Nullable;
7541
7542 case ParsedAttr::AT_TypeNullableResult:
7543 return NullabilityKind::NullableResult;
7544
7545 case ParsedAttr::AT_TypeNullUnspecified:
7546 return NullabilityKind::Unspecified;
7547
7548 default:
7549 llvm_unreachable("not a nullability attribute kind");
7550 }
7551}
7552
7553static bool CheckNullabilityTypeSpecifier(
7554 Sema &S, TypeProcessingState *State, ParsedAttr *PAttr, QualType &QT,
7555 NullabilityKind Nullability, SourceLocation NullabilityLoc,
7556 bool IsContextSensitive, bool AllowOnArrayType, bool OverrideExisting) {
7557 bool Implicit = (State == nullptr);
7558 if (!Implicit)
7559 recordNullabilitySeen(S, loc: NullabilityLoc);
7560
7561 // Check for existing nullability attributes on the type.
7562 QualType Desugared = QT;
7563 while (auto *Attributed = dyn_cast<AttributedType>(Val: Desugared.getTypePtr())) {
7564 // Check whether there is already a null
7565 if (auto ExistingNullability = Attributed->getImmediateNullability()) {
7566 // Duplicated nullability.
7567 if (Nullability == *ExistingNullability) {
7568 if (Implicit)
7569 break;
7570
7571 S.Diag(Loc: NullabilityLoc, DiagID: diag::warn_nullability_duplicate)
7572 << DiagNullabilityKind(Nullability, IsContextSensitive)
7573 << FixItHint::CreateRemoval(RemoveRange: NullabilityLoc);
7574
7575 break;
7576 }
7577
7578 if (!OverrideExisting) {
7579 // Conflicting nullability.
7580 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_conflicting)
7581 << DiagNullabilityKind(Nullability, IsContextSensitive)
7582 << DiagNullabilityKind(*ExistingNullability, false);
7583 return true;
7584 }
7585
7586 // Rebuild the attributed type, dropping the existing nullability.
7587 QT = rebuildAttributedTypeWithoutNullability(Ctx&: S.Context, Type: QT);
7588 }
7589
7590 Desugared = Attributed->getModifiedType();
7591 }
7592
7593 // If there is already a different nullability specifier, complain.
7594 // This (unlike the code above) looks through typedefs that might
7595 // have nullability specifiers on them, which means we cannot
7596 // provide a useful Fix-It.
7597 if (auto ExistingNullability = Desugared->getNullability()) {
7598 if (Nullability != *ExistingNullability && !Implicit) {
7599 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_conflicting)
7600 << DiagNullabilityKind(Nullability, IsContextSensitive)
7601 << DiagNullabilityKind(*ExistingNullability, false);
7602
7603 // Try to find the typedef with the existing nullability specifier.
7604 if (auto TT = Desugared->getAs<TypedefType>()) {
7605 TypedefNameDecl *typedefDecl = TT->getDecl();
7606 QualType underlyingType = typedefDecl->getUnderlyingType();
7607 if (auto typedefNullability =
7608 AttributedType::stripOuterNullability(T&: underlyingType)) {
7609 if (*typedefNullability == *ExistingNullability) {
7610 S.Diag(Loc: typedefDecl->getLocation(), DiagID: diag::note_nullability_here)
7611 << DiagNullabilityKind(*ExistingNullability, false);
7612 }
7613 }
7614 }
7615
7616 return true;
7617 }
7618 }
7619
7620 // If this definitely isn't a pointer type, reject the specifier.
7621 if (!Desugared->canHaveNullability() &&
7622 !(AllowOnArrayType && Desugared->isArrayType())) {
7623 if (!Implicit)
7624 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_nonpointer)
7625 << DiagNullabilityKind(Nullability, IsContextSensitive) << QT;
7626
7627 return true;
7628 }
7629
7630 // For the context-sensitive keywords/Objective-C property
7631 // attributes, require that the type be a single-level pointer.
7632 if (IsContextSensitive) {
7633 // Make sure that the pointee isn't itself a pointer type.
7634 const Type *pointeeType = nullptr;
7635 if (Desugared->isArrayType())
7636 pointeeType = Desugared->getArrayElementTypeNoTypeQual();
7637 else if (Desugared->isAnyPointerType())
7638 pointeeType = Desugared->getPointeeType().getTypePtr();
7639
7640 if (pointeeType && (pointeeType->isAnyPointerType() ||
7641 pointeeType->isObjCObjectPointerType() ||
7642 pointeeType->isMemberPointerType())) {
7643 S.Diag(Loc: NullabilityLoc, DiagID: diag::err_nullability_cs_multilevel)
7644 << DiagNullabilityKind(Nullability, true) << QT;
7645 S.Diag(Loc: NullabilityLoc, DiagID: diag::note_nullability_type_specifier)
7646 << DiagNullabilityKind(Nullability, false) << QT
7647 << FixItHint::CreateReplacement(RemoveRange: NullabilityLoc,
7648 Code: getNullabilitySpelling(kind: Nullability));
7649 return true;
7650 }
7651 }
7652
7653 // Form the attributed type.
7654 if (State) {
7655 assert(PAttr);
7656 Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: *PAttr, NK: Nullability);
7657 QT = State->getAttributedType(A, ModifiedType: QT, EquivType: QT);
7658 } else {
7659 QT = S.Context.getAttributedType(nullability: Nullability, modifiedType: QT, equivalentType: QT);
7660 }
7661 return false;
7662}
7663
7664static bool CheckNullabilityTypeSpecifier(TypeProcessingState &State,
7665 QualType &Type, ParsedAttr &Attr,
7666 bool AllowOnArrayType) {
7667 NullabilityKind Nullability = mapNullabilityAttrKind(kind: Attr.getKind());
7668 SourceLocation NullabilityLoc = Attr.getLoc();
7669 bool IsContextSensitive = Attr.isContextSensitiveKeywordAttribute();
7670
7671 return CheckNullabilityTypeSpecifier(S&: State.getSema(), State: &State, PAttr: &Attr, QT&: Type,
7672 Nullability, NullabilityLoc,
7673 IsContextSensitive, AllowOnArrayType,
7674 /*overrideExisting*/ OverrideExisting: false);
7675}
7676
7677bool Sema::CheckImplicitNullabilityTypeSpecifier(QualType &Type,
7678 NullabilityKind Nullability,
7679 SourceLocation DiagLoc,
7680 bool AllowArrayTypes,
7681 bool OverrideExisting) {
7682 return CheckNullabilityTypeSpecifier(
7683 S&: *this, State: nullptr, PAttr: nullptr, QT&: Type, Nullability, NullabilityLoc: DiagLoc,
7684 /*isContextSensitive*/ IsContextSensitive: false, AllowOnArrayType: AllowArrayTypes, OverrideExisting);
7685}
7686
7687bool Sema::CheckVarDeclSizeAddressSpace(const VarDecl *VD, LangAS AS) {
7688 QualType T = VD->getType();
7689
7690 // Check that the variable's type can fit in the specified address space. This
7691 // is determined by how far a pointer in that address space can reach.
7692 llvm::APInt MaxSizeForAddrSpace =
7693 llvm::APInt::getMaxValue(numBits: Context.getTargetInfo().getPointerWidth(AddrSpace: AS));
7694 std::optional<CharUnits> TSizeInChars = Context.getTypeSizeInCharsIfKnown(Ty: T);
7695 if (TSizeInChars && static_cast<uint64_t>(TSizeInChars->getQuantity()) >
7696 MaxSizeForAddrSpace.getZExtValue()) {
7697 Diag(Loc: VD->getLocation(), DiagID: diag::err_type_too_large_for_address_space)
7698 << T << MaxSizeForAddrSpace;
7699 return false;
7700 }
7701
7702 return true;
7703}
7704
7705/// Check the application of the Objective-C '__kindof' qualifier to
7706/// the given type.
7707static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7708 ParsedAttr &attr) {
7709 Sema &S = state.getSema();
7710
7711 if (isa<ObjCTypeParamType>(Val: type)) {
7712 // Build the attributed type to record where __kindof occurred.
7713 type = state.getAttributedType(
7714 A: createSimpleAttr<ObjCKindOfAttr>(Ctx&: S.Context, AL&: attr), ModifiedType: type, EquivType: type);
7715 return false;
7716 }
7717
7718 // Find out if it's an Objective-C object or object pointer type;
7719 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7720 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7721 : type->getAs<ObjCObjectType>();
7722
7723 // If not, we can't apply __kindof.
7724 if (!objType) {
7725 // FIXME: Handle dependent types that aren't yet object types.
7726 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_objc_kindof_nonobject)
7727 << type;
7728 return true;
7729 }
7730
7731 // Rebuild the "equivalent" type, which pushes __kindof down into
7732 // the object type.
7733 // There is no need to apply kindof on an unqualified id type.
7734 QualType equivType = S.Context.getObjCObjectType(
7735 Base: objType->getBaseType(), typeArgs: objType->getTypeArgsAsWritten(),
7736 protocols: objType->getProtocols(),
7737 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7738
7739 // If we started with an object pointer type, rebuild it.
7740 if (ptrType) {
7741 equivType = S.Context.getObjCObjectPointerType(OIT: equivType);
7742 if (auto nullability = type->getNullability()) {
7743 // We create a nullability attribute from the __kindof attribute.
7744 // Make sure that will make sense.
7745 assert(attr.getAttributeSpellingListIndex() == 0 &&
7746 "multiple spellings for __kindof?");
7747 Attr *A = createNullabilityAttr(Ctx&: S.Context, Attr&: attr, NK: *nullability);
7748 A->setImplicit(true);
7749 equivType = state.getAttributedType(A, ModifiedType: equivType, EquivType: equivType);
7750 }
7751 }
7752
7753 // Build the attributed type to record where __kindof occurred.
7754 type = state.getAttributedType(
7755 A: createSimpleAttr<ObjCKindOfAttr>(Ctx&: S.Context, AL&: attr), ModifiedType: type, EquivType: equivType);
7756 return false;
7757}
7758
7759/// Distribute a nullability type attribute that cannot be applied to
7760/// the type specifier to a pointer, block pointer, or member pointer
7761/// declarator, complaining if necessary.
7762///
7763/// \returns true if the nullability annotation was distributed, false
7764/// otherwise.
7765static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7766 QualType type, ParsedAttr &attr) {
7767 Declarator &declarator = state.getDeclarator();
7768
7769 /// Attempt to move the attribute to the specified chunk.
7770 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7771 // If there is already a nullability attribute there, don't add
7772 // one.
7773 if (hasNullabilityAttr(attrs: chunk.getAttrs()))
7774 return false;
7775
7776 // Complain about the nullability qualifier being in the wrong
7777 // place.
7778 enum {
7779 PK_Pointer,
7780 PK_BlockPointer,
7781 PK_MemberPointer,
7782 PK_FunctionPointer,
7783 PK_MemberFunctionPointer,
7784 } pointerKind
7785 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7786 : PK_Pointer)
7787 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7788 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7789
7790 auto diag = state.getSema().Diag(Loc: attr.getLoc(),
7791 DiagID: diag::warn_nullability_declspec)
7792 << DiagNullabilityKind(mapNullabilityAttrKind(kind: attr.getKind()),
7793 attr.isContextSensitiveKeywordAttribute())
7794 << type
7795 << static_cast<unsigned>(pointerKind);
7796
7797 // FIXME: MemberPointer chunks don't carry the location of the *.
7798 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7799 diag << FixItHint::CreateRemoval(RemoveRange: attr.getLoc())
7800 << FixItHint::CreateInsertion(
7801 InsertionLoc: state.getSema().getPreprocessor().getLocForEndOfToken(
7802 Loc: chunk.Loc),
7803 Code: " " + attr.getAttrName()->getName().str() + " ");
7804 }
7805
7806 moveAttrFromListToList(attr, fromList&: state.getCurrentAttributes(),
7807 toList&: chunk.getAttrs());
7808 return true;
7809 };
7810
7811 // Move it to the outermost pointer, member pointer, or block
7812 // pointer declarator.
7813 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7814 DeclaratorChunk &chunk = declarator.getTypeObject(i: i-1);
7815 switch (chunk.Kind) {
7816 case DeclaratorChunk::Pointer:
7817 case DeclaratorChunk::BlockPointer:
7818 case DeclaratorChunk::MemberPointer:
7819 return moveToChunk(chunk, false);
7820
7821 case DeclaratorChunk::Paren:
7822 case DeclaratorChunk::Array:
7823 continue;
7824
7825 case DeclaratorChunk::Function:
7826 // Try to move past the return type to a function/block/member
7827 // function pointer.
7828 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7829 declarator, i,
7830 /*onlyBlockPointers=*/false)) {
7831 return moveToChunk(*dest, true);
7832 }
7833
7834 return false;
7835
7836 // Don't walk through these.
7837 case DeclaratorChunk::Reference:
7838 case DeclaratorChunk::Pipe:
7839 return false;
7840 }
7841 }
7842
7843 return false;
7844}
7845
7846static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7847 assert(!Attr.isInvalid());
7848 switch (Attr.getKind()) {
7849 default:
7850 llvm_unreachable("not a calling convention attribute");
7851 case ParsedAttr::AT_CDecl:
7852 return createSimpleAttr<CDeclAttr>(Ctx, AL&: Attr);
7853 case ParsedAttr::AT_FastCall:
7854 return createSimpleAttr<FastCallAttr>(Ctx, AL&: Attr);
7855 case ParsedAttr::AT_StdCall:
7856 return createSimpleAttr<StdCallAttr>(Ctx, AL&: Attr);
7857 case ParsedAttr::AT_ThisCall:
7858 return createSimpleAttr<ThisCallAttr>(Ctx, AL&: Attr);
7859 case ParsedAttr::AT_RegCall:
7860 return createSimpleAttr<RegCallAttr>(Ctx, AL&: Attr);
7861 case ParsedAttr::AT_Pascal:
7862 return createSimpleAttr<PascalAttr>(Ctx, AL&: Attr);
7863 case ParsedAttr::AT_SwiftCall:
7864 return createSimpleAttr<SwiftCallAttr>(Ctx, AL&: Attr);
7865 case ParsedAttr::AT_SwiftAsyncCall:
7866 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, AL&: Attr);
7867 case ParsedAttr::AT_VectorCall:
7868 return createSimpleAttr<VectorCallAttr>(Ctx, AL&: Attr);
7869 case ParsedAttr::AT_AArch64VectorPcs:
7870 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, AL&: Attr);
7871 case ParsedAttr::AT_AArch64SVEPcs:
7872 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, AL&: Attr);
7873 case ParsedAttr::AT_ArmStreaming:
7874 return createSimpleAttr<ArmStreamingAttr>(Ctx, AL&: Attr);
7875 case ParsedAttr::AT_Pcs: {
7876 // The attribute may have had a fixit applied where we treated an
7877 // identifier as a string literal. The contents of the string are valid,
7878 // but the form may not be.
7879 StringRef Str;
7880 if (Attr.isArgExpr(Arg: 0))
7881 Str = cast<StringLiteral>(Val: Attr.getArgAsExpr(Arg: 0))->getString();
7882 else
7883 Str = Attr.getArgAsIdent(Arg: 0)->getIdentifierInfo()->getName();
7884 PcsAttr::PCSType Type;
7885 if (!PcsAttr::ConvertStrToPCSType(Val: Str, Out&: Type))
7886 llvm_unreachable("already validated the attribute");
7887 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7888 }
7889 case ParsedAttr::AT_IntelOclBicc:
7890 return createSimpleAttr<IntelOclBiccAttr>(Ctx, AL&: Attr);
7891 case ParsedAttr::AT_MSABI:
7892 return createSimpleAttr<MSABIAttr>(Ctx, AL&: Attr);
7893 case ParsedAttr::AT_SysVABI:
7894 return createSimpleAttr<SysVABIAttr>(Ctx, AL&: Attr);
7895 case ParsedAttr::AT_PreserveMost:
7896 return createSimpleAttr<PreserveMostAttr>(Ctx, AL&: Attr);
7897 case ParsedAttr::AT_PreserveAll:
7898 return createSimpleAttr<PreserveAllAttr>(Ctx, AL&: Attr);
7899 case ParsedAttr::AT_M68kRTD:
7900 return createSimpleAttr<M68kRTDAttr>(Ctx, AL&: Attr);
7901 case ParsedAttr::AT_PreserveNone:
7902 return createSimpleAttr<PreserveNoneAttr>(Ctx, AL&: Attr);
7903 case ParsedAttr::AT_RISCVVectorCC:
7904 return createSimpleAttr<RISCVVectorCCAttr>(Ctx, AL&: Attr);
7905 case ParsedAttr::AT_RISCVVLSCC: {
7906 // If the riscv_abi_vlen doesn't have any argument, we set set it to default
7907 // value 128.
7908 unsigned ABIVLen = 128;
7909 if (Attr.getNumArgs()) {
7910 std::optional<llvm::APSInt> MaybeABIVLen =
7911 Attr.getArgAsExpr(Arg: 0)->getIntegerConstantExpr(Ctx);
7912 if (!MaybeABIVLen)
7913 llvm_unreachable("Invalid RISC-V ABI VLEN");
7914 ABIVLen = MaybeABIVLen->getZExtValue();
7915 }
7916
7917 return ::new (Ctx) RISCVVLSCCAttr(Ctx, Attr, ABIVLen);
7918 }
7919 }
7920 llvm_unreachable("unexpected attribute kind!");
7921}
7922
7923std::optional<FunctionEffectMode>
7924Sema::ActOnEffectExpression(Expr *CondExpr, StringRef AttributeName) {
7925 if (CondExpr->isTypeDependent() || CondExpr->isValueDependent())
7926 return FunctionEffectMode::Dependent;
7927
7928 std::optional<llvm::APSInt> ConditionValue =
7929 CondExpr->getIntegerConstantExpr(Ctx: Context);
7930 if (!ConditionValue) {
7931 // FIXME: err_attribute_argument_type doesn't quote the attribute
7932 // name but needs to; users are inconsistent.
7933 Diag(Loc: CondExpr->getExprLoc(), DiagID: diag::err_attribute_argument_type)
7934 << AttributeName << AANT_ArgumentIntegerConstant
7935 << CondExpr->getSourceRange();
7936 return std::nullopt;
7937 }
7938 return !ConditionValue->isZero() ? FunctionEffectMode::True
7939 : FunctionEffectMode::False;
7940}
7941
7942static bool
7943handleNonBlockingNonAllocatingTypeAttr(TypeProcessingState &TPState,
7944 ParsedAttr &PAttr, QualType &QT,
7945 FunctionTypeUnwrapper &Unwrapped) {
7946 // Delay if this is not a function type.
7947 if (!Unwrapped.isFunctionType())
7948 return false;
7949
7950 Sema &S = TPState.getSema();
7951
7952 // Require FunctionProtoType.
7953 auto *FPT = Unwrapped.get()->getAs<FunctionProtoType>();
7954 if (FPT == nullptr) {
7955 S.Diag(Loc: PAttr.getLoc(), DiagID: diag::err_func_with_effects_no_prototype)
7956 << PAttr.getAttrName()->getName();
7957 return true;
7958 }
7959
7960 // Parse the new attribute.
7961 // non/blocking or non/allocating? Or conditional (computed)?
7962 bool IsNonBlocking = PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7963 PAttr.getKind() == ParsedAttr::AT_Blocking;
7964
7965 FunctionEffectMode NewMode = FunctionEffectMode::None;
7966 Expr *CondExpr = nullptr; // only valid if dependent
7967
7968 if (PAttr.getKind() == ParsedAttr::AT_NonBlocking ||
7969 PAttr.getKind() == ParsedAttr::AT_NonAllocating) {
7970 if (!PAttr.checkAtMostNumArgs(S, Num: 1)) {
7971 PAttr.setInvalid();
7972 return true;
7973 }
7974
7975 // Parse the condition, if any.
7976 if (PAttr.getNumArgs() == 1) {
7977 CondExpr = PAttr.getArgAsExpr(Arg: 0);
7978 std::optional<FunctionEffectMode> MaybeMode =
7979 S.ActOnEffectExpression(CondExpr, AttributeName: PAttr.getAttrName()->getName());
7980 if (!MaybeMode) {
7981 PAttr.setInvalid();
7982 return true;
7983 }
7984 NewMode = *MaybeMode;
7985 if (NewMode != FunctionEffectMode::Dependent)
7986 CondExpr = nullptr;
7987 } else {
7988 NewMode = FunctionEffectMode::True;
7989 }
7990 } else {
7991 // This is the `blocking` or `allocating` attribute.
7992 if (S.CheckAttrNoArgs(CurrAttr: PAttr)) {
7993 // The attribute has been marked invalid.
7994 return true;
7995 }
7996 NewMode = FunctionEffectMode::False;
7997 }
7998
7999 const FunctionEffect::Kind FEKind =
8000 (NewMode == FunctionEffectMode::False)
8001 ? (IsNonBlocking ? FunctionEffect::Kind::Blocking
8002 : FunctionEffect::Kind::Allocating)
8003 : (IsNonBlocking ? FunctionEffect::Kind::NonBlocking
8004 : FunctionEffect::Kind::NonAllocating);
8005 const FunctionEffectWithCondition NewEC{FunctionEffect(FEKind),
8006 EffectConditionExpr(CondExpr)};
8007
8008 if (S.diagnoseConflictingFunctionEffect(FX: FPT->getFunctionEffects(), EC: NewEC,
8009 NewAttrLoc: PAttr.getLoc())) {
8010 PAttr.setInvalid();
8011 return true;
8012 }
8013
8014 // Add the effect to the FunctionProtoType.
8015 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
8016 FunctionEffectSet FX(EPI.FunctionEffects);
8017 FunctionEffectSet::Conflicts Errs;
8018 [[maybe_unused]] bool Success = FX.insert(NewEC, Errs);
8019 assert(Success && "effect conflicts should have been diagnosed above");
8020 EPI.FunctionEffects = FunctionEffectsRef(FX);
8021
8022 QualType NewType = S.Context.getFunctionType(ResultTy: FPT->getReturnType(),
8023 Args: FPT->getParamTypes(), EPI);
8024 QT = Unwrapped.wrap(S, New: NewType->getAs<FunctionType>());
8025 return true;
8026}
8027
8028static bool checkMutualExclusion(TypeProcessingState &state,
8029 const FunctionProtoType::ExtProtoInfo &EPI,
8030 ParsedAttr &Attr,
8031 AttributeCommonInfo::Kind OtherKind) {
8032 auto OtherAttr = llvm::find_if(
8033 Range&: state.getCurrentAttributes(),
8034 P: [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
8035 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
8036 return false;
8037
8038 Sema &S = state.getSema();
8039 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8040 << *OtherAttr << Attr
8041 << (OtherAttr->isRegularKeywordAttribute() ||
8042 Attr.isRegularKeywordAttribute());
8043 S.Diag(Loc: OtherAttr->getLoc(), DiagID: diag::note_conflicting_attribute);
8044 Attr.setInvalid();
8045 return true;
8046}
8047
8048static bool handleArmAgnosticAttribute(Sema &S,
8049 FunctionProtoType::ExtProtoInfo &EPI,
8050 ParsedAttr &Attr) {
8051 if (!Attr.getNumArgs()) {
8052 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_missing_arm_state) << Attr;
8053 Attr.setInvalid();
8054 return true;
8055 }
8056
8057 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8058 StringRef StateName;
8059 SourceLocation LiteralLoc;
8060 if (!S.checkStringLiteralArgumentAttr(Attr, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc))
8061 return true;
8062
8063 if (StateName != "sme_za_state") {
8064 S.Diag(Loc: LiteralLoc, DiagID: diag::err_unknown_arm_state) << StateName;
8065 Attr.setInvalid();
8066 return true;
8067 }
8068
8069 if (EPI.AArch64SMEAttributes &
8070 (FunctionType::SME_ZAMask | FunctionType::SME_ZT0Mask)) {
8071 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_conflicting_attributes_arm_agnostic);
8072 Attr.setInvalid();
8073 return true;
8074 }
8075
8076 EPI.setArmSMEAttribute(Kind: FunctionType::SME_AgnosticZAStateMask);
8077 }
8078
8079 return false;
8080}
8081
8082static bool handleArmStateAttribute(Sema &S,
8083 FunctionProtoType::ExtProtoInfo &EPI,
8084 ParsedAttr &Attr,
8085 FunctionType::ArmStateValue State) {
8086 if (!Attr.getNumArgs()) {
8087 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_missing_arm_state) << Attr;
8088 Attr.setInvalid();
8089 return true;
8090 }
8091
8092 for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {
8093 StringRef StateName;
8094 SourceLocation LiteralLoc;
8095 if (!S.checkStringLiteralArgumentAttr(Attr, ArgNum: I, Str&: StateName, ArgLocation: &LiteralLoc))
8096 return true;
8097
8098 unsigned Shift;
8099 FunctionType::ArmStateValue ExistingState;
8100 if (StateName == "za") {
8101 Shift = FunctionType::SME_ZAShift;
8102 ExistingState = FunctionType::getArmZAState(AttrBits: EPI.AArch64SMEAttributes);
8103 } else if (StateName == "zt0") {
8104 Shift = FunctionType::SME_ZT0Shift;
8105 ExistingState = FunctionType::getArmZT0State(AttrBits: EPI.AArch64SMEAttributes);
8106 } else {
8107 S.Diag(Loc: LiteralLoc, DiagID: diag::err_unknown_arm_state) << StateName;
8108 Attr.setInvalid();
8109 return true;
8110 }
8111
8112 if (EPI.AArch64SMEAttributes & FunctionType::SME_AgnosticZAStateMask) {
8113 S.Diag(Loc: LiteralLoc, DiagID: diag::err_conflicting_attributes_arm_agnostic);
8114 Attr.setInvalid();
8115 return true;
8116 }
8117
8118 // __arm_in(S), __arm_out(S), __arm_inout(S) and __arm_preserves(S)
8119 // are all mutually exclusive for the same S, so check if there are
8120 // conflicting attributes.
8121 if (ExistingState != FunctionType::ARM_None && ExistingState != State) {
8122 S.Diag(Loc: LiteralLoc, DiagID: diag::err_conflicting_attributes_arm_state)
8123 << StateName;
8124 Attr.setInvalid();
8125 return true;
8126 }
8127
8128 EPI.setArmSMEAttribute(
8129 Kind: (FunctionType::AArch64SMETypeAttributes)((State << Shift)));
8130 }
8131 return false;
8132}
8133
8134/// Process an individual function attribute. Returns true to
8135/// indicate that the attribute was handled, false if it wasn't.
8136static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
8137 QualType &type, CUDAFunctionTarget CFT) {
8138 Sema &S = state.getSema();
8139
8140 FunctionTypeUnwrapper unwrapped(S, type);
8141
8142 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
8143 if (S.CheckAttrNoArgs(CurrAttr: attr))
8144 return true;
8145
8146 // Delay if this is not a function type.
8147 if (!unwrapped.isFunctionType())
8148 return false;
8149
8150 // Otherwise we can process right away.
8151 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(noReturn: true);
8152 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8153 return true;
8154 }
8155
8156 if (attr.getKind() == ParsedAttr::AT_CFIUncheckedCallee) {
8157 // Delay if this is not a prototyped function type.
8158 if (!unwrapped.isFunctionType())
8159 return false;
8160
8161 if (!unwrapped.get()->isFunctionProtoType()) {
8162 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
8163 << attr << attr.isRegularKeywordAttribute()
8164 << ExpectedFunctionWithProtoType;
8165 attr.setInvalid();
8166 return true;
8167 }
8168
8169 const auto *FPT = unwrapped.get()->getAs<FunctionProtoType>();
8170 type = S.Context.getFunctionType(
8171 ResultTy: FPT->getReturnType(), Args: FPT->getParamTypes(),
8172 EPI: FPT->getExtProtoInfo().withCFIUncheckedCallee(CFIUncheckedCallee: true));
8173 type = unwrapped.wrap(S, New: cast<FunctionType>(Val: type.getTypePtr()));
8174 return true;
8175 }
8176
8177 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
8178 // Delay if this is not a function type.
8179 if (!unwrapped.isFunctionType())
8180 return false;
8181
8182 // Ignore if we don't have CMSE enabled.
8183 if (!S.getLangOpts().Cmse) {
8184 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_ignored) << attr;
8185 attr.setInvalid();
8186 return true;
8187 }
8188
8189 // Otherwise we can process right away.
8190 FunctionType::ExtInfo EI =
8191 unwrapped.get()->getExtInfo().withCmseNSCall(cmseNSCall: true);
8192 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8193 return true;
8194 }
8195
8196 // ns_returns_retained is not always a type attribute, but if we got
8197 // here, we're treating it as one right now.
8198 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
8199 if (attr.getNumArgs()) return true;
8200
8201 // Delay if this is not a function type.
8202 if (!unwrapped.isFunctionType())
8203 return false;
8204
8205 // Check whether the return type is reasonable.
8206 if (S.ObjC().checkNSReturnsRetainedReturnType(
8207 loc: attr.getLoc(), type: unwrapped.get()->getReturnType()))
8208 return true;
8209
8210 // Only actually change the underlying type in ARC builds.
8211 QualType origType = type;
8212 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
8213 FunctionType::ExtInfo EI
8214 = unwrapped.get()->getExtInfo().withProducesResult(producesResult: true);
8215 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8216 }
8217 type = state.getAttributedType(
8218 A: createSimpleAttr<NSReturnsRetainedAttr>(Ctx&: S.Context, AL&: attr),
8219 ModifiedType: origType, EquivType: type);
8220 return true;
8221 }
8222
8223 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
8224 if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr))
8225 return true;
8226
8227 // Delay if this is not a function type.
8228 if (!unwrapped.isFunctionType())
8229 return false;
8230
8231 FunctionType::ExtInfo EI =
8232 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(noCallerSavedRegs: true);
8233 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8234 return true;
8235 }
8236
8237 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
8238 if (!S.getLangOpts().CFProtectionBranch) {
8239 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_nocf_check_attribute_ignored);
8240 attr.setInvalid();
8241 return true;
8242 }
8243
8244 if (S.CheckAttrTarget(CurrAttr: attr) || S.CheckAttrNoArgs(CurrAttr: attr))
8245 return true;
8246
8247 // If this is not a function type, warning will be asserted by subject
8248 // check.
8249 if (!unwrapped.isFunctionType())
8250 return true;
8251
8252 FunctionType::ExtInfo EI =
8253 unwrapped.get()->getExtInfo().withNoCfCheck(noCfCheck: true);
8254 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8255 return true;
8256 }
8257
8258 if (attr.getKind() == ParsedAttr::AT_Regparm) {
8259 unsigned value;
8260 if (S.CheckRegparmAttr(attr, value))
8261 return true;
8262
8263 // Delay if this is not a function type.
8264 if (!unwrapped.isFunctionType())
8265 return false;
8266
8267 // Diagnose regparm with fastcall.
8268 const FunctionType *fn = unwrapped.get();
8269 CallingConv CC = fn->getCallConv();
8270 if (CC == CC_X86FastCall) {
8271 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8272 << FunctionType::getNameForCallConv(CC) << "regparm"
8273 << attr.isRegularKeywordAttribute();
8274 attr.setInvalid();
8275 return true;
8276 }
8277
8278 FunctionType::ExtInfo EI =
8279 unwrapped.get()->getExtInfo().withRegParm(RegParm: value);
8280 type = unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8281 return true;
8282 }
8283
8284 if (attr.getKind() == ParsedAttr::AT_CFISalt) {
8285 if (attr.getNumArgs() != 1)
8286 return true;
8287
8288 StringRef Argument;
8289 if (!S.checkStringLiteralArgumentAttr(Attr: attr, ArgNum: 0, Str&: Argument))
8290 return true;
8291
8292 // Delay if this is not a function type.
8293 if (!unwrapped.isFunctionType())
8294 return false;
8295
8296 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8297 if (!FnTy) {
8298 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
8299 << attr << attr.isRegularKeywordAttribute()
8300 << ExpectedFunctionWithProtoType;
8301 attr.setInvalid();
8302 return true;
8303 }
8304
8305 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8306 EPI.ExtraAttributeInfo.CFISalt = Argument;
8307
8308 QualType newtype = S.Context.getFunctionType(ResultTy: FnTy->getReturnType(),
8309 Args: FnTy->getParamTypes(), EPI);
8310 type = unwrapped.wrap(S, New: newtype->getAs<FunctionType>());
8311 return true;
8312 }
8313
8314 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8315 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8316 attr.getKind() == ParsedAttr::AT_ArmPreserves ||
8317 attr.getKind() == ParsedAttr::AT_ArmIn ||
8318 attr.getKind() == ParsedAttr::AT_ArmOut ||
8319 attr.getKind() == ParsedAttr::AT_ArmInOut ||
8320 attr.getKind() == ParsedAttr::AT_ArmAgnostic) {
8321 if (S.CheckAttrTarget(CurrAttr: attr))
8322 return true;
8323
8324 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8325 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible)
8326 if (S.CheckAttrNoArgs(CurrAttr: attr))
8327 return true;
8328
8329 if (!unwrapped.isFunctionType())
8330 return false;
8331
8332 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8333 if (!FnTy) {
8334 // SME ACLE attributes are not supported on K&R-style unprototyped C
8335 // functions.
8336 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_wrong_decl_type)
8337 << attr << attr.isRegularKeywordAttribute()
8338 << ExpectedFunctionWithProtoType;
8339 attr.setInvalid();
8340 return false;
8341 }
8342
8343 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8344 switch (attr.getKind()) {
8345 case ParsedAttr::AT_ArmStreaming:
8346 if (checkMutualExclusion(state, EPI, Attr&: attr,
8347 OtherKind: ParsedAttr::AT_ArmStreamingCompatible))
8348 return true;
8349 EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMEnabledMask);
8350 break;
8351 case ParsedAttr::AT_ArmStreamingCompatible:
8352 if (checkMutualExclusion(state, EPI, Attr&: attr, OtherKind: ParsedAttr::AT_ArmStreaming))
8353 return true;
8354 EPI.setArmSMEAttribute(Kind: FunctionType::SME_PStateSMCompatibleMask);
8355 break;
8356 case ParsedAttr::AT_ArmPreserves:
8357 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Preserves))
8358 return true;
8359 break;
8360 case ParsedAttr::AT_ArmIn:
8361 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_In))
8362 return true;
8363 break;
8364 case ParsedAttr::AT_ArmOut:
8365 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_Out))
8366 return true;
8367 break;
8368 case ParsedAttr::AT_ArmInOut:
8369 if (handleArmStateAttribute(S, EPI, Attr&: attr, State: FunctionType::ARM_InOut))
8370 return true;
8371 break;
8372 case ParsedAttr::AT_ArmAgnostic:
8373 if (handleArmAgnosticAttribute(S, EPI, Attr&: attr))
8374 return true;
8375 break;
8376 default:
8377 llvm_unreachable("Unsupported attribute");
8378 }
8379
8380 QualType newtype = S.Context.getFunctionType(ResultTy: FnTy->getReturnType(),
8381 Args: FnTy->getParamTypes(), EPI);
8382 type = unwrapped.wrap(S, New: newtype->getAs<FunctionType>());
8383 return true;
8384 }
8385
8386 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8387 // Delay if this is not a function type.
8388 if (!unwrapped.isFunctionType())
8389 return false;
8390
8391 if (S.CheckAttrNoArgs(CurrAttr: attr)) {
8392 attr.setInvalid();
8393 return true;
8394 }
8395
8396 // Otherwise we can process right away.
8397 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8398
8399 // MSVC ignores nothrow if it is in conflict with an explicit exception
8400 // specification.
8401 if (Proto->hasExceptionSpec()) {
8402 switch (Proto->getExceptionSpecType()) {
8403 case EST_None:
8404 llvm_unreachable("This doesn't have an exception spec!");
8405
8406 case EST_DynamicNone:
8407 case EST_BasicNoexcept:
8408 case EST_NoexceptTrue:
8409 case EST_NoThrow:
8410 // Exception spec doesn't conflict with nothrow, so don't warn.
8411 [[fallthrough]];
8412 case EST_Unparsed:
8413 case EST_Uninstantiated:
8414 case EST_DependentNoexcept:
8415 case EST_Unevaluated:
8416 // We don't have enough information to properly determine if there is a
8417 // conflict, so suppress the warning.
8418 break;
8419 case EST_Dynamic:
8420 case EST_MSAny:
8421 case EST_NoexceptFalse:
8422 S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_nothrow_attribute_ignored);
8423 break;
8424 }
8425 return true;
8426 }
8427
8428 type = unwrapped.wrap(
8429 S, New: S.Context
8430 .getFunctionTypeWithExceptionSpec(
8431 Orig: QualType{Proto, 0},
8432 ESI: FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8433 ->getAs<FunctionType>());
8434 return true;
8435 }
8436
8437 if (attr.getKind() == ParsedAttr::AT_NonBlocking ||
8438 attr.getKind() == ParsedAttr::AT_NonAllocating ||
8439 attr.getKind() == ParsedAttr::AT_Blocking ||
8440 attr.getKind() == ParsedAttr::AT_Allocating) {
8441 return handleNonBlockingNonAllocatingTypeAttr(TPState&: state, PAttr&: attr, QT&: type, Unwrapped&: unwrapped);
8442 }
8443
8444 // Delay if the type didn't work out to a function.
8445 if (!unwrapped.isFunctionType()) return false;
8446
8447 // Otherwise, a calling convention.
8448 CallingConv CC;
8449 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/FD: nullptr, CFT))
8450 return true;
8451
8452 const FunctionType *fn = unwrapped.get();
8453 CallingConv CCOld = fn->getCallConv();
8454 Attr *CCAttr = getCCTypeAttr(Ctx&: S.Context, Attr&: attr);
8455
8456 if (CCOld != CC) {
8457 // Error out on when there's already an attribute on the type
8458 // and the CCs don't match.
8459 if (S.getCallingConvAttributedType(T: type)) {
8460 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8461 << FunctionType::getNameForCallConv(CC)
8462 << FunctionType::getNameForCallConv(CC: CCOld)
8463 << attr.isRegularKeywordAttribute();
8464 attr.setInvalid();
8465 return true;
8466 }
8467 }
8468
8469 // Diagnose use of variadic functions with calling conventions that
8470 // don't support them (e.g. because they're callee-cleanup).
8471 // We delay warning about this on unprototyped function declarations
8472 // until after redeclaration checking, just in case we pick up a
8473 // prototype that way. And apparently we also "delay" warning about
8474 // unprototyped function types in general, despite not necessarily having
8475 // much ability to diagnose it later.
8476 if (!supportsVariadicCall(CC)) {
8477 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(Val: fn);
8478 if (FnP && FnP->isVariadic()) {
8479 // stdcall and fastcall are ignored with a warning for GCC and MS
8480 // compatibility.
8481 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8482 return S.Diag(Loc: attr.getLoc(), DiagID: diag::warn_cconv_unsupported)
8483 << FunctionType::getNameForCallConv(CC)
8484 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8485
8486 attr.setInvalid();
8487 return S.Diag(Loc: attr.getLoc(), DiagID: diag::err_cconv_varargs)
8488 << FunctionType::getNameForCallConv(CC);
8489 }
8490 }
8491
8492 // Also diagnose fastcall with regparm.
8493 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8494 S.Diag(Loc: attr.getLoc(), DiagID: diag::err_attributes_are_not_compatible)
8495 << "regparm" << FunctionType::getNameForCallConv(CC: CC_X86FastCall)
8496 << attr.isRegularKeywordAttribute();
8497 attr.setInvalid();
8498 return true;
8499 }
8500
8501 // Modify the CC from the wrapped function type, wrap it all back, and then
8502 // wrap the whole thing in an AttributedType as written. The modified type
8503 // might have a different CC if we ignored the attribute.
8504 QualType Equivalent;
8505 if (CCOld == CC) {
8506 Equivalent = type;
8507 } else {
8508 auto EI = unwrapped.get()->getExtInfo().withCallingConv(cc: CC);
8509 Equivalent =
8510 unwrapped.wrap(S, New: S.Context.adjustFunctionType(Fn: unwrapped.get(), EInfo: EI));
8511 }
8512 type = state.getAttributedType(A: CCAttr, ModifiedType: type, EquivType: Equivalent);
8513 return true;
8514}
8515
8516bool Sema::hasExplicitCallingConv(QualType T) {
8517 const AttributedType *AT;
8518
8519 // Stop if we'd be stripping off a typedef sugar node to reach the
8520 // AttributedType.
8521 while ((AT = T->getAs<AttributedType>()) &&
8522 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8523 if (AT->isCallingConv())
8524 return true;
8525 T = AT->getModifiedType();
8526 }
8527 return false;
8528}
8529
8530void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8531 bool IsCtorOrDtor, SourceLocation Loc) {
8532 FunctionTypeUnwrapper Unwrapped(*this, T);
8533 const FunctionType *FT = Unwrapped.get();
8534 bool IsVariadic = (isa<FunctionProtoType>(Val: FT) &&
8535 cast<FunctionProtoType>(Val: FT)->isVariadic());
8536 CallingConv CurCC = FT->getCallConv();
8537 CallingConv ToCC =
8538 Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: HasThisPointer);
8539
8540 if (CurCC == ToCC)
8541 return;
8542
8543 // MS compiler ignores explicit calling convention attributes on structors. We
8544 // should do the same.
8545 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8546 // Issue a warning on ignored calling convention -- except of __stdcall.
8547 // Again, this is what MS compiler does.
8548 if (CurCC != CC_X86StdCall)
8549 Diag(Loc, DiagID: diag::warn_cconv_unsupported)
8550 << FunctionType::getNameForCallConv(CC: CurCC)
8551 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8552 // Default adjustment.
8553 } else {
8554 // Only adjust types with the default convention. For example, on Windows
8555 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8556 // __thiscall type to __cdecl for static methods.
8557 CallingConv DefaultCC =
8558 Context.getDefaultCallingConvention(IsVariadic, IsCXXMethod: !HasThisPointer);
8559
8560 if (CurCC != DefaultCC)
8561 return;
8562
8563 if (hasExplicitCallingConv(T))
8564 return;
8565 }
8566
8567 FT = Context.adjustFunctionType(Fn: FT, EInfo: FT->getExtInfo().withCallingConv(cc: ToCC));
8568 QualType Wrapped = Unwrapped.wrap(S&: *this, New: FT);
8569 T = Context.getAdjustedType(Orig: T, New: Wrapped);
8570}
8571
8572/// HandleVectorSizeAttribute - this attribute is only applicable to integral
8573/// and float scalars, although arrays, pointers, and function return values are
8574/// allowed in conjunction with this construct. Aggregates with this attribute
8575/// are invalid, even if they are of the same size as a corresponding scalar.
8576/// The raw attribute should contain precisely 1 argument, the vector size for
8577/// the variable, measured in bytes. If curType and rawAttr are well formed,
8578/// this routine will return a new vector type.
8579static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8580 Sema &S) {
8581 // Check the attribute arguments.
8582 if (Attr.getNumArgs() != 1) {
8583 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_number_arguments) << Attr
8584 << 1;
8585 Attr.setInvalid();
8586 return;
8587 }
8588
8589 Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0);
8590 QualType T = S.BuildVectorType(CurType, SizeExpr, AttrLoc: Attr.getLoc());
8591 if (!T.isNull())
8592 CurType = T;
8593 else
8594 Attr.setInvalid();
8595}
8596
8597/// Process the OpenCL-like ext_vector_type attribute when it occurs on
8598/// a type.
8599static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8600 Sema &S) {
8601 Expr *SizeExpr = Attr.getArgAsExpr(Arg: 0);
8602 QualType T = S.BuildExtVectorType(T: CurType, SizeExpr, AttrLoc: Attr.getLoc());
8603 if (!T.isNull())
8604 CurType = T;
8605}
8606
8607static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8608 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8609 if (!BTy)
8610 return false;
8611
8612 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8613
8614 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8615 // now.
8616 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8617 Triple.getArch() == llvm::Triple::aarch64_32 ||
8618 Triple.getArch() == llvm::Triple::aarch64_be;
8619 if (VecKind == VectorKind::NeonPoly) {
8620 if (IsPolyUnsigned) {
8621 // AArch64 polynomial vectors are unsigned.
8622 return BTy->getKind() == BuiltinType::UChar ||
8623 BTy->getKind() == BuiltinType::UShort ||
8624 BTy->getKind() == BuiltinType::ULong ||
8625 BTy->getKind() == BuiltinType::ULongLong;
8626 } else {
8627 // AArch32 polynomial vectors are signed.
8628 return BTy->getKind() == BuiltinType::SChar ||
8629 BTy->getKind() == BuiltinType::Short ||
8630 BTy->getKind() == BuiltinType::LongLong;
8631 }
8632 }
8633
8634 // Non-polynomial vector types: the usual suspects are allowed, as well as
8635 // float64_t on AArch64.
8636 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8637 BTy->getKind() == BuiltinType::Double)
8638 return true;
8639
8640 return BTy->getKind() == BuiltinType::SChar ||
8641 BTy->getKind() == BuiltinType::UChar ||
8642 BTy->getKind() == BuiltinType::Short ||
8643 BTy->getKind() == BuiltinType::UShort ||
8644 BTy->getKind() == BuiltinType::Int ||
8645 BTy->getKind() == BuiltinType::UInt ||
8646 BTy->getKind() == BuiltinType::Long ||
8647 BTy->getKind() == BuiltinType::ULong ||
8648 BTy->getKind() == BuiltinType::LongLong ||
8649 BTy->getKind() == BuiltinType::ULongLong ||
8650 BTy->getKind() == BuiltinType::Float ||
8651 BTy->getKind() == BuiltinType::Half ||
8652 BTy->getKind() == BuiltinType::BFloat16 ||
8653 BTy->getKind() == BuiltinType::MFloat8;
8654}
8655
8656static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8657 llvm::APSInt &Result) {
8658 const auto *AttrExpr = Attr.getArgAsExpr(Arg: 0);
8659 if (!AttrExpr->isTypeDependent()) {
8660 if (std::optional<llvm::APSInt> Res =
8661 AttrExpr->getIntegerConstantExpr(Ctx: S.Context)) {
8662 Result = *Res;
8663 return true;
8664 }
8665 }
8666 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_argument_type)
8667 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8668 Attr.setInvalid();
8669 return false;
8670}
8671
8672/// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8673/// "neon_polyvector_type" attributes are used to create vector types that
8674/// are mangled according to ARM's ABI. Otherwise, these types are identical
8675/// to those created with the "vector_size" attribute. Unlike "vector_size"
8676/// the argument to these Neon attributes is the number of vector elements,
8677/// not the vector size in bytes. The vector width and element type must
8678/// match one of the standard Neon vector types.
8679static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8680 Sema &S, VectorKind VecKind) {
8681 bool IsTargetOffloading = S.getLangOpts().isTargetDevice();
8682
8683 // Target must have NEON (or MVE, whose vectors are similar enough
8684 // not to need a separate attribute)
8685 if (!S.Context.getTargetInfo().hasFeature(Feature: "mve") &&
8686 VecKind == VectorKind::Neon &&
8687 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8688 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported_m_profile)
8689 << Attr << "'mve'";
8690 Attr.setInvalid();
8691 return;
8692 }
8693 if (!S.Context.getTargetInfo().hasFeature(Feature: "mve") &&
8694 VecKind == VectorKind::NeonPoly &&
8695 S.Context.getTargetInfo().getTriple().isArmMClass()) {
8696 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported_m_profile)
8697 << Attr << "'mve'";
8698 Attr.setInvalid();
8699 return;
8700 }
8701
8702 // The number of elements must be an ICE.
8703 llvm::APSInt numEltsInt(32);
8704 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: numEltsInt))
8705 return;
8706
8707 // Only certain element types are supported for Neon vectors.
8708 if (!isPermittedNeonBaseType(Ty&: CurType, VecKind, S) && !IsTargetOffloading) {
8709 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_vector_type) << CurType;
8710 Attr.setInvalid();
8711 return;
8712 }
8713
8714 // The total size of the vector must be 64 or 128 bits.
8715 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(T: CurType));
8716 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8717 unsigned vecSize = typeSize * numElts;
8718 if (vecSize != 64 && vecSize != 128) {
8719 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_neon_vector_size) << CurType;
8720 Attr.setInvalid();
8721 return;
8722 }
8723
8724 CurType = S.Context.getVectorType(VectorType: CurType, NumElts: numElts, VecKind);
8725}
8726
8727/// Handle the __ptrauth qualifier.
8728static void HandlePtrAuthQualifier(ASTContext &Ctx, QualType &T,
8729 const ParsedAttr &Attr, Sema &S) {
8730
8731 assert((Attr.getNumArgs() > 0 && Attr.getNumArgs() <= 3) &&
8732 "__ptrauth qualifier takes between 1 and 3 arguments");
8733 Expr *KeyArg = Attr.getArgAsExpr(Arg: 0);
8734 Expr *IsAddressDiscriminatedArg =
8735 Attr.getNumArgs() >= 2 ? Attr.getArgAsExpr(Arg: 1) : nullptr;
8736 Expr *ExtraDiscriminatorArg =
8737 Attr.getNumArgs() >= 3 ? Attr.getArgAsExpr(Arg: 2) : nullptr;
8738
8739 unsigned Key;
8740 if (S.checkConstantPointerAuthKey(keyExpr: KeyArg, key&: Key)) {
8741 Attr.setInvalid();
8742 return;
8743 }
8744 assert(Key <= PointerAuthQualifier::MaxKey && "ptrauth key is out of range");
8745
8746 bool IsInvalid = false;
8747 unsigned IsAddressDiscriminated, ExtraDiscriminator;
8748 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(Arg: IsAddressDiscriminatedArg,
8749 Kind: PointerAuthDiscArgKind::Addr,
8750 IntVal&: IsAddressDiscriminated);
8751 IsInvalid |= !S.checkPointerAuthDiscriminatorArg(
8752 Arg: ExtraDiscriminatorArg, Kind: PointerAuthDiscArgKind::Extra, IntVal&: ExtraDiscriminator);
8753
8754 if (IsInvalid) {
8755 Attr.setInvalid();
8756 return;
8757 }
8758
8759 if (!T->isSignableType(Ctx) && !T->isDependentType()) {
8760 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_qualifier_invalid_target) << T;
8761 Attr.setInvalid();
8762 return;
8763 }
8764
8765 if (T.getPointerAuth()) {
8766 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_qualifier_redundant) << T;
8767 Attr.setInvalid();
8768 return;
8769 }
8770
8771 if (!S.getLangOpts().PointerAuthIntrinsics) {
8772 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_ptrauth_disabled) << Attr.getRange();
8773 Attr.setInvalid();
8774 return;
8775 }
8776
8777 assert((!IsAddressDiscriminatedArg || IsAddressDiscriminated <= 1) &&
8778 "address discriminator arg should be either 0 or 1");
8779 PointerAuthQualifier Qual = PointerAuthQualifier::Create(
8780 Key, IsAddressDiscriminated, ExtraDiscriminator,
8781 AuthenticationMode: PointerAuthenticationMode::SignAndAuth, /*IsIsaPointer=*/false,
8782 /*AuthenticatesNullValues=*/false);
8783 T = S.Context.getPointerAuthType(Ty: T, PointerAuth: Qual);
8784}
8785
8786/// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8787/// used to create fixed-length versions of sizeless SVE types defined by
8788/// the ACLE, such as svint32_t and svbool_t.
8789static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8790 Sema &S) {
8791 // Target must have SVE.
8792 if (!S.Context.getTargetInfo().hasFeature(Feature: "sve")) {
8793 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported) << Attr << "'sve'";
8794 Attr.setInvalid();
8795 return;
8796 }
8797
8798 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8799 // if <bits>+ syntax is used.
8800 if (!S.getLangOpts().VScaleMin ||
8801 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8802 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_arm_feature_sve_bits_unsupported)
8803 << Attr;
8804 Attr.setInvalid();
8805 return;
8806 }
8807
8808 // The vector size must be an integer constant expression.
8809 llvm::APSInt SveVectorSizeInBits(32);
8810 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: SveVectorSizeInBits))
8811 return;
8812
8813 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8814
8815 // The attribute vector size must match -msve-vector-bits.
8816 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8817 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_sve_vector_size)
8818 << VecSize << S.getLangOpts().VScaleMin * 128;
8819 Attr.setInvalid();
8820 return;
8821 }
8822
8823 // Attribute can only be attached to a single SVE vector or predicate type.
8824 if (!CurType->isSveVLSBuiltinType()) {
8825 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_sve_type)
8826 << Attr << CurType;
8827 Attr.setInvalid();
8828 return;
8829 }
8830
8831 const auto *BT = CurType->castAs<BuiltinType>();
8832
8833 QualType EltType = CurType->getSveEltType(Ctx: S.Context);
8834 unsigned TypeSize = S.Context.getTypeSize(T: EltType);
8835 VectorKind VecKind = VectorKind::SveFixedLengthData;
8836 if (BT->getKind() == BuiltinType::SveBool) {
8837 // Predicates are represented as i8.
8838 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8839 VecKind = VectorKind::SveFixedLengthPredicate;
8840 } else
8841 VecSize /= TypeSize;
8842 CurType = S.Context.getVectorType(VectorType: EltType, NumElts: VecSize, VecKind);
8843}
8844
8845static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8846 QualType &CurType,
8847 ParsedAttr &Attr) {
8848 const VectorType *VT = dyn_cast<VectorType>(Val&: CurType);
8849 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8850 State.getSema().Diag(Loc: Attr.getLoc(),
8851 DiagID: diag::err_attribute_arm_mve_polymorphism);
8852 Attr.setInvalid();
8853 return;
8854 }
8855
8856 CurType =
8857 State.getAttributedType(A: createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8858 Ctx&: State.getSema().Context, AL&: Attr),
8859 ModifiedType: CurType, EquivType: CurType);
8860}
8861
8862/// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8863/// used to create fixed-length versions of sizeless RVV types such as
8864/// vint8m1_t_t.
8865static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8866 ParsedAttr &Attr, Sema &S) {
8867 // Target must have vector extension.
8868 if (!S.Context.getTargetInfo().hasFeature(Feature: "zve32x")) {
8869 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_unsupported)
8870 << Attr << "'zve32x'";
8871 Attr.setInvalid();
8872 return;
8873 }
8874
8875 auto VScale = S.Context.getTargetInfo().getVScaleRange(
8876 LangOpts: S.getLangOpts(), Mode: TargetInfo::ArmStreamingKind::NotStreaming);
8877 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8878 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_riscv_rvv_bits_unsupported)
8879 << Attr;
8880 Attr.setInvalid();
8881 return;
8882 }
8883
8884 // The vector size must be an integer constant expression.
8885 llvm::APSInt RVVVectorSizeInBits(32);
8886 if (!verifyValidIntegerConstantExpr(S, Attr, Result&: RVVVectorSizeInBits))
8887 return;
8888
8889 // Attribute can only be attached to a single RVV vector type.
8890 if (!CurType->isRVVVLSBuiltinType()) {
8891 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_invalid_rvv_type)
8892 << Attr << CurType;
8893 Attr.setInvalid();
8894 return;
8895 }
8896
8897 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8898
8899 ASTContext::BuiltinVectorTypeInfo Info =
8900 S.Context.getBuiltinVectorTypeInfo(VecTy: CurType->castAs<BuiltinType>());
8901 unsigned MinElts = Info.EC.getKnownMinValue();
8902
8903 VectorKind VecKind;
8904 unsigned ExpectedSize = VScale->first * MinElts;
8905 QualType EltType = CurType->getRVVEltType(Ctx: S.Context);
8906 unsigned EltSize = S.Context.getTypeSize(T: EltType);
8907 unsigned NumElts;
8908 if (Info.ElementType == S.Context.BoolTy) {
8909 // A mask is stored in bytes. One with fewer than 8 lanes takes a single
8910 // byte, and its lane count is recorded in the vector kind.
8911 NumElts = VecSize / S.Context.getCharWidth();
8912 unsigned SubByteLanes = 0;
8913 if (!NumElts) {
8914 NumElts = 1;
8915 if (VecSize == 1 || VecSize == 2 || VecSize == 4)
8916 SubByteLanes = VecSize;
8917 }
8918 // Record the ratio of the vbool<R>_t type in the vector kind, so that
8919 // later stages do not have to re-derive it from VLEN and the lane count.
8920 // vbool<R>_t has RVVBitsPerBlock / R lanes at vscale=1.
8921 VecKind = getRVVFixedLengthMaskVectorKind(
8922 RatioLog2: llvm::Log2_32(Value: llvm::RISCV::RVVBitsPerBlock / MinElts), SubByteLanes);
8923 } else {
8924 ExpectedSize *= EltSize;
8925 NumElts = VecSize / EltSize;
8926
8927 // Record the LMUL of the sizeless type in the vector kind, so that later
8928 // stages do not have to re-derive it from VLEN and the element count.
8929 // LMUL = MinElts * EltSize / RVVBitsPerBlock
8930 VecKind = getRVVFixedLengthDataVectorKind(
8931 LMulLog2: int(llvm::Log2_32(Value: MinElts * EltSize)) -
8932 int(llvm::Log2_32(Value: llvm::RISCV::RVVBitsPerBlock)));
8933 }
8934
8935 // The attribute vector size must match -mrvv-vector-bits.
8936 if (VecSize != ExpectedSize) {
8937 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_bad_rvv_vector_size)
8938 << VecSize << ExpectedSize;
8939 Attr.setInvalid();
8940 return;
8941 }
8942
8943 CurType = S.Context.getVectorType(VectorType: EltType, NumElts, VecKind);
8944}
8945
8946/// Handle OpenCL Access Qualifier Attribute.
8947static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8948 Sema &S) {
8949 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8950 if (!(CurType->isImageType() || CurType->isPipeType())) {
8951 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_opencl_invalid_access_qualifier);
8952 Attr.setInvalid();
8953 return;
8954 }
8955
8956 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8957 QualType BaseTy = TypedefTy->desugar();
8958
8959 std::string PrevAccessQual;
8960 if (BaseTy->isPipeType()) {
8961 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8962 OpenCLAccessAttr *Attr =
8963 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8964 PrevAccessQual = Attr->getSpelling();
8965 } else {
8966 PrevAccessQual = "read_only";
8967 }
8968 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8969
8970 switch (ImgType->getKind()) {
8971 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8972 case BuiltinType::Id: \
8973 PrevAccessQual = #Access; \
8974 break;
8975 #include "clang/Basic/OpenCLImageTypes.def"
8976 default:
8977 llvm_unreachable("Unable to find corresponding image type.");
8978 }
8979 } else {
8980 llvm_unreachable("unexpected type");
8981 }
8982 StringRef AttrName = Attr.getAttrName()->getName();
8983 if (PrevAccessQual == AttrName.ltrim(Chars: "_")) {
8984 // Duplicated qualifiers
8985 S.Diag(Loc: Attr.getLoc(), DiagID: diag::warn_duplicate_declspec)
8986 << AttrName << Attr.getRange();
8987 } else {
8988 // Contradicting qualifiers
8989 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_opencl_multiple_access_qualifiers);
8990 }
8991
8992 S.Diag(Loc: TypedefTy->getDecl()->getBeginLoc(),
8993 DiagID: diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8994 } else if (CurType->isPipeType()) {
8995 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8996 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8997 CurType = S.Context.getWritePipeType(T: ElemType);
8998 }
8999 }
9000}
9001
9002/// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
9003static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
9004 Sema &S) {
9005 if (!S.getLangOpts().MatrixTypes) {
9006 S.Diag(Loc: Attr.getLoc(), DiagID: diag::err_builtin_matrix_disabled);
9007 return;
9008 }
9009
9010 Expr *RowsExpr = Attr.getArgAsExpr(Arg: 0);
9011 Expr *ColsExpr = Attr.getArgAsExpr(Arg: 1);
9012 QualType T = S.BuildMatrixType(ElementTy: CurType, NumRows: RowsExpr, NumCols: ColsExpr, AttrLoc: Attr.getLoc());
9013 if (!T.isNull())
9014 CurType = T;
9015}
9016
9017static void HandleAnnotateTypeAttr(TypeProcessingState &State,
9018 QualType &CurType, const ParsedAttr &PA) {
9019 Sema &S = State.getSema();
9020
9021 if (PA.getNumArgs() < 1) {
9022 S.Diag(Loc: PA.getLoc(), DiagID: diag::err_attribute_too_few_arguments) << PA << 1;
9023 return;
9024 }
9025
9026 // Make sure that there is a string literal as the annotation's first
9027 // argument.
9028 StringRef Str;
9029 if (!S.checkStringLiteralArgumentAttr(Attr: PA, ArgNum: 0, Str))
9030 return;
9031
9032 llvm::SmallVector<Expr *, 4> Args;
9033 Args.reserve(N: PA.getNumArgs() - 1);
9034 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
9035 assert(!PA.isArgIdent(Idx));
9036 Args.push_back(Elt: PA.getArgAsExpr(Arg: Idx));
9037 }
9038 if (!S.ConstantFoldAttrArgs(CI: PA, Args))
9039 return;
9040 auto *AnnotateTypeAttr =
9041 AnnotateTypeAttr::Create(Ctx&: S.Context, Annotation: Str, Args: Args.data(), ArgsSize: Args.size(), CommonInfo: PA);
9042 CurType = State.getAttributedType(A: AnnotateTypeAttr, ModifiedType: CurType, EquivType: CurType);
9043}
9044
9045static void HandleLifetimeBoundAttr(TypeProcessingState &State,
9046 QualType &CurType,
9047 ParsedAttr &Attr) {
9048 if (State.getDeclarator().isDeclarationOfFunction()) {
9049 CurType = State.getAttributedType(
9050 A: createSimpleAttr<LifetimeBoundAttr>(Ctx&: State.getSema().Context, AL&: Attr),
9051 ModifiedType: CurType, EquivType: CurType);
9052 return;
9053 }
9054 State.getSema().Diag(Loc: Attr.getLoc(), DiagID: diag::err_attribute_wrong_decl_type)
9055 << Attr << Attr.isRegularKeywordAttribute()
9056 << ExpectedParameterOrImplicitObjectParameter;
9057}
9058
9059static void HandleLifetimeCaptureByAttr(TypeProcessingState &State,
9060 QualType &CurType, ParsedAttr &PA) {
9061 if (State.getDeclarator().isDeclarationOfFunction()) {
9062 auto *Attr = State.getSema().ParseLifetimeCaptureByAttr(AL: PA, ParamName: "this");
9063 if (Attr)
9064 CurType = State.getAttributedType(A: Attr, ModifiedType: CurType, EquivType: CurType);
9065 }
9066}
9067
9068static void HandleHLSLParamModifierAttr(TypeProcessingState &State,
9069 QualType &CurType,
9070 const ParsedAttr &Attr, Sema &S) {
9071 // Don't apply this attribute to template dependent types. It is applied on
9072 // substitution during template instantiation. Also skip parsing this if we've
9073 // already modified the type based on an earlier attribute.
9074 if (CurType->isDependentType() || State.didParseHLSLParamMod())
9075 return;
9076 if (Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_inout ||
9077 Attr.getSemanticSpelling() == HLSLParamModifierAttr::Keyword_out) {
9078 State.setParsedHLSLParamMod(true);
9079 }
9080}
9081
9082bool Sema::ProcessLateParsedTypeAttr(LateParsedTypeAttrInfo &LA, QualType &QT) {
9083 // A DeclSpec attribute runs this once per declarator, as in
9084 // `IP __counted_by(n) a, b;`. Reuse one node, as the eager path does, so no
9085 // node is left without a count.
9086 if (LA.TypeToComplete) {
9087 QT = QualType(LA.TypeToComplete, 0);
9088 return true;
9089 }
9090
9091 // Nesting is checked once the enclosing declarator chunks wrap the node.
9092 BoundsAttrFlags Flags;
9093 if (!ValidateBoundsAttrTypeForTypePosition(Ty: QT, AttrKind: LA.Kind, AttrLoc: LA.NameLoc,
9094 AttrRange: SourceRange(LA.NameLoc),
9095 /*PointerNestLevel=*/0, Flags))
9096 return false;
9097
9098 // The argument isn't parsed yet, so build the type without a count.
9099 CountAttributedType *CATy = getASTContext().getIncompleteCountAttributedType(
9100 WrappedTy: QT, CountInBytes: Flags.CountInBytes, OrNull: Flags.OrNull);
9101 QT = QualType(CATy, 0);
9102 LA.TypeToComplete = CATy;
9103 return true;
9104}
9105
9106static void processTypeAttrs(TypeProcessingState &state, QualType &type,
9107 TypeAttrLocation TAL,
9108 const ParsedAttributesView &attrs,
9109 CUDAFunctionTarget CFT) {
9110
9111 state.setParsedNoDeref(false);
9112 if (attrs.empty())
9113 return;
9114
9115 // Scan through and apply attributes to this type where it makes sense. Some
9116 // attributes (such as __address_space__, __vector_size__, etc) apply to the
9117 // type, but others can be present in the type specifiers even though they
9118 // apply to the decl. Here we apply type attributes and ignore the rest.
9119
9120 // This loop modifies the list pretty frequently, but we still need to make
9121 // sure we visit every element once. Copy the attributes list, and iterate
9122 // over that.
9123 ParsedAttributesView AttrsCopy{attrs};
9124 for (ParsedAttr &attr : AttrsCopy) {
9125
9126 // Skip attributes that were marked to be invalid.
9127 if (attr.isInvalid())
9128 continue;
9129
9130 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
9131 // [[gnu::...]] attributes are treated as declaration attributes, so may
9132 // not appertain to a DeclaratorChunk. If we handle them as type
9133 // attributes, accept them in that position and diagnose the GCC
9134 // incompatibility.
9135 if (attr.isGNUScope()) {
9136 assert(attr.isStandardAttributeSyntax());
9137 bool IsTypeAttr = attr.isTypeAttr();
9138 if (TAL == TAL_DeclChunk) {
9139 state.getSema().Diag(Loc: attr.getLoc(),
9140 DiagID: IsTypeAttr
9141 ? diag::warn_gcc_ignores_type_attr
9142 : diag::warn_cxx11_gnu_attribute_on_type)
9143 << attr;
9144 if (!IsTypeAttr)
9145 continue;
9146 }
9147 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
9148 !attr.isTypeAttr()) {
9149 // Otherwise, only consider type processing for a C++11 attribute if
9150 // - it has actually been applied to a type (decl-specifier-seq or
9151 // declarator chunk), or
9152 // - it is a type attribute, irrespective of where it was applied (so
9153 // that we can support the legacy behavior of some type attributes
9154 // that can be applied to the declaration name).
9155 continue;
9156 }
9157 }
9158
9159 if (attr.isTypeAttr() &&
9160 state.getSema().checkCommonAttributeFeatures(T: type, A: attr)) {
9161 attr.setInvalid();
9162 continue;
9163 }
9164
9165 // If this is an attribute we can handle, do so now,
9166 // otherwise, add it to the FnAttrs list for rechaining.
9167 switch (attr.getKind()) {
9168 default:
9169 // A [[]] attribute on a declarator chunk must appertain to a type.
9170 if ((attr.isStandardAttributeSyntax() ||
9171 attr.isRegularKeywordAttribute()) &&
9172 TAL == TAL_DeclChunk) {
9173 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::err_attribute_not_type_attr)
9174 << attr << attr.isRegularKeywordAttribute();
9175 attr.setUsedAsTypeAttr();
9176 }
9177 break;
9178
9179 case ParsedAttr::UnknownAttribute:
9180 if (attr.isStandardAttributeSyntax()) {
9181 state.getSema().DiagnoseUnknownAttribute(AL: attr);
9182 // Mark the attribute as invalid so we don't emit the same diagnostic
9183 // multiple times.
9184 attr.setInvalid();
9185 }
9186 break;
9187
9188 case ParsedAttr::IgnoredAttribute:
9189 break;
9190
9191 case ParsedAttr::AT_BTFTypeTag:
9192 HandleBTFTypeTagAttribute(Type&: type, Attr: attr, State&: state);
9193 attr.setUsedAsTypeAttr();
9194 break;
9195
9196 case ParsedAttr::AT_MayAlias:
9197 // FIXME: This attribute needs to actually be handled, but if we ignore
9198 // it it breaks large amounts of Linux software.
9199 attr.setUsedAsTypeAttr();
9200 break;
9201 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
9202 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
9203 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_deprecated_attribute)
9204 << attr;
9205 [[fallthrough]];
9206 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
9207 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
9208 case ParsedAttr::AT_OpenCLLocalAddressSpace:
9209 case ParsedAttr::AT_OpenCLConstantAddressSpace:
9210 case ParsedAttr::AT_OpenCLGenericAddressSpace:
9211 case ParsedAttr::AT_AddressSpace:
9212 case ParsedAttr::AT_SYCLPrivateAddressSpace:
9213 case ParsedAttr::AT_SYCLGlobalAddressSpace:
9214 case ParsedAttr::AT_SYCLLocalAddressSpace:
9215 case ParsedAttr::AT_SYCLConstantAddressSpace:
9216 case ParsedAttr::AT_SYCLGenericAddressSpace:
9217 HandleAddressSpaceTypeAttribute(Type&: type, Attr: attr, State&: state);
9218 attr.setUsedAsTypeAttr();
9219 break;
9220 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
9221 HandleAddressSpaceTypeAttribute(Type&: type, Attr: attr, State&: state);
9222 if (state.getDeclarator().getContext() == DeclaratorContext::Prototype) {
9223 if (state.getSema().getLangOpts().getHLSLVersion() <
9224 LangOptions::HLSL_202x)
9225 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_hlsl_groupshared_202x);
9226
9227 // Note: we don't check for the usage of HLSLParamModifiers in/out/inout
9228 // here because the check in the AT_HLSLParamModifier case is sufficient
9229 // regardless of the order of groupshared or in/out/inout specified in
9230 // the parameter. And checking there produces a better error message.
9231 }
9232 attr.setUsedAsTypeAttr();
9233 break;
9234 case ParsedAttr::AT_HLSLRowMajor:
9235 case ParsedAttr::AT_HLSLColumnMajor:
9236 if (Attr *A =
9237 state.getSema().HLSL().buildMatrixLayoutTypeAttr(T: type, AL: attr)) {
9238 MatrixType::LayoutKind Layout =
9239 attr.getKind() == ParsedAttr::AT_HLSLRowMajor
9240 ? MatrixType::LayoutKind::RowMajor
9241 : MatrixType::LayoutKind::ColumnMajor;
9242 QualType Equivalent =
9243 state.getSema().Context.getMatrixTypeWithLayout(T: type, Layout);
9244 type = state.getAttributedType(A, ModifiedType: type, EquivType: Equivalent);
9245 }
9246 attr.setUsedAsTypeAttr();
9247 break;
9248 OBJC_POINTER_TYPE_ATTRS_CASELIST:
9249 if (!handleObjCPointerTypeAttr(state, attr, type))
9250 distributeObjCPointerTypeAttr(state, attr, type);
9251 attr.setUsedAsTypeAttr();
9252 break;
9253 case ParsedAttr::AT_VectorSize:
9254 HandleVectorSizeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9255 attr.setUsedAsTypeAttr();
9256 break;
9257 case ParsedAttr::AT_ExtVectorType:
9258 HandleExtVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9259 attr.setUsedAsTypeAttr();
9260 break;
9261 case ParsedAttr::AT_NeonVectorType:
9262 HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(), VecKind: VectorKind::Neon);
9263 attr.setUsedAsTypeAttr();
9264 break;
9265 case ParsedAttr::AT_NeonPolyVectorType:
9266 HandleNeonVectorTypeAttr(CurType&: type, Attr: attr, S&: state.getSema(),
9267 VecKind: VectorKind::NeonPoly);
9268 attr.setUsedAsTypeAttr();
9269 break;
9270 case ParsedAttr::AT_ArmSveVectorBits:
9271 HandleArmSveVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema());
9272 attr.setUsedAsTypeAttr();
9273 break;
9274 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
9275 HandleArmMveStrictPolymorphismAttr(State&: state, CurType&: type, Attr&: attr);
9276 attr.setUsedAsTypeAttr();
9277 break;
9278 }
9279 case ParsedAttr::AT_RISCVRVVVectorBits:
9280 HandleRISCVRVVVectorBitsTypeAttr(CurType&: type, Attr&: attr, S&: state.getSema());
9281 attr.setUsedAsTypeAttr();
9282 break;
9283 case ParsedAttr::AT_OpenCLAccess:
9284 HandleOpenCLAccessAttr(CurType&: type, Attr: attr, S&: state.getSema());
9285 attr.setUsedAsTypeAttr();
9286 break;
9287 case ParsedAttr::AT_PointerAuth:
9288 HandlePtrAuthQualifier(Ctx&: state.getSema().Context, T&: type, Attr: attr,
9289 S&: state.getSema());
9290 attr.setUsedAsTypeAttr();
9291 break;
9292 case ParsedAttr::AT_LifetimeBound:
9293 if (TAL == TAL_DeclChunk)
9294 HandleLifetimeBoundAttr(State&: state, CurType&: type, Attr&: attr);
9295 break;
9296 case ParsedAttr::AT_LifetimeCaptureBy:
9297 if (TAL == TAL_DeclChunk)
9298 HandleLifetimeCaptureByAttr(State&: state, CurType&: type, PA&: attr);
9299 break;
9300 case ParsedAttr::AT_OverflowBehavior:
9301 HandleOverflowBehaviorAttr(Type&: type, Attr: attr, State&: state);
9302 attr.setUsedAsTypeAttr();
9303 break;
9304
9305 case ParsedAttr::AT_NoDeref: {
9306 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
9307 // See https://github.com/llvm/llvm-project/issues/55790 for details.
9308 // For the time being, we simply emit a warning that the attribute is
9309 // ignored.
9310 if (attr.isStandardAttributeSyntax()) {
9311 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::warn_attribute_ignored)
9312 << attr;
9313 break;
9314 }
9315 ASTContext &Ctx = state.getSema().Context;
9316 type = state.getAttributedType(A: createSimpleAttr<NoDerefAttr>(Ctx, AL&: attr),
9317 ModifiedType: type, EquivType: type);
9318 attr.setUsedAsTypeAttr();
9319 state.setParsedNoDeref(true);
9320 break;
9321 }
9322
9323 case ParsedAttr::AT_MatrixType:
9324 HandleMatrixTypeAttr(CurType&: type, Attr: attr, S&: state.getSema());
9325 attr.setUsedAsTypeAttr();
9326 break;
9327
9328 case ParsedAttr::AT_WebAssemblyFuncref: {
9329 if (!HandleWebAssemblyFuncrefAttr(State&: state, QT&: type, PAttr&: attr))
9330 attr.setUsedAsTypeAttr();
9331 break;
9332 }
9333
9334 case ParsedAttr::AT_HLSLParamModifier: {
9335 HandleHLSLParamModifierAttr(State&: state, CurType&: type, Attr: attr, S&: state.getSema());
9336 if (attrs.hasAttribute(K: ParsedAttr::AT_HLSLGroupSharedAddressSpace)) {
9337 state.getSema().Diag(Loc: attr.getLoc(), DiagID: diag::err_hlsl_attr_incompatible)
9338 << attr << "'groupshared'";
9339 attr.setInvalid();
9340 return;
9341 }
9342 attr.setUsedAsTypeAttr();
9343 break;
9344 }
9345
9346 case ParsedAttr::AT_SwiftAttr: {
9347 HandleSwiftAttr(State&: state, TAL, QT&: type, PAttr&: attr);
9348 break;
9349 }
9350
9351 MS_TYPE_ATTRS_CASELIST:
9352 if (!handleMSPointerTypeQualifierAttr(State&: state, PAttr&: attr, Type&: type))
9353 attr.setUsedAsTypeAttr();
9354 break;
9355
9356
9357 NULLABILITY_TYPE_ATTRS_CASELIST:
9358 // Either add nullability here or try to distribute it. We
9359 // don't want to distribute the nullability specifier past any
9360 // dependent type, because that complicates the user model.
9361 if (type->canHaveNullability() || type->isDependentType() ||
9362 type->isArrayType() ||
9363 !distributeNullabilityTypeAttr(state, type, attr)) {
9364 unsigned endIndex;
9365 if (TAL == TAL_DeclChunk)
9366 endIndex = state.getCurrentChunkIndex();
9367 else
9368 endIndex = state.getDeclarator().getNumTypeObjects();
9369 bool allowOnArrayType =
9370 state.getDeclarator().isPrototypeContext() &&
9371 !hasOuterPointerLikeChunk(D: state.getDeclarator(), endIndex);
9372 if (CheckNullabilityTypeSpecifier(State&: state, Type&: type, Attr&: attr,
9373 AllowOnArrayType: allowOnArrayType)) {
9374 attr.setInvalid();
9375 }
9376
9377 attr.setUsedAsTypeAttr();
9378 }
9379 break;
9380
9381 case ParsedAttr::AT_ObjCKindOf:
9382 // '__kindof' must be part of the decl-specifiers.
9383 switch (TAL) {
9384 case TAL_DeclSpec:
9385 break;
9386
9387 case TAL_DeclChunk:
9388 case TAL_DeclName:
9389 state.getSema().Diag(Loc: attr.getLoc(),
9390 DiagID: diag::err_objc_kindof_wrong_position)
9391 << FixItHint::CreateRemoval(RemoveRange: attr.getLoc())
9392 << FixItHint::CreateInsertion(
9393 InsertionLoc: state.getDeclarator().getDeclSpec().getBeginLoc(),
9394 Code: "__kindof ");
9395 break;
9396 }
9397
9398 // Apply it regardless.
9399 if (checkObjCKindOfType(state, type, attr))
9400 attr.setInvalid();
9401 break;
9402
9403 case ParsedAttr::AT_NoThrow:
9404 // Exception Specifications aren't generally supported in C mode throughout
9405 // clang, so revert to attribute-based handling for C.
9406 if (!state.getSema().getLangOpts().CPlusPlus)
9407 break;
9408 [[fallthrough]];
9409 FUNCTION_TYPE_ATTRS_CASELIST:
9410
9411 attr.setUsedAsTypeAttr();
9412
9413 // Attributes with standard syntax have strict rules for what they
9414 // appertain to and hence should not use the "distribution" logic below.
9415 if (attr.isStandardAttributeSyntax() ||
9416 attr.isRegularKeywordAttribute()) {
9417 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
9418 diagnoseBadTypeAttribute(S&: state.getSema(), attr, type);
9419 attr.setInvalid();
9420 }
9421 break;
9422 }
9423
9424 // Never process function type attributes as part of the
9425 // declaration-specifiers.
9426 if (TAL == TAL_DeclSpec)
9427 distributeFunctionTypeAttrFromDeclSpec(state, attr, declSpecType&: type, CFT);
9428
9429 // Otherwise, handle the possible delays.
9430 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
9431 distributeFunctionTypeAttr(state, attr, type);
9432 break;
9433 case ParsedAttr::AT_AcquireHandle: {
9434 if (!type->isFunctionType())
9435 return;
9436
9437 if (attr.getNumArgs() != 1) {
9438 state.getSema().Diag(Loc: attr.getLoc(),
9439 DiagID: diag::err_attribute_wrong_number_arguments)
9440 << attr << 1;
9441 attr.setInvalid();
9442 return;
9443 }
9444
9445 StringRef HandleType;
9446 if (!state.getSema().checkStringLiteralArgumentAttr(Attr: attr, ArgNum: 0, Str&: HandleType))
9447 return;
9448 type = state.getAttributedType(
9449 A: AcquireHandleAttr::Create(Ctx&: state.getSema().Context, HandleType, CommonInfo: attr),
9450 ModifiedType: type, EquivType: type);
9451 attr.setUsedAsTypeAttr();
9452 break;
9453 }
9454 case ParsedAttr::AT_AnnotateType: {
9455 HandleAnnotateTypeAttr(State&: state, CurType&: type, PA: attr);
9456 attr.setUsedAsTypeAttr();
9457 break;
9458 }
9459 case ParsedAttr::AT_HLSLResourceClass:
9460 case ParsedAttr::AT_HLSLResourceDimension:
9461 case ParsedAttr::AT_HLSLIsROV:
9462 case ParsedAttr::AT_HLSLRawBuffer:
9463 case ParsedAttr::AT_HLSLIsArray:
9464 case ParsedAttr::AT_HLSLIsMultiSampled:
9465 case ParsedAttr::AT_HLSLContainedType: {
9466 // Only collect HLSL resource type attributes that are in
9467 // decl-specifier-seq; do not collect attributes on declarations or those
9468 // that get to slide after declaration name.
9469 if (TAL == TAL_DeclSpec &&
9470 state.getSema().HLSL().handleResourceTypeAttr(T: type, AL: attr))
9471 attr.setUsedAsTypeAttr();
9472 break;
9473 }
9474 }
9475
9476 // Handle attributes that are defined in a macro. We do not want this to be
9477 // applied to ObjC builtin attributes.
9478 if (isa<AttributedType>(Val: type) && attr.hasMacroIdentifier() &&
9479 !type.getQualifiers().hasObjCLifetime() &&
9480 !type.getQualifiers().hasObjCGCAttr() &&
9481 attr.getKind() != ParsedAttr::AT_ObjCGC &&
9482 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
9483 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
9484 type = state.getSema().Context.getMacroQualifiedType(UnderlyingTy: type, MacroII);
9485 state.setExpansionLocForMacroQualifiedType(
9486 MQT: cast<MacroQualifiedType>(Val: type.getTypePtr()),
9487 Loc: attr.getMacroExpansionLoc());
9488 }
9489 }
9490}
9491
9492void Sema::completeExprArrayBound(Expr *E) {
9493 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E->IgnoreParens())) {
9494 if (VarDecl *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
9495 if (isTemplateInstantiation(Kind: Var->getTemplateSpecializationKind())) {
9496 auto *Def = Var->getDefinition();
9497 if (!Def) {
9498 SourceLocation PointOfInstantiation = E->getExprLoc();
9499 runWithSufficientStackSpace(Loc: PointOfInstantiation, Fn: [&] {
9500 InstantiateVariableDefinition(PointOfInstantiation, Var);
9501 });
9502 Def = Var->getDefinition();
9503
9504 // If we don't already have a point of instantiation, and we managed
9505 // to instantiate a definition, this is the point of instantiation.
9506 // Otherwise, we don't request an end-of-TU instantiation, so this is
9507 // not a point of instantiation.
9508 // FIXME: Is this really the right behavior?
9509 if (Var->getPointOfInstantiation().isInvalid() && Def) {
9510 assert(Var->getTemplateSpecializationKind() ==
9511 TSK_ImplicitInstantiation &&
9512 "explicit instantiation with no point of instantiation");
9513 Var->setTemplateSpecializationKind(
9514 TSK: Var->getTemplateSpecializationKind(), PointOfInstantiation);
9515 }
9516 }
9517
9518 // Update the type to the definition's type both here and within the
9519 // expression.
9520 if (Def) {
9521 DRE->setDecl(Def);
9522 QualType T = Def->getType();
9523 DRE->setType(T);
9524 // FIXME: Update the type on all intervening expressions.
9525 E->setType(T);
9526 }
9527
9528 // We still go on to try to complete the type independently, as it
9529 // may also require instantiations or diagnostics if it remains
9530 // incomplete.
9531 }
9532 }
9533 }
9534 if (const auto CastE = dyn_cast<ExplicitCastExpr>(Val: E)) {
9535 QualType DestType = CastE->getTypeAsWritten();
9536 if (const auto *IAT = Context.getAsIncompleteArrayType(T: DestType)) {
9537 // C++20 [expr.static.cast]p.4: ... If T is array of unknown bound,
9538 // this direct-initialization defines the type of the expression
9539 // as U[1]
9540 QualType ResultType = Context.getConstantArrayType(
9541 EltTy: IAT->getElementType(),
9542 ArySize: llvm::APInt(Context.getTypeSize(T: Context.getSizeType()), 1),
9543 /*SizeExpr=*/nullptr, ASM: ArraySizeModifier::Normal,
9544 /*IndexTypeQuals=*/0);
9545 E->setType(ResultType);
9546 }
9547 }
9548}
9549
9550QualType Sema::getCompletedType(Expr *E) {
9551 // Incomplete array types may be completed by the initializer attached to
9552 // their definitions. For static data members of class templates and for
9553 // variable templates, we need to instantiate the definition to get this
9554 // initializer and complete the type.
9555 if (E->getType()->isIncompleteArrayType())
9556 completeExprArrayBound(E);
9557
9558 // FIXME: Are there other cases which require instantiating something other
9559 // than the type to complete the type of an expression?
9560
9561 return E->getType();
9562}
9563
9564bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
9565 TypeDiagnoser &Diagnoser) {
9566 return RequireCompleteType(Loc: E->getExprLoc(), T: getCompletedType(E), Kind,
9567 Diagnoser);
9568}
9569
9570bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9571 BoundTypeDiagnoser<> Diagnoser(DiagID);
9572 return RequireCompleteExprType(E, Kind: CompleteTypeKind::Default, Diagnoser);
9573}
9574
9575bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9576 CompleteTypeKind Kind,
9577 TypeDiagnoser &Diagnoser) {
9578 if (RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser: &Diagnoser))
9579 return true;
9580 if (auto *TD = T->getAsTagDecl(); TD && !TD->isCompleteDefinitionRequired()) {
9581 TD->setCompleteDefinitionRequired();
9582 Consumer.HandleTagDeclRequiredDefinition(D: TD);
9583 }
9584 return false;
9585}
9586
9587bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9588 StructuralEquivalenceContext::NonEquivalentDeclSet NonEquivalentDecls;
9589 if (!Suggested)
9590 return false;
9591
9592 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9593 // and isolate from other C++ specific checks.
9594 StructuralEquivalenceContext Ctx(
9595 getLangOpts(), D->getASTContext(), Suggested->getASTContext(),
9596 NonEquivalentDecls, StructuralEquivalenceKind::Default,
9597 /*StrictTypeSpelling=*/false, /*Complain=*/true,
9598 /*ErrorOnTagTypeMismatch=*/true);
9599 return Ctx.IsEquivalent(D1: D, D2: Suggested);
9600}
9601
9602bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9603 AcceptableKind Kind, bool OnlyNeedComplete) {
9604 // Easy case: if we don't have modules, all declarations are visible.
9605 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9606 return true;
9607
9608 // If this definition was instantiated from a template, map back to the
9609 // pattern from which it was instantiated.
9610 if (isa<TagDecl>(Val: D) && cast<TagDecl>(Val: D)->isBeingDefined())
9611 // We're in the middle of defining it; this definition should be treated
9612 // as visible.
9613 return true;
9614
9615 auto DefinitionIsAcceptable = [&](NamedDecl *D) {
9616 // The (primary) definition might be in a visible module.
9617 if (isAcceptable(D, Kind))
9618 return true;
9619
9620 // A visible module might have a merged definition instead.
9621 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(Def: D)
9622 : hasVisibleMergedDefinition(Def: D)) {
9623 if (CodeSynthesisContexts.empty() &&
9624 !getLangOpts().ModulesLocalVisibility) {
9625 // Cache the fact that this definition is implicitly visible because
9626 // there is a visible merged definition.
9627 D->setVisibleDespiteOwningModule();
9628 }
9629 return true;
9630 }
9631
9632 return false;
9633 };
9634 auto IsDefinition = [](NamedDecl *D) {
9635 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D))
9636 return RD->isThisDeclarationADefinition();
9637 if (auto *ED = dyn_cast<EnumDecl>(Val: D))
9638 return ED->isThisDeclarationADefinition();
9639 if (auto *FD = dyn_cast<FunctionDecl>(Val: D))
9640 return FD->isThisDeclarationADefinition();
9641 if (auto *VD = dyn_cast<VarDecl>(Val: D))
9642 return VD->isThisDeclarationADefinition() == VarDecl::Definition;
9643 llvm_unreachable("unexpected decl type");
9644 };
9645 auto FoundAcceptableDefinition = [&](NamedDecl *D) {
9646 if (!isa<CXXRecordDecl, FunctionDecl, EnumDecl, VarDecl>(Val: D))
9647 return DefinitionIsAcceptable(D);
9648
9649 // See ASTDeclReader::attachPreviousDeclImpl. Now we still
9650 // may demote definition to declaration for decls in haeder modules,
9651 // so avoid looking at its redeclaration to save time.
9652 // NOTE: If we don't demote definition to declarations for decls
9653 // in header modules, remove the condition.
9654 if (D->getOwningModule() && D->getOwningModule()->isHeaderLikeModule())
9655 return DefinitionIsAcceptable(D);
9656
9657 for (auto *RD : D->redecls()) {
9658 auto *ND = cast<NamedDecl>(Val: RD);
9659 if (!IsDefinition(ND))
9660 continue;
9661 if (DefinitionIsAcceptable(ND)) {
9662 *Suggested = ND;
9663 return true;
9664 }
9665 }
9666
9667 return false;
9668 };
9669
9670 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
9671 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9672 RD = Pattern;
9673 D = RD->getDefinition();
9674 } else if (auto *ED = dyn_cast<EnumDecl>(Val: D)) {
9675 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9676 ED = Pattern;
9677 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9678 // If the enum has a fixed underlying type, it may have been forward
9679 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9680 // the enum and assign it the underlying type of `int`. Since we're only
9681 // looking for a complete type (not a definition), any visible declaration
9682 // of it will do.
9683 *Suggested = nullptr;
9684 for (auto *Redecl : ED->redecls()) {
9685 if (isAcceptable(D: Redecl, Kind))
9686 return true;
9687 if (Redecl->isThisDeclarationADefinition() ||
9688 (Redecl->isCanonicalDecl() && !*Suggested))
9689 *Suggested = Redecl;
9690 }
9691
9692 return false;
9693 }
9694 D = ED->getDefinition();
9695 } else if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
9696 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9697 FD = Pattern;
9698 D = FD->getDefinition();
9699 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
9700 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9701 VD = Pattern;
9702 D = VD->getDefinition();
9703 }
9704
9705 assert(D && "missing definition for pattern of instantiated definition");
9706
9707 *Suggested = D;
9708
9709 if (FoundAcceptableDefinition(D))
9710 return true;
9711
9712 // The external source may have additional definitions of this entity that are
9713 // visible, so complete the redeclaration chain now and ask again.
9714 if (auto *Source = Context.getExternalSource()) {
9715 Source->CompleteRedeclChain(D);
9716 return FoundAcceptableDefinition(D);
9717 }
9718
9719 return false;
9720}
9721
9722/// Determine whether there is any declaration of \p D that was ever a
9723/// definition (perhaps before module merging) and is currently visible.
9724/// \param D The definition of the entity.
9725/// \param Suggested Filled in with the declaration that should be made visible
9726/// in order to provide a definition of this entity.
9727/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9728/// not defined. This only matters for enums with a fixed underlying
9729/// type, since in all other cases, a type is complete if and only if it
9730/// is defined.
9731bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9732 bool OnlyNeedComplete) {
9733 return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Visible,
9734 OnlyNeedComplete);
9735}
9736
9737/// Determine whether there is any declaration of \p D that was ever a
9738/// definition (perhaps before module merging) and is currently
9739/// reachable.
9740/// \param D The definition of the entity.
9741/// \param Suggested Filled in with the declaration that should be made
9742/// reachable
9743/// in order to provide a definition of this entity.
9744/// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9745/// not defined. This only matters for enums with a fixed underlying
9746/// type, since in all other cases, a type is complete if and only if it
9747/// is defined.
9748bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9749 bool OnlyNeedComplete) {
9750 return hasAcceptableDefinition(D, Suggested, Kind: Sema::AcceptableKind::Reachable,
9751 OnlyNeedComplete);
9752}
9753
9754/// Locks in the inheritance model for the given class and all of its bases.
9755static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9756 RD = RD->getMostRecentDecl();
9757 if (!RD->hasAttr<MSInheritanceAttr>()) {
9758 MSInheritanceModel IM;
9759 bool BestCase = false;
9760 switch (S.MSPointerToMemberRepresentationMethod) {
9761 case LangOptions::PPTMK_BestCase:
9762 BestCase = true;
9763 IM = RD->calculateInheritanceModel();
9764 break;
9765 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9766 IM = MSInheritanceModel::Single;
9767 break;
9768 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9769 IM = MSInheritanceModel::Multiple;
9770 break;
9771 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9772 IM = MSInheritanceModel::Unspecified;
9773 break;
9774 }
9775
9776 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9777 ? S.ImplicitMSInheritanceAttrLoc
9778 : RD->getSourceRange();
9779 RD->addAttr(A: MSInheritanceAttr::CreateImplicit(
9780 Ctx&: S.getASTContext(), BestCase, Range: Loc, S: MSInheritanceAttr::Spelling(IM)));
9781 S.Consumer.AssignInheritanceModel(RD);
9782 }
9783}
9784
9785bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9786 CompleteTypeKind Kind,
9787 TypeDiagnoser *Diagnoser) {
9788 // FIXME: Add this assertion to make sure we always get instantiation points.
9789 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9790 // FIXME: Add this assertion to help us flush out problems with
9791 // checking for dependent types and type-dependent expressions.
9792 //
9793 // assert(!T->isDependentType() &&
9794 // "Can't ask whether a dependent type is complete");
9795
9796 if (const auto *MPTy = dyn_cast<MemberPointerType>(Val: T.getCanonicalType())) {
9797 if (CXXRecordDecl *RD = MPTy->getMostRecentCXXRecordDecl();
9798 RD && !RD->isDependentType()) {
9799 CanQualType T = Context.getCanonicalTagType(TD: RD);
9800 if (getLangOpts().CompleteMemberPointers && !RD->isBeingDefined() &&
9801 RequireCompleteType(Loc, T, Kind, DiagID: diag::err_memptr_incomplete))
9802 return true;
9803
9804 // We lock in the inheritance model once somebody has asked us to ensure
9805 // that a pointer-to-member type is complete.
9806 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9807 (void)isCompleteType(Loc, T);
9808 assignInheritanceModel(S&: *this, RD: MPTy->getMostRecentCXXRecordDecl());
9809 }
9810 }
9811 }
9812
9813 NamedDecl *Def = nullptr;
9814 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9815 bool Incomplete = (T->isIncompleteType(Def: &Def) ||
9816 (!AcceptSizeless && T->isSizelessBuiltinType()));
9817
9818 // Check that any necessary explicit specializations are visible. For an
9819 // enum, we just need the declaration, so don't check this.
9820 if (Def && !isa<EnumDecl>(Val: Def))
9821 checkSpecializationReachability(Loc, Spec: Def);
9822
9823 // If we have a complete type, we're done.
9824 if (!Incomplete) {
9825 NamedDecl *Suggested = nullptr;
9826 if (Def &&
9827 !hasReachableDefinition(D: Def, Suggested: &Suggested, /*OnlyNeedComplete=*/true)) {
9828 // If the user is going to see an error here, recover by making the
9829 // definition visible.
9830 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9831 if (Diagnoser && Suggested)
9832 diagnoseMissingImport(Loc, Decl: Suggested, MIK: MissingImportKind::Definition,
9833 /*Recover*/ TreatAsComplete);
9834 return !TreatAsComplete;
9835 }
9836 return false;
9837 }
9838
9839 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Val: Def);
9840 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Val: Def);
9841
9842 // Give the external source a chance to provide a definition of the type.
9843 // This is kept separate from completing the redeclaration chain so that
9844 // external sources such as LLDB can avoid synthesizing a type definition
9845 // unless it's actually needed.
9846 if (Tag || IFace) {
9847 // Avoid diagnosing invalid decls as incomplete.
9848 if (Def->isInvalidDecl())
9849 return true;
9850
9851 // Give the external AST source a chance to complete the type.
9852 if (auto *Source = Context.getExternalSource()) {
9853 if (Tag && Tag->hasExternalLexicalStorage())
9854 Source->CompleteType(Tag);
9855 if (IFace && IFace->hasExternalLexicalStorage())
9856 Source->CompleteType(Class: IFace);
9857 // If the external source completed the type, go through the motions
9858 // again to ensure we're allowed to use the completed type.
9859 if (!T->isIncompleteType())
9860 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9861 }
9862 }
9863
9864 // If we have a class template specialization or a class member of a
9865 // class template specialization, or an array with known size of such,
9866 // try to instantiate it.
9867 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Val: Tag)) {
9868 bool Instantiated = false;
9869 bool Diagnosed = false;
9870 if (RD->isDependentContext()) {
9871 // Don't try to instantiate a dependent class (eg, a member template of
9872 // an instantiated class template specialization).
9873 // FIXME: Can this ever happen?
9874 } else if (auto *ClassTemplateSpec =
9875 dyn_cast<ClassTemplateSpecializationDecl>(Val: RD)) {
9876 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9877 runWithSufficientStackSpace(Loc, Fn: [&] {
9878 Diagnosed = InstantiateClassTemplateSpecialization(
9879 PointOfInstantiation: Loc, ClassTemplateSpec, TSK: TSK_ImplicitInstantiation,
9880 /*Complain=*/Diagnoser, PrimaryStrictPackMatch: ClassTemplateSpec->hasStrictPackMatch());
9881 });
9882 Instantiated = true;
9883 }
9884 } else {
9885 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9886 if (!RD->isBeingDefined() && Pattern) {
9887 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9888 assert(MSI && "Missing member specialization information?");
9889 // This record was instantiated from a class within a template.
9890 if (MSI->getTemplateSpecializationKind() !=
9891 TSK_ExplicitSpecialization) {
9892 runWithSufficientStackSpace(Loc, Fn: [&] {
9893 Diagnosed = InstantiateClass(PointOfInstantiation: Loc, Instantiation: RD, Pattern,
9894 TemplateArgs: getTemplateInstantiationArgs(D: RD),
9895 TSK: TSK_ImplicitInstantiation,
9896 /*Complain=*/Diagnoser);
9897 });
9898 Instantiated = true;
9899 }
9900 }
9901 }
9902
9903 if (Instantiated) {
9904 // Instantiate* might have already complained that the template is not
9905 // defined, if we asked it to.
9906 if (Diagnoser && Diagnosed)
9907 return true;
9908 // If we instantiated a definition, check that it's usable, even if
9909 // instantiation produced an error, so that repeated calls to this
9910 // function give consistent answers.
9911 if (!T->isIncompleteType())
9912 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9913 }
9914 }
9915
9916 // FIXME: If we didn't instantiate a definition because of an explicit
9917 // specialization declaration, check that it's visible.
9918
9919 if (!Diagnoser)
9920 return true;
9921
9922 Diagnoser->diagnose(S&: *this, Loc, T);
9923
9924 // If the type was a forward declaration of a class/struct/union
9925 // type, produce a note.
9926 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9927 Diag(Loc: Tag->getLocation(), DiagID: Tag->isBeingDefined()
9928 ? diag::note_type_being_defined
9929 : diag::note_forward_declaration)
9930 << Context.getCanonicalTagType(TD: Tag);
9931
9932 // If the Objective-C class was a forward declaration, produce a note.
9933 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9934 Diag(Loc: IFace->getLocation(), DiagID: diag::note_forward_class);
9935
9936 // If we have external information that we can use to suggest a fix,
9937 // produce a note.
9938 if (ExternalSource)
9939 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9940
9941 return true;
9942}
9943
9944bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9945 CompleteTypeKind Kind, unsigned DiagID) {
9946 BoundTypeDiagnoser<> Diagnoser(DiagID);
9947 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9948}
9949
9950/// Get diagnostic %select index for tag kind for
9951/// literal type diagnostic message.
9952/// WARNING: Indexes apply to particular diagnostics only!
9953///
9954/// \returns diagnostic %select index.
9955static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9956 switch (Tag) {
9957 case TagTypeKind::Struct:
9958 return 0;
9959 case TagTypeKind::Interface:
9960 return 1;
9961 case TagTypeKind::Class:
9962 return 2;
9963 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9964 }
9965}
9966
9967bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9968 TypeDiagnoser &Diagnoser) {
9969 assert(!T->isDependentType() && "type should not be dependent");
9970
9971 QualType ElemType = Context.getBaseElementType(QT: T);
9972 if ((isCompleteType(Loc, T: ElemType) || ElemType->isVoidType()) &&
9973 T->isLiteralType(Ctx: Context))
9974 return false;
9975
9976 Diagnoser.diagnose(S&: *this, Loc, T);
9977
9978 if (T->isVariableArrayType())
9979 return true;
9980
9981 if (!ElemType->isRecordType())
9982 return true;
9983
9984 // A partially-defined class type can't be a literal type, because a literal
9985 // class type must have a trivial destructor (which can't be checked until
9986 // the class definition is complete).
9987 if (RequireCompleteType(Loc, T: ElemType, DiagID: diag::note_non_literal_incomplete, Args: T))
9988 return true;
9989
9990 const auto *RD = ElemType->castAsCXXRecordDecl();
9991 // [expr.prim.lambda]p3:
9992 // This class type is [not] a literal type.
9993 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9994 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_lambda);
9995 return true;
9996 }
9997
9998 // If the class has virtual base classes, then it's not an aggregate, and
9999 // cannot have any constexpr constructors or a trivial default constructor,
10000 // so is non-literal. This is better to diagnose than the resulting absence
10001 // of constexpr constructors.
10002 if (!getLangOpts().CPlusPlus26 && RD->getNumVBases()) {
10003 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_virtual_base)
10004 << getLiteralDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
10005 for (const auto &I : RD->vbases())
10006 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
10007 << I.getSourceRange();
10008 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
10009 !RD->hasTrivialDefaultConstructor()) {
10010 Diag(Loc: RD->getLocation(), DiagID: diag::note_non_literal_no_constexpr_ctors) << RD;
10011 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
10012 for (const auto &I : RD->bases()) {
10013 if (!I.getType()->isLiteralType(Ctx: Context)) {
10014 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_non_literal_base_class)
10015 << RD << I.getType() << I.getSourceRange();
10016 return true;
10017 }
10018 }
10019 for (const auto *I : RD->fields()) {
10020 if (!I->getType()->isLiteralType(Ctx: Context) ||
10021 I->getType().isVolatileQualified()) {
10022 Diag(Loc: I->getLocation(), DiagID: diag::note_non_literal_field)
10023 << RD << I << I->getType()
10024 << I->getType().isVolatileQualified();
10025 return true;
10026 }
10027 }
10028 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
10029 : !RD->hasTrivialDestructor()) {
10030 // All fields and bases are of literal types, so have trivial or constexpr
10031 // destructors. If this class's destructor is non-trivial / non-constexpr,
10032 // it must be user-declared.
10033 CXXDestructorDecl *Dtor = RD->getDestructor();
10034 assert(Dtor && "class has literal fields and bases but no dtor?");
10035 if (!Dtor)
10036 return true;
10037
10038 if (getLangOpts().CPlusPlus20) {
10039 Diag(Loc: Dtor->getLocation(), DiagID: diag::note_non_literal_non_constexpr_dtor)
10040 << RD;
10041 } else {
10042 Diag(Loc: Dtor->getLocation(), DiagID: Dtor->isUserProvided()
10043 ? diag::note_non_literal_user_provided_dtor
10044 : diag::note_non_literal_nontrivial_dtor)
10045 << RD;
10046 if (!Dtor->isUserProvided())
10047 SpecialMemberIsTrivial(MD: Dtor, CSM: CXXSpecialMemberKind::Destructor,
10048 TAH: TrivialABIHandling::IgnoreTrivialABI,
10049 /*Diagnose*/ true);
10050 }
10051 }
10052
10053 return true;
10054}
10055
10056bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
10057 BoundTypeDiagnoser<> Diagnoser(DiagID);
10058 return RequireLiteralType(Loc, T, Diagnoser);
10059}
10060
10061QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
10062 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10063
10064 if (!getLangOpts().CPlusPlus && E->refersToBitField())
10065 Diag(Loc: E->getExprLoc(), DiagID: diag::err_sizeof_alignof_typeof_bitfield)
10066 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
10067
10068 if (!E->isTypeDependent()) {
10069 QualType T = E->getType();
10070 if (const TagType *TT = T->getAs<TagType>())
10071 DiagnoseUseOfDecl(D: TT->getDecl(), Locs: E->getExprLoc());
10072 }
10073 return Context.getTypeOfExprType(E, Kind);
10074}
10075
10076static void
10077BuildTypeCoupledDecls(Expr *E,
10078 llvm::SmallVectorImpl<TypeCoupledDeclRefInfo> &Decls) {
10079 // Currently, 'counted_by' only allows direct DeclRefExpr to FieldDecl.
10080 auto *CountDecl = cast<DeclRefExpr>(Val: E)->getDecl();
10081 Decls.push_back(Elt: TypeCoupledDeclRefInfo(CountDecl, /*IsDref*/ false));
10082}
10083
10084bool Sema::ActOnLateParsedTypeAttrArgument(BoundsAttributedType *BATy,
10085 FieldDecl *FD, Expr *Arg) {
10086 assert(Arg);
10087
10088 // Only the counted_by family exists so far.
10089 auto *CATy = cast<CountAttributedType>(Val: BATy);
10090
10091 auto Reject = [&]() -> bool {
10092 // Guarded so shared declarators (`IP __counted_by(n) a, b;`) only complete
10093 // the node once.
10094 if (!CATy->getCountExpr())
10095 Context.completeCountAttributedType(CATy, CountExpr: Arg, DependentDecls: {});
10096 FD->setInvalidDecl();
10097 return false;
10098 };
10099
10100 if (Arg->containsErrors())
10101 return Reject();
10102
10103 if (CheckCountedByAttrOnField(FD, E: Arg, CountInBytes: CATy->isCountInBytes(),
10104 OrNull: CATy->isOrNull()))
10105 return Reject();
10106
10107 llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls;
10108 BuildTypeCoupledDecls(E: Arg, Decls);
10109 // Several declarators can share one node when the attribute was written in
10110 // declaration-specifier position (`IP __counted_by(n) a, b;`), so this runs
10111 // once per field
10112 if (!CATy->getCountExpr())
10113 Context.completeCountAttributedType(CATy, CountExpr: Arg, DependentDecls: Decls);
10114
10115 return true;
10116}
10117
10118QualType Sema::BuildCountAttributedArrayOrPointerType(QualType WrappedTy,
10119 Expr *CountExpr,
10120 bool CountInBytes,
10121 bool OrNull) {
10122 assert(WrappedTy->isIncompleteArrayType() || WrappedTy->isPointerType());
10123
10124 llvm::SmallVector<TypeCoupledDeclRefInfo, 1> Decls;
10125 BuildTypeCoupledDecls(E: CountExpr, Decls);
10126 /// When the resulting expression is invalid, we still create the AST using
10127 /// the original count expression for the sake of AST dump.
10128 return Context.getCountAttributedType(T: WrappedTy, CountExpr, CountInBytes,
10129 OrNull, DependentDecls: Decls);
10130}
10131
10132/// getDecltypeForExpr - Given an expr, will return the decltype for
10133/// that expression, according to the rules in C++11
10134/// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
10135QualType Sema::getDecltypeForExpr(Expr *E) {
10136
10137 Expr *IDExpr = E;
10138 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(Val: E))
10139 IDExpr = ImplCastExpr->getSubExpr();
10140
10141 if (auto *PackExpr = dyn_cast<PackIndexingExpr>(Val: E)) {
10142 if (E->isInstantiationDependent())
10143 IDExpr = PackExpr->getPackIdExpression();
10144 else
10145 IDExpr = PackExpr->getSelectedExpr();
10146 }
10147
10148 if (E->isTypeDependent())
10149 return Context.DependentTy;
10150
10151 // C++11 [dcl.type.simple]p4:
10152 // The type denoted by decltype(e) is defined as follows:
10153
10154 // C++20:
10155 // - if E is an unparenthesized id-expression naming a non-type
10156 // template-parameter (13.2), decltype(E) is the type of the
10157 // template-parameter after performing any necessary type deduction
10158 // Note that this does not pick up the implicit 'const' for a template
10159 // parameter object. This rule makes no difference before C++20 so we apply
10160 // it unconditionally.
10161 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(Val: IDExpr))
10162 IDExpr = SNTTPE->getReplacement();
10163
10164 // - if e is an unparenthesized id-expression or an unparenthesized class
10165 // member access (5.2.5), decltype(e) is the type of the entity named
10166 // by e. If there is no such entity, or if e names a set of overloaded
10167 // functions, the program is ill-formed;
10168 //
10169 // We apply the same rules for Objective-C ivar and property references.
10170 if (const auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr)) {
10171 const ValueDecl *VD = DRE->getDecl();
10172 QualType T = VD->getType();
10173 return isa<TemplateParamObjectDecl>(Val: VD) ? T.getUnqualifiedType() : T;
10174 }
10175 if (const auto *ME = dyn_cast<MemberExpr>(Val: IDExpr)) {
10176 if (const auto *VD = ME->getMemberDecl())
10177 if (isa<FieldDecl>(Val: VD) || isa<VarDecl>(Val: VD))
10178 return VD->getType();
10179 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(Val: IDExpr)) {
10180 return IR->getDecl()->getType();
10181 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(Val: IDExpr)) {
10182 if (PR->isExplicitProperty())
10183 return PR->getExplicitProperty()->getType();
10184 } else if (const auto *PE = dyn_cast<PredefinedExpr>(Val: IDExpr)) {
10185 return PE->getType();
10186 }
10187
10188 // C++11 [expr.lambda.prim]p18:
10189 // Every occurrence of decltype((x)) where x is a possibly
10190 // parenthesized id-expression that names an entity of automatic
10191 // storage duration is treated as if x were transformed into an
10192 // access to a corresponding data member of the closure type that
10193 // would have been declared if x were an odr-use of the denoted
10194 // entity.
10195 if (getCurLambda() && isa<ParenExpr>(Val: IDExpr)) {
10196 if (auto *DRE = dyn_cast<DeclRefExpr>(Val: IDExpr->IgnoreParens())) {
10197 if (auto *Var = dyn_cast<VarDecl>(Val: DRE->getDecl())) {
10198 QualType T = getCapturedDeclRefType(Var, Loc: DRE->getLocation());
10199 if (!T.isNull())
10200 return Context.getLValueReferenceType(T);
10201 }
10202 }
10203 }
10204
10205 return Context.getReferenceQualifiedType(e: E);
10206}
10207
10208QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
10209 assert(!E->hasPlaceholderType() && "unexpected placeholder");
10210
10211 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
10212 !E->isInstantiationDependent() && E->HasSideEffects(Ctx: Context, IncludePossibleEffects: false)) {
10213 // The expression operand for decltype is in an unevaluated expression
10214 // context, so side effects could result in unintended consequences.
10215 // Exclude instantiation-dependent expressions, because 'decltype' is often
10216 // used to build SFINAE gadgets.
10217 Diag(Loc: E->getExprLoc(), DiagID: diag::warn_side_effects_unevaluated_context);
10218 }
10219 return Context.getDecltypeType(e: E, UnderlyingType: getDecltypeForExpr(E));
10220}
10221
10222QualType Sema::ActOnPackIndexingType(QualType Pattern, Expr *IndexExpr,
10223 SourceLocation Loc) {
10224 if (!IndexExpr)
10225 return QualType();
10226
10227 // Diagnose unexpanded packs but continue to improve recovery.
10228 if (!Pattern->containsUnexpandedParameterPack())
10229 Diag(Loc, DiagID: diag::err_expected_name_of_pack) << Pattern;
10230
10231 QualType Type = BuildPackIndexingType(Pattern, IndexExpr, Loc);
10232
10233 if (!Type.isNull())
10234 DiagCompat(Loc, CompatDiagId: diag_compat::pack_indexing);
10235 return Type;
10236}
10237
10238QualType Sema::BuildPackIndexingType(QualType Pattern, Expr *IndexExpr,
10239 SourceLocation Loc, bool FullySubstituted,
10240 ArrayRef<QualType> Expansions) {
10241
10242 UnsignedOrNone Index = std::nullopt;
10243 if (!IndexExpr->isInstantiationDependent()) {
10244 llvm::APSInt Value;
10245 ExprResult Res = CheckConvertedConstantExpression(
10246 From: IndexExpr, T: Context.getSizeType(), Value, CCE: CCEKind::PackIndex);
10247
10248 if (!Res.isUsable() || !Value.isRepresentableByInt64())
10249 return QualType();
10250
10251 IndexExpr = Res.get();
10252 uint64_t V = Value.getZExtValue();
10253 if (FullySubstituted && V >= Expansions.size()) {
10254 Diag(Loc: IndexExpr->getBeginLoc(), DiagID: diag::err_pack_index_out_of_bound)
10255 << V << Pattern << Expansions.size();
10256 return QualType();
10257 }
10258 Index = static_cast<unsigned>(V);
10259 }
10260
10261 return Context.getPackIndexingType(Pattern, IndexExpr, FullySubstituted,
10262 Expansions, Index);
10263}
10264
10265static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
10266 SourceLocation Loc) {
10267 assert(BaseType->isEnumeralType());
10268 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
10269
10270 S.DiagnoseUseOfDecl(D: ED, Locs: Loc);
10271
10272 QualType Underlying = ED->getIntegerType();
10273 if (Underlying.isNull()) {
10274 Underlying = ED->getDefinition()->getIntegerType();
10275 assert(!Underlying.isNull());
10276 }
10277
10278 return Underlying;
10279}
10280
10281QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
10282 SourceLocation Loc) {
10283 if (!BaseType->isEnumeralType()) {
10284 Diag(Loc, DiagID: diag::err_only_enums_have_underlying_types);
10285 return QualType();
10286 }
10287
10288 // The enum could be incomplete if we're parsing its definition or
10289 // recovering from an error.
10290 NamedDecl *FwdDecl = nullptr;
10291 if (BaseType->isIncompleteType(Def: &FwdDecl)) {
10292 Diag(Loc, DiagID: diag::err_underlying_type_of_incomplete_enum) << BaseType;
10293 Diag(Loc: FwdDecl->getLocation(), DiagID: diag::note_forward_declaration) << FwdDecl;
10294 return QualType();
10295 }
10296
10297 return GetEnumUnderlyingType(S&: *this, BaseType, Loc);
10298}
10299
10300QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
10301 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
10302 ? BuildPointerType(T: BaseType.getNonReferenceType(), Loc,
10303 Entity: DeclarationName())
10304 : BaseType;
10305
10306 return Pointer.isNull() ? QualType() : Pointer;
10307}
10308
10309QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
10310 if (!BaseType->isAnyPointerType())
10311 return BaseType;
10312
10313 return BaseType->getPointeeType();
10314}
10315
10316QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
10317 QualType Underlying = BaseType.getNonReferenceType();
10318 if (Underlying->isArrayType())
10319 return Context.getDecayedType(T: Underlying);
10320
10321 if (Underlying->isFunctionType())
10322 return BuiltinAddPointer(BaseType, Loc);
10323
10324 SplitQualType Split = Underlying.getSplitUnqualifiedType();
10325 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
10326 // in the same group of qualifiers as 'const' and 'volatile', we're extending
10327 // '__decay(T)' so that it removes all qualifiers.
10328 Split.Quals.removeCVRQualifiers();
10329 return Context.getQualifiedType(split: Split);
10330}
10331
10332QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
10333 SourceLocation Loc) {
10334 assert(LangOpts.CPlusPlus);
10335 QualType Reference =
10336 BaseType.isReferenceable()
10337 ? BuildReferenceType(T: BaseType,
10338 SpelledAsLValue: UKind == UnaryTransformType::AddLvalueReference,
10339 Loc, Entity: DeclarationName())
10340 : BaseType;
10341 return Reference.isNull() ? QualType() : Reference;
10342}
10343
10344QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
10345 SourceLocation Loc) {
10346 if (UKind == UnaryTransformType::RemoveAllExtents)
10347 return Context.getBaseElementType(QT: BaseType);
10348
10349 if (const auto *AT = Context.getAsArrayType(T: BaseType))
10350 return AT->getElementType();
10351
10352 return BaseType;
10353}
10354
10355QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
10356 SourceLocation Loc) {
10357 assert(LangOpts.CPlusPlus);
10358 QualType T = BaseType.getNonReferenceType();
10359 if (UKind == UTTKind::RemoveCVRef &&
10360 (T.isConstQualified() || T.isVolatileQualified())) {
10361 Qualifiers Quals;
10362 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
10363 Quals.removeConst();
10364 Quals.removeVolatile();
10365 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
10366 }
10367 return T;
10368}
10369
10370QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
10371 SourceLocation Loc) {
10372 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
10373 BaseType->isFunctionType())
10374 return BaseType;
10375
10376 Qualifiers Quals;
10377 QualType Unqual = Context.getUnqualifiedArrayType(T: BaseType, Quals);
10378
10379 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
10380 Quals.removeConst();
10381 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
10382 Quals.removeVolatile();
10383 if (UKind == UTTKind::RemoveRestrict)
10384 Quals.removeRestrict();
10385
10386 return Context.getQualifiedType(T: Unqual, Qs: Quals);
10387}
10388
10389static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
10390 bool IsMakeSigned,
10391 SourceLocation Loc) {
10392 if (BaseType->isEnumeralType()) {
10393 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
10394 if (auto *BitInt = dyn_cast<BitIntType>(Val&: Underlying)) {
10395 unsigned int Bits = BitInt->getNumBits();
10396 if (Bits > 1)
10397 return S.Context.getBitIntType(Unsigned: !IsMakeSigned, NumBits: Bits);
10398
10399 S.Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10400 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
10401 return QualType();
10402 }
10403 if (Underlying->isBooleanType()) {
10404 S.Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10405 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
10406 << Underlying;
10407 return QualType();
10408 }
10409 }
10410
10411 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
10412 std::array<CanQualType *, 6> AllSignedIntegers = {
10413 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
10414 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
10415 ArrayRef<CanQualType *> AvailableSignedIntegers(
10416 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
10417 std::array<CanQualType *, 6> AllUnsignedIntegers = {
10418 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
10419 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
10420 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
10421 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
10422 AllUnsignedIntegers.size() -
10423 Int128Unsupported);
10424 ArrayRef<CanQualType *> *Consider =
10425 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
10426
10427 uint64_t BaseSize = S.Context.getTypeSize(T: BaseType);
10428 auto *Result =
10429 llvm::find_if(Range&: *Consider, P: [&S, BaseSize](const CanQual<Type> *T) {
10430 return BaseSize == S.Context.getTypeSize(T: T->getTypePtr());
10431 });
10432
10433 assert(Result != Consider->end());
10434 return QualType((*Result)->getTypePtr(), 0);
10435}
10436
10437QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
10438 SourceLocation Loc) {
10439 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
10440 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
10441 BaseType->isBooleanType() ||
10442 (BaseType->isBitIntType() &&
10443 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
10444 Diag(Loc, DiagID: diag::err_make_signed_integral_only)
10445 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
10446 return QualType();
10447 }
10448
10449 bool IsNonIntIntegral =
10450 BaseType->isChar16Type() || BaseType->isChar32Type() ||
10451 BaseType->isWideCharType() || BaseType->isEnumeralType();
10452
10453 QualType Underlying =
10454 IsNonIntIntegral
10455 ? ChangeIntegralSignedness(S&: *this, BaseType, IsMakeSigned, Loc)
10456 : IsMakeSigned ? Context.getCorrespondingSignedType(T: BaseType)
10457 : Context.getCorrespondingUnsignedType(T: BaseType);
10458 if (Underlying.isNull())
10459 return Underlying;
10460 return Context.getQualifiedType(T: Underlying, Qs: BaseType.getQualifiers());
10461}
10462
10463QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
10464 SourceLocation Loc) {
10465 if (BaseType->isDependentType())
10466 return Context.getUnaryTransformType(BaseType, UnderlyingType: BaseType, UKind);
10467 QualType Result;
10468 switch (UKind) {
10469 case UnaryTransformType::EnumUnderlyingType: {
10470 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
10471 break;
10472 }
10473 case UnaryTransformType::AddPointer: {
10474 Result = BuiltinAddPointer(BaseType, Loc);
10475 break;
10476 }
10477 case UnaryTransformType::RemovePointer: {
10478 Result = BuiltinRemovePointer(BaseType, Loc);
10479 break;
10480 }
10481 case UnaryTransformType::Decay: {
10482 Result = BuiltinDecay(BaseType, Loc);
10483 break;
10484 }
10485 case UnaryTransformType::AddLvalueReference:
10486 case UnaryTransformType::AddRvalueReference: {
10487 Result = BuiltinAddReference(BaseType, UKind, Loc);
10488 break;
10489 }
10490 case UnaryTransformType::RemoveAllExtents:
10491 case UnaryTransformType::RemoveExtent: {
10492 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
10493 break;
10494 }
10495 case UnaryTransformType::RemoveCVRef:
10496 case UnaryTransformType::RemoveReference: {
10497 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
10498 break;
10499 }
10500 case UnaryTransformType::RemoveConst:
10501 case UnaryTransformType::RemoveCV:
10502 case UnaryTransformType::RemoveRestrict:
10503 case UnaryTransformType::RemoveVolatile: {
10504 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
10505 break;
10506 }
10507 case UnaryTransformType::MakeSigned:
10508 case UnaryTransformType::MakeUnsigned: {
10509 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
10510 break;
10511 }
10512 }
10513
10514 return !Result.isNull()
10515 ? Context.getUnaryTransformType(BaseType, UnderlyingType: Result, UKind)
10516 : Result;
10517}
10518
10519QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
10520 if (!T->isDependentType() && !isa<AutoType>(Val: T)) {
10521 // FIXME: It isn't entirely clear whether incomplete atomic types
10522 // are allowed or not; for simplicity, ban them for the moment.
10523 if (RequireCompleteType(Loc, T, DiagID: diag::err_atomic_specifier_bad_type, Args: 0))
10524 return QualType();
10525
10526 int DisallowedKind = -1;
10527 if (T->isArrayType())
10528 DisallowedKind = 1;
10529 else if (T->isFunctionType())
10530 DisallowedKind = 2;
10531 else if (T->isReferenceType())
10532 DisallowedKind = 3;
10533 else if (T->isAtomicType())
10534 DisallowedKind = 4;
10535 else if (T.hasQualifiers())
10536 DisallowedKind = 5;
10537 else if (T->isSizelessType())
10538 DisallowedKind = 6;
10539 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
10540 // Some other non-trivially-copyable type (probably a C++ class)
10541 DisallowedKind = 7;
10542 else if (T->isBitIntType())
10543 DisallowedKind = 8;
10544 else if (getLangOpts().C23 && T->isUndeducedAutoType())
10545 // _Atomic auto is prohibited in C23
10546 DisallowedKind = 9;
10547 else if (T->isOverflowBehaviorType())
10548 // Overflow behavior types do not compose with _Atomic
10549 DisallowedKind = 10;
10550
10551 if (DisallowedKind != -1) {
10552 Diag(Loc, DiagID: diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
10553 return QualType();
10554 }
10555
10556 // FIXME: Do we need any handling for ARC here?
10557 }
10558
10559 // Build the pointer type.
10560 return Context.getAtomicType(T);
10561}
10562