[clang][modules] Don't prevent translation of FW_Private includes when explicitly...
[llvm-project.git] / clang / lib / Sema / SemaType.cpp
bloba46deed8e7c58b4d1a599db7b6882817b08cfc3c
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.
11 //===----------------------------------------------------------------------===//
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/Type.h"
24 #include "clang/AST/TypeLoc.h"
25 #include "clang/AST/TypeLocVisitor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/SourceLocation.h"
28 #include "clang/Basic/Specifiers.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Preprocessor.h"
31 #include "clang/Sema/DeclSpec.h"
32 #include "clang/Sema/DelayedDiagnostic.h"
33 #include "clang/Sema/Lookup.h"
34 #include "clang/Sema/ParsedTemplate.h"
35 #include "clang/Sema/ScopeInfo.h"
36 #include "clang/Sema/SemaInternal.h"
37 #include "clang/Sema/Template.h"
38 #include "clang/Sema/TemplateInstCallback.h"
39 #include "llvm/ADT/ArrayRef.h"
40 #include "llvm/ADT/SmallPtrSet.h"
41 #include "llvm/ADT/SmallString.h"
42 #include "llvm/ADT/StringExtras.h"
43 #include "llvm/IR/DerivedTypes.h"
44 #include "llvm/Support/Casting.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include <bitset>
47 #include <optional>
49 using namespace clang;
51 enum TypeDiagSelector {
52 TDS_Function,
53 TDS_Pointer,
54 TDS_ObjCObjOrBlock
57 /// isOmittedBlockReturnType - Return true if this declarator is missing a
58 /// return type because this is a omitted return type on a block literal.
59 static bool isOmittedBlockReturnType(const Declarator &D) {
60 if (D.getContext() != DeclaratorContext::BlockLiteral ||
61 D.getDeclSpec().hasTypeSpecifier())
62 return false;
64 if (D.getNumTypeObjects() == 0)
65 return true; // ^{ ... }
67 if (D.getNumTypeObjects() == 1 &&
68 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
69 return true; // ^(int X, float Y) { ... }
71 return false;
74 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
75 /// doesn't apply to the given type.
76 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
77 QualType type) {
78 TypeDiagSelector WhichType;
79 bool useExpansionLoc = true;
80 switch (attr.getKind()) {
81 case ParsedAttr::AT_ObjCGC:
82 WhichType = TDS_Pointer;
83 break;
84 case ParsedAttr::AT_ObjCOwnership:
85 WhichType = TDS_ObjCObjOrBlock;
86 break;
87 default:
88 // Assume everything else was a function attribute.
89 WhichType = TDS_Function;
90 useExpansionLoc = false;
91 break;
94 SourceLocation loc = attr.getLoc();
95 StringRef name = attr.getAttrName()->getName();
97 // The GC attributes are usually written with macros; special-case them.
98 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
99 : nullptr;
100 if (useExpansionLoc && loc.isMacroID() && II) {
101 if (II->isStr("strong")) {
102 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
103 } else if (II->isStr("weak")) {
104 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
108 S.Diag(loc, attr.isRegularKeywordAttribute()
109 ? diag::err_type_attribute_wrong_type
110 : diag::warn_type_attribute_wrong_type)
111 << name << WhichType << type;
114 // objc_gc applies to Objective-C pointers or, otherwise, to the
115 // smallest available pointer type (i.e. 'void*' in 'void**').
116 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
117 case ParsedAttr::AT_ObjCGC: \
118 case ParsedAttr::AT_ObjCOwnership
120 // Calling convention attributes.
121 #define CALLING_CONV_ATTRS_CASELIST \
122 case ParsedAttr::AT_CDecl: \
123 case ParsedAttr::AT_FastCall: \
124 case ParsedAttr::AT_StdCall: \
125 case ParsedAttr::AT_ThisCall: \
126 case ParsedAttr::AT_RegCall: \
127 case ParsedAttr::AT_Pascal: \
128 case ParsedAttr::AT_SwiftCall: \
129 case ParsedAttr::AT_SwiftAsyncCall: \
130 case ParsedAttr::AT_VectorCall: \
131 case ParsedAttr::AT_AArch64VectorPcs: \
132 case ParsedAttr::AT_AArch64SVEPcs: \
133 case ParsedAttr::AT_AMDGPUKernelCall: \
134 case ParsedAttr::AT_MSABI: \
135 case ParsedAttr::AT_SysVABI: \
136 case ParsedAttr::AT_Pcs: \
137 case ParsedAttr::AT_IntelOclBicc: \
138 case ParsedAttr::AT_PreserveMost: \
139 case ParsedAttr::AT_PreserveAll: \
140 case ParsedAttr::AT_M68kRTD
142 // Function type attributes.
143 #define FUNCTION_TYPE_ATTRS_CASELIST \
144 case ParsedAttr::AT_NSReturnsRetained: \
145 case ParsedAttr::AT_NoReturn: \
146 case ParsedAttr::AT_Regparm: \
147 case ParsedAttr::AT_CmseNSCall: \
148 case ParsedAttr::AT_ArmStreaming: \
149 case ParsedAttr::AT_ArmStreamingCompatible: \
150 case ParsedAttr::AT_ArmSharedZA: \
151 case ParsedAttr::AT_ArmPreservesZA: \
152 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
153 case ParsedAttr::AT_AnyX86NoCfCheck: \
154 CALLING_CONV_ATTRS_CASELIST
156 // Microsoft-specific type qualifiers.
157 #define MS_TYPE_ATTRS_CASELIST \
158 case ParsedAttr::AT_Ptr32: \
159 case ParsedAttr::AT_Ptr64: \
160 case ParsedAttr::AT_SPtr: \
161 case ParsedAttr::AT_UPtr
163 // Nullability qualifiers.
164 #define NULLABILITY_TYPE_ATTRS_CASELIST \
165 case ParsedAttr::AT_TypeNonNull: \
166 case ParsedAttr::AT_TypeNullable: \
167 case ParsedAttr::AT_TypeNullableResult: \
168 case ParsedAttr::AT_TypeNullUnspecified
170 namespace {
171 /// An object which stores processing state for the entire
172 /// GetTypeForDeclarator process.
173 class TypeProcessingState {
174 Sema &sema;
176 /// The declarator being processed.
177 Declarator &declarator;
179 /// The index of the declarator chunk we're currently processing.
180 /// May be the total number of valid chunks, indicating the
181 /// DeclSpec.
182 unsigned chunkIndex;
184 /// The original set of attributes on the DeclSpec.
185 SmallVector<ParsedAttr *, 2> savedAttrs;
187 /// A list of attributes to diagnose the uselessness of when the
188 /// processing is complete.
189 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
191 /// Attributes corresponding to AttributedTypeLocs that we have not yet
192 /// populated.
193 // FIXME: The two-phase mechanism by which we construct Types and fill
194 // their TypeLocs makes it hard to correctly assign these. We keep the
195 // attributes in creation order as an attempt to make them line up
196 // properly.
197 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
198 SmallVector<TypeAttrPair, 8> AttrsForTypes;
199 bool AttrsForTypesSorted = true;
201 /// MacroQualifiedTypes mapping to macro expansion locations that will be
202 /// stored in a MacroQualifiedTypeLoc.
203 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
205 /// Flag to indicate we parsed a noderef attribute. This is used for
206 /// validating that noderef was used on a pointer or array.
207 bool parsedNoDeref;
209 public:
210 TypeProcessingState(Sema &sema, Declarator &declarator)
211 : sema(sema), declarator(declarator),
212 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
214 Sema &getSema() const {
215 return sema;
218 Declarator &getDeclarator() const {
219 return declarator;
222 bool isProcessingDeclSpec() const {
223 return chunkIndex == declarator.getNumTypeObjects();
226 unsigned getCurrentChunkIndex() const {
227 return chunkIndex;
230 void setCurrentChunkIndex(unsigned idx) {
231 assert(idx <= declarator.getNumTypeObjects());
232 chunkIndex = idx;
235 ParsedAttributesView &getCurrentAttributes() const {
236 if (isProcessingDeclSpec())
237 return getMutableDeclSpec().getAttributes();
238 return declarator.getTypeObject(chunkIndex).getAttrs();
241 /// Save the current set of attributes on the DeclSpec.
242 void saveDeclSpecAttrs() {
243 // Don't try to save them multiple times.
244 if (!savedAttrs.empty())
245 return;
247 DeclSpec &spec = getMutableDeclSpec();
248 llvm::append_range(savedAttrs,
249 llvm::make_pointer_range(spec.getAttributes()));
252 /// Record that we had nowhere to put the given type attribute.
253 /// We will diagnose such attributes later.
254 void addIgnoredTypeAttr(ParsedAttr &attr) {
255 ignoredTypeAttrs.push_back(&attr);
258 /// Diagnose all the ignored type attributes, given that the
259 /// declarator worked out to the given type.
260 void diagnoseIgnoredTypeAttrs(QualType type) const {
261 for (auto *Attr : ignoredTypeAttrs)
262 diagnoseBadTypeAttribute(getSema(), *Attr, type);
265 /// Get an attributed type for the given attribute, and remember the Attr
266 /// object so that we can attach it to the AttributedTypeLoc.
267 QualType getAttributedType(Attr *A, QualType ModifiedType,
268 QualType EquivType) {
269 QualType T =
270 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
271 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
272 AttrsForTypesSorted = false;
273 return T;
276 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
277 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
278 QualType WrappedType) {
279 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
282 /// Completely replace the \c auto in \p TypeWithAuto by
283 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
284 /// necessary.
285 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
286 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
287 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
288 // Attributed type still should be an attributed type after replacement.
289 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
290 for (TypeAttrPair &A : AttrsForTypes) {
291 if (A.first == AttrTy)
292 A.first = NewAttrTy;
294 AttrsForTypesSorted = false;
296 return T;
299 /// Extract and remove the Attr* for a given attributed type.
300 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
301 if (!AttrsForTypesSorted) {
302 llvm::stable_sort(AttrsForTypes, llvm::less_first());
303 AttrsForTypesSorted = true;
306 // FIXME: This is quadratic if we have lots of reuses of the same
307 // attributed type.
308 for (auto It = std::partition_point(
309 AttrsForTypes.begin(), AttrsForTypes.end(),
310 [=](const TypeAttrPair &A) { return A.first < AT; });
311 It != AttrsForTypes.end() && It->first == AT; ++It) {
312 if (It->second) {
313 const Attr *Result = It->second;
314 It->second = nullptr;
315 return Result;
319 llvm_unreachable("no Attr* for AttributedType*");
322 SourceLocation
323 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
324 auto FoundLoc = LocsForMacros.find(MQT);
325 assert(FoundLoc != LocsForMacros.end() &&
326 "Unable to find macro expansion location for MacroQualifedType");
327 return FoundLoc->second;
330 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
331 SourceLocation Loc) {
332 LocsForMacros[MQT] = Loc;
335 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
337 bool didParseNoDeref() const { return parsedNoDeref; }
339 ~TypeProcessingState() {
340 if (savedAttrs.empty())
341 return;
343 getMutableDeclSpec().getAttributes().clearListOnly();
344 for (ParsedAttr *AL : savedAttrs)
345 getMutableDeclSpec().getAttributes().addAtEnd(AL);
348 private:
349 DeclSpec &getMutableDeclSpec() const {
350 return const_cast<DeclSpec&>(declarator.getDeclSpec());
353 } // end anonymous namespace
355 static void moveAttrFromListToList(ParsedAttr &attr,
356 ParsedAttributesView &fromList,
357 ParsedAttributesView &toList) {
358 fromList.remove(&attr);
359 toList.addAtEnd(&attr);
362 /// The location of a type attribute.
363 enum TypeAttrLocation {
364 /// The attribute is in the decl-specifier-seq.
365 TAL_DeclSpec,
366 /// The attribute is part of a DeclaratorChunk.
367 TAL_DeclChunk,
368 /// The attribute is immediately after the declaration's name.
369 TAL_DeclName
372 static void
373 processTypeAttrs(TypeProcessingState &state, QualType &type,
374 TypeAttrLocation TAL, const ParsedAttributesView &attrs,
375 Sema::CUDAFunctionTarget CFT = Sema::CFT_HostDevice);
377 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
378 QualType &type,
379 Sema::CUDAFunctionTarget CFT);
381 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
382 ParsedAttr &attr, QualType &type);
384 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
385 QualType &type);
387 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
388 ParsedAttr &attr, QualType &type);
390 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
391 ParsedAttr &attr, QualType &type) {
392 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
393 return handleObjCGCTypeAttr(state, attr, type);
394 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
395 return handleObjCOwnershipTypeAttr(state, attr, type);
398 /// Given the index of a declarator chunk, check whether that chunk
399 /// directly specifies the return type of a function and, if so, find
400 /// an appropriate place for it.
402 /// \param i - a notional index which the search will start
403 /// immediately inside
405 /// \param onlyBlockPointers Whether we should only look into block
406 /// pointer types (vs. all pointer types).
407 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
408 unsigned i,
409 bool onlyBlockPointers) {
410 assert(i <= declarator.getNumTypeObjects());
412 DeclaratorChunk *result = nullptr;
414 // First, look inwards past parens for a function declarator.
415 for (; i != 0; --i) {
416 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
417 switch (fnChunk.Kind) {
418 case DeclaratorChunk::Paren:
419 continue;
421 // If we find anything except a function, bail out.
422 case DeclaratorChunk::Pointer:
423 case DeclaratorChunk::BlockPointer:
424 case DeclaratorChunk::Array:
425 case DeclaratorChunk::Reference:
426 case DeclaratorChunk::MemberPointer:
427 case DeclaratorChunk::Pipe:
428 return result;
430 // If we do find a function declarator, scan inwards from that,
431 // looking for a (block-)pointer declarator.
432 case DeclaratorChunk::Function:
433 for (--i; i != 0; --i) {
434 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
435 switch (ptrChunk.Kind) {
436 case DeclaratorChunk::Paren:
437 case DeclaratorChunk::Array:
438 case DeclaratorChunk::Function:
439 case DeclaratorChunk::Reference:
440 case DeclaratorChunk::Pipe:
441 continue;
443 case DeclaratorChunk::MemberPointer:
444 case DeclaratorChunk::Pointer:
445 if (onlyBlockPointers)
446 continue;
448 [[fallthrough]];
450 case DeclaratorChunk::BlockPointer:
451 result = &ptrChunk;
452 goto continue_outer;
454 llvm_unreachable("bad declarator chunk kind");
457 // If we run out of declarators doing that, we're done.
458 return result;
460 llvm_unreachable("bad declarator chunk kind");
462 // Okay, reconsider from our new point.
463 continue_outer: ;
466 // Ran out of chunks, bail out.
467 return result;
470 /// Given that an objc_gc attribute was written somewhere on a
471 /// declaration *other* than on the declarator itself (for which, use
472 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
473 /// didn't apply in whatever position it was written in, try to move
474 /// it to a more appropriate position.
475 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
476 ParsedAttr &attr, QualType type) {
477 Declarator &declarator = state.getDeclarator();
479 // Move it to the outermost normal or block pointer declarator.
480 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
481 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
482 switch (chunk.Kind) {
483 case DeclaratorChunk::Pointer:
484 case DeclaratorChunk::BlockPointer: {
485 // But don't move an ARC ownership attribute to the return type
486 // of a block.
487 DeclaratorChunk *destChunk = nullptr;
488 if (state.isProcessingDeclSpec() &&
489 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
490 destChunk = maybeMovePastReturnType(declarator, i - 1,
491 /*onlyBlockPointers=*/true);
492 if (!destChunk) destChunk = &chunk;
494 moveAttrFromListToList(attr, state.getCurrentAttributes(),
495 destChunk->getAttrs());
496 return;
499 case DeclaratorChunk::Paren:
500 case DeclaratorChunk::Array:
501 continue;
503 // We may be starting at the return type of a block.
504 case DeclaratorChunk::Function:
505 if (state.isProcessingDeclSpec() &&
506 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
507 if (DeclaratorChunk *dest = maybeMovePastReturnType(
508 declarator, i,
509 /*onlyBlockPointers=*/true)) {
510 moveAttrFromListToList(attr, state.getCurrentAttributes(),
511 dest->getAttrs());
512 return;
515 goto error;
517 // Don't walk through these.
518 case DeclaratorChunk::Reference:
519 case DeclaratorChunk::MemberPointer:
520 case DeclaratorChunk::Pipe:
521 goto error;
524 error:
526 diagnoseBadTypeAttribute(state.getSema(), attr, type);
529 /// Distribute an objc_gc type attribute that was written on the
530 /// declarator.
531 static void distributeObjCPointerTypeAttrFromDeclarator(
532 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
533 Declarator &declarator = state.getDeclarator();
535 // objc_gc goes on the innermost pointer to something that's not a
536 // pointer.
537 unsigned innermost = -1U;
538 bool considerDeclSpec = true;
539 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
540 DeclaratorChunk &chunk = declarator.getTypeObject(i);
541 switch (chunk.Kind) {
542 case DeclaratorChunk::Pointer:
543 case DeclaratorChunk::BlockPointer:
544 innermost = i;
545 continue;
547 case DeclaratorChunk::Reference:
548 case DeclaratorChunk::MemberPointer:
549 case DeclaratorChunk::Paren:
550 case DeclaratorChunk::Array:
551 case DeclaratorChunk::Pipe:
552 continue;
554 case DeclaratorChunk::Function:
555 considerDeclSpec = false;
556 goto done;
559 done:
561 // That might actually be the decl spec if we weren't blocked by
562 // anything in the declarator.
563 if (considerDeclSpec) {
564 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
565 // Splice the attribute into the decl spec. Prevents the
566 // attribute from being applied multiple times and gives
567 // the source-location-filler something to work with.
568 state.saveDeclSpecAttrs();
569 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
570 declarator.getAttributes(), &attr);
571 return;
575 // Otherwise, if we found an appropriate chunk, splice the attribute
576 // into it.
577 if (innermost != -1U) {
578 moveAttrFromListToList(attr, declarator.getAttributes(),
579 declarator.getTypeObject(innermost).getAttrs());
580 return;
583 // Otherwise, diagnose when we're done building the type.
584 declarator.getAttributes().remove(&attr);
585 state.addIgnoredTypeAttr(attr);
588 /// A function type attribute was written somewhere in a declaration
589 /// *other* than on the declarator itself or in the decl spec. Given
590 /// that it didn't apply in whatever position it was written in, try
591 /// to move it to a more appropriate position.
592 static void distributeFunctionTypeAttr(TypeProcessingState &state,
593 ParsedAttr &attr, QualType type) {
594 Declarator &declarator = state.getDeclarator();
596 // Try to push the attribute from the return type of a function to
597 // the function itself.
598 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
599 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
600 switch (chunk.Kind) {
601 case DeclaratorChunk::Function:
602 moveAttrFromListToList(attr, state.getCurrentAttributes(),
603 chunk.getAttrs());
604 return;
606 case DeclaratorChunk::Paren:
607 case DeclaratorChunk::Pointer:
608 case DeclaratorChunk::BlockPointer:
609 case DeclaratorChunk::Array:
610 case DeclaratorChunk::Reference:
611 case DeclaratorChunk::MemberPointer:
612 case DeclaratorChunk::Pipe:
613 continue;
617 diagnoseBadTypeAttribute(state.getSema(), attr, type);
620 /// Try to distribute a function type attribute to the innermost
621 /// function chunk or type. Returns true if the attribute was
622 /// distributed, false if no location was found.
623 static bool distributeFunctionTypeAttrToInnermost(
624 TypeProcessingState &state, ParsedAttr &attr,
625 ParsedAttributesView &attrList, QualType &declSpecType,
626 Sema::CUDAFunctionTarget CFT) {
627 Declarator &declarator = state.getDeclarator();
629 // Put it on the innermost function chunk, if there is one.
630 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
631 DeclaratorChunk &chunk = declarator.getTypeObject(i);
632 if (chunk.Kind != DeclaratorChunk::Function) continue;
634 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
635 return true;
638 return handleFunctionTypeAttr(state, attr, declSpecType, CFT);
641 /// A function type attribute was written in the decl spec. Try to
642 /// apply it somewhere.
643 static void
644 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
645 ParsedAttr &attr, QualType &declSpecType,
646 Sema::CUDAFunctionTarget CFT) {
647 state.saveDeclSpecAttrs();
649 // Try to distribute to the innermost.
650 if (distributeFunctionTypeAttrToInnermost(
651 state, attr, state.getCurrentAttributes(), declSpecType, CFT))
652 return;
654 // If that failed, diagnose the bad attribute when the declarator is
655 // fully built.
656 state.addIgnoredTypeAttr(attr);
659 /// A function type attribute was written on the declarator or declaration.
660 /// Try to apply it somewhere.
661 /// `Attrs` is the attribute list containing the declaration (either of the
662 /// declarator or the declaration).
663 static void distributeFunctionTypeAttrFromDeclarator(
664 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType,
665 Sema::CUDAFunctionTarget CFT) {
666 Declarator &declarator = state.getDeclarator();
668 // Try to distribute to the innermost.
669 if (distributeFunctionTypeAttrToInnermost(
670 state, attr, declarator.getAttributes(), declSpecType, CFT))
671 return;
673 // If that failed, diagnose the bad attribute when the declarator is
674 // fully built.
675 declarator.getAttributes().remove(&attr);
676 state.addIgnoredTypeAttr(attr);
679 /// Given that there are attributes written on the declarator or declaration
680 /// itself, try to distribute any type attributes to the appropriate
681 /// declarator chunk.
683 /// These are attributes like the following:
684 /// int f ATTR;
685 /// int (f ATTR)();
686 /// but not necessarily this:
687 /// int f() ATTR;
689 /// `Attrs` is the attribute list containing the declaration (either of the
690 /// declarator or the declaration).
691 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
692 QualType &declSpecType,
693 Sema::CUDAFunctionTarget CFT) {
694 // The called functions in this loop actually remove things from the current
695 // list, so iterating over the existing list isn't possible. Instead, make a
696 // non-owning copy and iterate over that.
697 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
698 for (ParsedAttr &attr : AttrsCopy) {
699 // Do not distribute [[]] attributes. They have strict rules for what
700 // they appertain to.
701 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute())
702 continue;
704 switch (attr.getKind()) {
705 OBJC_POINTER_TYPE_ATTRS_CASELIST:
706 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
707 break;
709 FUNCTION_TYPE_ATTRS_CASELIST:
710 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType, CFT);
711 break;
713 MS_TYPE_ATTRS_CASELIST:
714 // Microsoft type attributes cannot go after the declarator-id.
715 continue;
717 NULLABILITY_TYPE_ATTRS_CASELIST:
718 // Nullability specifiers cannot go after the declarator-id.
720 // Objective-C __kindof does not get distributed.
721 case ParsedAttr::AT_ObjCKindOf:
722 continue;
724 default:
725 break;
730 /// Add a synthetic '()' to a block-literal declarator if it is
731 /// required, given the return type.
732 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
733 QualType declSpecType) {
734 Declarator &declarator = state.getDeclarator();
736 // First, check whether the declarator would produce a function,
737 // i.e. whether the innermost semantic chunk is a function.
738 if (declarator.isFunctionDeclarator()) {
739 // If so, make that declarator a prototyped declarator.
740 declarator.getFunctionTypeInfo().hasPrototype = true;
741 return;
744 // If there are any type objects, the type as written won't name a
745 // function, regardless of the decl spec type. This is because a
746 // block signature declarator is always an abstract-declarator, and
747 // abstract-declarators can't just be parentheses chunks. Therefore
748 // we need to build a function chunk unless there are no type
749 // objects and the decl spec type is a function.
750 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
751 return;
753 // Note that there *are* cases with invalid declarators where
754 // declarators consist solely of parentheses. In general, these
755 // occur only in failed efforts to make function declarators, so
756 // faking up the function chunk is still the right thing to do.
758 // Otherwise, we need to fake up a function declarator.
759 SourceLocation loc = declarator.getBeginLoc();
761 // ...and *prepend* it to the declarator.
762 SourceLocation NoLoc;
763 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
764 /*HasProto=*/true,
765 /*IsAmbiguous=*/false,
766 /*LParenLoc=*/NoLoc,
767 /*ArgInfo=*/nullptr,
768 /*NumParams=*/0,
769 /*EllipsisLoc=*/NoLoc,
770 /*RParenLoc=*/NoLoc,
771 /*RefQualifierIsLvalueRef=*/true,
772 /*RefQualifierLoc=*/NoLoc,
773 /*MutableLoc=*/NoLoc, EST_None,
774 /*ESpecRange=*/SourceRange(),
775 /*Exceptions=*/nullptr,
776 /*ExceptionRanges=*/nullptr,
777 /*NumExceptions=*/0,
778 /*NoexceptExpr=*/nullptr,
779 /*ExceptionSpecTokens=*/nullptr,
780 /*DeclsInPrototype=*/std::nullopt, loc, loc, declarator));
782 // For consistency, make sure the state still has us as processing
783 // the decl spec.
784 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
785 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
788 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
789 unsigned &TypeQuals,
790 QualType TypeSoFar,
791 unsigned RemoveTQs,
792 unsigned DiagID) {
793 // If this occurs outside a template instantiation, warn the user about
794 // it; they probably didn't mean to specify a redundant qualifier.
795 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
796 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
797 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
798 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
799 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
800 if (!(RemoveTQs & Qual.first))
801 continue;
803 if (!S.inTemplateInstantiation()) {
804 if (TypeQuals & Qual.first)
805 S.Diag(Qual.second, DiagID)
806 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
807 << FixItHint::CreateRemoval(Qual.second);
810 TypeQuals &= ~Qual.first;
814 /// Return true if this is omitted block return type. Also check type
815 /// attributes and type qualifiers when returning true.
816 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
817 QualType Result) {
818 if (!isOmittedBlockReturnType(declarator))
819 return false;
821 // Warn if we see type attributes for omitted return type on a block literal.
822 SmallVector<ParsedAttr *, 2> ToBeRemoved;
823 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
824 if (AL.isInvalid() || !AL.isTypeAttr())
825 continue;
826 S.Diag(AL.getLoc(),
827 diag::warn_block_literal_attributes_on_omitted_return_type)
828 << AL;
829 ToBeRemoved.push_back(&AL);
831 // Remove bad attributes from the list.
832 for (ParsedAttr *AL : ToBeRemoved)
833 declarator.getMutableDeclSpec().getAttributes().remove(AL);
835 // Warn if we see type qualifiers for omitted return type on a block literal.
836 const DeclSpec &DS = declarator.getDeclSpec();
837 unsigned TypeQuals = DS.getTypeQualifiers();
838 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
839 diag::warn_block_literal_qualifiers_on_omitted_return_type);
840 declarator.getMutableDeclSpec().ClearTypeQualifiers();
842 return true;
845 /// Apply Objective-C type arguments to the given type.
846 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
847 ArrayRef<TypeSourceInfo *> typeArgs,
848 SourceRange typeArgsRange, bool failOnError,
849 bool rebuilding) {
850 // We can only apply type arguments to an Objective-C class type.
851 const auto *objcObjectType = type->getAs<ObjCObjectType>();
852 if (!objcObjectType || !objcObjectType->getInterface()) {
853 S.Diag(loc, diag::err_objc_type_args_non_class)
854 << type
855 << typeArgsRange;
857 if (failOnError)
858 return QualType();
859 return type;
862 // The class type must be parameterized.
863 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
864 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
865 if (!typeParams) {
866 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
867 << objcClass->getDeclName()
868 << FixItHint::CreateRemoval(typeArgsRange);
870 if (failOnError)
871 return QualType();
873 return type;
876 // The type must not already be specialized.
877 if (objcObjectType->isSpecialized()) {
878 S.Diag(loc, diag::err_objc_type_args_specialized_class)
879 << type
880 << FixItHint::CreateRemoval(typeArgsRange);
882 if (failOnError)
883 return QualType();
885 return type;
888 // Check the type arguments.
889 SmallVector<QualType, 4> finalTypeArgs;
890 unsigned numTypeParams = typeParams->size();
891 bool anyPackExpansions = false;
892 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
893 TypeSourceInfo *typeArgInfo = typeArgs[i];
894 QualType typeArg = typeArgInfo->getType();
896 // Type arguments cannot have explicit qualifiers or nullability.
897 // We ignore indirect sources of these, e.g. behind typedefs or
898 // template arguments.
899 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
900 bool diagnosed = false;
901 SourceRange rangeToRemove;
902 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
903 rangeToRemove = attr.getLocalSourceRange();
904 if (attr.getTypePtr()->getImmediateNullability()) {
905 typeArg = attr.getTypePtr()->getModifiedType();
906 S.Diag(attr.getBeginLoc(),
907 diag::err_objc_type_arg_explicit_nullability)
908 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
909 diagnosed = true;
913 // When rebuilding, qualifiers might have gotten here through a
914 // final substitution.
915 if (!rebuilding && !diagnosed) {
916 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
917 << typeArg << typeArg.getQualifiers().getAsString()
918 << FixItHint::CreateRemoval(rangeToRemove);
922 // Remove qualifiers even if they're non-local.
923 typeArg = typeArg.getUnqualifiedType();
925 finalTypeArgs.push_back(typeArg);
927 if (typeArg->getAs<PackExpansionType>())
928 anyPackExpansions = true;
930 // Find the corresponding type parameter, if there is one.
931 ObjCTypeParamDecl *typeParam = nullptr;
932 if (!anyPackExpansions) {
933 if (i < numTypeParams) {
934 typeParam = typeParams->begin()[i];
935 } else {
936 // Too many arguments.
937 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
938 << false
939 << objcClass->getDeclName()
940 << (unsigned)typeArgs.size()
941 << numTypeParams;
942 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
943 << objcClass;
945 if (failOnError)
946 return QualType();
948 return type;
952 // Objective-C object pointer types must be substitutable for the bounds.
953 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
954 // If we don't have a type parameter to match against, assume
955 // everything is fine. There was a prior pack expansion that
956 // means we won't be able to match anything.
957 if (!typeParam) {
958 assert(anyPackExpansions && "Too many arguments?");
959 continue;
962 // Retrieve the bound.
963 QualType bound = typeParam->getUnderlyingType();
964 const auto *boundObjC = bound->castAs<ObjCObjectPointerType>();
966 // Determine whether the type argument is substitutable for the bound.
967 if (typeArgObjC->isObjCIdType()) {
968 // When the type argument is 'id', the only acceptable type
969 // parameter bound is 'id'.
970 if (boundObjC->isObjCIdType())
971 continue;
972 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
973 // Otherwise, we follow the assignability rules.
974 continue;
977 // Diagnose the mismatch.
978 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
979 diag::err_objc_type_arg_does_not_match_bound)
980 << typeArg << bound << typeParam->getDeclName();
981 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
982 << typeParam->getDeclName();
984 if (failOnError)
985 return QualType();
987 return type;
990 // Block pointer types are permitted for unqualified 'id' bounds.
991 if (typeArg->isBlockPointerType()) {
992 // If we don't have a type parameter to match against, assume
993 // everything is fine. There was a prior pack expansion that
994 // means we won't be able to match anything.
995 if (!typeParam) {
996 assert(anyPackExpansions && "Too many arguments?");
997 continue;
1000 // Retrieve the bound.
1001 QualType bound = typeParam->getUnderlyingType();
1002 if (bound->isBlockCompatibleObjCPointerType(S.Context))
1003 continue;
1005 // Diagnose the mismatch.
1006 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1007 diag::err_objc_type_arg_does_not_match_bound)
1008 << typeArg << bound << typeParam->getDeclName();
1009 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
1010 << typeParam->getDeclName();
1012 if (failOnError)
1013 return QualType();
1015 return type;
1018 // Dependent types will be checked at instantiation time.
1019 if (typeArg->isDependentType()) {
1020 continue;
1023 // Diagnose non-id-compatible type arguments.
1024 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1025 diag::err_objc_type_arg_not_id_compatible)
1026 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1028 if (failOnError)
1029 return QualType();
1031 return type;
1034 // Make sure we didn't have the wrong number of arguments.
1035 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1036 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1037 << (typeArgs.size() < typeParams->size())
1038 << objcClass->getDeclName()
1039 << (unsigned)finalTypeArgs.size()
1040 << (unsigned)numTypeParams;
1041 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1042 << objcClass;
1044 if (failOnError)
1045 return QualType();
1047 return type;
1050 // Success. Form the specialized type.
1051 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1054 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1055 SourceLocation ProtocolLAngleLoc,
1056 ArrayRef<ObjCProtocolDecl *> Protocols,
1057 ArrayRef<SourceLocation> ProtocolLocs,
1058 SourceLocation ProtocolRAngleLoc,
1059 bool FailOnError) {
1060 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1061 if (!Protocols.empty()) {
1062 bool HasError;
1063 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1064 HasError);
1065 if (HasError) {
1066 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1067 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1068 if (FailOnError) Result = QualType();
1070 if (FailOnError && Result.isNull())
1071 return QualType();
1074 return Result;
1077 QualType Sema::BuildObjCObjectType(
1078 QualType BaseType, SourceLocation Loc, SourceLocation TypeArgsLAngleLoc,
1079 ArrayRef<TypeSourceInfo *> TypeArgs, SourceLocation TypeArgsRAngleLoc,
1080 SourceLocation ProtocolLAngleLoc, ArrayRef<ObjCProtocolDecl *> Protocols,
1081 ArrayRef<SourceLocation> ProtocolLocs, SourceLocation ProtocolRAngleLoc,
1082 bool FailOnError, bool Rebuilding) {
1083 QualType Result = BaseType;
1084 if (!TypeArgs.empty()) {
1085 Result =
1086 applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1087 SourceRange(TypeArgsLAngleLoc, TypeArgsRAngleLoc),
1088 FailOnError, Rebuilding);
1089 if (FailOnError && Result.isNull())
1090 return QualType();
1093 if (!Protocols.empty()) {
1094 bool HasError;
1095 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1096 HasError);
1097 if (HasError) {
1098 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1099 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1100 if (FailOnError) Result = QualType();
1102 if (FailOnError && Result.isNull())
1103 return QualType();
1106 return Result;
1109 TypeResult Sema::actOnObjCProtocolQualifierType(
1110 SourceLocation lAngleLoc,
1111 ArrayRef<Decl *> protocols,
1112 ArrayRef<SourceLocation> protocolLocs,
1113 SourceLocation rAngleLoc) {
1114 // Form id<protocol-list>.
1115 QualType Result = Context.getObjCObjectType(
1116 Context.ObjCBuiltinIdTy, {},
1117 llvm::ArrayRef((ObjCProtocolDecl *const *)protocols.data(),
1118 protocols.size()),
1119 false);
1120 Result = Context.getObjCObjectPointerType(Result);
1122 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1123 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1125 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1126 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1128 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1129 .castAs<ObjCObjectTypeLoc>();
1130 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1131 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1133 // No type arguments.
1134 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1135 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1137 // Fill in protocol qualifiers.
1138 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1139 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1140 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1141 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1143 // We're done. Return the completed type to the parser.
1144 return CreateParsedType(Result, ResultTInfo);
1147 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1148 Scope *S,
1149 SourceLocation Loc,
1150 ParsedType BaseType,
1151 SourceLocation TypeArgsLAngleLoc,
1152 ArrayRef<ParsedType> TypeArgs,
1153 SourceLocation TypeArgsRAngleLoc,
1154 SourceLocation ProtocolLAngleLoc,
1155 ArrayRef<Decl *> Protocols,
1156 ArrayRef<SourceLocation> ProtocolLocs,
1157 SourceLocation ProtocolRAngleLoc) {
1158 TypeSourceInfo *BaseTypeInfo = nullptr;
1159 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1160 if (T.isNull())
1161 return true;
1163 // Handle missing type-source info.
1164 if (!BaseTypeInfo)
1165 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1167 // Extract type arguments.
1168 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1169 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1170 TypeSourceInfo *TypeArgInfo = nullptr;
1171 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1172 if (TypeArg.isNull()) {
1173 ActualTypeArgInfos.clear();
1174 break;
1177 assert(TypeArgInfo && "No type source info?");
1178 ActualTypeArgInfos.push_back(TypeArgInfo);
1181 // Build the object type.
1182 QualType Result = BuildObjCObjectType(
1183 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1184 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1185 ProtocolLAngleLoc,
1186 llvm::ArrayRef((ObjCProtocolDecl *const *)Protocols.data(),
1187 Protocols.size()),
1188 ProtocolLocs, ProtocolRAngleLoc,
1189 /*FailOnError=*/false,
1190 /*Rebuilding=*/false);
1192 if (Result == T)
1193 return BaseType;
1195 // Create source information for this type.
1196 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1197 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1199 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1200 // object pointer type. Fill in source information for it.
1201 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1202 // The '*' is implicit.
1203 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1204 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1207 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1208 // Protocol qualifier information.
1209 if (OTPTL.getNumProtocols() > 0) {
1210 assert(OTPTL.getNumProtocols() == Protocols.size());
1211 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1212 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1213 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1214 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1217 // We're done. Return the completed type to the parser.
1218 return CreateParsedType(Result, ResultTInfo);
1221 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1223 // Type argument information.
1224 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1225 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1226 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1227 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1228 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1229 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1230 } else {
1231 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1232 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1235 // Protocol qualifier information.
1236 if (ObjCObjectTL.getNumProtocols() > 0) {
1237 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1238 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1239 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1240 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1241 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1242 } else {
1243 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1244 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1247 // Base type.
1248 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1249 if (ObjCObjectTL.getType() == T)
1250 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1251 else
1252 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1254 // We're done. Return the completed type to the parser.
1255 return CreateParsedType(Result, ResultTInfo);
1258 static OpenCLAccessAttr::Spelling
1259 getImageAccess(const ParsedAttributesView &Attrs) {
1260 for (const ParsedAttr &AL : Attrs)
1261 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1262 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1263 return OpenCLAccessAttr::Keyword_read_only;
1266 static UnaryTransformType::UTTKind
1267 TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1268 switch (SwitchTST) {
1269 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1270 case TST_##Trait: \
1271 return UnaryTransformType::Enum;
1272 #include "clang/Basic/TransformTypeTraits.def"
1273 default:
1274 llvm_unreachable("attempted to parse a non-unary transform builtin");
1278 /// Convert the specified declspec to the appropriate type
1279 /// object.
1280 /// \param state Specifies the declarator containing the declaration specifier
1281 /// to be converted, along with other associated processing state.
1282 /// \returns The type described by the declaration specifiers. This function
1283 /// never returns null.
1284 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1285 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1286 // checking.
1288 Sema &S = state.getSema();
1289 Declarator &declarator = state.getDeclarator();
1290 DeclSpec &DS = declarator.getMutableDeclSpec();
1291 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1292 if (DeclLoc.isInvalid())
1293 DeclLoc = DS.getBeginLoc();
1295 ASTContext &Context = S.Context;
1297 QualType Result;
1298 switch (DS.getTypeSpecType()) {
1299 case DeclSpec::TST_void:
1300 Result = Context.VoidTy;
1301 break;
1302 case DeclSpec::TST_char:
1303 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1304 Result = Context.CharTy;
1305 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1306 Result = Context.SignedCharTy;
1307 else {
1308 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1309 "Unknown TSS value");
1310 Result = Context.UnsignedCharTy;
1312 break;
1313 case DeclSpec::TST_wchar:
1314 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1315 Result = Context.WCharTy;
1316 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1317 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1318 << DS.getSpecifierName(DS.getTypeSpecType(),
1319 Context.getPrintingPolicy());
1320 Result = Context.getSignedWCharType();
1321 } else {
1322 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1323 "Unknown TSS value");
1324 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1325 << DS.getSpecifierName(DS.getTypeSpecType(),
1326 Context.getPrintingPolicy());
1327 Result = Context.getUnsignedWCharType();
1329 break;
1330 case DeclSpec::TST_char8:
1331 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1332 "Unknown TSS value");
1333 Result = Context.Char8Ty;
1334 break;
1335 case DeclSpec::TST_char16:
1336 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1337 "Unknown TSS value");
1338 Result = Context.Char16Ty;
1339 break;
1340 case DeclSpec::TST_char32:
1341 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1342 "Unknown TSS value");
1343 Result = Context.Char32Ty;
1344 break;
1345 case DeclSpec::TST_unspecified:
1346 // If this is a missing declspec in a block literal return context, then it
1347 // is inferred from the return statements inside the block.
1348 // The declspec is always missing in a lambda expr context; it is either
1349 // specified with a trailing return type or inferred.
1350 if (S.getLangOpts().CPlusPlus14 &&
1351 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1352 // In C++1y, a lambda's implicit return type is 'auto'.
1353 Result = Context.getAutoDeductType();
1354 break;
1355 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1356 checkOmittedBlockReturnType(S, declarator,
1357 Context.DependentTy)) {
1358 Result = Context.DependentTy;
1359 break;
1362 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1363 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1364 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1365 // Note that the one exception to this is function definitions, which are
1366 // allowed to be completely missing a declspec. This is handled in the
1367 // parser already though by it pretending to have seen an 'int' in this
1368 // case.
1369 if (S.getLangOpts().isImplicitIntRequired()) {
1370 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1371 << DS.getSourceRange()
1372 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1373 } else if (!DS.hasTypeSpecifier()) {
1374 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1375 // "At least one type specifier shall be given in the declaration
1376 // specifiers in each declaration, and in the specifier-qualifier list in
1377 // each struct declaration and type name."
1378 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1379 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1380 << DS.getSourceRange();
1382 // When this occurs, often something is very broken with the value
1383 // being declared, poison it as invalid so we don't get chains of
1384 // errors.
1385 declarator.setInvalidType(true);
1386 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1387 DS.isTypeSpecPipe()) {
1388 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1389 << DS.getSourceRange();
1390 declarator.setInvalidType(true);
1391 } else {
1392 assert(S.getLangOpts().isImplicitIntAllowed() &&
1393 "implicit int is disabled?");
1394 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1395 << DS.getSourceRange()
1396 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1400 [[fallthrough]];
1401 case DeclSpec::TST_int: {
1402 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1403 switch (DS.getTypeSpecWidth()) {
1404 case TypeSpecifierWidth::Unspecified:
1405 Result = Context.IntTy;
1406 break;
1407 case TypeSpecifierWidth::Short:
1408 Result = Context.ShortTy;
1409 break;
1410 case TypeSpecifierWidth::Long:
1411 Result = Context.LongTy;
1412 break;
1413 case TypeSpecifierWidth::LongLong:
1414 Result = Context.LongLongTy;
1416 // 'long long' is a C99 or C++11 feature.
1417 if (!S.getLangOpts().C99) {
1418 if (S.getLangOpts().CPlusPlus)
1419 S.Diag(DS.getTypeSpecWidthLoc(),
1420 S.getLangOpts().CPlusPlus11 ?
1421 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1422 else
1423 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1425 break;
1427 } else {
1428 switch (DS.getTypeSpecWidth()) {
1429 case TypeSpecifierWidth::Unspecified:
1430 Result = Context.UnsignedIntTy;
1431 break;
1432 case TypeSpecifierWidth::Short:
1433 Result = Context.UnsignedShortTy;
1434 break;
1435 case TypeSpecifierWidth::Long:
1436 Result = Context.UnsignedLongTy;
1437 break;
1438 case TypeSpecifierWidth::LongLong:
1439 Result = Context.UnsignedLongLongTy;
1441 // 'long long' is a C99 or C++11 feature.
1442 if (!S.getLangOpts().C99) {
1443 if (S.getLangOpts().CPlusPlus)
1444 S.Diag(DS.getTypeSpecWidthLoc(),
1445 S.getLangOpts().CPlusPlus11 ?
1446 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1447 else
1448 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1450 break;
1453 break;
1455 case DeclSpec::TST_bitint: {
1456 if (!S.Context.getTargetInfo().hasBitIntType())
1457 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1458 Result =
1459 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1460 DS.getRepAsExpr(), DS.getBeginLoc());
1461 if (Result.isNull()) {
1462 Result = Context.IntTy;
1463 declarator.setInvalidType(true);
1465 break;
1467 case DeclSpec::TST_accum: {
1468 switch (DS.getTypeSpecWidth()) {
1469 case TypeSpecifierWidth::Short:
1470 Result = Context.ShortAccumTy;
1471 break;
1472 case TypeSpecifierWidth::Unspecified:
1473 Result = Context.AccumTy;
1474 break;
1475 case TypeSpecifierWidth::Long:
1476 Result = Context.LongAccumTy;
1477 break;
1478 case TypeSpecifierWidth::LongLong:
1479 llvm_unreachable("Unable to specify long long as _Accum width");
1482 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1483 Result = Context.getCorrespondingUnsignedType(Result);
1485 if (DS.isTypeSpecSat())
1486 Result = Context.getCorrespondingSaturatedType(Result);
1488 break;
1490 case DeclSpec::TST_fract: {
1491 switch (DS.getTypeSpecWidth()) {
1492 case TypeSpecifierWidth::Short:
1493 Result = Context.ShortFractTy;
1494 break;
1495 case TypeSpecifierWidth::Unspecified:
1496 Result = Context.FractTy;
1497 break;
1498 case TypeSpecifierWidth::Long:
1499 Result = Context.LongFractTy;
1500 break;
1501 case TypeSpecifierWidth::LongLong:
1502 llvm_unreachable("Unable to specify long long as _Fract width");
1505 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1506 Result = Context.getCorrespondingUnsignedType(Result);
1508 if (DS.isTypeSpecSat())
1509 Result = Context.getCorrespondingSaturatedType(Result);
1511 break;
1513 case DeclSpec::TST_int128:
1514 if (!S.Context.getTargetInfo().hasInt128Type() &&
1515 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1516 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice)))
1517 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1518 << "__int128";
1519 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1520 Result = Context.UnsignedInt128Ty;
1521 else
1522 Result = Context.Int128Ty;
1523 break;
1524 case DeclSpec::TST_float16:
1525 // CUDA host and device may have different _Float16 support, therefore
1526 // do not diagnose _Float16 usage to avoid false alarm.
1527 // ToDo: more precise diagnostics for CUDA.
1528 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1529 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1530 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1531 << "_Float16";
1532 Result = Context.Float16Ty;
1533 break;
1534 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1535 case DeclSpec::TST_BFloat16:
1536 if (!S.Context.getTargetInfo().hasBFloat16Type() &&
1537 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice) &&
1538 !S.getLangOpts().SYCLIsDevice)
1539 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__bf16";
1540 Result = Context.BFloat16Ty;
1541 break;
1542 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1543 case DeclSpec::TST_double:
1544 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1545 Result = Context.LongDoubleTy;
1546 else
1547 Result = Context.DoubleTy;
1548 if (S.getLangOpts().OpenCL) {
1549 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1550 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1551 << 0 << Result
1552 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1553 ? "cl_khr_fp64 and __opencl_c_fp64"
1554 : "cl_khr_fp64");
1555 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1556 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1558 break;
1559 case DeclSpec::TST_float128:
1560 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1561 !S.getLangOpts().SYCLIsDevice &&
1562 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1563 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1564 << "__float128";
1565 Result = Context.Float128Ty;
1566 break;
1567 case DeclSpec::TST_ibm128:
1568 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1569 !S.getLangOpts().SYCLIsDevice &&
1570 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsTargetDevice))
1571 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1572 Result = Context.Ibm128Ty;
1573 break;
1574 case DeclSpec::TST_bool:
1575 Result = Context.BoolTy; // _Bool or bool
1576 break;
1577 case DeclSpec::TST_decimal32: // _Decimal32
1578 case DeclSpec::TST_decimal64: // _Decimal64
1579 case DeclSpec::TST_decimal128: // _Decimal128
1580 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1581 Result = Context.IntTy;
1582 declarator.setInvalidType(true);
1583 break;
1584 case DeclSpec::TST_class:
1585 case DeclSpec::TST_enum:
1586 case DeclSpec::TST_union:
1587 case DeclSpec::TST_struct:
1588 case DeclSpec::TST_interface: {
1589 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1590 if (!D) {
1591 // This can happen in C++ with ambiguous lookups.
1592 Result = Context.IntTy;
1593 declarator.setInvalidType(true);
1594 break;
1597 // If the type is deprecated or unavailable, diagnose it.
1598 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1600 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1601 DS.getTypeSpecComplex() == 0 &&
1602 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1603 "No qualifiers on tag names!");
1605 // TypeQuals handled by caller.
1606 Result = Context.getTypeDeclType(D);
1608 // In both C and C++, make an ElaboratedType.
1609 ElaboratedTypeKeyword Keyword
1610 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1611 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1612 DS.isTypeSpecOwned() ? D : nullptr);
1613 break;
1615 case DeclSpec::TST_typename: {
1616 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1617 DS.getTypeSpecComplex() == 0 &&
1618 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1619 "Can't handle qualifiers on typedef names yet!");
1620 Result = S.GetTypeFromParser(DS.getRepAsType());
1621 if (Result.isNull()) {
1622 declarator.setInvalidType(true);
1625 // TypeQuals handled by caller.
1626 break;
1628 case DeclSpec::TST_typeof_unqualType:
1629 case DeclSpec::TST_typeofType:
1630 // FIXME: Preserve type source info.
1631 Result = S.GetTypeFromParser(DS.getRepAsType());
1632 assert(!Result.isNull() && "Didn't get a type for typeof?");
1633 if (!Result->isDependentType())
1634 if (const TagType *TT = Result->getAs<TagType>())
1635 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1636 // TypeQuals handled by caller.
1637 Result = Context.getTypeOfType(
1638 Result, DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType
1639 ? TypeOfKind::Unqualified
1640 : TypeOfKind::Qualified);
1641 break;
1642 case DeclSpec::TST_typeof_unqualExpr:
1643 case DeclSpec::TST_typeofExpr: {
1644 Expr *E = DS.getRepAsExpr();
1645 assert(E && "Didn't get an expression for typeof?");
1646 // TypeQuals handled by caller.
1647 Result = S.BuildTypeofExprType(E, DS.getTypeSpecType() ==
1648 DeclSpec::TST_typeof_unqualExpr
1649 ? TypeOfKind::Unqualified
1650 : TypeOfKind::Qualified);
1651 if (Result.isNull()) {
1652 Result = Context.IntTy;
1653 declarator.setInvalidType(true);
1655 break;
1657 case DeclSpec::TST_decltype: {
1658 Expr *E = DS.getRepAsExpr();
1659 assert(E && "Didn't get an expression for decltype?");
1660 // TypeQuals handled by caller.
1661 Result = S.BuildDecltypeType(E);
1662 if (Result.isNull()) {
1663 Result = Context.IntTy;
1664 declarator.setInvalidType(true);
1666 break;
1668 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1669 #include "clang/Basic/TransformTypeTraits.def"
1670 Result = S.GetTypeFromParser(DS.getRepAsType());
1671 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1672 Result = S.BuildUnaryTransformType(
1673 Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1674 DS.getTypeSpecTypeLoc());
1675 if (Result.isNull()) {
1676 Result = Context.IntTy;
1677 declarator.setInvalidType(true);
1679 break;
1681 case DeclSpec::TST_auto:
1682 case DeclSpec::TST_decltype_auto: {
1683 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1684 ? AutoTypeKeyword::DecltypeAuto
1685 : AutoTypeKeyword::Auto;
1687 ConceptDecl *TypeConstraintConcept = nullptr;
1688 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1689 if (DS.isConstrainedAuto()) {
1690 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1691 TypeConstraintConcept =
1692 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1693 TemplateArgumentListInfo TemplateArgsInfo;
1694 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1695 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1696 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1697 TemplateId->NumArgs);
1698 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1699 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1700 TemplateArgs.push_back(ArgLoc.getArgument());
1701 } else {
1702 declarator.setInvalidType(true);
1705 Result = S.Context.getAutoType(QualType(), AutoKW,
1706 /*IsDependent*/ false, /*IsPack=*/false,
1707 TypeConstraintConcept, TemplateArgs);
1708 break;
1711 case DeclSpec::TST_auto_type:
1712 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1713 break;
1715 case DeclSpec::TST_unknown_anytype:
1716 Result = Context.UnknownAnyTy;
1717 break;
1719 case DeclSpec::TST_atomic:
1720 Result = S.GetTypeFromParser(DS.getRepAsType());
1721 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1722 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1723 if (Result.isNull()) {
1724 Result = Context.IntTy;
1725 declarator.setInvalidType(true);
1727 break;
1729 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1730 case DeclSpec::TST_##ImgType##_t: \
1731 switch (getImageAccess(DS.getAttributes())) { \
1732 case OpenCLAccessAttr::Keyword_write_only: \
1733 Result = Context.Id##WOTy; \
1734 break; \
1735 case OpenCLAccessAttr::Keyword_read_write: \
1736 Result = Context.Id##RWTy; \
1737 break; \
1738 case OpenCLAccessAttr::Keyword_read_only: \
1739 Result = Context.Id##ROTy; \
1740 break; \
1741 case OpenCLAccessAttr::SpellingNotCalculated: \
1742 llvm_unreachable("Spelling not yet calculated"); \
1744 break;
1745 #include "clang/Basic/OpenCLImageTypes.def"
1747 case DeclSpec::TST_error:
1748 Result = Context.IntTy;
1749 declarator.setInvalidType(true);
1750 break;
1753 // FIXME: we want resulting declarations to be marked invalid, but claiming
1754 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1755 // a null type.
1756 if (Result->containsErrors())
1757 declarator.setInvalidType();
1759 if (S.getLangOpts().OpenCL) {
1760 const auto &OpenCLOptions = S.getOpenCLOptions();
1761 bool IsOpenCLC30Compatible =
1762 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1763 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1764 // support.
1765 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1766 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1767 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1768 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1769 // only when the optional feature is supported
1770 if ((Result->isImageType() || Result->isSamplerT()) &&
1771 (IsOpenCLC30Compatible &&
1772 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1773 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1774 << 0 << Result << "__opencl_c_images";
1775 declarator.setInvalidType();
1776 } else if (Result->isOCLImage3dWOType() &&
1777 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1778 S.getLangOpts())) {
1779 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1780 << 0 << Result
1781 << (IsOpenCLC30Compatible
1782 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1783 : "cl_khr_3d_image_writes");
1784 declarator.setInvalidType();
1788 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1789 DS.getTypeSpecType() == DeclSpec::TST_fract;
1791 // Only fixed point types can be saturated
1792 if (DS.isTypeSpecSat() && !IsFixedPointType)
1793 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1794 << DS.getSpecifierName(DS.getTypeSpecType(),
1795 Context.getPrintingPolicy());
1797 // Handle complex types.
1798 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1799 if (S.getLangOpts().Freestanding)
1800 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1801 Result = Context.getComplexType(Result);
1802 } else if (DS.isTypeAltiVecVector()) {
1803 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1804 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1805 VectorKind VecKind = VectorKind::AltiVecVector;
1806 if (DS.isTypeAltiVecPixel())
1807 VecKind = VectorKind::AltiVecPixel;
1808 else if (DS.isTypeAltiVecBool())
1809 VecKind = VectorKind::AltiVecBool;
1810 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1813 // FIXME: Imaginary.
1814 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1815 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1817 // Before we process any type attributes, synthesize a block literal
1818 // function declarator if necessary.
1819 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1820 maybeSynthesizeBlockSignature(state, Result);
1822 // Apply any type attributes from the decl spec. This may cause the
1823 // list of type attributes to be temporarily saved while the type
1824 // attributes are pushed around.
1825 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1826 if (!DS.isTypeSpecPipe()) {
1827 // We also apply declaration attributes that "slide" to the decl spec.
1828 // Ordering can be important for attributes. The decalaration attributes
1829 // come syntactically before the decl spec attributes, so we process them
1830 // in that order.
1831 ParsedAttributesView SlidingAttrs;
1832 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1833 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1834 SlidingAttrs.addAtEnd(&AL);
1836 // For standard syntax attributes, which would normally appertain to the
1837 // declaration here, suggest moving them to the type instead. But only
1838 // do this for our own vendor attributes; moving other vendors'
1839 // attributes might hurt portability.
1840 // There's one special case that we need to deal with here: The
1841 // `MatrixType` attribute may only be used in a typedef declaration. If
1842 // it's being used anywhere else, don't output the warning as
1843 // ProcessDeclAttributes() will output an error anyway.
1844 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1845 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1846 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1847 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1848 << AL;
1852 // During this call to processTypeAttrs(),
1853 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1854 // reference to the DeclSpec attributes, rather than the declaration
1855 // attributes. However, this doesn't matter, as getCurrentAttributes()
1856 // is only called when distributing attributes from one attribute list
1857 // to another. Declaration attributes are always C++11 attributes, and these
1858 // are never distributed.
1859 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1860 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1863 // Apply const/volatile/restrict qualifiers to T.
1864 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1865 // Warn about CV qualifiers on function types.
1866 // C99 6.7.3p8:
1867 // If the specification of a function type includes any type qualifiers,
1868 // the behavior is undefined.
1869 // C++11 [dcl.fct]p7:
1870 // The effect of a cv-qualifier-seq in a function declarator is not the
1871 // same as adding cv-qualification on top of the function type. In the
1872 // latter case, the cv-qualifiers are ignored.
1873 if (Result->isFunctionType()) {
1874 diagnoseAndRemoveTypeQualifiers(
1875 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1876 S.getLangOpts().CPlusPlus
1877 ? diag::warn_typecheck_function_qualifiers_ignored
1878 : diag::warn_typecheck_function_qualifiers_unspecified);
1879 // No diagnostic for 'restrict' or '_Atomic' applied to a
1880 // function type; we'll diagnose those later, in BuildQualifiedType.
1883 // C++11 [dcl.ref]p1:
1884 // Cv-qualified references are ill-formed except when the
1885 // cv-qualifiers are introduced through the use of a typedef-name
1886 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1888 // There don't appear to be any other contexts in which a cv-qualified
1889 // reference type could be formed, so the 'ill-formed' clause here appears
1890 // to never happen.
1891 if (TypeQuals && Result->isReferenceType()) {
1892 diagnoseAndRemoveTypeQualifiers(
1893 S, DS, TypeQuals, Result,
1894 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1895 diag::warn_typecheck_reference_qualifiers);
1898 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1899 // than once in the same specifier-list or qualifier-list, either directly
1900 // or via one or more typedefs."
1901 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1902 && TypeQuals & Result.getCVRQualifiers()) {
1903 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1904 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1905 << "const";
1908 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1909 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1910 << "volatile";
1913 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1914 // produce a warning in this case.
1917 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1919 // If adding qualifiers fails, just use the unqualified type.
1920 if (Qualified.isNull())
1921 declarator.setInvalidType(true);
1922 else
1923 Result = Qualified;
1926 assert(!Result.isNull() && "This function should not return a null type");
1927 return Result;
1930 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1931 if (Entity)
1932 return Entity.getAsString();
1934 return "type name";
1937 static bool isDependentOrGNUAutoType(QualType T) {
1938 if (T->isDependentType())
1939 return true;
1941 const auto *AT = dyn_cast<AutoType>(T);
1942 return AT && AT->isGNUAutoType();
1945 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1946 Qualifiers Qs, const DeclSpec *DS) {
1947 if (T.isNull())
1948 return QualType();
1950 // Ignore any attempt to form a cv-qualified reference.
1951 if (T->isReferenceType()) {
1952 Qs.removeConst();
1953 Qs.removeVolatile();
1956 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1957 // object or incomplete types shall not be restrict-qualified."
1958 if (Qs.hasRestrict()) {
1959 unsigned DiagID = 0;
1960 QualType ProblemTy;
1962 if (T->isAnyPointerType() || T->isReferenceType() ||
1963 T->isMemberPointerType()) {
1964 QualType EltTy;
1965 if (T->isObjCObjectPointerType())
1966 EltTy = T;
1967 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1968 EltTy = PTy->getPointeeType();
1969 else
1970 EltTy = T->getPointeeType();
1972 // If we have a pointer or reference, the pointee must have an object
1973 // incomplete type.
1974 if (!EltTy->isIncompleteOrObjectType()) {
1975 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1976 ProblemTy = EltTy;
1978 } else if (!isDependentOrGNUAutoType(T)) {
1979 // For an __auto_type variable, we may not have seen the initializer yet
1980 // and so have no idea whether the underlying type is a pointer type or
1981 // not.
1982 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1983 ProblemTy = T;
1986 if (DiagID) {
1987 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1988 Qs.removeRestrict();
1992 return Context.getQualifiedType(T, Qs);
1995 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1996 unsigned CVRAU, const DeclSpec *DS) {
1997 if (T.isNull())
1998 return QualType();
2000 // Ignore any attempt to form a cv-qualified reference.
2001 if (T->isReferenceType())
2002 CVRAU &=
2003 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
2005 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
2006 // TQ_unaligned;
2007 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
2009 // C11 6.7.3/5:
2010 // If the same qualifier appears more than once in the same
2011 // specifier-qualifier-list, either directly or via one or more typedefs,
2012 // the behavior is the same as if it appeared only once.
2014 // It's not specified what happens when the _Atomic qualifier is applied to
2015 // a type specified with the _Atomic specifier, but we assume that this
2016 // should be treated as if the _Atomic qualifier appeared multiple times.
2017 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
2018 // C11 6.7.3/5:
2019 // If other qualifiers appear along with the _Atomic qualifier in a
2020 // specifier-qualifier-list, the resulting type is the so-qualified
2021 // atomic type.
2023 // Don't need to worry about array types here, since _Atomic can't be
2024 // applied to such types.
2025 SplitQualType Split = T.getSplitUnqualifiedType();
2026 T = BuildAtomicType(QualType(Split.Ty, 0),
2027 DS ? DS->getAtomicSpecLoc() : Loc);
2028 if (T.isNull())
2029 return T;
2030 Split.Quals.addCVRQualifiers(CVR);
2031 return BuildQualifiedType(T, Loc, Split.Quals);
2034 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2035 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2036 return BuildQualifiedType(T, Loc, Q, DS);
2039 /// Build a paren type including \p T.
2040 QualType Sema::BuildParenType(QualType T) {
2041 return Context.getParenType(T);
2044 /// Given that we're building a pointer or reference to the given
2045 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2046 SourceLocation loc,
2047 bool isReference) {
2048 // Bail out if retention is unrequired or already specified.
2049 if (!type->isObjCLifetimeType() ||
2050 type.getObjCLifetime() != Qualifiers::OCL_None)
2051 return type;
2053 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2055 // If the object type is const-qualified, we can safely use
2056 // __unsafe_unretained. This is safe (because there are no read
2057 // barriers), and it'll be safe to coerce anything but __weak* to
2058 // the resulting type.
2059 if (type.isConstQualified()) {
2060 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2062 // Otherwise, check whether the static type does not require
2063 // retaining. This currently only triggers for Class (possibly
2064 // protocol-qualifed, and arrays thereof).
2065 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2066 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2068 // If we are in an unevaluated context, like sizeof, skip adding a
2069 // qualification.
2070 } else if (S.isUnevaluatedContext()) {
2071 return type;
2073 // If that failed, give an error and recover using __strong. __strong
2074 // is the option most likely to prevent spurious second-order diagnostics,
2075 // like when binding a reference to a field.
2076 } else {
2077 // These types can show up in private ivars in system headers, so
2078 // we need this to not be an error in those cases. Instead we
2079 // want to delay.
2080 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2081 S.DelayedDiagnostics.add(
2082 sema::DelayedDiagnostic::makeForbiddenType(loc,
2083 diag::err_arc_indirect_no_ownership, type, isReference));
2084 } else {
2085 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2087 implicitLifetime = Qualifiers::OCL_Strong;
2089 assert(implicitLifetime && "didn't infer any lifetime!");
2091 Qualifiers qs;
2092 qs.addObjCLifetime(implicitLifetime);
2093 return S.Context.getQualifiedType(type, qs);
2096 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2097 std::string Quals = FnTy->getMethodQuals().getAsString();
2099 switch (FnTy->getRefQualifier()) {
2100 case RQ_None:
2101 break;
2103 case RQ_LValue:
2104 if (!Quals.empty())
2105 Quals += ' ';
2106 Quals += '&';
2107 break;
2109 case RQ_RValue:
2110 if (!Quals.empty())
2111 Quals += ' ';
2112 Quals += "&&";
2113 break;
2116 return Quals;
2119 namespace {
2120 /// Kinds of declarator that cannot contain a qualified function type.
2122 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2123 /// a function type with a cv-qualifier or a ref-qualifier can only appear
2124 /// at the topmost level of a type.
2126 /// Parens and member pointers are permitted. We don't diagnose array and
2127 /// function declarators, because they don't allow function types at all.
2129 /// The values of this enum are used in diagnostics.
2130 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2131 } // end anonymous namespace
2133 /// Check whether the type T is a qualified function type, and if it is,
2134 /// diagnose that it cannot be contained within the given kind of declarator.
2135 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2136 QualifiedFunctionKind QFK) {
2137 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2138 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2139 if (!FPT ||
2140 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2141 return false;
2143 S.Diag(Loc, diag::err_compound_qualified_function_type)
2144 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2145 << getFunctionQualifiersAsString(FPT);
2146 return true;
2149 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2150 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2151 if (!FPT ||
2152 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2153 return false;
2155 Diag(Loc, diag::err_qualified_function_typeid)
2156 << T << getFunctionQualifiersAsString(FPT);
2157 return true;
2160 // Helper to deduce addr space of a pointee type in OpenCL mode.
2161 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2162 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2163 !PointeeType->isSamplerT() &&
2164 !PointeeType.hasAddressSpace())
2165 PointeeType = S.getASTContext().getAddrSpaceQualType(
2166 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2167 return PointeeType;
2170 /// Build a pointer type.
2172 /// \param T The type to which we'll be building a pointer.
2174 /// \param Loc The location of the entity whose type involves this
2175 /// pointer type or, if there is no such entity, the location of the
2176 /// type that will have pointer type.
2178 /// \param Entity The name of the entity that involves the pointer
2179 /// type, if known.
2181 /// \returns A suitable pointer type, if there are no
2182 /// errors. Otherwise, returns a NULL type.
2183 QualType Sema::BuildPointerType(QualType T,
2184 SourceLocation Loc, DeclarationName Entity) {
2185 if (T->isReferenceType()) {
2186 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2187 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2188 << getPrintableNameForEntity(Entity) << T;
2189 return QualType();
2192 if (T->isFunctionType() && getLangOpts().OpenCL &&
2193 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2194 getLangOpts())) {
2195 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2196 return QualType();
2199 if (getLangOpts().HLSL && Loc.isValid()) {
2200 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2201 return QualType();
2204 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2205 return QualType();
2207 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2209 // In ARC, it is forbidden to build pointers to unqualified pointers.
2210 if (getLangOpts().ObjCAutoRefCount)
2211 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2213 if (getLangOpts().OpenCL)
2214 T = deduceOpenCLPointeeAddrSpace(*this, T);
2216 // In WebAssembly, pointers to reference types and pointers to tables are
2217 // illegal.
2218 if (getASTContext().getTargetInfo().getTriple().isWasm()) {
2219 if (T.isWebAssemblyReferenceType()) {
2220 Diag(Loc, diag::err_wasm_reference_pr) << 0;
2221 return QualType();
2224 // We need to desugar the type here in case T is a ParenType.
2225 if (T->getUnqualifiedDesugaredType()->isWebAssemblyTableType()) {
2226 Diag(Loc, diag::err_wasm_table_pr) << 0;
2227 return QualType();
2231 // Build the pointer type.
2232 return Context.getPointerType(T);
2235 /// Build a reference type.
2237 /// \param T The type to which we'll be building a reference.
2239 /// \param Loc The location of the entity whose type involves this
2240 /// reference type or, if there is no such entity, the location of the
2241 /// type that will have reference type.
2243 /// \param Entity The name of the entity that involves the reference
2244 /// type, if known.
2246 /// \returns A suitable reference type, if there are no
2247 /// errors. Otherwise, returns a NULL type.
2248 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2249 SourceLocation Loc,
2250 DeclarationName Entity) {
2251 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2252 "Unresolved overloaded function type");
2254 // C++0x [dcl.ref]p6:
2255 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2256 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2257 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2258 // the type "lvalue reference to T", while an attempt to create the type
2259 // "rvalue reference to cv TR" creates the type TR.
2260 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2262 // C++ [dcl.ref]p4: There shall be no references to references.
2264 // According to C++ DR 106, references to references are only
2265 // diagnosed when they are written directly (e.g., "int & &"),
2266 // but not when they happen via a typedef:
2268 // typedef int& intref;
2269 // typedef intref& intref2;
2271 // Parser::ParseDeclaratorInternal diagnoses the case where
2272 // references are written directly; here, we handle the
2273 // collapsing of references-to-references as described in C++0x.
2274 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2276 // C++ [dcl.ref]p1:
2277 // A declarator that specifies the type "reference to cv void"
2278 // is ill-formed.
2279 if (T->isVoidType()) {
2280 Diag(Loc, diag::err_reference_to_void);
2281 return QualType();
2284 if (getLangOpts().HLSL && Loc.isValid()) {
2285 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2286 return QualType();
2289 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2290 return QualType();
2292 if (T->isFunctionType() && getLangOpts().OpenCL &&
2293 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2294 getLangOpts())) {
2295 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2296 return QualType();
2299 // In ARC, it is forbidden to build references to unqualified pointers.
2300 if (getLangOpts().ObjCAutoRefCount)
2301 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2303 if (getLangOpts().OpenCL)
2304 T = deduceOpenCLPointeeAddrSpace(*this, T);
2306 // In WebAssembly, references to reference types and tables are illegal.
2307 if (getASTContext().getTargetInfo().getTriple().isWasm() &&
2308 T.isWebAssemblyReferenceType()) {
2309 Diag(Loc, diag::err_wasm_reference_pr) << 1;
2310 return QualType();
2312 if (T->isWebAssemblyTableType()) {
2313 Diag(Loc, diag::err_wasm_table_pr) << 1;
2314 return QualType();
2317 // Handle restrict on references.
2318 if (LValueRef)
2319 return Context.getLValueReferenceType(T, SpelledAsLValue);
2320 return Context.getRValueReferenceType(T);
2323 /// Build a Read-only Pipe type.
2325 /// \param T The type to which we'll be building a Pipe.
2327 /// \param Loc We do not use it for now.
2329 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2330 /// NULL type.
2331 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2332 return Context.getReadPipeType(T);
2335 /// Build a Write-only Pipe type.
2337 /// \param T The type to which we'll be building a Pipe.
2339 /// \param Loc We do not use it for now.
2341 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2342 /// NULL type.
2343 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2344 return Context.getWritePipeType(T);
2347 /// Build a bit-precise integer type.
2349 /// \param IsUnsigned Boolean representing the signedness of the type.
2351 /// \param BitWidth Size of this int type in bits, or an expression representing
2352 /// that.
2354 /// \param Loc Location of the keyword.
2355 QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2356 SourceLocation Loc) {
2357 if (BitWidth->isInstantiationDependent())
2358 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2360 llvm::APSInt Bits(32);
2361 ExprResult ICE =
2362 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2364 if (ICE.isInvalid())
2365 return QualType();
2367 size_t NumBits = Bits.getZExtValue();
2368 if (!IsUnsigned && NumBits < 2) {
2369 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2370 return QualType();
2373 if (IsUnsigned && NumBits < 1) {
2374 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2375 return QualType();
2378 const TargetInfo &TI = getASTContext().getTargetInfo();
2379 if (NumBits > TI.getMaxBitIntWidth()) {
2380 Diag(Loc, diag::err_bit_int_max_size)
2381 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2382 return QualType();
2385 return Context.getBitIntType(IsUnsigned, NumBits);
2388 /// Check whether the specified array bound can be evaluated using the relevant
2389 /// language rules. If so, returns the possibly-converted expression and sets
2390 /// SizeVal to the size. If not, but the expression might be a VLA bound,
2391 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
2392 /// ExprError().
2393 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2394 llvm::APSInt &SizeVal, unsigned VLADiag,
2395 bool VLAIsError) {
2396 if (S.getLangOpts().CPlusPlus14 &&
2397 (VLAIsError ||
2398 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2399 // C++14 [dcl.array]p1:
2400 // The constant-expression shall be a converted constant expression of
2401 // type std::size_t.
2403 // Don't apply this rule if we might be forming a VLA: in that case, we
2404 // allow non-constant expressions and constant-folding. We only need to use
2405 // the converted constant expression rules (to properly convert the source)
2406 // when the source expression is of class type.
2407 return S.CheckConvertedConstantExpression(
2408 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2411 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2412 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2413 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2414 public:
2415 unsigned VLADiag;
2416 bool VLAIsError;
2417 bool IsVLA = false;
2419 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2420 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2422 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2423 QualType T) override {
2424 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2427 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2428 SourceLocation Loc) override {
2429 IsVLA = !VLAIsError;
2430 return S.Diag(Loc, VLADiag);
2433 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2434 SourceLocation Loc) override {
2435 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2437 } Diagnoser(VLADiag, VLAIsError);
2439 ExprResult R =
2440 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2441 if (Diagnoser.IsVLA)
2442 return ExprResult();
2443 return R;
2446 bool Sema::checkArrayElementAlignment(QualType EltTy, SourceLocation Loc) {
2447 EltTy = Context.getBaseElementType(EltTy);
2448 if (EltTy->isIncompleteType() || EltTy->isDependentType() ||
2449 EltTy->isUndeducedType())
2450 return true;
2452 CharUnits Size = Context.getTypeSizeInChars(EltTy);
2453 CharUnits Alignment = Context.getTypeAlignInChars(EltTy);
2455 if (Size.isMultipleOf(Alignment))
2456 return true;
2458 Diag(Loc, diag::err_array_element_alignment)
2459 << EltTy << Size.getQuantity() << Alignment.getQuantity();
2460 return false;
2463 /// Build an array type.
2465 /// \param T The type of each element in the array.
2467 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2469 /// \param ArraySize Expression describing the size of the array.
2471 /// \param Brackets The range from the opening '[' to the closing ']'.
2473 /// \param Entity The name of the entity that involves the array
2474 /// type, if known.
2476 /// \returns A suitable array type, if there are no errors. Otherwise,
2477 /// returns a NULL type.
2478 QualType Sema::BuildArrayType(QualType T, ArraySizeModifier ASM,
2479 Expr *ArraySize, unsigned Quals,
2480 SourceRange Brackets, DeclarationName Entity) {
2482 SourceLocation Loc = Brackets.getBegin();
2483 if (getLangOpts().CPlusPlus) {
2484 // C++ [dcl.array]p1:
2485 // T is called the array element type; this type shall not be a reference
2486 // type, the (possibly cv-qualified) type void, a function type or an
2487 // abstract class type.
2489 // C++ [dcl.array]p3:
2490 // When several "array of" specifications are adjacent, [...] only the
2491 // first of the constant expressions that specify the bounds of the arrays
2492 // may be omitted.
2494 // Note: function types are handled in the common path with C.
2495 if (T->isReferenceType()) {
2496 Diag(Loc, diag::err_illegal_decl_array_of_references)
2497 << getPrintableNameForEntity(Entity) << T;
2498 return QualType();
2501 if (T->isVoidType() || T->isIncompleteArrayType()) {
2502 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2503 return QualType();
2506 if (RequireNonAbstractType(Brackets.getBegin(), T,
2507 diag::err_array_of_abstract_type))
2508 return QualType();
2510 // Mentioning a member pointer type for an array type causes us to lock in
2511 // an inheritance model, even if it's inside an unused typedef.
2512 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2513 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2514 if (!MPTy->getClass()->isDependentType())
2515 (void)isCompleteType(Loc, T);
2517 } else {
2518 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2519 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2520 if (!T.isWebAssemblyReferenceType() &&
2521 RequireCompleteSizedType(Loc, T,
2522 diag::err_array_incomplete_or_sizeless_type))
2523 return QualType();
2526 // Multi-dimensional arrays of WebAssembly references are not allowed.
2527 if (Context.getTargetInfo().getTriple().isWasm() && T->isArrayType()) {
2528 const auto *ATy = dyn_cast<ArrayType>(T);
2529 if (ATy && ATy->getElementType().isWebAssemblyReferenceType()) {
2530 Diag(Loc, diag::err_wasm_reftype_multidimensional_array);
2531 return QualType();
2535 if (T->isSizelessType() && !T.isWebAssemblyReferenceType()) {
2536 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2537 return QualType();
2540 if (T->isFunctionType()) {
2541 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2542 << getPrintableNameForEntity(Entity) << T;
2543 return QualType();
2546 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2547 // If the element type is a struct or union that contains a variadic
2548 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2549 if (EltTy->getDecl()->hasFlexibleArrayMember())
2550 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2551 } else if (T->isObjCObjectType()) {
2552 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2553 return QualType();
2556 if (!checkArrayElementAlignment(T, Loc))
2557 return QualType();
2559 // Do placeholder conversions on the array size expression.
2560 if (ArraySize && ArraySize->hasPlaceholderType()) {
2561 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2562 if (Result.isInvalid()) return QualType();
2563 ArraySize = Result.get();
2566 // Do lvalue-to-rvalue conversions on the array size expression.
2567 if (ArraySize && !ArraySize->isPRValue()) {
2568 ExprResult Result = DefaultLvalueConversion(ArraySize);
2569 if (Result.isInvalid())
2570 return QualType();
2572 ArraySize = Result.get();
2575 // C99 6.7.5.2p1: The size expression shall have integer type.
2576 // C++11 allows contextual conversions to such types.
2577 if (!getLangOpts().CPlusPlus11 &&
2578 ArraySize && !ArraySize->isTypeDependent() &&
2579 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2580 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2581 << ArraySize->getType() << ArraySize->getSourceRange();
2582 return QualType();
2585 auto IsStaticAssertLike = [](const Expr *ArraySize, ASTContext &Context) {
2586 if (!ArraySize)
2587 return false;
2589 // If the array size expression is a conditional expression whose branches
2590 // are both integer constant expressions, one negative and one positive,
2591 // then it's assumed to be like an old-style static assertion. e.g.,
2592 // int old_style_assert[expr ? 1 : -1];
2593 // We will accept any integer constant expressions instead of assuming the
2594 // values 1 and -1 are always used.
2595 if (const auto *CondExpr = dyn_cast_if_present<ConditionalOperator>(
2596 ArraySize->IgnoreParenImpCasts())) {
2597 std::optional<llvm::APSInt> LHS =
2598 CondExpr->getLHS()->getIntegerConstantExpr(Context);
2599 std::optional<llvm::APSInt> RHS =
2600 CondExpr->getRHS()->getIntegerConstantExpr(Context);
2601 return LHS && RHS && LHS->isNegative() != RHS->isNegative();
2603 return false;
2606 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2607 unsigned VLADiag;
2608 bool VLAIsError;
2609 if (getLangOpts().OpenCL) {
2610 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2611 VLADiag = diag::err_opencl_vla;
2612 VLAIsError = true;
2613 } else if (getLangOpts().C99) {
2614 VLADiag = diag::warn_vla_used;
2615 VLAIsError = false;
2616 } else if (isSFINAEContext()) {
2617 VLADiag = diag::err_vla_in_sfinae;
2618 VLAIsError = true;
2619 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2620 VLADiag = diag::err_openmp_vla_in_task_untied;
2621 VLAIsError = true;
2622 } else if (getLangOpts().CPlusPlus) {
2623 if (getLangOpts().CPlusPlus11 && IsStaticAssertLike(ArraySize, Context))
2624 VLADiag = getLangOpts().GNUMode
2625 ? diag::ext_vla_cxx_in_gnu_mode_static_assert
2626 : diag::ext_vla_cxx_static_assert;
2627 else
2628 VLADiag = getLangOpts().GNUMode ? diag::ext_vla_cxx_in_gnu_mode
2629 : diag::ext_vla_cxx;
2630 VLAIsError = false;
2631 } else {
2632 VLADiag = diag::ext_vla;
2633 VLAIsError = false;
2636 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2637 if (!ArraySize) {
2638 if (ASM == ArraySizeModifier::Star) {
2639 Diag(Loc, VLADiag);
2640 if (VLAIsError)
2641 return QualType();
2643 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2644 } else {
2645 T = Context.getIncompleteArrayType(T, ASM, Quals);
2647 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2648 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2649 } else {
2650 ExprResult R =
2651 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2652 if (R.isInvalid())
2653 return QualType();
2655 if (!R.isUsable()) {
2656 // C99: an array with a non-ICE size is a VLA. We accept any expression
2657 // that we can fold to a non-zero positive value as a non-VLA as an
2658 // extension.
2659 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2660 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2661 !T->isConstantSizeType()) {
2662 // C99: an array with an element type that has a non-constant-size is a
2663 // VLA.
2664 // FIXME: Add a note to explain why this isn't a VLA.
2665 Diag(Loc, VLADiag);
2666 if (VLAIsError)
2667 return QualType();
2668 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2669 } else {
2670 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2671 // have a value greater than zero.
2672 // In C++, this follows from narrowing conversions being disallowed.
2673 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2674 if (Entity)
2675 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2676 << getPrintableNameForEntity(Entity)
2677 << ArraySize->getSourceRange();
2678 else
2679 Diag(ArraySize->getBeginLoc(),
2680 diag::err_typecheck_negative_array_size)
2681 << ArraySize->getSourceRange();
2682 return QualType();
2684 if (ConstVal == 0 && !T.isWebAssemblyReferenceType()) {
2685 // GCC accepts zero sized static arrays. We allow them when
2686 // we're not in a SFINAE context.
2687 Diag(ArraySize->getBeginLoc(),
2688 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2689 : diag::ext_typecheck_zero_array_size)
2690 << 0 << ArraySize->getSourceRange();
2693 // Is the array too large?
2694 unsigned ActiveSizeBits =
2695 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2696 !T->isIncompleteType() && !T->isUndeducedType())
2697 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2698 : ConstVal.getActiveBits();
2699 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2700 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2701 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2702 return QualType();
2705 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2709 if (T->isVariableArrayType()) {
2710 if (!Context.getTargetInfo().isVLASupported()) {
2711 // CUDA device code and some other targets don't support VLAs.
2712 bool IsCUDADevice = (getLangOpts().CUDA && getLangOpts().CUDAIsDevice);
2713 targetDiag(Loc,
2714 IsCUDADevice ? diag::err_cuda_vla : diag::err_vla_unsupported)
2715 << (IsCUDADevice ? CurrentCUDATarget() : 0);
2716 } else if (sema::FunctionScopeInfo *FSI = getCurFunction()) {
2717 // VLAs are supported on this target, but we may need to do delayed
2718 // checking that the VLA is not being used within a coroutine.
2719 FSI->setHasVLA(Loc);
2723 // If this is not C99, diagnose array size modifiers on non-VLAs.
2724 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2725 (ASM != ArraySizeModifier::Normal || Quals != 0)) {
2726 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2727 : diag::ext_c99_array_usage)
2728 << llvm::to_underlying(ASM);
2731 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2732 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2733 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2734 if (getLangOpts().OpenCL) {
2735 const QualType ArrType = Context.getBaseElementType(T);
2736 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2737 ArrType->isSamplerT() || ArrType->isImageType()) {
2738 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2739 return QualType();
2743 return T;
2746 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2747 SourceLocation AttrLoc) {
2748 // The base type must be integer (not Boolean or enumeration) or float, and
2749 // can't already be a vector.
2750 if ((!CurType->isDependentType() &&
2751 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2752 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2753 !CurType->isBitIntType()) ||
2754 CurType->isArrayType()) {
2755 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2756 return QualType();
2758 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2759 if (const auto *BIT = CurType->getAs<BitIntType>()) {
2760 unsigned NumBits = BIT->getNumBits();
2761 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2762 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2763 << (NumBits < 8);
2764 return QualType();
2768 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2769 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2770 VectorKind::Generic);
2772 std::optional<llvm::APSInt> VecSize =
2773 SizeExpr->getIntegerConstantExpr(Context);
2774 if (!VecSize) {
2775 Diag(AttrLoc, diag::err_attribute_argument_type)
2776 << "vector_size" << AANT_ArgumentIntegerConstant
2777 << SizeExpr->getSourceRange();
2778 return QualType();
2781 if (CurType->isDependentType())
2782 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2783 VectorKind::Generic);
2785 // vecSize is specified in bytes - convert to bits.
2786 if (!VecSize->isIntN(61)) {
2787 // Bit size will overflow uint64.
2788 Diag(AttrLoc, diag::err_attribute_size_too_large)
2789 << SizeExpr->getSourceRange() << "vector";
2790 return QualType();
2792 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2793 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2795 if (VectorSizeBits == 0) {
2796 Diag(AttrLoc, diag::err_attribute_zero_size)
2797 << SizeExpr->getSourceRange() << "vector";
2798 return QualType();
2801 if (!TypeSize || VectorSizeBits % TypeSize) {
2802 Diag(AttrLoc, diag::err_attribute_invalid_size)
2803 << SizeExpr->getSourceRange();
2804 return QualType();
2807 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2808 Diag(AttrLoc, diag::err_attribute_size_too_large)
2809 << SizeExpr->getSourceRange() << "vector";
2810 return QualType();
2813 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2814 VectorKind::Generic);
2817 /// Build an ext-vector type.
2819 /// Run the required checks for the extended vector type.
2820 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2821 SourceLocation AttrLoc) {
2822 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2823 // in conjunction with complex types (pointers, arrays, functions, etc.).
2825 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2826 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2827 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2828 // of bool aren't allowed.
2830 // We explictly allow bool elements in ext_vector_type for C/C++.
2831 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2832 if ((!T->isDependentType() && !T->isIntegerType() &&
2833 !T->isRealFloatingType()) ||
2834 (IsNoBoolVecLang && T->isBooleanType())) {
2835 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2836 return QualType();
2839 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2840 if (T->isBitIntType()) {
2841 unsigned NumBits = T->castAs<BitIntType>()->getNumBits();
2842 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2843 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2844 << (NumBits < 8);
2845 return QualType();
2849 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2850 std::optional<llvm::APSInt> vecSize =
2851 ArraySize->getIntegerConstantExpr(Context);
2852 if (!vecSize) {
2853 Diag(AttrLoc, diag::err_attribute_argument_type)
2854 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2855 << ArraySize->getSourceRange();
2856 return QualType();
2859 if (!vecSize->isIntN(32)) {
2860 Diag(AttrLoc, diag::err_attribute_size_too_large)
2861 << ArraySize->getSourceRange() << "vector";
2862 return QualType();
2864 // Unlike gcc's vector_size attribute, the size is specified as the
2865 // number of elements, not the number of bytes.
2866 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2868 if (vectorSize == 0) {
2869 Diag(AttrLoc, diag::err_attribute_zero_size)
2870 << ArraySize->getSourceRange() << "vector";
2871 return QualType();
2874 return Context.getExtVectorType(T, vectorSize);
2877 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2880 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2881 SourceLocation AttrLoc) {
2882 assert(Context.getLangOpts().MatrixTypes &&
2883 "Should never build a matrix type when it is disabled");
2885 // Check element type, if it is not dependent.
2886 if (!ElementTy->isDependentType() &&
2887 !MatrixType::isValidElementType(ElementTy)) {
2888 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2889 return QualType();
2892 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2893 NumRows->isValueDependent() || NumCols->isValueDependent())
2894 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2895 AttrLoc);
2897 std::optional<llvm::APSInt> ValueRows =
2898 NumRows->getIntegerConstantExpr(Context);
2899 std::optional<llvm::APSInt> ValueColumns =
2900 NumCols->getIntegerConstantExpr(Context);
2902 auto const RowRange = NumRows->getSourceRange();
2903 auto const ColRange = NumCols->getSourceRange();
2905 // Both are row and column expressions are invalid.
2906 if (!ValueRows && !ValueColumns) {
2907 Diag(AttrLoc, diag::err_attribute_argument_type)
2908 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2909 << ColRange;
2910 return QualType();
2913 // Only the row expression is invalid.
2914 if (!ValueRows) {
2915 Diag(AttrLoc, diag::err_attribute_argument_type)
2916 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2917 return QualType();
2920 // Only the column expression is invalid.
2921 if (!ValueColumns) {
2922 Diag(AttrLoc, diag::err_attribute_argument_type)
2923 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2924 return QualType();
2927 // Check the matrix dimensions.
2928 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2929 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2930 if (MatrixRows == 0 && MatrixColumns == 0) {
2931 Diag(AttrLoc, diag::err_attribute_zero_size)
2932 << "matrix" << RowRange << ColRange;
2933 return QualType();
2935 if (MatrixRows == 0) {
2936 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2937 return QualType();
2939 if (MatrixColumns == 0) {
2940 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2941 return QualType();
2943 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2944 Diag(AttrLoc, diag::err_attribute_size_too_large)
2945 << RowRange << "matrix row";
2946 return QualType();
2948 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2949 Diag(AttrLoc, diag::err_attribute_size_too_large)
2950 << ColRange << "matrix column";
2951 return QualType();
2953 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2956 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2957 if (T->isArrayType() || T->isFunctionType()) {
2958 Diag(Loc, diag::err_func_returning_array_function)
2959 << T->isFunctionType() << T;
2960 return true;
2963 // Functions cannot return half FP.
2964 if (T->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
2965 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
2966 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2967 FixItHint::CreateInsertion(Loc, "*");
2968 return true;
2971 // Methods cannot return interface types. All ObjC objects are
2972 // passed by reference.
2973 if (T->isObjCObjectType()) {
2974 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2975 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2976 return true;
2979 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2980 T.hasNonTrivialToPrimitiveCopyCUnion())
2981 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2982 NTCUK_Destruct|NTCUK_Copy);
2984 // C++2a [dcl.fct]p12:
2985 // A volatile-qualified return type is deprecated
2986 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2987 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2989 if (T.getAddressSpace() != LangAS::Default && getLangOpts().HLSL)
2990 return true;
2991 return false;
2994 /// Check the extended parameter information. Most of the necessary
2995 /// checking should occur when applying the parameter attribute; the
2996 /// only other checks required are positional restrictions.
2997 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2998 const FunctionProtoType::ExtProtoInfo &EPI,
2999 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
3000 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
3002 bool emittedError = false;
3003 auto actualCC = EPI.ExtInfo.getCC();
3004 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
3005 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
3006 bool isCompatible =
3007 (required == RequiredCC::OnlySwift)
3008 ? (actualCC == CC_Swift)
3009 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
3010 if (isCompatible || emittedError)
3011 return;
3012 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
3013 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
3014 << (required == RequiredCC::OnlySwift);
3015 emittedError = true;
3017 for (size_t paramIndex = 0, numParams = paramTypes.size();
3018 paramIndex != numParams; ++paramIndex) {
3019 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
3020 // Nothing interesting to check for orindary-ABI parameters.
3021 case ParameterABI::Ordinary:
3022 continue;
3024 // swift_indirect_result parameters must be a prefix of the function
3025 // arguments.
3026 case ParameterABI::SwiftIndirectResult:
3027 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3028 if (paramIndex != 0 &&
3029 EPI.ExtParameterInfos[paramIndex - 1].getABI()
3030 != ParameterABI::SwiftIndirectResult) {
3031 S.Diag(getParamLoc(paramIndex),
3032 diag::err_swift_indirect_result_not_first);
3034 continue;
3036 case ParameterABI::SwiftContext:
3037 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
3038 continue;
3040 // SwiftAsyncContext is not limited to swiftasynccall functions.
3041 case ParameterABI::SwiftAsyncContext:
3042 continue;
3044 // swift_error parameters must be preceded by a swift_context parameter.
3045 case ParameterABI::SwiftErrorResult:
3046 checkCompatible(paramIndex, RequiredCC::OnlySwift);
3047 if (paramIndex == 0 ||
3048 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
3049 ParameterABI::SwiftContext) {
3050 S.Diag(getParamLoc(paramIndex),
3051 diag::err_swift_error_result_not_after_swift_context);
3053 continue;
3055 llvm_unreachable("bad ABI kind");
3059 QualType Sema::BuildFunctionType(QualType T,
3060 MutableArrayRef<QualType> ParamTypes,
3061 SourceLocation Loc, DeclarationName Entity,
3062 const FunctionProtoType::ExtProtoInfo &EPI) {
3063 bool Invalid = false;
3065 Invalid |= CheckFunctionReturnType(T, Loc);
3067 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
3068 // FIXME: Loc is too inprecise here, should use proper locations for args.
3069 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
3070 if (ParamType->isVoidType()) {
3071 Diag(Loc, diag::err_param_with_void_type);
3072 Invalid = true;
3073 } else if (ParamType->isHalfType() && !getLangOpts().NativeHalfArgsAndReturns &&
3074 !Context.getTargetInfo().allowHalfArgsAndReturns()) {
3075 // Disallow half FP arguments.
3076 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
3077 FixItHint::CreateInsertion(Loc, "*");
3078 Invalid = true;
3079 } else if (ParamType->isWebAssemblyTableType()) {
3080 Diag(Loc, diag::err_wasm_table_as_function_parameter);
3081 Invalid = true;
3084 // C++2a [dcl.fct]p4:
3085 // A parameter with volatile-qualified type is deprecated
3086 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
3087 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
3089 ParamTypes[Idx] = ParamType;
3092 if (EPI.ExtParameterInfos) {
3093 checkExtParameterInfos(*this, ParamTypes, EPI,
3094 [=](unsigned i) { return Loc; });
3097 if (EPI.ExtInfo.getProducesResult()) {
3098 // This is just a warning, so we can't fail to build if we see it.
3099 checkNSReturnsRetainedReturnType(Loc, T);
3102 if (Invalid)
3103 return QualType();
3105 return Context.getFunctionType(T, ParamTypes, EPI);
3108 /// Build a member pointer type \c T Class::*.
3110 /// \param T the type to which the member pointer refers.
3111 /// \param Class the class type into which the member pointer points.
3112 /// \param Loc the location where this type begins
3113 /// \param Entity the name of the entity that will have this member pointer type
3115 /// \returns a member pointer type, if successful, or a NULL type if there was
3116 /// an error.
3117 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
3118 SourceLocation Loc,
3119 DeclarationName Entity) {
3120 // Verify that we're not building a pointer to pointer to function with
3121 // exception specification.
3122 if (CheckDistantExceptionSpec(T)) {
3123 Diag(Loc, diag::err_distant_exception_spec);
3124 return QualType();
3127 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3128 // with reference type, or "cv void."
3129 if (T->isReferenceType()) {
3130 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3131 << getPrintableNameForEntity(Entity) << T;
3132 return QualType();
3135 if (T->isVoidType()) {
3136 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3137 << getPrintableNameForEntity(Entity);
3138 return QualType();
3141 if (!Class->isDependentType() && !Class->isRecordType()) {
3142 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3143 return QualType();
3146 if (T->isFunctionType() && getLangOpts().OpenCL &&
3147 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3148 getLangOpts())) {
3149 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3150 return QualType();
3153 if (getLangOpts().HLSL && Loc.isValid()) {
3154 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3155 return QualType();
3158 // Adjust the default free function calling convention to the default method
3159 // calling convention.
3160 bool IsCtorOrDtor =
3161 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3162 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3163 if (T->isFunctionType())
3164 adjustMemberFunctionCC(T, /*HasThisPointer=*/true, IsCtorOrDtor, Loc);
3166 return Context.getMemberPointerType(T, Class.getTypePtr());
3169 /// Build a block pointer type.
3171 /// \param T The type to which we'll be building a block pointer.
3173 /// \param Loc The source location, used for diagnostics.
3175 /// \param Entity The name of the entity that involves the block pointer
3176 /// type, if known.
3178 /// \returns A suitable block pointer type, if there are no
3179 /// errors. Otherwise, returns a NULL type.
3180 QualType Sema::BuildBlockPointerType(QualType T,
3181 SourceLocation Loc,
3182 DeclarationName Entity) {
3183 if (!T->isFunctionType()) {
3184 Diag(Loc, diag::err_nonfunction_block_type);
3185 return QualType();
3188 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3189 return QualType();
3191 if (getLangOpts().OpenCL)
3192 T = deduceOpenCLPointeeAddrSpace(*this, T);
3194 return Context.getBlockPointerType(T);
3197 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3198 QualType QT = Ty.get();
3199 if (QT.isNull()) {
3200 if (TInfo) *TInfo = nullptr;
3201 return QualType();
3204 TypeSourceInfo *DI = nullptr;
3205 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3206 QT = LIT->getType();
3207 DI = LIT->getTypeSourceInfo();
3210 if (TInfo) *TInfo = DI;
3211 return QT;
3214 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3215 Qualifiers::ObjCLifetime ownership,
3216 unsigned chunkIndex);
3218 /// Given that this is the declaration of a parameter under ARC,
3219 /// attempt to infer attributes and such for pointer-to-whatever
3220 /// types.
3221 static void inferARCWriteback(TypeProcessingState &state,
3222 QualType &declSpecType) {
3223 Sema &S = state.getSema();
3224 Declarator &declarator = state.getDeclarator();
3226 // TODO: should we care about decl qualifiers?
3228 // Check whether the declarator has the expected form. We walk
3229 // from the inside out in order to make the block logic work.
3230 unsigned outermostPointerIndex = 0;
3231 bool isBlockPointer = false;
3232 unsigned numPointers = 0;
3233 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3234 unsigned chunkIndex = i;
3235 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3236 switch (chunk.Kind) {
3237 case DeclaratorChunk::Paren:
3238 // Ignore parens.
3239 break;
3241 case DeclaratorChunk::Reference:
3242 case DeclaratorChunk::Pointer:
3243 // Count the number of pointers. Treat references
3244 // interchangeably as pointers; if they're mis-ordered, normal
3245 // type building will discover that.
3246 outermostPointerIndex = chunkIndex;
3247 numPointers++;
3248 break;
3250 case DeclaratorChunk::BlockPointer:
3251 // If we have a pointer to block pointer, that's an acceptable
3252 // indirect reference; anything else is not an application of
3253 // the rules.
3254 if (numPointers != 1) return;
3255 numPointers++;
3256 outermostPointerIndex = chunkIndex;
3257 isBlockPointer = true;
3259 // We don't care about pointer structure in return values here.
3260 goto done;
3262 case DeclaratorChunk::Array: // suppress if written (id[])?
3263 case DeclaratorChunk::Function:
3264 case DeclaratorChunk::MemberPointer:
3265 case DeclaratorChunk::Pipe:
3266 return;
3269 done:
3271 // If we have *one* pointer, then we want to throw the qualifier on
3272 // the declaration-specifiers, which means that it needs to be a
3273 // retainable object type.
3274 if (numPointers == 1) {
3275 // If it's not a retainable object type, the rule doesn't apply.
3276 if (!declSpecType->isObjCRetainableType()) return;
3278 // If it already has lifetime, don't do anything.
3279 if (declSpecType.getObjCLifetime()) return;
3281 // Otherwise, modify the type in-place.
3282 Qualifiers qs;
3284 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3285 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3286 else
3287 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3288 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3290 // If we have *two* pointers, then we want to throw the qualifier on
3291 // the outermost pointer.
3292 } else if (numPointers == 2) {
3293 // If we don't have a block pointer, we need to check whether the
3294 // declaration-specifiers gave us something that will turn into a
3295 // retainable object pointer after we slap the first pointer on it.
3296 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3297 return;
3299 // Look for an explicit lifetime attribute there.
3300 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3301 if (chunk.Kind != DeclaratorChunk::Pointer &&
3302 chunk.Kind != DeclaratorChunk::BlockPointer)
3303 return;
3304 for (const ParsedAttr &AL : chunk.getAttrs())
3305 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3306 return;
3308 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3309 outermostPointerIndex);
3311 // Any other number of pointers/references does not trigger the rule.
3312 } else return;
3314 // TODO: mark whether we did this inference?
3317 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3318 SourceLocation FallbackLoc,
3319 SourceLocation ConstQualLoc,
3320 SourceLocation VolatileQualLoc,
3321 SourceLocation RestrictQualLoc,
3322 SourceLocation AtomicQualLoc,
3323 SourceLocation UnalignedQualLoc) {
3324 if (!Quals)
3325 return;
3327 struct Qual {
3328 const char *Name;
3329 unsigned Mask;
3330 SourceLocation Loc;
3331 } const QualKinds[5] = {
3332 { "const", DeclSpec::TQ_const, ConstQualLoc },
3333 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3334 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3335 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3336 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3339 SmallString<32> QualStr;
3340 unsigned NumQuals = 0;
3341 SourceLocation Loc;
3342 FixItHint FixIts[5];
3344 // Build a string naming the redundant qualifiers.
3345 for (auto &E : QualKinds) {
3346 if (Quals & E.Mask) {
3347 if (!QualStr.empty()) QualStr += ' ';
3348 QualStr += E.Name;
3350 // If we have a location for the qualifier, offer a fixit.
3351 SourceLocation QualLoc = E.Loc;
3352 if (QualLoc.isValid()) {
3353 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3354 if (Loc.isInvalid() ||
3355 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3356 Loc = QualLoc;
3359 ++NumQuals;
3363 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3364 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3367 // Diagnose pointless type qualifiers on the return type of a function.
3368 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3369 Declarator &D,
3370 unsigned FunctionChunkIndex) {
3371 const DeclaratorChunk::FunctionTypeInfo &FTI =
3372 D.getTypeObject(FunctionChunkIndex).Fun;
3373 if (FTI.hasTrailingReturnType()) {
3374 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3375 RetTy.getLocalCVRQualifiers(),
3376 FTI.getTrailingReturnTypeLoc());
3377 return;
3380 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3381 End = D.getNumTypeObjects();
3382 OuterChunkIndex != End; ++OuterChunkIndex) {
3383 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3384 switch (OuterChunk.Kind) {
3385 case DeclaratorChunk::Paren:
3386 continue;
3388 case DeclaratorChunk::Pointer: {
3389 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3390 S.diagnoseIgnoredQualifiers(
3391 diag::warn_qual_return_type,
3392 PTI.TypeQuals,
3393 SourceLocation(),
3394 PTI.ConstQualLoc,
3395 PTI.VolatileQualLoc,
3396 PTI.RestrictQualLoc,
3397 PTI.AtomicQualLoc,
3398 PTI.UnalignedQualLoc);
3399 return;
3402 case DeclaratorChunk::Function:
3403 case DeclaratorChunk::BlockPointer:
3404 case DeclaratorChunk::Reference:
3405 case DeclaratorChunk::Array:
3406 case DeclaratorChunk::MemberPointer:
3407 case DeclaratorChunk::Pipe:
3408 // FIXME: We can't currently provide an accurate source location and a
3409 // fix-it hint for these.
3410 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3411 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3412 RetTy.getCVRQualifiers() | AtomicQual,
3413 D.getIdentifierLoc());
3414 return;
3417 llvm_unreachable("unknown declarator chunk kind");
3420 // If the qualifiers come from a conversion function type, don't diagnose
3421 // them -- they're not necessarily redundant, since such a conversion
3422 // operator can be explicitly called as "x.operator const int()".
3423 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3424 return;
3426 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3427 // which are present there.
3428 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3429 D.getDeclSpec().getTypeQualifiers(),
3430 D.getIdentifierLoc(),
3431 D.getDeclSpec().getConstSpecLoc(),
3432 D.getDeclSpec().getVolatileSpecLoc(),
3433 D.getDeclSpec().getRestrictSpecLoc(),
3434 D.getDeclSpec().getAtomicSpecLoc(),
3435 D.getDeclSpec().getUnalignedSpecLoc());
3438 static std::pair<QualType, TypeSourceInfo *>
3439 InventTemplateParameter(TypeProcessingState &state, QualType T,
3440 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3441 InventedTemplateParameterInfo &Info) {
3442 Sema &S = state.getSema();
3443 Declarator &D = state.getDeclarator();
3445 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3446 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3447 const bool IsParameterPack = D.hasEllipsis();
3449 // If auto is mentioned in a lambda parameter or abbreviated function
3450 // template context, convert it to a template parameter type.
3452 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3453 // template parameter type. Template parameters are temporarily added
3454 // to the TU until the associated TemplateDecl is created.
3455 TemplateTypeParmDecl *InventedTemplateParam =
3456 TemplateTypeParmDecl::Create(
3457 S.Context, S.Context.getTranslationUnitDecl(),
3458 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3459 /*NameLoc=*/D.getIdentifierLoc(),
3460 TemplateParameterDepth, AutoParameterPosition,
3461 S.InventAbbreviatedTemplateParameterTypeName(
3462 D.getIdentifier(), AutoParameterPosition), false,
3463 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3464 InventedTemplateParam->setImplicit();
3465 Info.TemplateParams.push_back(InventedTemplateParam);
3467 // Attach type constraints to the new parameter.
3468 if (Auto->isConstrained()) {
3469 if (TrailingTSI) {
3470 // The 'auto' appears in a trailing return type we've already built;
3471 // extract its type constraints to attach to the template parameter.
3472 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3473 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3474 bool Invalid = false;
3475 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3476 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3477 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3478 Sema::UPPC_TypeConstraint))
3479 Invalid = true;
3480 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3483 if (!Invalid) {
3484 S.AttachTypeConstraint(
3485 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3486 AutoLoc.getNamedConcept(),
3487 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3488 InventedTemplateParam, D.getEllipsisLoc());
3490 } else {
3491 // The 'auto' appears in the decl-specifiers; we've not finished forming
3492 // TypeSourceInfo for it yet.
3493 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3494 TemplateArgumentListInfo TemplateArgsInfo;
3495 bool Invalid = false;
3496 if (TemplateId->LAngleLoc.isValid()) {
3497 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3498 TemplateId->NumArgs);
3499 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3501 if (D.getEllipsisLoc().isInvalid()) {
3502 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3503 if (S.DiagnoseUnexpandedParameterPack(Arg,
3504 Sema::UPPC_TypeConstraint)) {
3505 Invalid = true;
3506 break;
3511 if (!Invalid) {
3512 S.AttachTypeConstraint(
3513 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3514 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3515 TemplateId->TemplateNameLoc),
3516 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3517 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3518 InventedTemplateParam, D.getEllipsisLoc());
3523 // Replace the 'auto' in the function parameter with this invented
3524 // template type parameter.
3525 // FIXME: Retain some type sugar to indicate that this was written
3526 // as 'auto'?
3527 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3528 QualType NewT = state.ReplaceAutoType(T, Replacement);
3529 TypeSourceInfo *NewTSI =
3530 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3531 : nullptr;
3532 return {NewT, NewTSI};
3535 static TypeSourceInfo *
3536 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3537 QualType T, TypeSourceInfo *ReturnTypeInfo);
3539 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3540 TypeSourceInfo *&ReturnTypeInfo) {
3541 Sema &SemaRef = state.getSema();
3542 Declarator &D = state.getDeclarator();
3543 QualType T;
3544 ReturnTypeInfo = nullptr;
3546 // The TagDecl owned by the DeclSpec.
3547 TagDecl *OwnedTagDecl = nullptr;
3549 switch (D.getName().getKind()) {
3550 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3551 case UnqualifiedIdKind::IK_OperatorFunctionId:
3552 case UnqualifiedIdKind::IK_Identifier:
3553 case UnqualifiedIdKind::IK_LiteralOperatorId:
3554 case UnqualifiedIdKind::IK_TemplateId:
3555 T = ConvertDeclSpecToType(state);
3557 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3558 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3559 // Owned declaration is embedded in declarator.
3560 OwnedTagDecl->setEmbeddedInDeclarator(true);
3562 break;
3564 case UnqualifiedIdKind::IK_ConstructorName:
3565 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3566 case UnqualifiedIdKind::IK_DestructorName:
3567 // Constructors and destructors don't have return types. Use
3568 // "void" instead.
3569 T = SemaRef.Context.VoidTy;
3570 processTypeAttrs(state, T, TAL_DeclSpec,
3571 D.getMutableDeclSpec().getAttributes());
3572 break;
3574 case UnqualifiedIdKind::IK_DeductionGuideName:
3575 // Deduction guides have a trailing return type and no type in their
3576 // decl-specifier sequence. Use a placeholder return type for now.
3577 T = SemaRef.Context.DependentTy;
3578 break;
3580 case UnqualifiedIdKind::IK_ConversionFunctionId:
3581 // The result type of a conversion function is the type that it
3582 // converts to.
3583 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3584 &ReturnTypeInfo);
3585 break;
3588 // Note: We don't need to distribute declaration attributes (i.e.
3589 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3590 // and those don't get distributed.
3591 distributeTypeAttrsFromDeclarator(
3592 state, T, SemaRef.IdentifyCUDATarget(D.getAttributes()));
3594 // Find the deduced type in this type. Look in the trailing return type if we
3595 // have one, otherwise in the DeclSpec type.
3596 // FIXME: The standard wording doesn't currently describe this.
3597 DeducedType *Deduced = T->getContainedDeducedType();
3598 bool DeducedIsTrailingReturnType = false;
3599 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3600 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3601 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3602 DeducedIsTrailingReturnType = true;
3605 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3606 if (Deduced) {
3607 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3608 int Error = -1;
3610 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3611 // class template argument deduction)?
3612 bool IsCXXAutoType =
3613 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3614 bool IsDeducedReturnType = false;
3616 switch (D.getContext()) {
3617 case DeclaratorContext::LambdaExpr:
3618 // Declared return type of a lambda-declarator is implicit and is always
3619 // 'auto'.
3620 break;
3621 case DeclaratorContext::ObjCParameter:
3622 case DeclaratorContext::ObjCResult:
3623 Error = 0;
3624 break;
3625 case DeclaratorContext::RequiresExpr:
3626 Error = 22;
3627 break;
3628 case DeclaratorContext::Prototype:
3629 case DeclaratorContext::LambdaExprParameter: {
3630 InventedTemplateParameterInfo *Info = nullptr;
3631 if (D.getContext() == DeclaratorContext::Prototype) {
3632 // With concepts we allow 'auto' in function parameters.
3633 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3634 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3635 Error = 0;
3636 break;
3637 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3638 Error = 21;
3639 break;
3642 Info = &SemaRef.InventedParameterInfos.back();
3643 } else {
3644 // In C++14, generic lambdas allow 'auto' in their parameters.
3645 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3646 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3647 Error = 16;
3648 break;
3650 Info = SemaRef.getCurLambda();
3651 assert(Info && "No LambdaScopeInfo on the stack!");
3654 // We'll deal with inventing template parameters for 'auto' in trailing
3655 // return types when we pick up the trailing return type when processing
3656 // the function chunk.
3657 if (!DeducedIsTrailingReturnType)
3658 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3659 break;
3661 case DeclaratorContext::Member: {
3662 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3663 D.isFunctionDeclarator())
3664 break;
3665 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3666 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3667 Error = 6; // Interface member.
3668 } else {
3669 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3670 case TTK_Enum: llvm_unreachable("unhandled tag kind");
3671 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3672 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3673 case TTK_Class: Error = 5; /* Class member */ break;
3674 case TTK_Interface: Error = 6; /* Interface member */ break;
3677 if (D.getDeclSpec().isFriendSpecified())
3678 Error = 20; // Friend type
3679 break;
3681 case DeclaratorContext::CXXCatch:
3682 case DeclaratorContext::ObjCCatch:
3683 Error = 7; // Exception declaration
3684 break;
3685 case DeclaratorContext::TemplateParam:
3686 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3687 !SemaRef.getLangOpts().CPlusPlus20)
3688 Error = 19; // Template parameter (until C++20)
3689 else if (!SemaRef.getLangOpts().CPlusPlus17)
3690 Error = 8; // Template parameter (until C++17)
3691 break;
3692 case DeclaratorContext::BlockLiteral:
3693 Error = 9; // Block literal
3694 break;
3695 case DeclaratorContext::TemplateArg:
3696 // Within a template argument list, a deduced template specialization
3697 // type will be reinterpreted as a template template argument.
3698 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3699 !D.getNumTypeObjects() &&
3700 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3701 break;
3702 [[fallthrough]];
3703 case DeclaratorContext::TemplateTypeArg:
3704 Error = 10; // Template type argument
3705 break;
3706 case DeclaratorContext::AliasDecl:
3707 case DeclaratorContext::AliasTemplate:
3708 Error = 12; // Type alias
3709 break;
3710 case DeclaratorContext::TrailingReturn:
3711 case DeclaratorContext::TrailingReturnVar:
3712 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3713 Error = 13; // Function return type
3714 IsDeducedReturnType = true;
3715 break;
3716 case DeclaratorContext::ConversionId:
3717 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3718 Error = 14; // conversion-type-id
3719 IsDeducedReturnType = true;
3720 break;
3721 case DeclaratorContext::FunctionalCast:
3722 if (isa<DeducedTemplateSpecializationType>(Deduced))
3723 break;
3724 if (SemaRef.getLangOpts().CPlusPlus23 && IsCXXAutoType &&
3725 !Auto->isDecltypeAuto())
3726 break; // auto(x)
3727 [[fallthrough]];
3728 case DeclaratorContext::TypeName:
3729 case DeclaratorContext::Association:
3730 Error = 15; // Generic
3731 break;
3732 case DeclaratorContext::File:
3733 case DeclaratorContext::Block:
3734 case DeclaratorContext::ForInit:
3735 case DeclaratorContext::SelectionInit:
3736 case DeclaratorContext::Condition:
3737 // FIXME: P0091R3 (erroneously) does not permit class template argument
3738 // deduction in conditions, for-init-statements, and other declarations
3739 // that are not simple-declarations.
3740 break;
3741 case DeclaratorContext::CXXNew:
3742 // FIXME: P0091R3 does not permit class template argument deduction here,
3743 // but we follow GCC and allow it anyway.
3744 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3745 Error = 17; // 'new' type
3746 break;
3747 case DeclaratorContext::KNRTypeList:
3748 Error = 18; // K&R function parameter
3749 break;
3752 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3753 Error = 11;
3755 // In Objective-C it is an error to use 'auto' on a function declarator
3756 // (and everywhere for '__auto_type').
3757 if (D.isFunctionDeclarator() &&
3758 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3759 Error = 13;
3761 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3762 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3763 AutoRange = D.getName().getSourceRange();
3765 if (Error != -1) {
3766 unsigned Kind;
3767 if (Auto) {
3768 switch (Auto->getKeyword()) {
3769 case AutoTypeKeyword::Auto: Kind = 0; break;
3770 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3771 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3773 } else {
3774 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3775 "unknown auto type");
3776 Kind = 3;
3779 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3780 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3782 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3783 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3784 << QualType(Deduced, 0) << AutoRange;
3785 if (auto *TD = TN.getAsTemplateDecl())
3786 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3788 T = SemaRef.Context.IntTy;
3789 D.setInvalidType(true);
3790 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3791 // If there was a trailing return type, we already got
3792 // warn_cxx98_compat_trailing_return_type in the parser.
3793 SemaRef.Diag(AutoRange.getBegin(),
3794 D.getContext() == DeclaratorContext::LambdaExprParameter
3795 ? diag::warn_cxx11_compat_generic_lambda
3796 : IsDeducedReturnType
3797 ? diag::warn_cxx11_compat_deduced_return_type
3798 : diag::warn_cxx98_compat_auto_type_specifier)
3799 << AutoRange;
3803 if (SemaRef.getLangOpts().CPlusPlus &&
3804 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3805 // Check the contexts where C++ forbids the declaration of a new class
3806 // or enumeration in a type-specifier-seq.
3807 unsigned DiagID = 0;
3808 switch (D.getContext()) {
3809 case DeclaratorContext::TrailingReturn:
3810 case DeclaratorContext::TrailingReturnVar:
3811 // Class and enumeration definitions are syntactically not allowed in
3812 // trailing return types.
3813 llvm_unreachable("parser should not have allowed this");
3814 break;
3815 case DeclaratorContext::File:
3816 case DeclaratorContext::Member:
3817 case DeclaratorContext::Block:
3818 case DeclaratorContext::ForInit:
3819 case DeclaratorContext::SelectionInit:
3820 case DeclaratorContext::BlockLiteral:
3821 case DeclaratorContext::LambdaExpr:
3822 // C++11 [dcl.type]p3:
3823 // A type-specifier-seq shall not define a class or enumeration unless
3824 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3825 // the declaration of a template-declaration.
3826 case DeclaratorContext::AliasDecl:
3827 break;
3828 case DeclaratorContext::AliasTemplate:
3829 DiagID = diag::err_type_defined_in_alias_template;
3830 break;
3831 case DeclaratorContext::TypeName:
3832 case DeclaratorContext::FunctionalCast:
3833 case DeclaratorContext::ConversionId:
3834 case DeclaratorContext::TemplateParam:
3835 case DeclaratorContext::CXXNew:
3836 case DeclaratorContext::CXXCatch:
3837 case DeclaratorContext::ObjCCatch:
3838 case DeclaratorContext::TemplateArg:
3839 case DeclaratorContext::TemplateTypeArg:
3840 case DeclaratorContext::Association:
3841 DiagID = diag::err_type_defined_in_type_specifier;
3842 break;
3843 case DeclaratorContext::Prototype:
3844 case DeclaratorContext::LambdaExprParameter:
3845 case DeclaratorContext::ObjCParameter:
3846 case DeclaratorContext::ObjCResult:
3847 case DeclaratorContext::KNRTypeList:
3848 case DeclaratorContext::RequiresExpr:
3849 // C++ [dcl.fct]p6:
3850 // Types shall not be defined in return or parameter types.
3851 DiagID = diag::err_type_defined_in_param_type;
3852 break;
3853 case DeclaratorContext::Condition:
3854 // C++ 6.4p2:
3855 // The type-specifier-seq shall not contain typedef and shall not declare
3856 // a new class or enumeration.
3857 DiagID = diag::err_type_defined_in_condition;
3858 break;
3861 if (DiagID != 0) {
3862 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3863 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3864 D.setInvalidType(true);
3868 assert(!T.isNull() && "This function should not return a null type");
3869 return T;
3872 /// Produce an appropriate diagnostic for an ambiguity between a function
3873 /// declarator and a C++ direct-initializer.
3874 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3875 DeclaratorChunk &DeclType, QualType RT) {
3876 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3877 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3879 // If the return type is void there is no ambiguity.
3880 if (RT->isVoidType())
3881 return;
3883 // An initializer for a non-class type can have at most one argument.
3884 if (!RT->isRecordType() && FTI.NumParams > 1)
3885 return;
3887 // An initializer for a reference must have exactly one argument.
3888 if (RT->isReferenceType() && FTI.NumParams != 1)
3889 return;
3891 // Only warn if this declarator is declaring a function at block scope, and
3892 // doesn't have a storage class (such as 'extern') specified.
3893 if (!D.isFunctionDeclarator() ||
3894 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3895 !S.CurContext->isFunctionOrMethod() ||
3896 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3897 return;
3899 // Inside a condition, a direct initializer is not permitted. We allow one to
3900 // be parsed in order to give better diagnostics in condition parsing.
3901 if (D.getContext() == DeclaratorContext::Condition)
3902 return;
3904 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3906 S.Diag(DeclType.Loc,
3907 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3908 : diag::warn_empty_parens_are_function_decl)
3909 << ParenRange;
3911 // If the declaration looks like:
3912 // T var1,
3913 // f();
3914 // and name lookup finds a function named 'f', then the ',' was
3915 // probably intended to be a ';'.
3916 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3917 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3918 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3919 if (Comma.getFileID() != Name.getFileID() ||
3920 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3921 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3922 Sema::LookupOrdinaryName);
3923 if (S.LookupName(Result, S.getCurScope()))
3924 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3925 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3926 << D.getIdentifier();
3927 Result.suppressDiagnostics();
3931 if (FTI.NumParams > 0) {
3932 // For a declaration with parameters, eg. "T var(T());", suggest adding
3933 // parens around the first parameter to turn the declaration into a
3934 // variable declaration.
3935 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3936 SourceLocation B = Range.getBegin();
3937 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3938 // FIXME: Maybe we should suggest adding braces instead of parens
3939 // in C++11 for classes that don't have an initializer_list constructor.
3940 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3941 << FixItHint::CreateInsertion(B, "(")
3942 << FixItHint::CreateInsertion(E, ")");
3943 } else {
3944 // For a declaration without parameters, eg. "T var();", suggest replacing
3945 // the parens with an initializer to turn the declaration into a variable
3946 // declaration.
3947 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3949 // Empty parens mean value-initialization, and no parens mean
3950 // default initialization. These are equivalent if the default
3951 // constructor is user-provided or if zero-initialization is a
3952 // no-op.
3953 if (RD && RD->hasDefinition() &&
3954 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3955 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3956 << FixItHint::CreateRemoval(ParenRange);
3957 else {
3958 std::string Init =
3959 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3960 if (Init.empty() && S.LangOpts.CPlusPlus11)
3961 Init = "{}";
3962 if (!Init.empty())
3963 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3964 << FixItHint::CreateReplacement(ParenRange, Init);
3969 /// Produce an appropriate diagnostic for a declarator with top-level
3970 /// parentheses.
3971 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3972 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3973 assert(Paren.Kind == DeclaratorChunk::Paren &&
3974 "do not have redundant top-level parentheses");
3976 // This is a syntactic check; we're not interested in cases that arise
3977 // during template instantiation.
3978 if (S.inTemplateInstantiation())
3979 return;
3981 // Check whether this could be intended to be a construction of a temporary
3982 // object in C++ via a function-style cast.
3983 bool CouldBeTemporaryObject =
3984 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3985 !D.isInvalidType() && D.getIdentifier() &&
3986 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3987 (T->isRecordType() || T->isDependentType()) &&
3988 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3990 bool StartsWithDeclaratorId = true;
3991 for (auto &C : D.type_objects()) {
3992 switch (C.Kind) {
3993 case DeclaratorChunk::Paren:
3994 if (&C == &Paren)
3995 continue;
3996 [[fallthrough]];
3997 case DeclaratorChunk::Pointer:
3998 StartsWithDeclaratorId = false;
3999 continue;
4001 case DeclaratorChunk::Array:
4002 if (!C.Arr.NumElts)
4003 CouldBeTemporaryObject = false;
4004 continue;
4006 case DeclaratorChunk::Reference:
4007 // FIXME: Suppress the warning here if there is no initializer; we're
4008 // going to give an error anyway.
4009 // We assume that something like 'T (&x) = y;' is highly likely to not
4010 // be intended to be a temporary object.
4011 CouldBeTemporaryObject = false;
4012 StartsWithDeclaratorId = false;
4013 continue;
4015 case DeclaratorChunk::Function:
4016 // In a new-type-id, function chunks require parentheses.
4017 if (D.getContext() == DeclaratorContext::CXXNew)
4018 return;
4019 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
4020 // redundant-parens warning, but we don't know whether the function
4021 // chunk was syntactically valid as an expression here.
4022 CouldBeTemporaryObject = false;
4023 continue;
4025 case DeclaratorChunk::BlockPointer:
4026 case DeclaratorChunk::MemberPointer:
4027 case DeclaratorChunk::Pipe:
4028 // These cannot appear in expressions.
4029 CouldBeTemporaryObject = false;
4030 StartsWithDeclaratorId = false;
4031 continue;
4035 // FIXME: If there is an initializer, assume that this is not intended to be
4036 // a construction of a temporary object.
4038 // Check whether the name has already been declared; if not, this is not a
4039 // function-style cast.
4040 if (CouldBeTemporaryObject) {
4041 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
4042 Sema::LookupOrdinaryName);
4043 if (!S.LookupName(Result, S.getCurScope()))
4044 CouldBeTemporaryObject = false;
4045 Result.suppressDiagnostics();
4048 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
4050 if (!CouldBeTemporaryObject) {
4051 // If we have A (::B), the parentheses affect the meaning of the program.
4052 // Suppress the warning in that case. Don't bother looking at the DeclSpec
4053 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
4054 // formally unambiguous.
4055 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
4056 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
4057 NNS = NNS->getPrefix()) {
4058 if (NNS->getKind() == NestedNameSpecifier::Global)
4059 return;
4063 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
4064 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
4065 << FixItHint::CreateRemoval(Paren.EndLoc);
4066 return;
4069 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
4070 << ParenRange << D.getIdentifier();
4071 auto *RD = T->getAsCXXRecordDecl();
4072 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
4073 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
4074 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
4075 << D.getIdentifier();
4076 // FIXME: A cast to void is probably a better suggestion in cases where it's
4077 // valid (when there is no initializer and we're not in a condition).
4078 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
4079 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
4080 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
4081 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
4082 << FixItHint::CreateRemoval(Paren.Loc)
4083 << FixItHint::CreateRemoval(Paren.EndLoc);
4086 /// Helper for figuring out the default CC for a function declarator type. If
4087 /// this is the outermost chunk, then we can determine the CC from the
4088 /// declarator context. If not, then this could be either a member function
4089 /// type or normal function type.
4090 static CallingConv getCCForDeclaratorChunk(
4091 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
4092 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
4093 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
4095 // Check for an explicit CC attribute.
4096 for (const ParsedAttr &AL : AttrList) {
4097 switch (AL.getKind()) {
4098 CALLING_CONV_ATTRS_CASELIST : {
4099 // Ignore attributes that don't validate or can't apply to the
4100 // function type. We'll diagnose the failure to apply them in
4101 // handleFunctionTypeAttr.
4102 CallingConv CC;
4103 if (!S.CheckCallingConvAttr(AL, CC, /*FunctionDecl=*/nullptr,
4104 S.IdentifyCUDATarget(D.getAttributes())) &&
4105 (!FTI.isVariadic || supportsVariadicCall(CC))) {
4106 return CC;
4108 break;
4111 default:
4112 break;
4116 bool IsCXXInstanceMethod = false;
4118 if (S.getLangOpts().CPlusPlus) {
4119 // Look inwards through parentheses to see if this chunk will form a
4120 // member pointer type or if we're the declarator. Any type attributes
4121 // between here and there will override the CC we choose here.
4122 unsigned I = ChunkIndex;
4123 bool FoundNonParen = false;
4124 while (I && !FoundNonParen) {
4125 --I;
4126 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4127 FoundNonParen = true;
4130 if (FoundNonParen) {
4131 // If we're not the declarator, we're a regular function type unless we're
4132 // in a member pointer.
4133 IsCXXInstanceMethod =
4134 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4135 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4136 // This can only be a call operator for a lambda, which is an instance
4137 // method, unless explicitly specified as 'static'.
4138 IsCXXInstanceMethod =
4139 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static;
4140 } else {
4141 // We're the innermost decl chunk, so must be a function declarator.
4142 assert(D.isFunctionDeclarator());
4144 // If we're inside a record, we're declaring a method, but it could be
4145 // explicitly or implicitly static.
4146 IsCXXInstanceMethod =
4147 D.isFirstDeclarationOfMember() &&
4148 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4149 !D.isStaticMember();
4153 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4154 IsCXXInstanceMethod);
4156 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4157 // and AMDGPU targets, hence it cannot be treated as a calling
4158 // convention attribute. This is the simplest place to infer
4159 // calling convention for OpenCL kernels.
4160 if (S.getLangOpts().OpenCL) {
4161 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4162 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4163 CC = CC_OpenCLKernel;
4164 break;
4167 } else if (S.getLangOpts().CUDA) {
4168 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4169 // sure the kernels will be marked with the right calling convention so that
4170 // they will be visible by the APIs that ingest SPIR-V.
4171 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4172 if (Triple.getArch() == llvm::Triple::spirv32 ||
4173 Triple.getArch() == llvm::Triple::spirv64) {
4174 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4175 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4176 CC = CC_OpenCLKernel;
4177 break;
4183 return CC;
4186 namespace {
4187 /// A simple notion of pointer kinds, which matches up with the various
4188 /// pointer declarators.
4189 enum class SimplePointerKind {
4190 Pointer,
4191 BlockPointer,
4192 MemberPointer,
4193 Array,
4195 } // end anonymous namespace
4197 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4198 switch (nullability) {
4199 case NullabilityKind::NonNull:
4200 if (!Ident__Nonnull)
4201 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4202 return Ident__Nonnull;
4204 case NullabilityKind::Nullable:
4205 if (!Ident__Nullable)
4206 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4207 return Ident__Nullable;
4209 case NullabilityKind::NullableResult:
4210 if (!Ident__Nullable_result)
4211 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4212 return Ident__Nullable_result;
4214 case NullabilityKind::Unspecified:
4215 if (!Ident__Null_unspecified)
4216 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4217 return Ident__Null_unspecified;
4219 llvm_unreachable("Unknown nullability kind.");
4222 /// Retrieve the identifier "NSError".
4223 IdentifierInfo *Sema::getNSErrorIdent() {
4224 if (!Ident_NSError)
4225 Ident_NSError = PP.getIdentifierInfo("NSError");
4227 return Ident_NSError;
4230 /// Check whether there is a nullability attribute of any kind in the given
4231 /// attribute list.
4232 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4233 for (const ParsedAttr &AL : attrs) {
4234 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4235 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4236 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4237 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4238 return true;
4241 return false;
4244 namespace {
4245 /// Describes the kind of a pointer a declarator describes.
4246 enum class PointerDeclaratorKind {
4247 // Not a pointer.
4248 NonPointer,
4249 // Single-level pointer.
4250 SingleLevelPointer,
4251 // Multi-level pointer (of any pointer kind).
4252 MultiLevelPointer,
4253 // CFFooRef*
4254 MaybePointerToCFRef,
4255 // CFErrorRef*
4256 CFErrorRefPointer,
4257 // NSError**
4258 NSErrorPointerPointer,
4261 /// Describes a declarator chunk wrapping a pointer that marks inference as
4262 /// unexpected.
4263 // These values must be kept in sync with diagnostics.
4264 enum class PointerWrappingDeclaratorKind {
4265 /// Pointer is top-level.
4266 None = -1,
4267 /// Pointer is an array element.
4268 Array = 0,
4269 /// Pointer is the referent type of a C++ reference.
4270 Reference = 1
4272 } // end anonymous namespace
4274 /// Classify the given declarator, whose type-specified is \c type, based on
4275 /// what kind of pointer it refers to.
4277 /// This is used to determine the default nullability.
4278 static PointerDeclaratorKind
4279 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4280 PointerWrappingDeclaratorKind &wrappingKind) {
4281 unsigned numNormalPointers = 0;
4283 // For any dependent type, we consider it a non-pointer.
4284 if (type->isDependentType())
4285 return PointerDeclaratorKind::NonPointer;
4287 // Look through the declarator chunks to identify pointers.
4288 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4289 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4290 switch (chunk.Kind) {
4291 case DeclaratorChunk::Array:
4292 if (numNormalPointers == 0)
4293 wrappingKind = PointerWrappingDeclaratorKind::Array;
4294 break;
4296 case DeclaratorChunk::Function:
4297 case DeclaratorChunk::Pipe:
4298 break;
4300 case DeclaratorChunk::BlockPointer:
4301 case DeclaratorChunk::MemberPointer:
4302 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4303 : PointerDeclaratorKind::SingleLevelPointer;
4305 case DeclaratorChunk::Paren:
4306 break;
4308 case DeclaratorChunk::Reference:
4309 if (numNormalPointers == 0)
4310 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4311 break;
4313 case DeclaratorChunk::Pointer:
4314 ++numNormalPointers;
4315 if (numNormalPointers > 2)
4316 return PointerDeclaratorKind::MultiLevelPointer;
4317 break;
4321 // Then, dig into the type specifier itself.
4322 unsigned numTypeSpecifierPointers = 0;
4323 do {
4324 // Decompose normal pointers.
4325 if (auto ptrType = type->getAs<PointerType>()) {
4326 ++numNormalPointers;
4328 if (numNormalPointers > 2)
4329 return PointerDeclaratorKind::MultiLevelPointer;
4331 type = ptrType->getPointeeType();
4332 ++numTypeSpecifierPointers;
4333 continue;
4336 // Decompose block pointers.
4337 if (type->getAs<BlockPointerType>()) {
4338 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4339 : PointerDeclaratorKind::SingleLevelPointer;
4342 // Decompose member pointers.
4343 if (type->getAs<MemberPointerType>()) {
4344 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4345 : PointerDeclaratorKind::SingleLevelPointer;
4348 // Look at Objective-C object pointers.
4349 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4350 ++numNormalPointers;
4351 ++numTypeSpecifierPointers;
4353 // If this is NSError**, report that.
4354 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4355 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4356 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4357 return PointerDeclaratorKind::NSErrorPointerPointer;
4361 break;
4364 // Look at Objective-C class types.
4365 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4366 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4367 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4368 return PointerDeclaratorKind::NSErrorPointerPointer;
4371 break;
4374 // If at this point we haven't seen a pointer, we won't see one.
4375 if (numNormalPointers == 0)
4376 return PointerDeclaratorKind::NonPointer;
4378 if (auto recordType = type->getAs<RecordType>()) {
4379 RecordDecl *recordDecl = recordType->getDecl();
4381 // If this is CFErrorRef*, report it as such.
4382 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4383 S.isCFError(recordDecl)) {
4384 return PointerDeclaratorKind::CFErrorRefPointer;
4386 break;
4389 break;
4390 } while (true);
4392 switch (numNormalPointers) {
4393 case 0:
4394 return PointerDeclaratorKind::NonPointer;
4396 case 1:
4397 return PointerDeclaratorKind::SingleLevelPointer;
4399 case 2:
4400 return PointerDeclaratorKind::MaybePointerToCFRef;
4402 default:
4403 return PointerDeclaratorKind::MultiLevelPointer;
4407 bool Sema::isCFError(RecordDecl *RD) {
4408 // If we already know about CFError, test it directly.
4409 if (CFError)
4410 return CFError == RD;
4412 // Check whether this is CFError, which we identify based on its bridge to
4413 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4414 // declared with "objc_bridge_mutable", so look for either one of the two
4415 // attributes.
4416 if (RD->getTagKind() == TTK_Struct) {
4417 IdentifierInfo *bridgedType = nullptr;
4418 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4419 bridgedType = bridgeAttr->getBridgedType();
4420 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4421 bridgedType = bridgeAttr->getBridgedType();
4423 if (bridgedType == getNSErrorIdent()) {
4424 CFError = RD;
4425 return true;
4429 return false;
4432 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4433 SourceLocation loc) {
4434 // If we're anywhere in a function, method, or closure context, don't perform
4435 // completeness checks.
4436 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4437 if (ctx->isFunctionOrMethod())
4438 return FileID();
4440 if (ctx->isFileContext())
4441 break;
4444 // We only care about the expansion location.
4445 loc = S.SourceMgr.getExpansionLoc(loc);
4446 FileID file = S.SourceMgr.getFileID(loc);
4447 if (file.isInvalid())
4448 return FileID();
4450 // Retrieve file information.
4451 bool invalid = false;
4452 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4453 if (invalid || !sloc.isFile())
4454 return FileID();
4456 // We don't want to perform completeness checks on the main file or in
4457 // system headers.
4458 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4459 if (fileInfo.getIncludeLoc().isInvalid())
4460 return FileID();
4461 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4462 S.Diags.getSuppressSystemWarnings()) {
4463 return FileID();
4466 return file;
4469 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4470 /// taking into account whitespace before and after.
4471 template <typename DiagBuilderT>
4472 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4473 SourceLocation PointerLoc,
4474 NullabilityKind Nullability) {
4475 assert(PointerLoc.isValid());
4476 if (PointerLoc.isMacroID())
4477 return;
4479 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4480 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4481 return;
4483 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4484 if (!NextChar)
4485 return;
4487 SmallString<32> InsertionTextBuf{" "};
4488 InsertionTextBuf += getNullabilitySpelling(Nullability);
4489 InsertionTextBuf += " ";
4490 StringRef InsertionText = InsertionTextBuf.str();
4492 if (isWhitespace(*NextChar)) {
4493 InsertionText = InsertionText.drop_back();
4494 } else if (NextChar[-1] == '[') {
4495 if (NextChar[0] == ']')
4496 InsertionText = InsertionText.drop_back().drop_front();
4497 else
4498 InsertionText = InsertionText.drop_front();
4499 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4500 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4501 InsertionText = InsertionText.drop_back().drop_front();
4504 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4507 static void emitNullabilityConsistencyWarning(Sema &S,
4508 SimplePointerKind PointerKind,
4509 SourceLocation PointerLoc,
4510 SourceLocation PointerEndLoc) {
4511 assert(PointerLoc.isValid());
4513 if (PointerKind == SimplePointerKind::Array) {
4514 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4515 } else {
4516 S.Diag(PointerLoc, diag::warn_nullability_missing)
4517 << static_cast<unsigned>(PointerKind);
4520 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4521 if (FixItLoc.isMacroID())
4522 return;
4524 auto addFixIt = [&](NullabilityKind Nullability) {
4525 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4526 Diag << static_cast<unsigned>(Nullability);
4527 Diag << static_cast<unsigned>(PointerKind);
4528 fixItNullability(S, Diag, FixItLoc, Nullability);
4530 addFixIt(NullabilityKind::Nullable);
4531 addFixIt(NullabilityKind::NonNull);
4534 /// Complains about missing nullability if the file containing \p pointerLoc
4535 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4536 /// pragma).
4538 /// If the file has \e not seen other uses of nullability, this particular
4539 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4540 static void
4541 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4542 SourceLocation pointerLoc,
4543 SourceLocation pointerEndLoc = SourceLocation()) {
4544 // Determine which file we're performing consistency checking for.
4545 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4546 if (file.isInvalid())
4547 return;
4549 // If we haven't seen any type nullability in this file, we won't warn now
4550 // about anything.
4551 FileNullability &fileNullability = S.NullabilityMap[file];
4552 if (!fileNullability.SawTypeNullability) {
4553 // If this is the first pointer declarator in the file, and the appropriate
4554 // warning is on, record it in case we need to diagnose it retroactively.
4555 diag::kind diagKind;
4556 if (pointerKind == SimplePointerKind::Array)
4557 diagKind = diag::warn_nullability_missing_array;
4558 else
4559 diagKind = diag::warn_nullability_missing;
4561 if (fileNullability.PointerLoc.isInvalid() &&
4562 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4563 fileNullability.PointerLoc = pointerLoc;
4564 fileNullability.PointerEndLoc = pointerEndLoc;
4565 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4568 return;
4571 // Complain about missing nullability.
4572 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4575 /// Marks that a nullability feature has been used in the file containing
4576 /// \p loc.
4578 /// If this file already had pointer types in it that were missing nullability,
4579 /// the first such instance is retroactively diagnosed.
4581 /// \sa checkNullabilityConsistency
4582 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4583 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4584 if (file.isInvalid())
4585 return;
4587 FileNullability &fileNullability = S.NullabilityMap[file];
4588 if (fileNullability.SawTypeNullability)
4589 return;
4590 fileNullability.SawTypeNullability = true;
4592 // If we haven't seen any type nullability before, now we have. Retroactively
4593 // diagnose the first unannotated pointer, if there was one.
4594 if (fileNullability.PointerLoc.isInvalid())
4595 return;
4597 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4598 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4599 fileNullability.PointerEndLoc);
4602 /// Returns true if any of the declarator chunks before \p endIndex include a
4603 /// level of indirection: array, pointer, reference, or pointer-to-member.
4605 /// Because declarator chunks are stored in outer-to-inner order, testing
4606 /// every chunk before \p endIndex is testing all chunks that embed the current
4607 /// chunk as part of their type.
4609 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4610 /// end index, in which case all chunks are tested.
4611 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4612 unsigned i = endIndex;
4613 while (i != 0) {
4614 // Walk outwards along the declarator chunks.
4615 --i;
4616 const DeclaratorChunk &DC = D.getTypeObject(i);
4617 switch (DC.Kind) {
4618 case DeclaratorChunk::Paren:
4619 break;
4620 case DeclaratorChunk::Array:
4621 case DeclaratorChunk::Pointer:
4622 case DeclaratorChunk::Reference:
4623 case DeclaratorChunk::MemberPointer:
4624 return true;
4625 case DeclaratorChunk::Function:
4626 case DeclaratorChunk::BlockPointer:
4627 case DeclaratorChunk::Pipe:
4628 // These are invalid anyway, so just ignore.
4629 break;
4632 return false;
4635 static bool IsNoDerefableChunk(const DeclaratorChunk &Chunk) {
4636 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4637 Chunk.Kind == DeclaratorChunk::Array);
4640 template<typename AttrT>
4641 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4642 AL.setUsedAsTypeAttr();
4643 return ::new (Ctx) AttrT(Ctx, AL);
4646 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4647 NullabilityKind NK) {
4648 switch (NK) {
4649 case NullabilityKind::NonNull:
4650 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4652 case NullabilityKind::Nullable:
4653 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4655 case NullabilityKind::NullableResult:
4656 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4658 case NullabilityKind::Unspecified:
4659 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4661 llvm_unreachable("unknown NullabilityKind");
4664 // Diagnose whether this is a case with the multiple addr spaces.
4665 // Returns true if this is an invalid case.
4666 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4667 // by qualifiers for two or more different address spaces."
4668 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4669 LangAS ASNew,
4670 SourceLocation AttrLoc) {
4671 if (ASOld != LangAS::Default) {
4672 if (ASOld != ASNew) {
4673 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4674 return true;
4676 // Emit a warning if they are identical; it's likely unintended.
4677 S.Diag(AttrLoc,
4678 diag::warn_attribute_address_multiple_identical_qualifiers);
4680 return false;
4683 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4684 QualType declSpecType,
4685 TypeSourceInfo *TInfo) {
4686 // The TypeSourceInfo that this function returns will not be a null type.
4687 // If there is an error, this function will fill in a dummy type as fallback.
4688 QualType T = declSpecType;
4689 Declarator &D = state.getDeclarator();
4690 Sema &S = state.getSema();
4691 ASTContext &Context = S.Context;
4692 const LangOptions &LangOpts = S.getLangOpts();
4694 // The name we're declaring, if any.
4695 DeclarationName Name;
4696 if (D.getIdentifier())
4697 Name = D.getIdentifier();
4699 // Does this declaration declare a typedef-name?
4700 bool IsTypedefName =
4701 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4702 D.getContext() == DeclaratorContext::AliasDecl ||
4703 D.getContext() == DeclaratorContext::AliasTemplate;
4705 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4706 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4707 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4708 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4710 // If T is 'decltype(auto)', the only declarators we can have are parens
4711 // and at most one function declarator if this is a function declaration.
4712 // If T is a deduced class template specialization type, we can have no
4713 // declarator chunks at all.
4714 if (auto *DT = T->getAs<DeducedType>()) {
4715 const AutoType *AT = T->getAs<AutoType>();
4716 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4717 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4718 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4719 unsigned Index = E - I - 1;
4720 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4721 unsigned DiagId = IsClassTemplateDeduction
4722 ? diag::err_deduced_class_template_compound_type
4723 : diag::err_decltype_auto_compound_type;
4724 unsigned DiagKind = 0;
4725 switch (DeclChunk.Kind) {
4726 case DeclaratorChunk::Paren:
4727 // FIXME: Rejecting this is a little silly.
4728 if (IsClassTemplateDeduction) {
4729 DiagKind = 4;
4730 break;
4732 continue;
4733 case DeclaratorChunk::Function: {
4734 if (IsClassTemplateDeduction) {
4735 DiagKind = 3;
4736 break;
4738 unsigned FnIndex;
4739 if (D.isFunctionDeclarationContext() &&
4740 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4741 continue;
4742 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4743 break;
4745 case DeclaratorChunk::Pointer:
4746 case DeclaratorChunk::BlockPointer:
4747 case DeclaratorChunk::MemberPointer:
4748 DiagKind = 0;
4749 break;
4750 case DeclaratorChunk::Reference:
4751 DiagKind = 1;
4752 break;
4753 case DeclaratorChunk::Array:
4754 DiagKind = 2;
4755 break;
4756 case DeclaratorChunk::Pipe:
4757 break;
4760 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4761 D.setInvalidType(true);
4762 break;
4767 // Determine whether we should infer _Nonnull on pointer types.
4768 std::optional<NullabilityKind> inferNullability;
4769 bool inferNullabilityCS = false;
4770 bool inferNullabilityInnerOnly = false;
4771 bool inferNullabilityInnerOnlyComplete = false;
4773 // Are we in an assume-nonnull region?
4774 bool inAssumeNonNullRegion = false;
4775 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4776 if (assumeNonNullLoc.isValid()) {
4777 inAssumeNonNullRegion = true;
4778 recordNullabilitySeen(S, assumeNonNullLoc);
4781 // Whether to complain about missing nullability specifiers or not.
4782 enum {
4783 /// Never complain.
4784 CAMN_No,
4785 /// Complain on the inner pointers (but not the outermost
4786 /// pointer).
4787 CAMN_InnerPointers,
4788 /// Complain about any pointers that don't have nullability
4789 /// specified or inferred.
4790 CAMN_Yes
4791 } complainAboutMissingNullability = CAMN_No;
4792 unsigned NumPointersRemaining = 0;
4793 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4795 if (IsTypedefName) {
4796 // For typedefs, we do not infer any nullability (the default),
4797 // and we only complain about missing nullability specifiers on
4798 // inner pointers.
4799 complainAboutMissingNullability = CAMN_InnerPointers;
4801 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
4802 !T->getNullability()) {
4803 // Note that we allow but don't require nullability on dependent types.
4804 ++NumPointersRemaining;
4807 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4808 DeclaratorChunk &chunk = D.getTypeObject(i);
4809 switch (chunk.Kind) {
4810 case DeclaratorChunk::Array:
4811 case DeclaratorChunk::Function:
4812 case DeclaratorChunk::Pipe:
4813 break;
4815 case DeclaratorChunk::BlockPointer:
4816 case DeclaratorChunk::MemberPointer:
4817 ++NumPointersRemaining;
4818 break;
4820 case DeclaratorChunk::Paren:
4821 case DeclaratorChunk::Reference:
4822 continue;
4824 case DeclaratorChunk::Pointer:
4825 ++NumPointersRemaining;
4826 continue;
4829 } else {
4830 bool isFunctionOrMethod = false;
4831 switch (auto context = state.getDeclarator().getContext()) {
4832 case DeclaratorContext::ObjCParameter:
4833 case DeclaratorContext::ObjCResult:
4834 case DeclaratorContext::Prototype:
4835 case DeclaratorContext::TrailingReturn:
4836 case DeclaratorContext::TrailingReturnVar:
4837 isFunctionOrMethod = true;
4838 [[fallthrough]];
4840 case DeclaratorContext::Member:
4841 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4842 complainAboutMissingNullability = CAMN_No;
4843 break;
4846 // Weak properties are inferred to be nullable.
4847 if (state.getDeclarator().isObjCWeakProperty()) {
4848 // Weak properties cannot be nonnull, and should not complain about
4849 // missing nullable attributes during completeness checks.
4850 complainAboutMissingNullability = CAMN_No;
4851 if (inAssumeNonNullRegion) {
4852 inferNullability = NullabilityKind::Nullable;
4854 break;
4857 [[fallthrough]];
4859 case DeclaratorContext::File:
4860 case DeclaratorContext::KNRTypeList: {
4861 complainAboutMissingNullability = CAMN_Yes;
4863 // Nullability inference depends on the type and declarator.
4864 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4865 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4866 case PointerDeclaratorKind::NonPointer:
4867 case PointerDeclaratorKind::MultiLevelPointer:
4868 // Cannot infer nullability.
4869 break;
4871 case PointerDeclaratorKind::SingleLevelPointer:
4872 // Infer _Nonnull if we are in an assumes-nonnull region.
4873 if (inAssumeNonNullRegion) {
4874 complainAboutInferringWithinChunk = wrappingKind;
4875 inferNullability = NullabilityKind::NonNull;
4876 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4877 context == DeclaratorContext::ObjCResult);
4879 break;
4881 case PointerDeclaratorKind::CFErrorRefPointer:
4882 case PointerDeclaratorKind::NSErrorPointerPointer:
4883 // Within a function or method signature, infer _Nullable at both
4884 // levels.
4885 if (isFunctionOrMethod && inAssumeNonNullRegion)
4886 inferNullability = NullabilityKind::Nullable;
4887 break;
4889 case PointerDeclaratorKind::MaybePointerToCFRef:
4890 if (isFunctionOrMethod) {
4891 // On pointer-to-pointer parameters marked cf_returns_retained or
4892 // cf_returns_not_retained, if the outer pointer is explicit then
4893 // infer the inner pointer as _Nullable.
4894 auto hasCFReturnsAttr =
4895 [](const ParsedAttributesView &AttrList) -> bool {
4896 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4897 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4899 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4900 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4901 hasCFReturnsAttr(D.getAttributes()) ||
4902 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4903 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4904 inferNullability = NullabilityKind::Nullable;
4905 inferNullabilityInnerOnly = true;
4909 break;
4911 break;
4914 case DeclaratorContext::ConversionId:
4915 complainAboutMissingNullability = CAMN_Yes;
4916 break;
4918 case DeclaratorContext::AliasDecl:
4919 case DeclaratorContext::AliasTemplate:
4920 case DeclaratorContext::Block:
4921 case DeclaratorContext::BlockLiteral:
4922 case DeclaratorContext::Condition:
4923 case DeclaratorContext::CXXCatch:
4924 case DeclaratorContext::CXXNew:
4925 case DeclaratorContext::ForInit:
4926 case DeclaratorContext::SelectionInit:
4927 case DeclaratorContext::LambdaExpr:
4928 case DeclaratorContext::LambdaExprParameter:
4929 case DeclaratorContext::ObjCCatch:
4930 case DeclaratorContext::TemplateParam:
4931 case DeclaratorContext::TemplateArg:
4932 case DeclaratorContext::TemplateTypeArg:
4933 case DeclaratorContext::TypeName:
4934 case DeclaratorContext::FunctionalCast:
4935 case DeclaratorContext::RequiresExpr:
4936 case DeclaratorContext::Association:
4937 // Don't infer in these contexts.
4938 break;
4942 // Local function that returns true if its argument looks like a va_list.
4943 auto isVaList = [&S](QualType T) -> bool {
4944 auto *typedefTy = T->getAs<TypedefType>();
4945 if (!typedefTy)
4946 return false;
4947 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4948 do {
4949 if (typedefTy->getDecl() == vaListTypedef)
4950 return true;
4951 if (auto *name = typedefTy->getDecl()->getIdentifier())
4952 if (name->isStr("va_list"))
4953 return true;
4954 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4955 } while (typedefTy);
4956 return false;
4959 // Local function that checks the nullability for a given pointer declarator.
4960 // Returns true if _Nonnull was inferred.
4961 auto inferPointerNullability =
4962 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4963 SourceLocation pointerEndLoc,
4964 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4965 // We've seen a pointer.
4966 if (NumPointersRemaining > 0)
4967 --NumPointersRemaining;
4969 // If a nullability attribute is present, there's nothing to do.
4970 if (hasNullabilityAttr(attrs))
4971 return nullptr;
4973 // If we're supposed to infer nullability, do so now.
4974 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4975 ParsedAttr::Form form =
4976 inferNullabilityCS
4977 ? ParsedAttr::Form::ContextSensitiveKeyword()
4978 : ParsedAttr::Form::Keyword(false /*IsAlignAs*/,
4979 false /*IsRegularKeywordAttribute*/);
4980 ParsedAttr *nullabilityAttr = Pool.create(
4981 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4982 nullptr, SourceLocation(), nullptr, 0, form);
4984 attrs.addAtEnd(nullabilityAttr);
4986 if (inferNullabilityCS) {
4987 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4988 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4991 if (pointerLoc.isValid() &&
4992 complainAboutInferringWithinChunk !=
4993 PointerWrappingDeclaratorKind::None) {
4994 auto Diag =
4995 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4996 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4997 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
5000 if (inferNullabilityInnerOnly)
5001 inferNullabilityInnerOnlyComplete = true;
5002 return nullabilityAttr;
5005 // If we're supposed to complain about missing nullability, do so
5006 // now if it's truly missing.
5007 switch (complainAboutMissingNullability) {
5008 case CAMN_No:
5009 break;
5011 case CAMN_InnerPointers:
5012 if (NumPointersRemaining == 0)
5013 break;
5014 [[fallthrough]];
5016 case CAMN_Yes:
5017 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
5019 return nullptr;
5022 // If the type itself could have nullability but does not, infer pointer
5023 // nullability and perform consistency checking.
5024 if (S.CodeSynthesisContexts.empty()) {
5025 if (T->canHaveNullability(/*ResultIfUnknown*/ false) &&
5026 !T->getNullability()) {
5027 if (isVaList(T)) {
5028 // Record that we've seen a pointer, but do nothing else.
5029 if (NumPointersRemaining > 0)
5030 --NumPointersRemaining;
5031 } else {
5032 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
5033 if (T->isBlockPointerType())
5034 pointerKind = SimplePointerKind::BlockPointer;
5035 else if (T->isMemberPointerType())
5036 pointerKind = SimplePointerKind::MemberPointer;
5038 if (auto *attr = inferPointerNullability(
5039 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
5040 D.getDeclSpec().getEndLoc(),
5041 D.getMutableDeclSpec().getAttributes(),
5042 D.getMutableDeclSpec().getAttributePool())) {
5043 T = state.getAttributedType(
5044 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
5049 if (complainAboutMissingNullability == CAMN_Yes && T->isArrayType() &&
5050 !T->getNullability() && !isVaList(T) && D.isPrototypeContext() &&
5051 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
5052 checkNullabilityConsistency(S, SimplePointerKind::Array,
5053 D.getDeclSpec().getTypeSpecTypeLoc());
5057 bool ExpectNoDerefChunk =
5058 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
5060 // Walk the DeclTypeInfo, building the recursive type as we go.
5061 // DeclTypeInfos are ordered from the identifier out, which is
5062 // opposite of what we want :).
5064 // Track if the produced type matches the structure of the declarator.
5065 // This is used later to decide if we can fill `TypeLoc` from
5066 // `DeclaratorChunk`s. E.g. it must be false if Clang recovers from
5067 // an error by replacing the type with `int`.
5068 bool AreDeclaratorChunksValid = true;
5069 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5070 unsigned chunkIndex = e - i - 1;
5071 state.setCurrentChunkIndex(chunkIndex);
5072 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
5073 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
5074 switch (DeclType.Kind) {
5075 case DeclaratorChunk::Paren:
5076 if (i == 0)
5077 warnAboutRedundantParens(S, D, T);
5078 T = S.BuildParenType(T);
5079 break;
5080 case DeclaratorChunk::BlockPointer:
5081 // If blocks are disabled, emit an error.
5082 if (!LangOpts.Blocks)
5083 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
5085 // Handle pointer nullability.
5086 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
5087 DeclType.EndLoc, DeclType.getAttrs(),
5088 state.getDeclarator().getAttributePool());
5090 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
5091 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
5092 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
5093 // qualified with const.
5094 if (LangOpts.OpenCL)
5095 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
5096 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
5098 break;
5099 case DeclaratorChunk::Pointer:
5100 // Verify that we're not building a pointer to pointer to function with
5101 // exception specification.
5102 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5103 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5104 D.setInvalidType(true);
5105 // Build the type anyway.
5108 // Handle pointer nullability
5109 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
5110 DeclType.EndLoc, DeclType.getAttrs(),
5111 state.getDeclarator().getAttributePool());
5113 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
5114 T = Context.getObjCObjectPointerType(T);
5115 if (DeclType.Ptr.TypeQuals)
5116 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5117 break;
5120 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
5121 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
5122 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
5123 if (LangOpts.OpenCL) {
5124 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
5125 T->isBlockPointerType()) {
5126 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
5127 D.setInvalidType(true);
5131 T = S.BuildPointerType(T, DeclType.Loc, Name);
5132 if (DeclType.Ptr.TypeQuals)
5133 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
5134 break;
5135 case DeclaratorChunk::Reference: {
5136 // Verify that we're not building a reference to pointer to function with
5137 // exception specification.
5138 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5139 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5140 D.setInvalidType(true);
5141 // Build the type anyway.
5143 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5145 if (DeclType.Ref.HasRestrict)
5146 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5147 break;
5149 case DeclaratorChunk::Array: {
5150 // Verify that we're not building an array of pointers to function with
5151 // exception specification.
5152 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5153 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5154 D.setInvalidType(true);
5155 // Build the type anyway.
5157 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5158 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5159 ArraySizeModifier ASM;
5161 // Microsoft property fields can have multiple sizeless array chunks
5162 // (i.e. int x[][][]). Skip all of these except one to avoid creating
5163 // bad incomplete array types.
5164 if (chunkIndex != 0 && !ArraySize &&
5165 D.getDeclSpec().getAttributes().hasMSPropertyAttr()) {
5166 // This is a sizeless chunk. If the next is also, skip this one.
5167 DeclaratorChunk &NextDeclType = D.getTypeObject(chunkIndex - 1);
5168 if (NextDeclType.Kind == DeclaratorChunk::Array &&
5169 !NextDeclType.Arr.NumElts)
5170 break;
5173 if (ATI.isStar)
5174 ASM = ArraySizeModifier::Star;
5175 else if (ATI.hasStatic)
5176 ASM = ArraySizeModifier::Static;
5177 else
5178 ASM = ArraySizeModifier::Normal;
5179 if (ASM == ArraySizeModifier::Star && !D.isPrototypeContext()) {
5180 // FIXME: This check isn't quite right: it allows star in prototypes
5181 // for function definitions, and disallows some edge cases detailed
5182 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5183 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5184 ASM = ArraySizeModifier::Normal;
5185 D.setInvalidType(true);
5188 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5189 // shall appear only in a declaration of a function parameter with an
5190 // array type, ...
5191 if (ASM == ArraySizeModifier::Static || ATI.TypeQuals) {
5192 if (!(D.isPrototypeContext() ||
5193 D.getContext() == DeclaratorContext::KNRTypeList)) {
5194 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype)
5195 << (ASM == ArraySizeModifier::Static ? "'static'"
5196 : "type qualifier");
5197 // Remove the 'static' and the type qualifiers.
5198 if (ASM == ArraySizeModifier::Static)
5199 ASM = ArraySizeModifier::Normal;
5200 ATI.TypeQuals = 0;
5201 D.setInvalidType(true);
5204 // C99 6.7.5.2p1: ... and then only in the outermost array type
5205 // derivation.
5206 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5207 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost)
5208 << (ASM == ArraySizeModifier::Static ? "'static'"
5209 : "type qualifier");
5210 if (ASM == ArraySizeModifier::Static)
5211 ASM = ArraySizeModifier::Normal;
5212 ATI.TypeQuals = 0;
5213 D.setInvalidType(true);
5217 // Array parameters can be marked nullable as well, although it's not
5218 // necessary if they're marked 'static'.
5219 if (complainAboutMissingNullability == CAMN_Yes &&
5220 !hasNullabilityAttr(DeclType.getAttrs()) &&
5221 ASM != ArraySizeModifier::Static && D.isPrototypeContext() &&
5222 !hasOuterPointerLikeChunk(D, chunkIndex)) {
5223 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5226 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5227 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5228 break;
5230 case DeclaratorChunk::Function: {
5231 // If the function declarator has a prototype (i.e. it is not () and
5232 // does not have a K&R-style identifier list), then the arguments are part
5233 // of the type, otherwise the argument list is ().
5234 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5235 IsQualifiedFunction =
5236 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5238 // Check for auto functions and trailing return type and adjust the
5239 // return type accordingly.
5240 if (!D.isInvalidType()) {
5241 // trailing-return-type is only required if we're declaring a function,
5242 // and not, for instance, a pointer to a function.
5243 if (D.getDeclSpec().hasAutoTypeSpec() &&
5244 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5245 if (!S.getLangOpts().CPlusPlus14) {
5246 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5247 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5248 ? diag::err_auto_missing_trailing_return
5249 : diag::err_deduced_return_type);
5250 T = Context.IntTy;
5251 D.setInvalidType(true);
5252 AreDeclaratorChunksValid = false;
5253 } else {
5254 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5255 diag::warn_cxx11_compat_deduced_return_type);
5257 } else if (FTI.hasTrailingReturnType()) {
5258 // T must be exactly 'auto' at this point. See CWG issue 681.
5259 if (isa<ParenType>(T)) {
5260 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5261 << T << D.getSourceRange();
5262 D.setInvalidType(true);
5263 // FIXME: recover and fill decls in `TypeLoc`s.
5264 AreDeclaratorChunksValid = false;
5265 } else if (D.getName().getKind() ==
5266 UnqualifiedIdKind::IK_DeductionGuideName) {
5267 if (T != Context.DependentTy) {
5268 S.Diag(D.getDeclSpec().getBeginLoc(),
5269 diag::err_deduction_guide_with_complex_decl)
5270 << D.getSourceRange();
5271 D.setInvalidType(true);
5272 // FIXME: recover and fill decls in `TypeLoc`s.
5273 AreDeclaratorChunksValid = false;
5275 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5276 (T.hasQualifiers() || !isa<AutoType>(T) ||
5277 cast<AutoType>(T)->getKeyword() !=
5278 AutoTypeKeyword::Auto ||
5279 cast<AutoType>(T)->isConstrained())) {
5280 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5281 diag::err_trailing_return_without_auto)
5282 << T << D.getDeclSpec().getSourceRange();
5283 D.setInvalidType(true);
5284 // FIXME: recover and fill decls in `TypeLoc`s.
5285 AreDeclaratorChunksValid = false;
5287 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5288 if (T.isNull()) {
5289 // An error occurred parsing the trailing return type.
5290 T = Context.IntTy;
5291 D.setInvalidType(true);
5292 } else if (AutoType *Auto = T->getContainedAutoType()) {
5293 // If the trailing return type contains an `auto`, we may need to
5294 // invent a template parameter for it, for cases like
5295 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5296 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5297 if (D.getContext() == DeclaratorContext::Prototype)
5298 InventedParamInfo = &S.InventedParameterInfos.back();
5299 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5300 InventedParamInfo = S.getCurLambda();
5301 if (InventedParamInfo) {
5302 std::tie(T, TInfo) = InventTemplateParameter(
5303 state, T, TInfo, Auto, *InventedParamInfo);
5306 } else {
5307 // This function type is not the type of the entity being declared,
5308 // so checking the 'auto' is not the responsibility of this chunk.
5312 // C99 6.7.5.3p1: The return type may not be a function or array type.
5313 // For conversion functions, we'll diagnose this particular error later.
5314 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5315 (D.getName().getKind() !=
5316 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5317 unsigned diagID = diag::err_func_returning_array_function;
5318 // Last processing chunk in block context means this function chunk
5319 // represents the block.
5320 if (chunkIndex == 0 &&
5321 D.getContext() == DeclaratorContext::BlockLiteral)
5322 diagID = diag::err_block_returning_array_function;
5323 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5324 T = Context.IntTy;
5325 D.setInvalidType(true);
5326 AreDeclaratorChunksValid = false;
5329 // Do not allow returning half FP value.
5330 // FIXME: This really should be in BuildFunctionType.
5331 if (T->isHalfType()) {
5332 if (S.getLangOpts().OpenCL) {
5333 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5334 S.getLangOpts())) {
5335 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5336 << T << 0 /*pointer hint*/;
5337 D.setInvalidType(true);
5339 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5340 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5341 S.Diag(D.getIdentifierLoc(),
5342 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5343 D.setInvalidType(true);
5347 if (LangOpts.OpenCL) {
5348 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5349 // function.
5350 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5351 T->isPipeType()) {
5352 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5353 << T << 1 /*hint off*/;
5354 D.setInvalidType(true);
5356 // OpenCL doesn't support variadic functions and blocks
5357 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5358 // We also allow here any toolchain reserved identifiers.
5359 if (FTI.isVariadic &&
5360 !S.getOpenCLOptions().isAvailableOption(
5361 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5362 !(D.getIdentifier() &&
5363 ((D.getIdentifier()->getName() == "printf" &&
5364 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5365 D.getIdentifier()->getName().startswith("__")))) {
5366 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5367 D.setInvalidType(true);
5371 // Methods cannot return interface types. All ObjC objects are
5372 // passed by reference.
5373 if (T->isObjCObjectType()) {
5374 SourceLocation DiagLoc, FixitLoc;
5375 if (TInfo) {
5376 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5377 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5378 } else {
5379 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5380 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5382 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5383 << 0 << T
5384 << FixItHint::CreateInsertion(FixitLoc, "*");
5386 T = Context.getObjCObjectPointerType(T);
5387 if (TInfo) {
5388 TypeLocBuilder TLB;
5389 TLB.pushFullCopy(TInfo->getTypeLoc());
5390 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5391 TLoc.setStarLoc(FixitLoc);
5392 TInfo = TLB.getTypeSourceInfo(Context, T);
5393 } else {
5394 AreDeclaratorChunksValid = false;
5397 D.setInvalidType(true);
5400 // cv-qualifiers on return types are pointless except when the type is a
5401 // class type in C++.
5402 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5403 !(S.getLangOpts().CPlusPlus &&
5404 (T->isDependentType() || T->isRecordType()))) {
5405 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5406 D.getFunctionDefinitionKind() ==
5407 FunctionDefinitionKind::Definition) {
5408 // [6.9.1/3] qualified void return is invalid on a C
5409 // function definition. Apparently ok on declarations and
5410 // in C++ though (!)
5411 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5412 } else
5413 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5415 // C++2a [dcl.fct]p12:
5416 // A volatile-qualified return type is deprecated
5417 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5418 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5421 // Objective-C ARC ownership qualifiers are ignored on the function
5422 // return type (by type canonicalization). Complain if this attribute
5423 // was written here.
5424 if (T.getQualifiers().hasObjCLifetime()) {
5425 SourceLocation AttrLoc;
5426 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5427 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5428 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5429 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5430 AttrLoc = AL.getLoc();
5431 break;
5435 if (AttrLoc.isInvalid()) {
5436 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5437 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5438 AttrLoc = AL.getLoc();
5439 break;
5444 if (AttrLoc.isValid()) {
5445 // The ownership attributes are almost always written via
5446 // the predefined
5447 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5448 if (AttrLoc.isMacroID())
5449 AttrLoc =
5450 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5452 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5453 << T.getQualifiers().getObjCLifetime();
5457 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5458 // C++ [dcl.fct]p6:
5459 // Types shall not be defined in return or parameter types.
5460 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5461 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5462 << Context.getTypeDeclType(Tag);
5465 // Exception specs are not allowed in typedefs. Complain, but add it
5466 // anyway.
5467 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5468 S.Diag(FTI.getExceptionSpecLocBeg(),
5469 diag::err_exception_spec_in_typedef)
5470 << (D.getContext() == DeclaratorContext::AliasDecl ||
5471 D.getContext() == DeclaratorContext::AliasTemplate);
5473 // If we see "T var();" or "T var(T());" at block scope, it is probably
5474 // an attempt to initialize a variable, not a function declaration.
5475 if (FTI.isAmbiguous)
5476 warnAboutAmbiguousFunction(S, D, DeclType, T);
5478 FunctionType::ExtInfo EI(
5479 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5481 // OpenCL disallows functions without a prototype, but it doesn't enforce
5482 // strict prototypes as in C23 because it allows a function definition to
5483 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5484 if (!FTI.NumParams && !FTI.isVariadic &&
5485 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5486 // Simple void foo(), where the incoming T is the result type.
5487 T = Context.getFunctionNoProtoType(T, EI);
5488 } else {
5489 // We allow a zero-parameter variadic function in C if the
5490 // function is marked with the "overloadable" attribute. Scan
5491 // for this attribute now. We also allow it in C23 per WG14 N2975.
5492 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
5493 if (LangOpts.C23)
5494 S.Diag(FTI.getEllipsisLoc(),
5495 diag::warn_c17_compat_ellipsis_only_parameter);
5496 else if (!D.getDeclarationAttributes().hasAttribute(
5497 ParsedAttr::AT_Overloadable) &&
5498 !D.getAttributes().hasAttribute(
5499 ParsedAttr::AT_Overloadable) &&
5500 !D.getDeclSpec().getAttributes().hasAttribute(
5501 ParsedAttr::AT_Overloadable))
5502 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5505 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5506 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5507 // definition.
5508 S.Diag(FTI.Params[0].IdentLoc,
5509 diag::err_ident_list_in_fn_declaration);
5510 D.setInvalidType(true);
5511 // Recover by creating a K&R-style function type, if possible.
5512 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5513 ? Context.getFunctionNoProtoType(T, EI)
5514 : Context.IntTy;
5515 AreDeclaratorChunksValid = false;
5516 break;
5519 FunctionProtoType::ExtProtoInfo EPI;
5520 EPI.ExtInfo = EI;
5521 EPI.Variadic = FTI.isVariadic;
5522 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5523 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5524 EPI.TypeQuals.addCVRUQualifiers(
5525 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5526 : 0);
5527 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5528 : FTI.RefQualifierIsLValueRef? RQ_LValue
5529 : RQ_RValue;
5531 // Otherwise, we have a function with a parameter list that is
5532 // potentially variadic.
5533 SmallVector<QualType, 16> ParamTys;
5534 ParamTys.reserve(FTI.NumParams);
5536 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5537 ExtParameterInfos(FTI.NumParams);
5538 bool HasAnyInterestingExtParameterInfos = false;
5540 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5541 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5542 QualType ParamTy = Param->getType();
5543 assert(!ParamTy.isNull() && "Couldn't parse type?");
5545 // Look for 'void'. void is allowed only as a single parameter to a
5546 // function with no other parameters (C99 6.7.5.3p10). We record
5547 // int(void) as a FunctionProtoType with an empty parameter list.
5548 if (ParamTy->isVoidType()) {
5549 // If this is something like 'float(int, void)', reject it. 'void'
5550 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5551 // have parameters of incomplete type.
5552 if (FTI.NumParams != 1 || FTI.isVariadic) {
5553 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5554 ParamTy = Context.IntTy;
5555 Param->setType(ParamTy);
5556 } else if (FTI.Params[i].Ident) {
5557 // Reject, but continue to parse 'int(void abc)'.
5558 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5559 ParamTy = Context.IntTy;
5560 Param->setType(ParamTy);
5561 } else {
5562 // Reject, but continue to parse 'float(const void)'.
5563 if (ParamTy.hasQualifiers())
5564 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5566 // Do not add 'void' to the list.
5567 break;
5569 } else if (ParamTy->isHalfType()) {
5570 // Disallow half FP parameters.
5571 // FIXME: This really should be in BuildFunctionType.
5572 if (S.getLangOpts().OpenCL) {
5573 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5574 S.getLangOpts())) {
5575 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5576 << ParamTy << 0;
5577 D.setInvalidType();
5578 Param->setInvalidDecl();
5580 } else if (!S.getLangOpts().NativeHalfArgsAndReturns &&
5581 !S.Context.getTargetInfo().allowHalfArgsAndReturns()) {
5582 S.Diag(Param->getLocation(),
5583 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5584 D.setInvalidType();
5586 } else if (!FTI.hasPrototype) {
5587 if (Context.isPromotableIntegerType(ParamTy)) {
5588 ParamTy = Context.getPromotedIntegerType(ParamTy);
5589 Param->setKNRPromoted(true);
5590 } else if (const BuiltinType *BTy = ParamTy->getAs<BuiltinType>()) {
5591 if (BTy->getKind() == BuiltinType::Float) {
5592 ParamTy = Context.DoubleTy;
5593 Param->setKNRPromoted(true);
5596 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5597 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5598 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5599 << ParamTy << 1 /*hint off*/;
5600 D.setInvalidType();
5603 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5604 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5605 HasAnyInterestingExtParameterInfos = true;
5608 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5609 ExtParameterInfos[i] =
5610 ExtParameterInfos[i].withABI(attr->getABI());
5611 HasAnyInterestingExtParameterInfos = true;
5614 if (Param->hasAttr<PassObjectSizeAttr>()) {
5615 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5616 HasAnyInterestingExtParameterInfos = true;
5619 if (Param->hasAttr<NoEscapeAttr>()) {
5620 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5621 HasAnyInterestingExtParameterInfos = true;
5624 ParamTys.push_back(ParamTy);
5627 if (HasAnyInterestingExtParameterInfos) {
5628 EPI.ExtParameterInfos = ExtParameterInfos.data();
5629 checkExtParameterInfos(S, ParamTys, EPI,
5630 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5633 SmallVector<QualType, 4> Exceptions;
5634 SmallVector<ParsedType, 2> DynamicExceptions;
5635 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5636 Expr *NoexceptExpr = nullptr;
5638 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5639 // FIXME: It's rather inefficient to have to split into two vectors
5640 // here.
5641 unsigned N = FTI.getNumExceptions();
5642 DynamicExceptions.reserve(N);
5643 DynamicExceptionRanges.reserve(N);
5644 for (unsigned I = 0; I != N; ++I) {
5645 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5646 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5648 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5649 NoexceptExpr = FTI.NoexceptExpr;
5652 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5653 FTI.getExceptionSpecType(),
5654 DynamicExceptions,
5655 DynamicExceptionRanges,
5656 NoexceptExpr,
5657 Exceptions,
5658 EPI.ExceptionSpec);
5660 // FIXME: Set address space from attrs for C++ mode here.
5661 // OpenCLCPlusPlus: A class member function has an address space.
5662 auto IsClassMember = [&]() {
5663 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5664 state.getDeclarator()
5665 .getCXXScopeSpec()
5666 .getScopeRep()
5667 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5668 state.getDeclarator().getContext() ==
5669 DeclaratorContext::Member ||
5670 state.getDeclarator().getContext() ==
5671 DeclaratorContext::LambdaExpr;
5674 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5675 LangAS ASIdx = LangAS::Default;
5676 // Take address space attr if any and mark as invalid to avoid adding
5677 // them later while creating QualType.
5678 if (FTI.MethodQualifiers)
5679 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5680 LangAS ASIdxNew = attr.asOpenCLLangAS();
5681 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5682 attr.getLoc()))
5683 D.setInvalidType(true);
5684 else
5685 ASIdx = ASIdxNew;
5687 // If a class member function's address space is not set, set it to
5688 // __generic.
5689 LangAS AS =
5690 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5691 : ASIdx);
5692 EPI.TypeQuals.addAddressSpace(AS);
5694 T = Context.getFunctionType(T, ParamTys, EPI);
5696 break;
5698 case DeclaratorChunk::MemberPointer: {
5699 // The scope spec must refer to a class, or be dependent.
5700 CXXScopeSpec &SS = DeclType.Mem.Scope();
5701 QualType ClsType;
5703 // Handle pointer nullability.
5704 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5705 DeclType.EndLoc, DeclType.getAttrs(),
5706 state.getDeclarator().getAttributePool());
5708 if (SS.isInvalid()) {
5709 // Avoid emitting extra errors if we already errored on the scope.
5710 D.setInvalidType(true);
5711 } else if (S.isDependentScopeSpecifier(SS) ||
5712 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5713 NestedNameSpecifier *NNS = SS.getScopeRep();
5714 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5715 switch (NNS->getKind()) {
5716 case NestedNameSpecifier::Identifier:
5717 ClsType = Context.getDependentNameType(
5718 ElaboratedTypeKeyword::None, NNSPrefix, NNS->getAsIdentifier());
5719 break;
5721 case NestedNameSpecifier::Namespace:
5722 case NestedNameSpecifier::NamespaceAlias:
5723 case NestedNameSpecifier::Global:
5724 case NestedNameSpecifier::Super:
5725 llvm_unreachable("Nested-name-specifier must name a type");
5727 case NestedNameSpecifier::TypeSpec:
5728 case NestedNameSpecifier::TypeSpecWithTemplate:
5729 ClsType = QualType(NNS->getAsType(), 0);
5730 // Note: if the NNS has a prefix and ClsType is a nondependent
5731 // TemplateSpecializationType, then the NNS prefix is NOT included
5732 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5733 // NOTE: in particular, no wrap occurs if ClsType already is an
5734 // Elaborated, DependentName, or DependentTemplateSpecialization.
5735 if (isa<TemplateSpecializationType>(NNS->getAsType()))
5736 ClsType = Context.getElaboratedType(ElaboratedTypeKeyword::None,
5737 NNSPrefix, ClsType);
5738 break;
5740 } else {
5741 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5742 diag::err_illegal_decl_mempointer_in_nonclass)
5743 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5744 << DeclType.Mem.Scope().getRange();
5745 D.setInvalidType(true);
5748 if (!ClsType.isNull())
5749 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5750 D.getIdentifier());
5751 else
5752 AreDeclaratorChunksValid = false;
5754 if (T.isNull()) {
5755 T = Context.IntTy;
5756 D.setInvalidType(true);
5757 AreDeclaratorChunksValid = false;
5758 } else if (DeclType.Mem.TypeQuals) {
5759 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5761 break;
5764 case DeclaratorChunk::Pipe: {
5765 T = S.BuildReadPipeType(T, DeclType.Loc);
5766 processTypeAttrs(state, T, TAL_DeclSpec,
5767 D.getMutableDeclSpec().getAttributes());
5768 break;
5772 if (T.isNull()) {
5773 D.setInvalidType(true);
5774 T = Context.IntTy;
5775 AreDeclaratorChunksValid = false;
5778 // See if there are any attributes on this declarator chunk.
5779 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs(),
5780 S.IdentifyCUDATarget(D.getAttributes()));
5782 if (DeclType.Kind != DeclaratorChunk::Paren) {
5783 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5784 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5786 ExpectNoDerefChunk = state.didParseNoDeref();
5790 if (ExpectNoDerefChunk)
5791 S.Diag(state.getDeclarator().getBeginLoc(),
5792 diag::warn_noderef_on_non_pointer_or_array);
5794 // GNU warning -Wstrict-prototypes
5795 // Warn if a function declaration or definition is without a prototype.
5796 // This warning is issued for all kinds of unprototyped function
5797 // declarations (i.e. function type typedef, function pointer etc.)
5798 // C99 6.7.5.3p14:
5799 // The empty list in a function declarator that is not part of a definition
5800 // of that function specifies that no information about the number or types
5801 // of the parameters is supplied.
5802 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5803 // function declarations whose behavior changes in C23.
5804 if (!LangOpts.requiresStrictPrototypes()) {
5805 bool IsBlock = false;
5806 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5807 switch (DeclType.Kind) {
5808 case DeclaratorChunk::BlockPointer:
5809 IsBlock = true;
5810 break;
5811 case DeclaratorChunk::Function: {
5812 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5813 // We suppress the warning when there's no LParen location, as this
5814 // indicates the declaration was an implicit declaration, which gets
5815 // warned about separately via -Wimplicit-function-declaration. We also
5816 // suppress the warning when we know the function has a prototype.
5817 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5818 FTI.getLParenLoc().isValid())
5819 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5820 << IsBlock
5821 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5822 IsBlock = false;
5823 break;
5825 default:
5826 break;
5831 assert(!T.isNull() && "T must not be null after this point");
5833 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5834 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5835 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5837 // C++ 8.3.5p4:
5838 // A cv-qualifier-seq shall only be part of the function type
5839 // for a nonstatic member function, the function type to which a pointer
5840 // to member refers, or the top-level function type of a function typedef
5841 // declaration.
5843 // Core issue 547 also allows cv-qualifiers on function types that are
5844 // top-level template type arguments.
5845 enum {
5846 NonMember,
5847 Member,
5848 ExplicitObjectMember,
5849 DeductionGuide
5850 } Kind = NonMember;
5851 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5852 Kind = DeductionGuide;
5853 else if (!D.getCXXScopeSpec().isSet()) {
5854 if ((D.getContext() == DeclaratorContext::Member ||
5855 D.getContext() == DeclaratorContext::LambdaExpr) &&
5856 !D.getDeclSpec().isFriendSpecified())
5857 Kind = Member;
5858 } else {
5859 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5860 if (!DC || DC->isRecord())
5861 Kind = Member;
5864 if (Kind == Member) {
5865 unsigned I;
5866 if (D.isFunctionDeclarator(I)) {
5867 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5868 if (Chunk.Fun.NumParams) {
5869 auto *P = dyn_cast_or_null<ParmVarDecl>(Chunk.Fun.Params->Param);
5870 if (P && P->isExplicitObjectParameter())
5871 Kind = ExplicitObjectMember;
5876 // C++11 [dcl.fct]p6 (w/DR1417):
5877 // An attempt to specify a function type with a cv-qualifier-seq or a
5878 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5879 // - the function type for a non-static member function,
5880 // - the function type to which a pointer to member refers,
5881 // - the top-level function type of a function typedef declaration or
5882 // alias-declaration,
5883 // - the type-id in the default argument of a type-parameter, or
5884 // - the type-id of a template-argument for a type-parameter
5886 // FIXME: Checking this here is insufficient. We accept-invalid on:
5888 // template<typename T> struct S { void f(T); };
5889 // S<int() const> s;
5891 // ... for instance.
5892 if (IsQualifiedFunction &&
5893 !(Kind == Member && !D.isExplicitObjectMemberFunction() &&
5894 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5895 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5896 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5897 SourceLocation Loc = D.getBeginLoc();
5898 SourceRange RemovalRange;
5899 unsigned I;
5900 if (D.isFunctionDeclarator(I)) {
5901 SmallVector<SourceLocation, 4> RemovalLocs;
5902 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5903 assert(Chunk.Kind == DeclaratorChunk::Function);
5905 if (Chunk.Fun.hasRefQualifier())
5906 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5908 if (Chunk.Fun.hasMethodTypeQualifiers())
5909 Chunk.Fun.MethodQualifiers->forEachQualifier(
5910 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5911 SourceLocation SL) { RemovalLocs.push_back(SL); });
5913 if (!RemovalLocs.empty()) {
5914 llvm::sort(RemovalLocs,
5915 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5916 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5917 Loc = RemovalLocs.front();
5921 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5922 << Kind << D.isFunctionDeclarator() << T
5923 << getFunctionQualifiersAsString(FnTy)
5924 << FixItHint::CreateRemoval(RemovalRange);
5926 // Strip the cv-qualifiers and ref-qualifiers from the type.
5927 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5928 EPI.TypeQuals.removeCVRQualifiers();
5929 EPI.RefQualifier = RQ_None;
5931 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5932 EPI);
5933 // Rebuild any parens around the identifier in the function type.
5934 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5935 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5936 break;
5937 T = S.BuildParenType(T);
5942 // Apply any undistributed attributes from the declaration or declarator.
5943 ParsedAttributesView NonSlidingAttrs;
5944 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5945 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5946 NonSlidingAttrs.addAtEnd(&AL);
5949 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5950 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5952 // Diagnose any ignored type attributes.
5953 state.diagnoseIgnoredTypeAttrs(T);
5955 // C++0x [dcl.constexpr]p9:
5956 // A constexpr specifier used in an object declaration declares the object
5957 // as const.
5958 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5959 T->isObjectType())
5960 T.addConst();
5962 // C++2a [dcl.fct]p4:
5963 // A parameter with volatile-qualified type is deprecated
5964 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5965 (D.getContext() == DeclaratorContext::Prototype ||
5966 D.getContext() == DeclaratorContext::LambdaExprParameter))
5967 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5969 // If there was an ellipsis in the declarator, the declaration declares a
5970 // parameter pack whose type may be a pack expansion type.
5971 if (D.hasEllipsis()) {
5972 // C++0x [dcl.fct]p13:
5973 // A declarator-id or abstract-declarator containing an ellipsis shall
5974 // only be used in a parameter-declaration. Such a parameter-declaration
5975 // is a parameter pack (14.5.3). [...]
5976 switch (D.getContext()) {
5977 case DeclaratorContext::Prototype:
5978 case DeclaratorContext::LambdaExprParameter:
5979 case DeclaratorContext::RequiresExpr:
5980 // C++0x [dcl.fct]p13:
5981 // [...] When it is part of a parameter-declaration-clause, the
5982 // parameter pack is a function parameter pack (14.5.3). The type T
5983 // of the declarator-id of the function parameter pack shall contain
5984 // a template parameter pack; each template parameter pack in T is
5985 // expanded by the function parameter pack.
5987 // We represent function parameter packs as function parameters whose
5988 // type is a pack expansion.
5989 if (!T->containsUnexpandedParameterPack() &&
5990 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5991 S.Diag(D.getEllipsisLoc(),
5992 diag::err_function_parameter_pack_without_parameter_packs)
5993 << T << D.getSourceRange();
5994 D.setEllipsisLoc(SourceLocation());
5995 } else {
5996 T = Context.getPackExpansionType(T, std::nullopt,
5997 /*ExpectPackInType=*/false);
5999 break;
6000 case DeclaratorContext::TemplateParam:
6001 // C++0x [temp.param]p15:
6002 // If a template-parameter is a [...] is a parameter-declaration that
6003 // declares a parameter pack (8.3.5), then the template-parameter is a
6004 // template parameter pack (14.5.3).
6006 // Note: core issue 778 clarifies that, if there are any unexpanded
6007 // parameter packs in the type of the non-type template parameter, then
6008 // it expands those parameter packs.
6009 if (T->containsUnexpandedParameterPack())
6010 T = Context.getPackExpansionType(T, std::nullopt);
6011 else
6012 S.Diag(D.getEllipsisLoc(),
6013 LangOpts.CPlusPlus11
6014 ? diag::warn_cxx98_compat_variadic_templates
6015 : diag::ext_variadic_templates);
6016 break;
6018 case DeclaratorContext::File:
6019 case DeclaratorContext::KNRTypeList:
6020 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
6021 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
6022 case DeclaratorContext::TypeName:
6023 case DeclaratorContext::FunctionalCast:
6024 case DeclaratorContext::CXXNew:
6025 case DeclaratorContext::AliasDecl:
6026 case DeclaratorContext::AliasTemplate:
6027 case DeclaratorContext::Member:
6028 case DeclaratorContext::Block:
6029 case DeclaratorContext::ForInit:
6030 case DeclaratorContext::SelectionInit:
6031 case DeclaratorContext::Condition:
6032 case DeclaratorContext::CXXCatch:
6033 case DeclaratorContext::ObjCCatch:
6034 case DeclaratorContext::BlockLiteral:
6035 case DeclaratorContext::LambdaExpr:
6036 case DeclaratorContext::ConversionId:
6037 case DeclaratorContext::TrailingReturn:
6038 case DeclaratorContext::TrailingReturnVar:
6039 case DeclaratorContext::TemplateArg:
6040 case DeclaratorContext::TemplateTypeArg:
6041 case DeclaratorContext::Association:
6042 // FIXME: We may want to allow parameter packs in block-literal contexts
6043 // in the future.
6044 S.Diag(D.getEllipsisLoc(),
6045 diag::err_ellipsis_in_declarator_not_parameter);
6046 D.setEllipsisLoc(SourceLocation());
6047 break;
6051 assert(!T.isNull() && "T must not be null at the end of this function");
6052 if (!AreDeclaratorChunksValid)
6053 return Context.getTrivialTypeSourceInfo(T);
6054 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
6057 /// GetTypeForDeclarator - Convert the type for the specified
6058 /// declarator to Type instances.
6060 /// The result of this call will never be null, but the associated
6061 /// type may be a null type if there's an unrecoverable error.
6062 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
6063 // Determine the type of the declarator. Not all forms of declarator
6064 // have a type.
6066 TypeProcessingState state(*this, D);
6068 TypeSourceInfo *ReturnTypeInfo = nullptr;
6069 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6070 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
6071 inferARCWriteback(state, T);
6073 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
6076 static void transferARCOwnershipToDeclSpec(Sema &S,
6077 QualType &declSpecTy,
6078 Qualifiers::ObjCLifetime ownership) {
6079 if (declSpecTy->isObjCRetainableType() &&
6080 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
6081 Qualifiers qs;
6082 qs.addObjCLifetime(ownership);
6083 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
6087 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
6088 Qualifiers::ObjCLifetime ownership,
6089 unsigned chunkIndex) {
6090 Sema &S = state.getSema();
6091 Declarator &D = state.getDeclarator();
6093 // Look for an explicit lifetime attribute.
6094 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
6095 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
6096 return;
6098 const char *attrStr = nullptr;
6099 switch (ownership) {
6100 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
6101 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
6102 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
6103 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
6104 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
6107 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
6108 Arg->Ident = &S.Context.Idents.get(attrStr);
6109 Arg->Loc = SourceLocation();
6111 ArgsUnion Args(Arg);
6113 // If there wasn't one, add one (with an invalid source location
6114 // so that we don't make an AttributedType for it).
6115 ParsedAttr *attr = D.getAttributePool().create(
6116 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
6117 /*scope*/ nullptr, SourceLocation(),
6118 /*args*/ &Args, 1, ParsedAttr::Form::GNU());
6119 chunk.getAttrs().addAtEnd(attr);
6120 // TODO: mark whether we did this inference?
6123 /// Used for transferring ownership in casts resulting in l-values.
6124 static void transferARCOwnership(TypeProcessingState &state,
6125 QualType &declSpecTy,
6126 Qualifiers::ObjCLifetime ownership) {
6127 Sema &S = state.getSema();
6128 Declarator &D = state.getDeclarator();
6130 int inner = -1;
6131 bool hasIndirection = false;
6132 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6133 DeclaratorChunk &chunk = D.getTypeObject(i);
6134 switch (chunk.Kind) {
6135 case DeclaratorChunk::Paren:
6136 // Ignore parens.
6137 break;
6139 case DeclaratorChunk::Array:
6140 case DeclaratorChunk::Reference:
6141 case DeclaratorChunk::Pointer:
6142 if (inner != -1)
6143 hasIndirection = true;
6144 inner = i;
6145 break;
6147 case DeclaratorChunk::BlockPointer:
6148 if (inner != -1)
6149 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
6150 return;
6152 case DeclaratorChunk::Function:
6153 case DeclaratorChunk::MemberPointer:
6154 case DeclaratorChunk::Pipe:
6155 return;
6159 if (inner == -1)
6160 return;
6162 DeclaratorChunk &chunk = D.getTypeObject(inner);
6163 if (chunk.Kind == DeclaratorChunk::Pointer) {
6164 if (declSpecTy->isObjCRetainableType())
6165 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6166 if (declSpecTy->isObjCObjectType() && hasIndirection)
6167 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
6168 } else {
6169 assert(chunk.Kind == DeclaratorChunk::Array ||
6170 chunk.Kind == DeclaratorChunk::Reference);
6171 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
6175 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
6176 TypeProcessingState state(*this, D);
6178 TypeSourceInfo *ReturnTypeInfo = nullptr;
6179 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
6181 if (getLangOpts().ObjC) {
6182 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6183 if (ownership != Qualifiers::OCL_None)
6184 transferARCOwnership(state, declSpecTy, ownership);
6187 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6190 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6191 TypeProcessingState &State) {
6192 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6195 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6196 const ParsedAttributesView &Attrs) {
6197 for (const ParsedAttr &AL : Attrs) {
6198 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6199 MTL.setAttrNameLoc(AL.getLoc());
6200 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6201 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6202 MTL.setAttrOperandParensRange(SourceRange());
6203 return;
6207 llvm_unreachable("no matrix_type attribute found at the expected location!");
6210 namespace {
6211 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6212 Sema &SemaRef;
6213 ASTContext &Context;
6214 TypeProcessingState &State;
6215 const DeclSpec &DS;
6217 public:
6218 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6219 const DeclSpec &DS)
6220 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6222 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6223 Visit(TL.getModifiedLoc());
6224 fillAttributedTypeLoc(TL, State);
6226 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6227 Visit(TL.getWrappedLoc());
6229 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6230 Visit(TL.getInnerLoc());
6231 TL.setExpansionLoc(
6232 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6234 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6235 Visit(TL.getUnqualifiedLoc());
6237 // Allow to fill pointee's type locations, e.g.,
6238 // int __attr * __attr * __attr *p;
6239 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6240 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6241 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6243 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6244 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6245 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6246 // addition field. What we have is good enough for display of location
6247 // of 'fixit' on interface name.
6248 TL.setNameEndLoc(DS.getEndLoc());
6250 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6251 TypeSourceInfo *RepTInfo = nullptr;
6252 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6253 TL.copy(RepTInfo->getTypeLoc());
6255 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6256 TypeSourceInfo *RepTInfo = nullptr;
6257 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6258 TL.copy(RepTInfo->getTypeLoc());
6260 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6261 TypeSourceInfo *TInfo = nullptr;
6262 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6264 // If we got no declarator info from previous Sema routines,
6265 // just fill with the typespec loc.
6266 if (!TInfo) {
6267 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6268 return;
6271 TypeLoc OldTL = TInfo->getTypeLoc();
6272 if (TInfo->getType()->getAs<ElaboratedType>()) {
6273 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6274 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6275 .castAs<TemplateSpecializationTypeLoc>();
6276 TL.copy(NamedTL);
6277 } else {
6278 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6279 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6283 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6284 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr ||
6285 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualExpr);
6286 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6287 TL.setParensRange(DS.getTypeofParensRange());
6289 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6290 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType ||
6291 DS.getTypeSpecType() == DeclSpec::TST_typeof_unqualType);
6292 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6293 TL.setParensRange(DS.getTypeofParensRange());
6294 assert(DS.getRepAsType());
6295 TypeSourceInfo *TInfo = nullptr;
6296 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6297 TL.setUnmodifiedTInfo(TInfo);
6299 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6300 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6301 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6302 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6304 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6305 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6306 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6307 TL.setParensRange(DS.getTypeofParensRange());
6308 assert(DS.getRepAsType());
6309 TypeSourceInfo *TInfo = nullptr;
6310 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6311 TL.setUnderlyingTInfo(TInfo);
6313 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6314 // By default, use the source location of the type specifier.
6315 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6316 if (TL.needsExtraLocalData()) {
6317 // Set info for the written builtin specifiers.
6318 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6319 // Try to have a meaningful source location.
6320 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6321 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6322 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6323 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6326 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6327 if (DS.getTypeSpecType() == TST_typename) {
6328 TypeSourceInfo *TInfo = nullptr;
6329 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6330 if (TInfo)
6331 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6332 TL.copy(ETL);
6333 return;
6336 const ElaboratedType *T = TL.getTypePtr();
6337 TL.setElaboratedKeywordLoc(T->getKeyword() != ElaboratedTypeKeyword::None
6338 ? DS.getTypeSpecTypeLoc()
6339 : SourceLocation());
6340 const CXXScopeSpec& SS = DS.getTypeSpecScope();
6341 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6342 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6344 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6345 assert(DS.getTypeSpecType() == TST_typename);
6346 TypeSourceInfo *TInfo = nullptr;
6347 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6348 assert(TInfo);
6349 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6351 void VisitDependentTemplateSpecializationTypeLoc(
6352 DependentTemplateSpecializationTypeLoc TL) {
6353 assert(DS.getTypeSpecType() == TST_typename);
6354 TypeSourceInfo *TInfo = nullptr;
6355 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6356 assert(TInfo);
6357 TL.copy(
6358 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6360 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6361 assert(DS.getTypeSpecType() == TST_auto ||
6362 DS.getTypeSpecType() == TST_decltype_auto ||
6363 DS.getTypeSpecType() == TST_auto_type ||
6364 DS.getTypeSpecType() == TST_unspecified);
6365 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6366 if (DS.getTypeSpecType() == TST_decltype_auto)
6367 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6368 if (!DS.isConstrainedAuto())
6369 return;
6370 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6371 if (!TemplateId)
6372 return;
6374 NestedNameSpecifierLoc NNS =
6375 (DS.getTypeSpecScope().isNotEmpty()
6376 ? DS.getTypeSpecScope().getWithLocInContext(Context)
6377 : NestedNameSpecifierLoc());
6378 TemplateArgumentListInfo TemplateArgsInfo(TemplateId->LAngleLoc,
6379 TemplateId->RAngleLoc);
6380 if (TemplateId->NumArgs > 0) {
6381 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6382 TemplateId->NumArgs);
6383 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6385 DeclarationNameInfo DNI = DeclarationNameInfo(
6386 TL.getTypePtr()->getTypeConstraintConcept()->getDeclName(),
6387 TemplateId->TemplateNameLoc);
6388 auto *CR = ConceptReference::Create(
6389 Context, NNS, TemplateId->TemplateKWLoc, DNI,
6390 /*FoundDecl=*/nullptr,
6391 /*NamedDecl=*/TL.getTypePtr()->getTypeConstraintConcept(),
6392 ASTTemplateArgumentListInfo::Create(Context, TemplateArgsInfo));
6393 TL.setConceptReference(CR);
6395 void VisitTagTypeLoc(TagTypeLoc TL) {
6396 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6398 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6399 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6400 // or an _Atomic qualifier.
6401 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6402 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6403 TL.setParensRange(DS.getTypeofParensRange());
6405 TypeSourceInfo *TInfo = nullptr;
6406 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6407 assert(TInfo);
6408 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6409 } else {
6410 TL.setKWLoc(DS.getAtomicSpecLoc());
6411 // No parens, to indicate this was spelled as an _Atomic qualifier.
6412 TL.setParensRange(SourceRange());
6413 Visit(TL.getValueLoc());
6417 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6418 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6420 TypeSourceInfo *TInfo = nullptr;
6421 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6422 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6425 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6426 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6429 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6430 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6433 void VisitTypeLoc(TypeLoc TL) {
6434 // FIXME: add other typespec types and change this to an assert.
6435 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6439 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6440 ASTContext &Context;
6441 TypeProcessingState &State;
6442 const DeclaratorChunk &Chunk;
6444 public:
6445 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6446 const DeclaratorChunk &Chunk)
6447 : Context(Context), State(State), Chunk(Chunk) {}
6449 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6450 llvm_unreachable("qualified type locs not expected here!");
6452 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6453 llvm_unreachable("decayed type locs not expected here!");
6456 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6457 fillAttributedTypeLoc(TL, State);
6459 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6460 // nothing
6462 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6463 // nothing
6465 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6466 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6467 TL.setCaretLoc(Chunk.Loc);
6469 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6470 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6471 TL.setStarLoc(Chunk.Loc);
6473 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6474 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6475 TL.setStarLoc(Chunk.Loc);
6477 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6478 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6479 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6480 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6482 const Type* ClsTy = TL.getClass();
6483 QualType ClsQT = QualType(ClsTy, 0);
6484 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6485 // Now copy source location info into the type loc component.
6486 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6487 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6488 case NestedNameSpecifier::Identifier:
6489 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6491 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6492 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6493 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6494 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6496 break;
6498 case NestedNameSpecifier::TypeSpec:
6499 case NestedNameSpecifier::TypeSpecWithTemplate:
6500 if (isa<ElaboratedType>(ClsTy)) {
6501 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6502 ETLoc.setElaboratedKeywordLoc(SourceLocation());
6503 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6504 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6505 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6506 } else {
6507 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6509 break;
6511 case NestedNameSpecifier::Namespace:
6512 case NestedNameSpecifier::NamespaceAlias:
6513 case NestedNameSpecifier::Global:
6514 case NestedNameSpecifier::Super:
6515 llvm_unreachable("Nested-name-specifier must name a type");
6518 // Finally fill in MemberPointerLocInfo fields.
6519 TL.setStarLoc(Chunk.Mem.StarLoc);
6520 TL.setClassTInfo(ClsTInfo);
6522 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6523 assert(Chunk.Kind == DeclaratorChunk::Reference);
6524 // 'Amp' is misleading: this might have been originally
6525 /// spelled with AmpAmp.
6526 TL.setAmpLoc(Chunk.Loc);
6528 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6529 assert(Chunk.Kind == DeclaratorChunk::Reference);
6530 assert(!Chunk.Ref.LValueRef);
6531 TL.setAmpAmpLoc(Chunk.Loc);
6533 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6534 assert(Chunk.Kind == DeclaratorChunk::Array);
6535 TL.setLBracketLoc(Chunk.Loc);
6536 TL.setRBracketLoc(Chunk.EndLoc);
6537 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6539 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6540 assert(Chunk.Kind == DeclaratorChunk::Function);
6541 TL.setLocalRangeBegin(Chunk.Loc);
6542 TL.setLocalRangeEnd(Chunk.EndLoc);
6544 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6545 TL.setLParenLoc(FTI.getLParenLoc());
6546 TL.setRParenLoc(FTI.getRParenLoc());
6547 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6548 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6549 TL.setParam(tpi++, Param);
6551 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6553 void VisitParenTypeLoc(ParenTypeLoc TL) {
6554 assert(Chunk.Kind == DeclaratorChunk::Paren);
6555 TL.setLParenLoc(Chunk.Loc);
6556 TL.setRParenLoc(Chunk.EndLoc);
6558 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6559 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6560 TL.setKWLoc(Chunk.Loc);
6562 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6563 TL.setNameLoc(Chunk.Loc);
6565 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6566 TL.setExpansionLoc(Chunk.Loc);
6568 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6569 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6570 TL.setNameLoc(Chunk.Loc);
6572 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6573 TL.setNameLoc(Chunk.Loc);
6575 void
6576 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6577 TL.setNameLoc(Chunk.Loc);
6579 void VisitMatrixTypeLoc(MatrixTypeLoc TL) {
6580 fillMatrixTypeLoc(TL, Chunk.getAttrs());
6583 void VisitTypeLoc(TypeLoc TL) {
6584 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6587 } // end anonymous namespace
6589 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6590 SourceLocation Loc;
6591 switch (Chunk.Kind) {
6592 case DeclaratorChunk::Function:
6593 case DeclaratorChunk::Array:
6594 case DeclaratorChunk::Paren:
6595 case DeclaratorChunk::Pipe:
6596 llvm_unreachable("cannot be _Atomic qualified");
6598 case DeclaratorChunk::Pointer:
6599 Loc = Chunk.Ptr.AtomicQualLoc;
6600 break;
6602 case DeclaratorChunk::BlockPointer:
6603 case DeclaratorChunk::Reference:
6604 case DeclaratorChunk::MemberPointer:
6605 // FIXME: Provide a source location for the _Atomic keyword.
6606 break;
6609 ATL.setKWLoc(Loc);
6610 ATL.setParensRange(SourceRange());
6613 static void
6614 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6615 const ParsedAttributesView &Attrs) {
6616 for (const ParsedAttr &AL : Attrs) {
6617 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6618 DASTL.setAttrNameLoc(AL.getLoc());
6619 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6620 DASTL.setAttrOperandParensRange(SourceRange());
6621 return;
6625 llvm_unreachable(
6626 "no address_space attribute found at the expected location!");
6629 /// Create and instantiate a TypeSourceInfo with type source information.
6631 /// \param T QualType referring to the type as written in source code.
6633 /// \param ReturnTypeInfo For declarators whose return type does not show
6634 /// up in the normal place in the declaration specifiers (such as a C++
6635 /// conversion function), this pointer will refer to a type source information
6636 /// for that return type.
6637 static TypeSourceInfo *
6638 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6639 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6640 Sema &S = State.getSema();
6641 Declarator &D = State.getDeclarator();
6643 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6644 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6646 // Handle parameter packs whose type is a pack expansion.
6647 if (isa<PackExpansionType>(T)) {
6648 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6649 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6652 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6653 // Microsoft property fields can have multiple sizeless array chunks
6654 // (i.e. int x[][][]). Don't create more than one level of incomplete array.
6655 if (CurrTL.getTypeLocClass() == TypeLoc::IncompleteArray && e != 1 &&
6656 D.getDeclSpec().getAttributes().hasMSPropertyAttr())
6657 continue;
6659 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6660 // declarator chunk.
6661 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6662 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6663 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6666 bool HasDesugaredTypeLoc = true;
6667 while (HasDesugaredTypeLoc) {
6668 switch (CurrTL.getTypeLocClass()) {
6669 case TypeLoc::MacroQualified: {
6670 auto TL = CurrTL.castAs<MacroQualifiedTypeLoc>();
6671 TL.setExpansionLoc(
6672 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6673 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6674 break;
6677 case TypeLoc::Attributed: {
6678 auto TL = CurrTL.castAs<AttributedTypeLoc>();
6679 fillAttributedTypeLoc(TL, State);
6680 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6681 break;
6684 case TypeLoc::Adjusted:
6685 case TypeLoc::BTFTagAttributed: {
6686 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6687 break;
6690 case TypeLoc::DependentAddressSpace: {
6691 auto TL = CurrTL.castAs<DependentAddressSpaceTypeLoc>();
6692 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6693 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6694 break;
6697 default:
6698 HasDesugaredTypeLoc = false;
6699 break;
6703 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6704 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6707 // If we have different source information for the return type, use
6708 // that. This really only applies to C++ conversion functions.
6709 if (ReturnTypeInfo) {
6710 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6711 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6712 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6713 } else {
6714 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6717 return TInfo;
6720 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6721 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6722 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6723 // and Sema during declaration parsing. Try deallocating/caching them when
6724 // it's appropriate, instead of allocating them and keeping them around.
6725 LocInfoType *LocT = (LocInfoType *)BumpAlloc.Allocate(sizeof(LocInfoType),
6726 alignof(LocInfoType));
6727 new (LocT) LocInfoType(T, TInfo);
6728 assert(LocT->getTypeClass() != T->getTypeClass() &&
6729 "LocInfoType's TypeClass conflicts with an existing Type class");
6730 return ParsedType::make(QualType(LocT, 0));
6733 void LocInfoType::getAsStringInternal(std::string &Str,
6734 const PrintingPolicy &Policy) const {
6735 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6736 " was used directly instead of getting the QualType through"
6737 " GetTypeFromParser");
6740 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6741 // C99 6.7.6: Type names have no identifier. This is already validated by
6742 // the parser.
6743 assert(D.getIdentifier() == nullptr &&
6744 "Type name should have no identifier!");
6746 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6747 QualType T = TInfo->getType();
6748 if (D.isInvalidType())
6749 return true;
6751 // Make sure there are no unused decl attributes on the declarator.
6752 // We don't want to do this for ObjC parameters because we're going
6753 // to apply them to the actual parameter declaration.
6754 // Likewise, we don't want to do this for alias declarations, because
6755 // we are actually going to build a declaration from this eventually.
6756 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6757 D.getContext() != DeclaratorContext::AliasDecl &&
6758 D.getContext() != DeclaratorContext::AliasTemplate)
6759 checkUnusedDeclAttributes(D);
6761 if (getLangOpts().CPlusPlus) {
6762 // Check that there are no default arguments (C++ only).
6763 CheckExtraCXXDefaultArguments(D);
6766 return CreateParsedType(T, TInfo);
6769 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6770 QualType T = Context.getObjCInstanceType();
6771 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6772 return CreateParsedType(T, TInfo);
6775 //===----------------------------------------------------------------------===//
6776 // Type Attribute Processing
6777 //===----------------------------------------------------------------------===//
6779 /// Build an AddressSpace index from a constant expression and diagnose any
6780 /// errors related to invalid address_spaces. Returns true on successfully
6781 /// building an AddressSpace index.
6782 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6783 const Expr *AddrSpace,
6784 SourceLocation AttrLoc) {
6785 if (!AddrSpace->isValueDependent()) {
6786 std::optional<llvm::APSInt> OptAddrSpace =
6787 AddrSpace->getIntegerConstantExpr(S.Context);
6788 if (!OptAddrSpace) {
6789 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6790 << "'address_space'" << AANT_ArgumentIntegerConstant
6791 << AddrSpace->getSourceRange();
6792 return false;
6794 llvm::APSInt &addrSpace = *OptAddrSpace;
6796 // Bounds checking.
6797 if (addrSpace.isSigned()) {
6798 if (addrSpace.isNegative()) {
6799 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6800 << AddrSpace->getSourceRange();
6801 return false;
6803 addrSpace.setIsSigned(false);
6806 llvm::APSInt max(addrSpace.getBitWidth());
6807 max =
6808 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6810 if (addrSpace > max) {
6811 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6812 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6813 return false;
6816 ASIdx =
6817 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6818 return true;
6821 // Default value for DependentAddressSpaceTypes
6822 ASIdx = LangAS::Default;
6823 return true;
6826 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6827 /// is uninstantiated. If instantiated it will apply the appropriate address
6828 /// space to the type. This function allows dependent template variables to be
6829 /// used in conjunction with the address_space attribute
6830 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6831 SourceLocation AttrLoc) {
6832 if (!AddrSpace->isValueDependent()) {
6833 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6834 AttrLoc))
6835 return QualType();
6837 return Context.getAddrSpaceQualType(T, ASIdx);
6840 // A check with similar intentions as checking if a type already has an
6841 // address space except for on a dependent types, basically if the
6842 // current type is already a DependentAddressSpaceType then its already
6843 // lined up to have another address space on it and we can't have
6844 // multiple address spaces on the one pointer indirection
6845 if (T->getAs<DependentAddressSpaceType>()) {
6846 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6847 return QualType();
6850 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6853 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6854 SourceLocation AttrLoc) {
6855 LangAS ASIdx;
6856 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6857 return QualType();
6858 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6861 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6862 TypeProcessingState &State) {
6863 Sema &S = State.getSema();
6865 // Check the number of attribute arguments.
6866 if (Attr.getNumArgs() != 1) {
6867 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6868 << Attr << 1;
6869 Attr.setInvalid();
6870 return;
6873 // Ensure the argument is a string.
6874 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6875 if (!StrLiteral) {
6876 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6877 << Attr << AANT_ArgumentString;
6878 Attr.setInvalid();
6879 return;
6882 ASTContext &Ctx = S.Context;
6883 StringRef BTFTypeTag = StrLiteral->getString();
6884 Type = State.getBTFTagAttributedType(
6885 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6888 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6889 /// specified type. The attribute contains 1 argument, the id of the address
6890 /// space for the type.
6891 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6892 const ParsedAttr &Attr,
6893 TypeProcessingState &State) {
6894 Sema &S = State.getSema();
6896 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6897 // qualified by an address-space qualifier."
6898 if (Type->isFunctionType()) {
6899 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6900 Attr.setInvalid();
6901 return;
6904 LangAS ASIdx;
6905 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6907 // Check the attribute arguments.
6908 if (Attr.getNumArgs() != 1) {
6909 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6910 << 1;
6911 Attr.setInvalid();
6912 return;
6915 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6916 LangAS ASIdx;
6917 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6918 Attr.setInvalid();
6919 return;
6922 ASTContext &Ctx = S.Context;
6923 auto *ASAttr =
6924 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6926 // If the expression is not value dependent (not templated), then we can
6927 // apply the address space qualifiers just to the equivalent type.
6928 // Otherwise, we make an AttributedType with the modified and equivalent
6929 // type the same, and wrap it in a DependentAddressSpaceType. When this
6930 // dependent type is resolved, the qualifier is added to the equivalent type
6931 // later.
6932 QualType T;
6933 if (!ASArgExpr->isValueDependent()) {
6934 QualType EquivType =
6935 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6936 if (EquivType.isNull()) {
6937 Attr.setInvalid();
6938 return;
6940 T = State.getAttributedType(ASAttr, Type, EquivType);
6941 } else {
6942 T = State.getAttributedType(ASAttr, Type, Type);
6943 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6946 if (!T.isNull())
6947 Type = T;
6948 else
6949 Attr.setInvalid();
6950 } else {
6951 // The keyword-based type attributes imply which address space to use.
6952 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6953 : Attr.asOpenCLLangAS();
6954 if (S.getLangOpts().HLSL)
6955 ASIdx = Attr.asHLSLLangAS();
6957 if (ASIdx == LangAS::Default)
6958 llvm_unreachable("Invalid address space");
6960 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6961 Attr.getLoc())) {
6962 Attr.setInvalid();
6963 return;
6966 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6970 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6971 /// attribute on the specified type.
6973 /// Returns 'true' if the attribute was handled.
6974 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6975 ParsedAttr &attr, QualType &type) {
6976 bool NonObjCPointer = false;
6978 if (!type->isDependentType() && !type->isUndeducedType()) {
6979 if (const PointerType *ptr = type->getAs<PointerType>()) {
6980 QualType pointee = ptr->getPointeeType();
6981 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6982 return false;
6983 // It is important not to lose the source info that there was an attribute
6984 // applied to non-objc pointer. We will create an attributed type but
6985 // its type will be the same as the original type.
6986 NonObjCPointer = true;
6987 } else if (!type->isObjCRetainableType()) {
6988 return false;
6991 // Don't accept an ownership attribute in the declspec if it would
6992 // just be the return type of a block pointer.
6993 if (state.isProcessingDeclSpec()) {
6994 Declarator &D = state.getDeclarator();
6995 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6996 /*onlyBlockPointers=*/true))
6997 return false;
7001 Sema &S = state.getSema();
7002 SourceLocation AttrLoc = attr.getLoc();
7003 if (AttrLoc.isMacroID())
7004 AttrLoc =
7005 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
7007 if (!attr.isArgIdent(0)) {
7008 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
7009 << AANT_ArgumentString;
7010 attr.setInvalid();
7011 return true;
7014 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7015 Qualifiers::ObjCLifetime lifetime;
7016 if (II->isStr("none"))
7017 lifetime = Qualifiers::OCL_ExplicitNone;
7018 else if (II->isStr("strong"))
7019 lifetime = Qualifiers::OCL_Strong;
7020 else if (II->isStr("weak"))
7021 lifetime = Qualifiers::OCL_Weak;
7022 else if (II->isStr("autoreleasing"))
7023 lifetime = Qualifiers::OCL_Autoreleasing;
7024 else {
7025 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
7026 attr.setInvalid();
7027 return true;
7030 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
7031 // outside of ARC mode.
7032 if (!S.getLangOpts().ObjCAutoRefCount &&
7033 lifetime != Qualifiers::OCL_Weak &&
7034 lifetime != Qualifiers::OCL_ExplicitNone) {
7035 return true;
7038 SplitQualType underlyingType = type.split();
7040 // Check for redundant/conflicting ownership qualifiers.
7041 if (Qualifiers::ObjCLifetime previousLifetime
7042 = type.getQualifiers().getObjCLifetime()) {
7043 // If it's written directly, that's an error.
7044 if (S.Context.hasDirectOwnershipQualifier(type)) {
7045 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
7046 << type;
7047 return true;
7050 // Otherwise, if the qualifiers actually conflict, pull sugar off
7051 // and remove the ObjCLifetime qualifiers.
7052 if (previousLifetime != lifetime) {
7053 // It's possible to have multiple local ObjCLifetime qualifiers. We
7054 // can't stop after we reach a type that is directly qualified.
7055 const Type *prevTy = nullptr;
7056 while (!prevTy || prevTy != underlyingType.Ty) {
7057 prevTy = underlyingType.Ty;
7058 underlyingType = underlyingType.getSingleStepDesugaredType();
7060 underlyingType.Quals.removeObjCLifetime();
7064 underlyingType.Quals.addObjCLifetime(lifetime);
7066 if (NonObjCPointer) {
7067 StringRef name = attr.getAttrName()->getName();
7068 switch (lifetime) {
7069 case Qualifiers::OCL_None:
7070 case Qualifiers::OCL_ExplicitNone:
7071 break;
7072 case Qualifiers::OCL_Strong: name = "__strong"; break;
7073 case Qualifiers::OCL_Weak: name = "__weak"; break;
7074 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
7076 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
7077 << TDS_ObjCObjOrBlock << type;
7080 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
7081 // because having both 'T' and '__unsafe_unretained T' exist in the type
7082 // system causes unfortunate widespread consistency problems. (For example,
7083 // they're not considered compatible types, and we mangle them identicially
7084 // as template arguments.) These problems are all individually fixable,
7085 // but it's easier to just not add the qualifier and instead sniff it out
7086 // in specific places using isObjCInertUnsafeUnretainedType().
7088 // Doing this does means we miss some trivial consistency checks that
7089 // would've triggered in ARC, but that's better than trying to solve all
7090 // the coexistence problems with __unsafe_unretained.
7091 if (!S.getLangOpts().ObjCAutoRefCount &&
7092 lifetime == Qualifiers::OCL_ExplicitNone) {
7093 type = state.getAttributedType(
7094 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
7095 type, type);
7096 return true;
7099 QualType origType = type;
7100 if (!NonObjCPointer)
7101 type = S.Context.getQualifiedType(underlyingType);
7103 // If we have a valid source location for the attribute, use an
7104 // AttributedType instead.
7105 if (AttrLoc.isValid()) {
7106 type = state.getAttributedType(::new (S.Context)
7107 ObjCOwnershipAttr(S.Context, attr, II),
7108 origType, type);
7111 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
7112 unsigned diagnostic, QualType type) {
7113 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
7114 S.DelayedDiagnostics.add(
7115 sema::DelayedDiagnostic::makeForbiddenType(
7116 S.getSourceManager().getExpansionLoc(loc),
7117 diagnostic, type, /*ignored*/ 0));
7118 } else {
7119 S.Diag(loc, diagnostic);
7123 // Sometimes, __weak isn't allowed.
7124 if (lifetime == Qualifiers::OCL_Weak &&
7125 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
7127 // Use a specialized diagnostic if the runtime just doesn't support them.
7128 unsigned diagnostic =
7129 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
7130 : diag::err_arc_weak_no_runtime);
7132 // In any case, delay the diagnostic until we know what we're parsing.
7133 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
7135 attr.setInvalid();
7136 return true;
7139 // Forbid __weak for class objects marked as
7140 // objc_arc_weak_reference_unavailable
7141 if (lifetime == Qualifiers::OCL_Weak) {
7142 if (const ObjCObjectPointerType *ObjT =
7143 type->getAs<ObjCObjectPointerType>()) {
7144 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
7145 if (Class->isArcWeakrefUnavailable()) {
7146 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
7147 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
7148 diag::note_class_declared);
7154 return true;
7157 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
7158 /// attribute on the specified type. Returns true to indicate that
7159 /// the attribute was handled, false to indicate that the type does
7160 /// not permit the attribute.
7161 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7162 QualType &type) {
7163 Sema &S = state.getSema();
7165 // Delay if this isn't some kind of pointer.
7166 if (!type->isPointerType() &&
7167 !type->isObjCObjectPointerType() &&
7168 !type->isBlockPointerType())
7169 return false;
7171 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
7172 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
7173 attr.setInvalid();
7174 return true;
7177 // Check the attribute arguments.
7178 if (!attr.isArgIdent(0)) {
7179 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
7180 << attr << AANT_ArgumentString;
7181 attr.setInvalid();
7182 return true;
7184 Qualifiers::GC GCAttr;
7185 if (attr.getNumArgs() > 1) {
7186 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
7187 << 1;
7188 attr.setInvalid();
7189 return true;
7192 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
7193 if (II->isStr("weak"))
7194 GCAttr = Qualifiers::Weak;
7195 else if (II->isStr("strong"))
7196 GCAttr = Qualifiers::Strong;
7197 else {
7198 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
7199 << attr << II;
7200 attr.setInvalid();
7201 return true;
7204 QualType origType = type;
7205 type = S.Context.getObjCGCQualType(origType, GCAttr);
7207 // Make an attributed type to preserve the source information.
7208 if (attr.getLoc().isValid())
7209 type = state.getAttributedType(
7210 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7212 return true;
7215 namespace {
7216 /// A helper class to unwrap a type down to a function for the
7217 /// purposes of applying attributes there.
7219 /// Use:
7220 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7221 /// if (unwrapped.isFunctionType()) {
7222 /// const FunctionType *fn = unwrapped.get();
7223 /// // change fn somehow
7224 /// T = unwrapped.wrap(fn);
7225 /// }
7226 struct FunctionTypeUnwrapper {
7227 enum WrapKind {
7228 Desugar,
7229 Attributed,
7230 Parens,
7231 Array,
7232 Pointer,
7233 BlockPointer,
7234 Reference,
7235 MemberPointer,
7236 MacroQualified,
7239 QualType Original;
7240 const FunctionType *Fn;
7241 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7243 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7244 while (true) {
7245 const Type *Ty = T.getTypePtr();
7246 if (isa<FunctionType>(Ty)) {
7247 Fn = cast<FunctionType>(Ty);
7248 return;
7249 } else if (isa<ParenType>(Ty)) {
7250 T = cast<ParenType>(Ty)->getInnerType();
7251 Stack.push_back(Parens);
7252 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7253 isa<IncompleteArrayType>(Ty)) {
7254 T = cast<ArrayType>(Ty)->getElementType();
7255 Stack.push_back(Array);
7256 } else if (isa<PointerType>(Ty)) {
7257 T = cast<PointerType>(Ty)->getPointeeType();
7258 Stack.push_back(Pointer);
7259 } else if (isa<BlockPointerType>(Ty)) {
7260 T = cast<BlockPointerType>(Ty)->getPointeeType();
7261 Stack.push_back(BlockPointer);
7262 } else if (isa<MemberPointerType>(Ty)) {
7263 T = cast<MemberPointerType>(Ty)->getPointeeType();
7264 Stack.push_back(MemberPointer);
7265 } else if (isa<ReferenceType>(Ty)) {
7266 T = cast<ReferenceType>(Ty)->getPointeeType();
7267 Stack.push_back(Reference);
7268 } else if (isa<AttributedType>(Ty)) {
7269 T = cast<AttributedType>(Ty)->getEquivalentType();
7270 Stack.push_back(Attributed);
7271 } else if (isa<MacroQualifiedType>(Ty)) {
7272 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7273 Stack.push_back(MacroQualified);
7274 } else {
7275 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7276 if (Ty == DTy) {
7277 Fn = nullptr;
7278 return;
7281 T = QualType(DTy, 0);
7282 Stack.push_back(Desugar);
7287 bool isFunctionType() const { return (Fn != nullptr); }
7288 const FunctionType *get() const { return Fn; }
7290 QualType wrap(Sema &S, const FunctionType *New) {
7291 // If T wasn't modified from the unwrapped type, do nothing.
7292 if (New == get()) return Original;
7294 Fn = New;
7295 return wrap(S.Context, Original, 0);
7298 private:
7299 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7300 if (I == Stack.size())
7301 return C.getQualifiedType(Fn, Old.getQualifiers());
7303 // Build up the inner type, applying the qualifiers from the old
7304 // type to the new type.
7305 SplitQualType SplitOld = Old.split();
7307 // As a special case, tail-recurse if there are no qualifiers.
7308 if (SplitOld.Quals.empty())
7309 return wrap(C, SplitOld.Ty, I);
7310 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7313 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7314 if (I == Stack.size()) return QualType(Fn, 0);
7316 switch (static_cast<WrapKind>(Stack[I++])) {
7317 case Desugar:
7318 // This is the point at which we potentially lose source
7319 // information.
7320 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7322 case Attributed:
7323 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7325 case Parens: {
7326 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7327 return C.getParenType(New);
7330 case MacroQualified:
7331 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7333 case Array: {
7334 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7335 QualType New = wrap(C, CAT->getElementType(), I);
7336 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7337 CAT->getSizeModifier(),
7338 CAT->getIndexTypeCVRQualifiers());
7341 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7342 QualType New = wrap(C, VAT->getElementType(), I);
7343 return C.getVariableArrayType(
7344 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7345 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7348 const auto *IAT = cast<IncompleteArrayType>(Old);
7349 QualType New = wrap(C, IAT->getElementType(), I);
7350 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7351 IAT->getIndexTypeCVRQualifiers());
7354 case Pointer: {
7355 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7356 return C.getPointerType(New);
7359 case BlockPointer: {
7360 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7361 return C.getBlockPointerType(New);
7364 case MemberPointer: {
7365 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7366 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7367 return C.getMemberPointerType(New, OldMPT->getClass());
7370 case Reference: {
7371 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7372 QualType New = wrap(C, OldRef->getPointeeType(), I);
7373 if (isa<LValueReferenceType>(OldRef))
7374 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7375 else
7376 return C.getRValueReferenceType(New);
7380 llvm_unreachable("unknown wrapping kind");
7383 } // end anonymous namespace
7385 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7386 ParsedAttr &PAttr, QualType &Type) {
7387 Sema &S = State.getSema();
7389 Attr *A;
7390 switch (PAttr.getKind()) {
7391 default: llvm_unreachable("Unknown attribute kind");
7392 case ParsedAttr::AT_Ptr32:
7393 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7394 break;
7395 case ParsedAttr::AT_Ptr64:
7396 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7397 break;
7398 case ParsedAttr::AT_SPtr:
7399 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7400 break;
7401 case ParsedAttr::AT_UPtr:
7402 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7403 break;
7406 std::bitset<attr::LastAttr> Attrs;
7407 QualType Desugared = Type;
7408 for (;;) {
7409 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7410 Desugared = TT->desugar();
7411 continue;
7412 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7413 Desugared = ET->desugar();
7414 continue;
7416 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7417 if (!AT)
7418 break;
7419 Attrs[AT->getAttrKind()] = true;
7420 Desugared = AT->getModifiedType();
7423 // You cannot specify duplicate type attributes, so if the attribute has
7424 // already been applied, flag it.
7425 attr::Kind NewAttrKind = A->getKind();
7426 if (Attrs[NewAttrKind]) {
7427 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7428 return true;
7430 Attrs[NewAttrKind] = true;
7432 // You cannot have both __sptr and __uptr on the same type, nor can you
7433 // have __ptr32 and __ptr64.
7434 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7435 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7436 << "'__ptr32'"
7437 << "'__ptr64'" << /*isRegularKeyword=*/0;
7438 return true;
7439 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7440 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7441 << "'__sptr'"
7442 << "'__uptr'" << /*isRegularKeyword=*/0;
7443 return true;
7446 // Check the raw (i.e., desugared) Canonical type to see if it
7447 // is a pointer type.
7448 if (!isa<PointerType>(Desugared)) {
7449 // Pointer type qualifiers can only operate on pointer types, but not
7450 // pointer-to-member types.
7451 if (Type->isMemberPointerType())
7452 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7453 else
7454 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7455 return true;
7458 // Add address space to type based on its attributes.
7459 LangAS ASIdx = LangAS::Default;
7460 uint64_t PtrWidth =
7461 S.Context.getTargetInfo().getPointerWidth(LangAS::Default);
7462 if (PtrWidth == 32) {
7463 if (Attrs[attr::Ptr64])
7464 ASIdx = LangAS::ptr64;
7465 else if (Attrs[attr::UPtr])
7466 ASIdx = LangAS::ptr32_uptr;
7467 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7468 if (Attrs[attr::UPtr])
7469 ASIdx = LangAS::ptr32_uptr;
7470 else
7471 ASIdx = LangAS::ptr32_sptr;
7474 QualType Pointee = Type->getPointeeType();
7475 if (ASIdx != LangAS::Default)
7476 Pointee = S.Context.getAddrSpaceQualType(
7477 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7478 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7479 return false;
7482 static bool HandleWebAssemblyFuncrefAttr(TypeProcessingState &State,
7483 QualType &QT, ParsedAttr &PAttr) {
7484 assert(PAttr.getKind() == ParsedAttr::AT_WebAssemblyFuncref);
7486 Sema &S = State.getSema();
7487 Attr *A = createSimpleAttr<WebAssemblyFuncrefAttr>(S.Context, PAttr);
7489 std::bitset<attr::LastAttr> Attrs;
7490 attr::Kind NewAttrKind = A->getKind();
7491 const auto *AT = dyn_cast<AttributedType>(QT);
7492 while (AT) {
7493 Attrs[AT->getAttrKind()] = true;
7494 AT = dyn_cast<AttributedType>(AT->getModifiedType());
7497 // You cannot specify duplicate type attributes, so if the attribute has
7498 // already been applied, flag it.
7499 if (Attrs[NewAttrKind]) {
7500 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7501 return true;
7504 // Add address space to type based on its attributes.
7505 LangAS ASIdx = LangAS::wasm_funcref;
7506 QualType Pointee = QT->getPointeeType();
7507 Pointee = S.Context.getAddrSpaceQualType(
7508 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7509 QT = State.getAttributedType(A, QT, S.Context.getPointerType(Pointee));
7510 return false;
7513 /// Map a nullability attribute kind to a nullability kind.
7514 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7515 switch (kind) {
7516 case ParsedAttr::AT_TypeNonNull:
7517 return NullabilityKind::NonNull;
7519 case ParsedAttr::AT_TypeNullable:
7520 return NullabilityKind::Nullable;
7522 case ParsedAttr::AT_TypeNullableResult:
7523 return NullabilityKind::NullableResult;
7525 case ParsedAttr::AT_TypeNullUnspecified:
7526 return NullabilityKind::Unspecified;
7528 default:
7529 llvm_unreachable("not a nullability attribute kind");
7533 /// Applies a nullability type specifier to the given type, if possible.
7535 /// \param state The type processing state.
7537 /// \param type The type to which the nullability specifier will be
7538 /// added. On success, this type will be updated appropriately.
7540 /// \param attr The attribute as written on the type.
7542 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7543 /// array type (e.g., because it will decay to a pointer).
7545 /// \returns true if a problem has been diagnosed, false on success.
7546 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7547 QualType &type,
7548 ParsedAttr &attr,
7549 bool allowOnArrayType) {
7550 Sema &S = state.getSema();
7552 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7553 SourceLocation nullabilityLoc = attr.getLoc();
7554 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7556 recordNullabilitySeen(S, nullabilityLoc);
7558 // Check for existing nullability attributes on the type.
7559 QualType desugared = type;
7560 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7561 // Check whether there is already a null
7562 if (auto existingNullability = attributed->getImmediateNullability()) {
7563 // Duplicated nullability.
7564 if (nullability == *existingNullability) {
7565 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7566 << DiagNullabilityKind(nullability, isContextSensitive)
7567 << FixItHint::CreateRemoval(nullabilityLoc);
7569 break;
7572 // Conflicting nullability.
7573 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7574 << DiagNullabilityKind(nullability, isContextSensitive)
7575 << DiagNullabilityKind(*existingNullability, false);
7576 return true;
7579 desugared = attributed->getModifiedType();
7582 // If there is already a different nullability specifier, complain.
7583 // This (unlike the code above) looks through typedefs that might
7584 // have nullability specifiers on them, which means we cannot
7585 // provide a useful Fix-It.
7586 if (auto existingNullability = desugared->getNullability()) {
7587 if (nullability != *existingNullability) {
7588 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7589 << DiagNullabilityKind(nullability, isContextSensitive)
7590 << DiagNullabilityKind(*existingNullability, false);
7592 // Try to find the typedef with the existing nullability specifier.
7593 if (auto typedefType = desugared->getAs<TypedefType>()) {
7594 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7595 QualType underlyingType = typedefDecl->getUnderlyingType();
7596 if (auto typedefNullability
7597 = AttributedType::stripOuterNullability(underlyingType)) {
7598 if (*typedefNullability == *existingNullability) {
7599 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7600 << DiagNullabilityKind(*existingNullability, false);
7605 return true;
7609 // If this definitely isn't a pointer type, reject the specifier.
7610 if (!desugared->canHaveNullability() &&
7611 !(allowOnArrayType && desugared->isArrayType())) {
7612 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7613 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7614 return true;
7617 // For the context-sensitive keywords/Objective-C property
7618 // attributes, require that the type be a single-level pointer.
7619 if (isContextSensitive) {
7620 // Make sure that the pointee isn't itself a pointer type.
7621 const Type *pointeeType = nullptr;
7622 if (desugared->isArrayType())
7623 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7624 else if (desugared->isAnyPointerType())
7625 pointeeType = desugared->getPointeeType().getTypePtr();
7627 if (pointeeType && (pointeeType->isAnyPointerType() ||
7628 pointeeType->isObjCObjectPointerType() ||
7629 pointeeType->isMemberPointerType())) {
7630 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7631 << DiagNullabilityKind(nullability, true)
7632 << type;
7633 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7634 << DiagNullabilityKind(nullability, false)
7635 << type
7636 << FixItHint::CreateReplacement(nullabilityLoc,
7637 getNullabilitySpelling(nullability));
7638 return true;
7642 // Form the attributed type.
7643 type = state.getAttributedType(
7644 createNullabilityAttr(S.Context, attr, nullability), type, type);
7645 return false;
7648 /// Check the application of the Objective-C '__kindof' qualifier to
7649 /// the given type.
7650 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7651 ParsedAttr &attr) {
7652 Sema &S = state.getSema();
7654 if (isa<ObjCTypeParamType>(type)) {
7655 // Build the attributed type to record where __kindof occurred.
7656 type = state.getAttributedType(
7657 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7658 return false;
7661 // Find out if it's an Objective-C object or object pointer type;
7662 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7663 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7664 : type->getAs<ObjCObjectType>();
7666 // If not, we can't apply __kindof.
7667 if (!objType) {
7668 // FIXME: Handle dependent types that aren't yet object types.
7669 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7670 << type;
7671 return true;
7674 // Rebuild the "equivalent" type, which pushes __kindof down into
7675 // the object type.
7676 // There is no need to apply kindof on an unqualified id type.
7677 QualType equivType = S.Context.getObjCObjectType(
7678 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7679 objType->getProtocols(),
7680 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7682 // If we started with an object pointer type, rebuild it.
7683 if (ptrType) {
7684 equivType = S.Context.getObjCObjectPointerType(equivType);
7685 if (auto nullability = type->getNullability()) {
7686 // We create a nullability attribute from the __kindof attribute.
7687 // Make sure that will make sense.
7688 assert(attr.getAttributeSpellingListIndex() == 0 &&
7689 "multiple spellings for __kindof?");
7690 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7691 A->setImplicit(true);
7692 equivType = state.getAttributedType(A, equivType, equivType);
7696 // Build the attributed type to record where __kindof occurred.
7697 type = state.getAttributedType(
7698 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7699 return false;
7702 /// Distribute a nullability type attribute that cannot be applied to
7703 /// the type specifier to a pointer, block pointer, or member pointer
7704 /// declarator, complaining if necessary.
7706 /// \returns true if the nullability annotation was distributed, false
7707 /// otherwise.
7708 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7709 QualType type, ParsedAttr &attr) {
7710 Declarator &declarator = state.getDeclarator();
7712 /// Attempt to move the attribute to the specified chunk.
7713 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7714 // If there is already a nullability attribute there, don't add
7715 // one.
7716 if (hasNullabilityAttr(chunk.getAttrs()))
7717 return false;
7719 // Complain about the nullability qualifier being in the wrong
7720 // place.
7721 enum {
7722 PK_Pointer,
7723 PK_BlockPointer,
7724 PK_MemberPointer,
7725 PK_FunctionPointer,
7726 PK_MemberFunctionPointer,
7727 } pointerKind
7728 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7729 : PK_Pointer)
7730 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7731 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7733 auto diag = state.getSema().Diag(attr.getLoc(),
7734 diag::warn_nullability_declspec)
7735 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7736 attr.isContextSensitiveKeywordAttribute())
7737 << type
7738 << static_cast<unsigned>(pointerKind);
7740 // FIXME: MemberPointer chunks don't carry the location of the *.
7741 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7742 diag << FixItHint::CreateRemoval(attr.getLoc())
7743 << FixItHint::CreateInsertion(
7744 state.getSema().getPreprocessor().getLocForEndOfToken(
7745 chunk.Loc),
7746 " " + attr.getAttrName()->getName().str() + " ");
7749 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7750 chunk.getAttrs());
7751 return true;
7754 // Move it to the outermost pointer, member pointer, or block
7755 // pointer declarator.
7756 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7757 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7758 switch (chunk.Kind) {
7759 case DeclaratorChunk::Pointer:
7760 case DeclaratorChunk::BlockPointer:
7761 case DeclaratorChunk::MemberPointer:
7762 return moveToChunk(chunk, false);
7764 case DeclaratorChunk::Paren:
7765 case DeclaratorChunk::Array:
7766 continue;
7768 case DeclaratorChunk::Function:
7769 // Try to move past the return type to a function/block/member
7770 // function pointer.
7771 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7772 declarator, i,
7773 /*onlyBlockPointers=*/false)) {
7774 return moveToChunk(*dest, true);
7777 return false;
7779 // Don't walk through these.
7780 case DeclaratorChunk::Reference:
7781 case DeclaratorChunk::Pipe:
7782 return false;
7786 return false;
7789 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7790 assert(!Attr.isInvalid());
7791 switch (Attr.getKind()) {
7792 default:
7793 llvm_unreachable("not a calling convention attribute");
7794 case ParsedAttr::AT_CDecl:
7795 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7796 case ParsedAttr::AT_FastCall:
7797 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7798 case ParsedAttr::AT_StdCall:
7799 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7800 case ParsedAttr::AT_ThisCall:
7801 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7802 case ParsedAttr::AT_RegCall:
7803 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7804 case ParsedAttr::AT_Pascal:
7805 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7806 case ParsedAttr::AT_SwiftCall:
7807 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7808 case ParsedAttr::AT_SwiftAsyncCall:
7809 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7810 case ParsedAttr::AT_VectorCall:
7811 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7812 case ParsedAttr::AT_AArch64VectorPcs:
7813 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7814 case ParsedAttr::AT_AArch64SVEPcs:
7815 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7816 case ParsedAttr::AT_ArmStreaming:
7817 return createSimpleAttr<ArmStreamingAttr>(Ctx, Attr);
7818 case ParsedAttr::AT_AMDGPUKernelCall:
7819 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7820 case ParsedAttr::AT_Pcs: {
7821 // The attribute may have had a fixit applied where we treated an
7822 // identifier as a string literal. The contents of the string are valid,
7823 // but the form may not be.
7824 StringRef Str;
7825 if (Attr.isArgExpr(0))
7826 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7827 else
7828 Str = Attr.getArgAsIdent(0)->Ident->getName();
7829 PcsAttr::PCSType Type;
7830 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7831 llvm_unreachable("already validated the attribute");
7832 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7834 case ParsedAttr::AT_IntelOclBicc:
7835 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7836 case ParsedAttr::AT_MSABI:
7837 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7838 case ParsedAttr::AT_SysVABI:
7839 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7840 case ParsedAttr::AT_PreserveMost:
7841 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7842 case ParsedAttr::AT_PreserveAll:
7843 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7844 case ParsedAttr::AT_M68kRTD:
7845 return createSimpleAttr<M68kRTDAttr>(Ctx, Attr);
7847 llvm_unreachable("unexpected attribute kind!");
7850 static bool checkMutualExclusion(TypeProcessingState &state,
7851 const FunctionProtoType::ExtProtoInfo &EPI,
7852 ParsedAttr &Attr,
7853 AttributeCommonInfo::Kind OtherKind) {
7854 auto OtherAttr = std::find_if(
7855 state.getCurrentAttributes().begin(), state.getCurrentAttributes().end(),
7856 [OtherKind](const ParsedAttr &A) { return A.getKind() == OtherKind; });
7857 if (OtherAttr == state.getCurrentAttributes().end() || OtherAttr->isInvalid())
7858 return false;
7860 Sema &S = state.getSema();
7861 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
7862 << *OtherAttr << Attr
7863 << (OtherAttr->isRegularKeywordAttribute() ||
7864 Attr.isRegularKeywordAttribute());
7865 S.Diag(OtherAttr->getLoc(), diag::note_conflicting_attribute);
7866 Attr.setInvalid();
7867 return true;
7870 /// Process an individual function attribute. Returns true to
7871 /// indicate that the attribute was handled, false if it wasn't.
7872 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7873 QualType &type,
7874 Sema::CUDAFunctionTarget CFT) {
7875 Sema &S = state.getSema();
7877 FunctionTypeUnwrapper unwrapped(S, type);
7879 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7880 if (S.CheckAttrNoArgs(attr))
7881 return true;
7883 // Delay if this is not a function type.
7884 if (!unwrapped.isFunctionType())
7885 return false;
7887 // Otherwise we can process right away.
7888 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7889 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7890 return true;
7893 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7894 // Delay if this is not a function type.
7895 if (!unwrapped.isFunctionType())
7896 return false;
7898 // Ignore if we don't have CMSE enabled.
7899 if (!S.getLangOpts().Cmse) {
7900 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7901 attr.setInvalid();
7902 return true;
7905 // Otherwise we can process right away.
7906 FunctionType::ExtInfo EI =
7907 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7908 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7909 return true;
7912 // ns_returns_retained is not always a type attribute, but if we got
7913 // here, we're treating it as one right now.
7914 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7915 if (attr.getNumArgs()) return true;
7917 // Delay if this is not a function type.
7918 if (!unwrapped.isFunctionType())
7919 return false;
7921 // Check whether the return type is reasonable.
7922 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7923 unwrapped.get()->getReturnType()))
7924 return true;
7926 // Only actually change the underlying type in ARC builds.
7927 QualType origType = type;
7928 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7929 FunctionType::ExtInfo EI
7930 = unwrapped.get()->getExtInfo().withProducesResult(true);
7931 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7933 type = state.getAttributedType(
7934 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7935 origType, type);
7936 return true;
7939 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7940 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7941 return true;
7943 // Delay if this is not a function type.
7944 if (!unwrapped.isFunctionType())
7945 return false;
7947 FunctionType::ExtInfo EI =
7948 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7949 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7950 return true;
7953 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7954 if (!S.getLangOpts().CFProtectionBranch) {
7955 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7956 attr.setInvalid();
7957 return true;
7960 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7961 return true;
7963 // If this is not a function type, warning will be asserted by subject
7964 // check.
7965 if (!unwrapped.isFunctionType())
7966 return true;
7968 FunctionType::ExtInfo EI =
7969 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7970 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7971 return true;
7974 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7975 unsigned value;
7976 if (S.CheckRegparmAttr(attr, value))
7977 return true;
7979 // Delay if this is not a function type.
7980 if (!unwrapped.isFunctionType())
7981 return false;
7983 // Diagnose regparm with fastcall.
7984 const FunctionType *fn = unwrapped.get();
7985 CallingConv CC = fn->getCallConv();
7986 if (CC == CC_X86FastCall) {
7987 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7988 << FunctionType::getNameForCallConv(CC) << "regparm"
7989 << attr.isRegularKeywordAttribute();
7990 attr.setInvalid();
7991 return true;
7994 FunctionType::ExtInfo EI =
7995 unwrapped.get()->getExtInfo().withRegParm(value);
7996 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7997 return true;
8000 if (attr.getKind() == ParsedAttr::AT_ArmStreaming ||
8001 attr.getKind() == ParsedAttr::AT_ArmStreamingCompatible ||
8002 attr.getKind() == ParsedAttr::AT_ArmSharedZA ||
8003 attr.getKind() == ParsedAttr::AT_ArmPreservesZA){
8004 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
8005 return true;
8007 if (!unwrapped.isFunctionType())
8008 return false;
8010 const auto *FnTy = unwrapped.get()->getAs<FunctionProtoType>();
8011 if (!FnTy) {
8012 // SME ACLE attributes are not supported on K&R-style unprototyped C
8013 // functions.
8014 S.Diag(attr.getLoc(), diag::warn_attribute_wrong_decl_type) <<
8015 attr << attr.isRegularKeywordAttribute() << ExpectedFunctionWithProtoType;
8016 attr.setInvalid();
8017 return false;
8020 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
8021 switch (attr.getKind()) {
8022 case ParsedAttr::AT_ArmStreaming:
8023 if (checkMutualExclusion(state, EPI, attr,
8024 ParsedAttr::AT_ArmStreamingCompatible))
8025 return true;
8026 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMEnabledMask);
8027 break;
8028 case ParsedAttr::AT_ArmStreamingCompatible:
8029 if (checkMutualExclusion(state, EPI, attr, ParsedAttr::AT_ArmStreaming))
8030 return true;
8031 EPI.setArmSMEAttribute(FunctionType::SME_PStateSMCompatibleMask);
8032 break;
8033 case ParsedAttr::AT_ArmSharedZA:
8034 EPI.setArmSMEAttribute(FunctionType::SME_PStateZASharedMask);
8035 break;
8036 case ParsedAttr::AT_ArmPreservesZA:
8037 EPI.setArmSMEAttribute(FunctionType::SME_PStateZAPreservedMask);
8038 break;
8039 default:
8040 llvm_unreachable("Unsupported attribute");
8043 QualType newtype = S.Context.getFunctionType(FnTy->getReturnType(),
8044 FnTy->getParamTypes(), EPI);
8045 type = unwrapped.wrap(S, newtype->getAs<FunctionType>());
8046 return true;
8049 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
8050 // Delay if this is not a function type.
8051 if (!unwrapped.isFunctionType())
8052 return false;
8054 if (S.CheckAttrNoArgs(attr)) {
8055 attr.setInvalid();
8056 return true;
8059 // Otherwise we can process right away.
8060 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
8062 // MSVC ignores nothrow if it is in conflict with an explicit exception
8063 // specification.
8064 if (Proto->hasExceptionSpec()) {
8065 switch (Proto->getExceptionSpecType()) {
8066 case EST_None:
8067 llvm_unreachable("This doesn't have an exception spec!");
8069 case EST_DynamicNone:
8070 case EST_BasicNoexcept:
8071 case EST_NoexceptTrue:
8072 case EST_NoThrow:
8073 // Exception spec doesn't conflict with nothrow, so don't warn.
8074 [[fallthrough]];
8075 case EST_Unparsed:
8076 case EST_Uninstantiated:
8077 case EST_DependentNoexcept:
8078 case EST_Unevaluated:
8079 // We don't have enough information to properly determine if there is a
8080 // conflict, so suppress the warning.
8081 break;
8082 case EST_Dynamic:
8083 case EST_MSAny:
8084 case EST_NoexceptFalse:
8085 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
8086 break;
8088 return true;
8091 type = unwrapped.wrap(
8092 S, S.Context
8093 .getFunctionTypeWithExceptionSpec(
8094 QualType{Proto, 0},
8095 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
8096 ->getAs<FunctionType>());
8097 return true;
8100 // Delay if the type didn't work out to a function.
8101 if (!unwrapped.isFunctionType()) return false;
8103 // Otherwise, a calling convention.
8104 CallingConv CC;
8105 if (S.CheckCallingConvAttr(attr, CC, /*FunctionDecl=*/nullptr, CFT))
8106 return true;
8108 const FunctionType *fn = unwrapped.get();
8109 CallingConv CCOld = fn->getCallConv();
8110 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
8112 if (CCOld != CC) {
8113 // Error out on when there's already an attribute on the type
8114 // and the CCs don't match.
8115 if (S.getCallingConvAttributedType(type)) {
8116 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8117 << FunctionType::getNameForCallConv(CC)
8118 << FunctionType::getNameForCallConv(CCOld)
8119 << attr.isRegularKeywordAttribute();
8120 attr.setInvalid();
8121 return true;
8125 // Diagnose use of variadic functions with calling conventions that
8126 // don't support them (e.g. because they're callee-cleanup).
8127 // We delay warning about this on unprototyped function declarations
8128 // until after redeclaration checking, just in case we pick up a
8129 // prototype that way. And apparently we also "delay" warning about
8130 // unprototyped function types in general, despite not necessarily having
8131 // much ability to diagnose it later.
8132 if (!supportsVariadicCall(CC)) {
8133 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
8134 if (FnP && FnP->isVariadic()) {
8135 // stdcall and fastcall are ignored with a warning for GCC and MS
8136 // compatibility.
8137 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
8138 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
8139 << FunctionType::getNameForCallConv(CC)
8140 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
8142 attr.setInvalid();
8143 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
8144 << FunctionType::getNameForCallConv(CC);
8148 // Also diagnose fastcall with regparm.
8149 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
8150 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
8151 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall)
8152 << attr.isRegularKeywordAttribute();
8153 attr.setInvalid();
8154 return true;
8157 // Modify the CC from the wrapped function type, wrap it all back, and then
8158 // wrap the whole thing in an AttributedType as written. The modified type
8159 // might have a different CC if we ignored the attribute.
8160 QualType Equivalent;
8161 if (CCOld == CC) {
8162 Equivalent = type;
8163 } else {
8164 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
8165 Equivalent =
8166 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
8168 type = state.getAttributedType(CCAttr, type, Equivalent);
8169 return true;
8172 bool Sema::hasExplicitCallingConv(QualType T) {
8173 const AttributedType *AT;
8175 // Stop if we'd be stripping off a typedef sugar node to reach the
8176 // AttributedType.
8177 while ((AT = T->getAs<AttributedType>()) &&
8178 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
8179 if (AT->isCallingConv())
8180 return true;
8181 T = AT->getModifiedType();
8183 return false;
8186 void Sema::adjustMemberFunctionCC(QualType &T, bool HasThisPointer,
8187 bool IsCtorOrDtor, SourceLocation Loc) {
8188 FunctionTypeUnwrapper Unwrapped(*this, T);
8189 const FunctionType *FT = Unwrapped.get();
8190 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
8191 cast<FunctionProtoType>(FT)->isVariadic());
8192 CallingConv CurCC = FT->getCallConv();
8193 CallingConv ToCC =
8194 Context.getDefaultCallingConvention(IsVariadic, HasThisPointer);
8196 if (CurCC == ToCC)
8197 return;
8199 // MS compiler ignores explicit calling convention attributes on structors. We
8200 // should do the same.
8201 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
8202 // Issue a warning on ignored calling convention -- except of __stdcall.
8203 // Again, this is what MS compiler does.
8204 if (CurCC != CC_X86StdCall)
8205 Diag(Loc, diag::warn_cconv_unsupported)
8206 << FunctionType::getNameForCallConv(CurCC)
8207 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
8208 // Default adjustment.
8209 } else {
8210 // Only adjust types with the default convention. For example, on Windows
8211 // we should adjust a __cdecl type to __thiscall for instance methods, and a
8212 // __thiscall type to __cdecl for static methods.
8213 CallingConv DefaultCC =
8214 Context.getDefaultCallingConvention(IsVariadic, !HasThisPointer);
8216 if (CurCC != DefaultCC)
8217 return;
8219 if (hasExplicitCallingConv(T))
8220 return;
8223 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
8224 QualType Wrapped = Unwrapped.wrap(*this, FT);
8225 T = Context.getAdjustedType(T, Wrapped);
8228 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
8229 /// and float scalars, although arrays, pointers, and function return values are
8230 /// allowed in conjunction with this construct. Aggregates with this attribute
8231 /// are invalid, even if they are of the same size as a corresponding scalar.
8232 /// The raw attribute should contain precisely 1 argument, the vector size for
8233 /// the variable, measured in bytes. If curType and rawAttr are well formed,
8234 /// this routine will return a new vector type.
8235 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
8236 Sema &S) {
8237 // Check the attribute arguments.
8238 if (Attr.getNumArgs() != 1) {
8239 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8240 << 1;
8241 Attr.setInvalid();
8242 return;
8245 Expr *SizeExpr = Attr.getArgAsExpr(0);
8246 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
8247 if (!T.isNull())
8248 CurType = T;
8249 else
8250 Attr.setInvalid();
8253 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
8254 /// a type.
8255 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8256 Sema &S) {
8257 // check the attribute arguments.
8258 if (Attr.getNumArgs() != 1) {
8259 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8260 << 1;
8261 return;
8264 Expr *SizeExpr = Attr.getArgAsExpr(0);
8265 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
8266 if (!T.isNull())
8267 CurType = T;
8270 static bool isPermittedNeonBaseType(QualType &Ty, VectorKind VecKind, Sema &S) {
8271 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
8272 if (!BTy)
8273 return false;
8275 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
8277 // Signed poly is mathematically wrong, but has been baked into some ABIs by
8278 // now.
8279 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
8280 Triple.getArch() == llvm::Triple::aarch64_32 ||
8281 Triple.getArch() == llvm::Triple::aarch64_be;
8282 if (VecKind == VectorKind::NeonPoly) {
8283 if (IsPolyUnsigned) {
8284 // AArch64 polynomial vectors are unsigned.
8285 return BTy->getKind() == BuiltinType::UChar ||
8286 BTy->getKind() == BuiltinType::UShort ||
8287 BTy->getKind() == BuiltinType::ULong ||
8288 BTy->getKind() == BuiltinType::ULongLong;
8289 } else {
8290 // AArch32 polynomial vectors are signed.
8291 return BTy->getKind() == BuiltinType::SChar ||
8292 BTy->getKind() == BuiltinType::Short ||
8293 BTy->getKind() == BuiltinType::LongLong;
8297 // Non-polynomial vector types: the usual suspects are allowed, as well as
8298 // float64_t on AArch64.
8299 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
8300 BTy->getKind() == BuiltinType::Double)
8301 return true;
8303 return BTy->getKind() == BuiltinType::SChar ||
8304 BTy->getKind() == BuiltinType::UChar ||
8305 BTy->getKind() == BuiltinType::Short ||
8306 BTy->getKind() == BuiltinType::UShort ||
8307 BTy->getKind() == BuiltinType::Int ||
8308 BTy->getKind() == BuiltinType::UInt ||
8309 BTy->getKind() == BuiltinType::Long ||
8310 BTy->getKind() == BuiltinType::ULong ||
8311 BTy->getKind() == BuiltinType::LongLong ||
8312 BTy->getKind() == BuiltinType::ULongLong ||
8313 BTy->getKind() == BuiltinType::Float ||
8314 BTy->getKind() == BuiltinType::Half ||
8315 BTy->getKind() == BuiltinType::BFloat16;
8318 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
8319 llvm::APSInt &Result) {
8320 const auto *AttrExpr = Attr.getArgAsExpr(0);
8321 if (!AttrExpr->isTypeDependent()) {
8322 if (std::optional<llvm::APSInt> Res =
8323 AttrExpr->getIntegerConstantExpr(S.Context)) {
8324 Result = *Res;
8325 return true;
8328 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8329 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8330 Attr.setInvalid();
8331 return false;
8334 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8335 /// "neon_polyvector_type" attributes are used to create vector types that
8336 /// are mangled according to ARM's ABI. Otherwise, these types are identical
8337 /// to those created with the "vector_size" attribute. Unlike "vector_size"
8338 /// the argument to these Neon attributes is the number of vector elements,
8339 /// not the vector size in bytes. The vector width and element type must
8340 /// match one of the standard Neon vector types.
8341 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8342 Sema &S, VectorKind VecKind) {
8343 bool IsTargetCUDAAndHostARM = false;
8344 if (S.getLangOpts().CUDAIsDevice) {
8345 const TargetInfo *AuxTI = S.getASTContext().getAuxTargetInfo();
8346 IsTargetCUDAAndHostARM =
8347 AuxTI && (AuxTI->getTriple().isAArch64() || AuxTI->getTriple().isARM());
8350 // Target must have NEON (or MVE, whose vectors are similar enough
8351 // not to need a separate attribute)
8352 if (!(S.Context.getTargetInfo().hasFeature("neon") ||
8353 S.Context.getTargetInfo().hasFeature("mve") ||
8354 IsTargetCUDAAndHostARM)) {
8355 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8356 << Attr << "'neon' or 'mve'";
8357 Attr.setInvalid();
8358 return;
8360 // Check the attribute arguments.
8361 if (Attr.getNumArgs() != 1) {
8362 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8363 << Attr << 1;
8364 Attr.setInvalid();
8365 return;
8367 // The number of elements must be an ICE.
8368 llvm::APSInt numEltsInt(32);
8369 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8370 return;
8372 // Only certain element types are supported for Neon vectors.
8373 if (!isPermittedNeonBaseType(CurType, VecKind, S) &&
8374 !IsTargetCUDAAndHostARM) {
8375 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8376 Attr.setInvalid();
8377 return;
8380 // The total size of the vector must be 64 or 128 bits.
8381 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8382 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8383 unsigned vecSize = typeSize * numElts;
8384 if (vecSize != 64 && vecSize != 128) {
8385 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8386 Attr.setInvalid();
8387 return;
8390 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8393 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8394 /// used to create fixed-length versions of sizeless SVE types defined by
8395 /// the ACLE, such as svint32_t and svbool_t.
8396 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8397 Sema &S) {
8398 // Target must have SVE.
8399 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8400 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8401 Attr.setInvalid();
8402 return;
8405 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8406 // if <bits>+ syntax is used.
8407 if (!S.getLangOpts().VScaleMin ||
8408 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8409 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8410 << Attr;
8411 Attr.setInvalid();
8412 return;
8415 // Check the attribute arguments.
8416 if (Attr.getNumArgs() != 1) {
8417 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8418 << Attr << 1;
8419 Attr.setInvalid();
8420 return;
8423 // The vector size must be an integer constant expression.
8424 llvm::APSInt SveVectorSizeInBits(32);
8425 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8426 return;
8428 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8430 // The attribute vector size must match -msve-vector-bits.
8431 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8432 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8433 << VecSize << S.getLangOpts().VScaleMin * 128;
8434 Attr.setInvalid();
8435 return;
8438 // Attribute can only be attached to a single SVE vector or predicate type.
8439 if (!CurType->isSveVLSBuiltinType()) {
8440 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8441 << Attr << CurType;
8442 Attr.setInvalid();
8443 return;
8446 const auto *BT = CurType->castAs<BuiltinType>();
8448 QualType EltType = CurType->getSveEltType(S.Context);
8449 unsigned TypeSize = S.Context.getTypeSize(EltType);
8450 VectorKind VecKind = VectorKind::SveFixedLengthData;
8451 if (BT->getKind() == BuiltinType::SveBool) {
8452 // Predicates are represented as i8.
8453 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8454 VecKind = VectorKind::SveFixedLengthPredicate;
8455 } else
8456 VecSize /= TypeSize;
8457 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8460 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8461 QualType &CurType,
8462 ParsedAttr &Attr) {
8463 const VectorType *VT = dyn_cast<VectorType>(CurType);
8464 if (!VT || VT->getVectorKind() != VectorKind::Neon) {
8465 State.getSema().Diag(Attr.getLoc(),
8466 diag::err_attribute_arm_mve_polymorphism);
8467 Attr.setInvalid();
8468 return;
8471 CurType =
8472 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8473 State.getSema().Context, Attr),
8474 CurType, CurType);
8477 /// HandleRISCVRVVVectorBitsTypeAttr - The "riscv_rvv_vector_bits" attribute is
8478 /// used to create fixed-length versions of sizeless RVV types such as
8479 /// vint8m1_t_t.
8480 static void HandleRISCVRVVVectorBitsTypeAttr(QualType &CurType,
8481 ParsedAttr &Attr, Sema &S) {
8482 // Target must have vector extension.
8483 if (!S.Context.getTargetInfo().hasFeature("zve32x")) {
8484 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8485 << Attr << "'zve32x'";
8486 Attr.setInvalid();
8487 return;
8490 auto VScale = S.Context.getTargetInfo().getVScaleRange(S.getLangOpts());
8491 if (!VScale || !VScale->first || VScale->first != VScale->second) {
8492 S.Diag(Attr.getLoc(), diag::err_attribute_riscv_rvv_bits_unsupported)
8493 << Attr;
8494 Attr.setInvalid();
8495 return;
8498 // Check the attribute arguments.
8499 if (Attr.getNumArgs() != 1) {
8500 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8501 << Attr << 1;
8502 Attr.setInvalid();
8503 return;
8506 // The vector size must be an integer constant expression.
8507 llvm::APSInt RVVVectorSizeInBits(32);
8508 if (!verifyValidIntegerConstantExpr(S, Attr, RVVVectorSizeInBits))
8509 return;
8511 // Attribute can only be attached to a single RVV vector type.
8512 if (!CurType->isRVVVLSBuiltinType()) {
8513 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_rvv_type)
8514 << Attr << CurType;
8515 Attr.setInvalid();
8516 return;
8519 unsigned VecSize = static_cast<unsigned>(RVVVectorSizeInBits.getZExtValue());
8521 ASTContext::BuiltinVectorTypeInfo Info =
8522 S.Context.getBuiltinVectorTypeInfo(CurType->castAs<BuiltinType>());
8523 unsigned EltSize = S.Context.getTypeSize(Info.ElementType);
8524 unsigned MinElts = Info.EC.getKnownMinValue();
8526 // The attribute vector size must match -mrvv-vector-bits.
8527 unsigned ExpectedSize = VScale->first * MinElts * EltSize;
8528 if (VecSize != ExpectedSize) {
8529 S.Diag(Attr.getLoc(), diag::err_attribute_bad_rvv_vector_size)
8530 << VecSize << ExpectedSize;
8531 Attr.setInvalid();
8532 return;
8535 VectorKind VecKind = VectorKind::RVVFixedLengthData;
8536 VecSize /= EltSize;
8537 CurType = S.Context.getVectorType(Info.ElementType, VecSize, VecKind);
8540 /// Handle OpenCL Access Qualifier Attribute.
8541 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8542 Sema &S) {
8543 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8544 if (!(CurType->isImageType() || CurType->isPipeType())) {
8545 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8546 Attr.setInvalid();
8547 return;
8550 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8551 QualType BaseTy = TypedefTy->desugar();
8553 std::string PrevAccessQual;
8554 if (BaseTy->isPipeType()) {
8555 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8556 OpenCLAccessAttr *Attr =
8557 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8558 PrevAccessQual = Attr->getSpelling();
8559 } else {
8560 PrevAccessQual = "read_only";
8562 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8564 switch (ImgType->getKind()) {
8565 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8566 case BuiltinType::Id: \
8567 PrevAccessQual = #Access; \
8568 break;
8569 #include "clang/Basic/OpenCLImageTypes.def"
8570 default:
8571 llvm_unreachable("Unable to find corresponding image type.");
8573 } else {
8574 llvm_unreachable("unexpected type");
8576 StringRef AttrName = Attr.getAttrName()->getName();
8577 if (PrevAccessQual == AttrName.ltrim("_")) {
8578 // Duplicated qualifiers
8579 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8580 << AttrName << Attr.getRange();
8581 } else {
8582 // Contradicting qualifiers
8583 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8586 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8587 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8588 } else if (CurType->isPipeType()) {
8589 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8590 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8591 CurType = S.Context.getWritePipeType(ElemType);
8596 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8597 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8598 Sema &S) {
8599 if (!S.getLangOpts().MatrixTypes) {
8600 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8601 return;
8604 if (Attr.getNumArgs() != 2) {
8605 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8606 << Attr << 2;
8607 return;
8610 Expr *RowsExpr = Attr.getArgAsExpr(0);
8611 Expr *ColsExpr = Attr.getArgAsExpr(1);
8612 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8613 if (!T.isNull())
8614 CurType = T;
8617 static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8618 QualType &CurType, const ParsedAttr &PA) {
8619 Sema &S = State.getSema();
8621 if (PA.getNumArgs() < 1) {
8622 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8623 return;
8626 // Make sure that there is a string literal as the annotation's first
8627 // argument.
8628 StringRef Str;
8629 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8630 return;
8632 llvm::SmallVector<Expr *, 4> Args;
8633 Args.reserve(PA.getNumArgs() - 1);
8634 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8635 assert(!PA.isArgIdent(Idx));
8636 Args.push_back(PA.getArgAsExpr(Idx));
8638 if (!S.ConstantFoldAttrArgs(PA, Args))
8639 return;
8640 auto *AnnotateTypeAttr =
8641 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8642 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8645 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8646 QualType &CurType,
8647 ParsedAttr &Attr) {
8648 if (State.getDeclarator().isDeclarationOfFunction()) {
8649 CurType = State.getAttributedType(
8650 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8651 CurType, CurType);
8655 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8656 TypeAttrLocation TAL,
8657 const ParsedAttributesView &attrs,
8658 Sema::CUDAFunctionTarget CFT) {
8660 state.setParsedNoDeref(false);
8661 if (attrs.empty())
8662 return;
8664 // Scan through and apply attributes to this type where it makes sense. Some
8665 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8666 // type, but others can be present in the type specifiers even though they
8667 // apply to the decl. Here we apply type attributes and ignore the rest.
8669 // This loop modifies the list pretty frequently, but we still need to make
8670 // sure we visit every element once. Copy the attributes list, and iterate
8671 // over that.
8672 ParsedAttributesView AttrsCopy{attrs};
8673 for (ParsedAttr &attr : AttrsCopy) {
8675 // Skip attributes that were marked to be invalid.
8676 if (attr.isInvalid())
8677 continue;
8679 if (attr.isStandardAttributeSyntax() || attr.isRegularKeywordAttribute()) {
8680 // [[gnu::...]] attributes are treated as declaration attributes, so may
8681 // not appertain to a DeclaratorChunk. If we handle them as type
8682 // attributes, accept them in that position and diagnose the GCC
8683 // incompatibility.
8684 if (attr.isGNUScope()) {
8685 assert(attr.isStandardAttributeSyntax());
8686 bool IsTypeAttr = attr.isTypeAttr();
8687 if (TAL == TAL_DeclChunk) {
8688 state.getSema().Diag(attr.getLoc(),
8689 IsTypeAttr
8690 ? diag::warn_gcc_ignores_type_attr
8691 : diag::warn_cxx11_gnu_attribute_on_type)
8692 << attr;
8693 if (!IsTypeAttr)
8694 continue;
8696 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8697 !attr.isTypeAttr()) {
8698 // Otherwise, only consider type processing for a C++11 attribute if
8699 // - it has actually been applied to a type (decl-specifier-seq or
8700 // declarator chunk), or
8701 // - it is a type attribute, irrespective of where it was applied (so
8702 // that we can support the legacy behavior of some type attributes
8703 // that can be applied to the declaration name).
8704 continue;
8708 // If this is an attribute we can handle, do so now,
8709 // otherwise, add it to the FnAttrs list for rechaining.
8710 switch (attr.getKind()) {
8711 default:
8712 // A [[]] attribute on a declarator chunk must appertain to a type.
8713 if ((attr.isStandardAttributeSyntax() ||
8714 attr.isRegularKeywordAttribute()) &&
8715 TAL == TAL_DeclChunk) {
8716 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8717 << attr << attr.isRegularKeywordAttribute();
8718 attr.setUsedAsTypeAttr();
8720 break;
8722 case ParsedAttr::UnknownAttribute:
8723 if (attr.isStandardAttributeSyntax()) {
8724 state.getSema().Diag(attr.getLoc(),
8725 diag::warn_unknown_attribute_ignored)
8726 << attr << attr.getRange();
8727 // Mark the attribute as invalid so we don't emit the same diagnostic
8728 // multiple times.
8729 attr.setInvalid();
8731 break;
8733 case ParsedAttr::IgnoredAttribute:
8734 break;
8736 case ParsedAttr::AT_BTFTypeTag:
8737 HandleBTFTypeTagAttribute(type, attr, state);
8738 attr.setUsedAsTypeAttr();
8739 break;
8741 case ParsedAttr::AT_MayAlias:
8742 // FIXME: This attribute needs to actually be handled, but if we ignore
8743 // it it breaks large amounts of Linux software.
8744 attr.setUsedAsTypeAttr();
8745 break;
8746 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8747 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8748 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8749 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8750 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8751 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8752 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8753 case ParsedAttr::AT_HLSLGroupSharedAddressSpace:
8754 case ParsedAttr::AT_AddressSpace:
8755 HandleAddressSpaceTypeAttribute(type, attr, state);
8756 attr.setUsedAsTypeAttr();
8757 break;
8758 OBJC_POINTER_TYPE_ATTRS_CASELIST:
8759 if (!handleObjCPointerTypeAttr(state, attr, type))
8760 distributeObjCPointerTypeAttr(state, attr, type);
8761 attr.setUsedAsTypeAttr();
8762 break;
8763 case ParsedAttr::AT_VectorSize:
8764 HandleVectorSizeAttr(type, attr, state.getSema());
8765 attr.setUsedAsTypeAttr();
8766 break;
8767 case ParsedAttr::AT_ExtVectorType:
8768 HandleExtVectorTypeAttr(type, attr, state.getSema());
8769 attr.setUsedAsTypeAttr();
8770 break;
8771 case ParsedAttr::AT_NeonVectorType:
8772 HandleNeonVectorTypeAttr(type, attr, state.getSema(), VectorKind::Neon);
8773 attr.setUsedAsTypeAttr();
8774 break;
8775 case ParsedAttr::AT_NeonPolyVectorType:
8776 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8777 VectorKind::NeonPoly);
8778 attr.setUsedAsTypeAttr();
8779 break;
8780 case ParsedAttr::AT_ArmSveVectorBits:
8781 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8782 attr.setUsedAsTypeAttr();
8783 break;
8784 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8785 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8786 attr.setUsedAsTypeAttr();
8787 break;
8789 case ParsedAttr::AT_RISCVRVVVectorBits:
8790 HandleRISCVRVVVectorBitsTypeAttr(type, attr, state.getSema());
8791 attr.setUsedAsTypeAttr();
8792 break;
8793 case ParsedAttr::AT_OpenCLAccess:
8794 HandleOpenCLAccessAttr(type, attr, state.getSema());
8795 attr.setUsedAsTypeAttr();
8796 break;
8797 case ParsedAttr::AT_LifetimeBound:
8798 if (TAL == TAL_DeclChunk)
8799 HandleLifetimeBoundAttr(state, type, attr);
8800 break;
8802 case ParsedAttr::AT_NoDeref: {
8803 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8804 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8805 // For the time being, we simply emit a warning that the attribute is
8806 // ignored.
8807 if (attr.isStandardAttributeSyntax()) {
8808 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8809 << attr;
8810 break;
8812 ASTContext &Ctx = state.getSema().Context;
8813 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8814 type, type);
8815 attr.setUsedAsTypeAttr();
8816 state.setParsedNoDeref(true);
8817 break;
8820 case ParsedAttr::AT_MatrixType:
8821 HandleMatrixTypeAttr(type, attr, state.getSema());
8822 attr.setUsedAsTypeAttr();
8823 break;
8825 case ParsedAttr::AT_WebAssemblyFuncref: {
8826 if (!HandleWebAssemblyFuncrefAttr(state, type, attr))
8827 attr.setUsedAsTypeAttr();
8828 break;
8831 MS_TYPE_ATTRS_CASELIST:
8832 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8833 attr.setUsedAsTypeAttr();
8834 break;
8837 NULLABILITY_TYPE_ATTRS_CASELIST:
8838 // Either add nullability here or try to distribute it. We
8839 // don't want to distribute the nullability specifier past any
8840 // dependent type, because that complicates the user model.
8841 if (type->canHaveNullability() || type->isDependentType() ||
8842 type->isArrayType() ||
8843 !distributeNullabilityTypeAttr(state, type, attr)) {
8844 unsigned endIndex;
8845 if (TAL == TAL_DeclChunk)
8846 endIndex = state.getCurrentChunkIndex();
8847 else
8848 endIndex = state.getDeclarator().getNumTypeObjects();
8849 bool allowOnArrayType =
8850 state.getDeclarator().isPrototypeContext() &&
8851 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8852 if (checkNullabilityTypeSpecifier(
8853 state,
8854 type,
8855 attr,
8856 allowOnArrayType)) {
8857 attr.setInvalid();
8860 attr.setUsedAsTypeAttr();
8862 break;
8864 case ParsedAttr::AT_ObjCKindOf:
8865 // '__kindof' must be part of the decl-specifiers.
8866 switch (TAL) {
8867 case TAL_DeclSpec:
8868 break;
8870 case TAL_DeclChunk:
8871 case TAL_DeclName:
8872 state.getSema().Diag(attr.getLoc(),
8873 diag::err_objc_kindof_wrong_position)
8874 << FixItHint::CreateRemoval(attr.getLoc())
8875 << FixItHint::CreateInsertion(
8876 state.getDeclarator().getDeclSpec().getBeginLoc(),
8877 "__kindof ");
8878 break;
8881 // Apply it regardless.
8882 if (checkObjCKindOfType(state, type, attr))
8883 attr.setInvalid();
8884 break;
8886 case ParsedAttr::AT_NoThrow:
8887 // Exception Specifications aren't generally supported in C mode throughout
8888 // clang, so revert to attribute-based handling for C.
8889 if (!state.getSema().getLangOpts().CPlusPlus)
8890 break;
8891 [[fallthrough]];
8892 FUNCTION_TYPE_ATTRS_CASELIST:
8893 attr.setUsedAsTypeAttr();
8895 // Attributes with standard syntax have strict rules for what they
8896 // appertain to and hence should not use the "distribution" logic below.
8897 if (attr.isStandardAttributeSyntax() ||
8898 attr.isRegularKeywordAttribute()) {
8899 if (!handleFunctionTypeAttr(state, attr, type, CFT)) {
8900 diagnoseBadTypeAttribute(state.getSema(), attr, type);
8901 attr.setInvalid();
8903 break;
8906 // Never process function type attributes as part of the
8907 // declaration-specifiers.
8908 if (TAL == TAL_DeclSpec)
8909 distributeFunctionTypeAttrFromDeclSpec(state, attr, type, CFT);
8911 // Otherwise, handle the possible delays.
8912 else if (!handleFunctionTypeAttr(state, attr, type, CFT))
8913 distributeFunctionTypeAttr(state, attr, type);
8914 break;
8915 case ParsedAttr::AT_AcquireHandle: {
8916 if (!type->isFunctionType())
8917 return;
8919 if (attr.getNumArgs() != 1) {
8920 state.getSema().Diag(attr.getLoc(),
8921 diag::err_attribute_wrong_number_arguments)
8922 << attr << 1;
8923 attr.setInvalid();
8924 return;
8927 StringRef HandleType;
8928 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8929 return;
8930 type = state.getAttributedType(
8931 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8932 type, type);
8933 attr.setUsedAsTypeAttr();
8934 break;
8936 case ParsedAttr::AT_AnnotateType: {
8937 HandleAnnotateTypeAttr(state, type, attr);
8938 attr.setUsedAsTypeAttr();
8939 break;
8943 // Handle attributes that are defined in a macro. We do not want this to be
8944 // applied to ObjC builtin attributes.
8945 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8946 !type.getQualifiers().hasObjCLifetime() &&
8947 !type.getQualifiers().hasObjCGCAttr() &&
8948 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8949 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8950 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8951 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8952 state.setExpansionLocForMacroQualifiedType(
8953 cast<MacroQualifiedType>(type.getTypePtr()),
8954 attr.getMacroExpansionLoc());
8959 void Sema::completeExprArrayBound(Expr *E) {
8960 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8961 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8962 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8963 auto *Def = Var->getDefinition();
8964 if (!Def) {
8965 SourceLocation PointOfInstantiation = E->getExprLoc();
8966 runWithSufficientStackSpace(PointOfInstantiation, [&] {
8967 InstantiateVariableDefinition(PointOfInstantiation, Var);
8969 Def = Var->getDefinition();
8971 // If we don't already have a point of instantiation, and we managed
8972 // to instantiate a definition, this is the point of instantiation.
8973 // Otherwise, we don't request an end-of-TU instantiation, so this is
8974 // not a point of instantiation.
8975 // FIXME: Is this really the right behavior?
8976 if (Var->getPointOfInstantiation().isInvalid() && Def) {
8977 assert(Var->getTemplateSpecializationKind() ==
8978 TSK_ImplicitInstantiation &&
8979 "explicit instantiation with no point of instantiation");
8980 Var->setTemplateSpecializationKind(
8981 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8985 // Update the type to the definition's type both here and within the
8986 // expression.
8987 if (Def) {
8988 DRE->setDecl(Def);
8989 QualType T = Def->getType();
8990 DRE->setType(T);
8991 // FIXME: Update the type on all intervening expressions.
8992 E->setType(T);
8995 // We still go on to try to complete the type independently, as it
8996 // may also require instantiations or diagnostics if it remains
8997 // incomplete.
9003 QualType Sema::getCompletedType(Expr *E) {
9004 // Incomplete array types may be completed by the initializer attached to
9005 // their definitions. For static data members of class templates and for
9006 // variable templates, we need to instantiate the definition to get this
9007 // initializer and complete the type.
9008 if (E->getType()->isIncompleteArrayType())
9009 completeExprArrayBound(E);
9011 // FIXME: Are there other cases which require instantiating something other
9012 // than the type to complete the type of an expression?
9014 return E->getType();
9017 /// Ensure that the type of the given expression is complete.
9019 /// This routine checks whether the expression \p E has a complete type. If the
9020 /// expression refers to an instantiable construct, that instantiation is
9021 /// performed as needed to complete its type. Furthermore
9022 /// Sema::RequireCompleteType is called for the expression's type (or in the
9023 /// case of a reference type, the referred-to type).
9025 /// \param E The expression whose type is required to be complete.
9026 /// \param Kind Selects which completeness rules should be applied.
9027 /// \param Diagnoser The object that will emit a diagnostic if the type is
9028 /// incomplete.
9030 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
9031 /// otherwise.
9032 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
9033 TypeDiagnoser &Diagnoser) {
9034 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
9035 Diagnoser);
9038 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
9039 BoundTypeDiagnoser<> Diagnoser(DiagID);
9040 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
9043 /// Ensure that the type T is a complete type.
9045 /// This routine checks whether the type @p T is complete in any
9046 /// context where a complete type is required. If @p T is a complete
9047 /// type, returns false. If @p T is a class template specialization,
9048 /// this routine then attempts to perform class template
9049 /// instantiation. If instantiation fails, or if @p T is incomplete
9050 /// and cannot be completed, issues the diagnostic @p diag (giving it
9051 /// the type @p T) and returns true.
9053 /// @param Loc The location in the source that the incomplete type
9054 /// diagnostic should refer to.
9056 /// @param T The type that this routine is examining for completeness.
9058 /// @param Kind Selects which completeness rules should be applied.
9060 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
9061 /// @c false otherwise.
9062 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9063 CompleteTypeKind Kind,
9064 TypeDiagnoser &Diagnoser) {
9065 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
9066 return true;
9067 if (const TagType *Tag = T->getAs<TagType>()) {
9068 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
9069 Tag->getDecl()->setCompleteDefinitionRequired();
9070 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
9073 return false;
9076 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
9077 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
9078 if (!Suggested)
9079 return false;
9081 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
9082 // and isolate from other C++ specific checks.
9083 StructuralEquivalenceContext Ctx(
9084 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
9085 StructuralEquivalenceKind::Default,
9086 false /*StrictTypeSpelling*/, true /*Complain*/,
9087 true /*ErrorOnTagTypeMismatch*/);
9088 return Ctx.IsEquivalent(D, Suggested);
9091 bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
9092 AcceptableKind Kind, bool OnlyNeedComplete) {
9093 // Easy case: if we don't have modules, all declarations are visible.
9094 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
9095 return true;
9097 // If this definition was instantiated from a template, map back to the
9098 // pattern from which it was instantiated.
9099 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
9100 // We're in the middle of defining it; this definition should be treated
9101 // as visible.
9102 return true;
9103 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
9104 if (auto *Pattern = RD->getTemplateInstantiationPattern())
9105 RD = Pattern;
9106 D = RD->getDefinition();
9107 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
9108 if (auto *Pattern = ED->getTemplateInstantiationPattern())
9109 ED = Pattern;
9110 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
9111 // If the enum has a fixed underlying type, it may have been forward
9112 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
9113 // the enum and assign it the underlying type of `int`. Since we're only
9114 // looking for a complete type (not a definition), any visible declaration
9115 // of it will do.
9116 *Suggested = nullptr;
9117 for (auto *Redecl : ED->redecls()) {
9118 if (isAcceptable(Redecl, Kind))
9119 return true;
9120 if (Redecl->isThisDeclarationADefinition() ||
9121 (Redecl->isCanonicalDecl() && !*Suggested))
9122 *Suggested = Redecl;
9125 return false;
9127 D = ED->getDefinition();
9128 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
9129 if (auto *Pattern = FD->getTemplateInstantiationPattern())
9130 FD = Pattern;
9131 D = FD->getDefinition();
9132 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
9133 if (auto *Pattern = VD->getTemplateInstantiationPattern())
9134 VD = Pattern;
9135 D = VD->getDefinition();
9138 assert(D && "missing definition for pattern of instantiated definition");
9140 *Suggested = D;
9142 auto DefinitionIsAcceptable = [&] {
9143 // The (primary) definition might be in a visible module.
9144 if (isAcceptable(D, Kind))
9145 return true;
9147 // A visible module might have a merged definition instead.
9148 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
9149 : hasVisibleMergedDefinition(D)) {
9150 if (CodeSynthesisContexts.empty() &&
9151 !getLangOpts().ModulesLocalVisibility) {
9152 // Cache the fact that this definition is implicitly visible because
9153 // there is a visible merged definition.
9154 D->setVisibleDespiteOwningModule();
9156 return true;
9159 return false;
9162 if (DefinitionIsAcceptable())
9163 return true;
9165 // The external source may have additional definitions of this entity that are
9166 // visible, so complete the redeclaration chain now and ask again.
9167 if (auto *Source = Context.getExternalSource()) {
9168 Source->CompleteRedeclChain(D);
9169 return DefinitionIsAcceptable();
9172 return false;
9175 /// Determine whether there is any declaration of \p D that was ever a
9176 /// definition (perhaps before module merging) and is currently visible.
9177 /// \param D The definition of the entity.
9178 /// \param Suggested Filled in with the declaration that should be made visible
9179 /// in order to provide a definition of this entity.
9180 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9181 /// not defined. This only matters for enums with a fixed underlying
9182 /// type, since in all other cases, a type is complete if and only if it
9183 /// is defined.
9184 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
9185 bool OnlyNeedComplete) {
9186 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
9187 OnlyNeedComplete);
9190 /// Determine whether there is any declaration of \p D that was ever a
9191 /// definition (perhaps before module merging) and is currently
9192 /// reachable.
9193 /// \param D The definition of the entity.
9194 /// \param Suggested Filled in with the declaration that should be made
9195 /// reachable
9196 /// in order to provide a definition of this entity.
9197 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
9198 /// not defined. This only matters for enums with a fixed underlying
9199 /// type, since in all other cases, a type is complete if and only if it
9200 /// is defined.
9201 bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
9202 bool OnlyNeedComplete) {
9203 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
9204 OnlyNeedComplete);
9207 /// Locks in the inheritance model for the given class and all of its bases.
9208 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
9209 RD = RD->getMostRecentNonInjectedDecl();
9210 if (!RD->hasAttr<MSInheritanceAttr>()) {
9211 MSInheritanceModel IM;
9212 bool BestCase = false;
9213 switch (S.MSPointerToMemberRepresentationMethod) {
9214 case LangOptions::PPTMK_BestCase:
9215 BestCase = true;
9216 IM = RD->calculateInheritanceModel();
9217 break;
9218 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
9219 IM = MSInheritanceModel::Single;
9220 break;
9221 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
9222 IM = MSInheritanceModel::Multiple;
9223 break;
9224 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
9225 IM = MSInheritanceModel::Unspecified;
9226 break;
9229 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
9230 ? S.ImplicitMSInheritanceAttrLoc
9231 : RD->getSourceRange();
9232 RD->addAttr(MSInheritanceAttr::CreateImplicit(
9233 S.getASTContext(), BestCase, Loc, MSInheritanceAttr::Spelling(IM)));
9234 S.Consumer.AssignInheritanceModel(RD);
9238 /// The implementation of RequireCompleteType
9239 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
9240 CompleteTypeKind Kind,
9241 TypeDiagnoser *Diagnoser) {
9242 // FIXME: Add this assertion to make sure we always get instantiation points.
9243 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
9244 // FIXME: Add this assertion to help us flush out problems with
9245 // checking for dependent types and type-dependent expressions.
9247 // assert(!T->isDependentType() &&
9248 // "Can't ask whether a dependent type is complete");
9250 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
9251 if (!MPTy->getClass()->isDependentType()) {
9252 if (getLangOpts().CompleteMemberPointers &&
9253 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
9254 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
9255 diag::err_memptr_incomplete))
9256 return true;
9258 // We lock in the inheritance model once somebody has asked us to ensure
9259 // that a pointer-to-member type is complete.
9260 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
9261 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
9262 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
9267 NamedDecl *Def = nullptr;
9268 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
9269 bool Incomplete = (T->isIncompleteType(&Def) ||
9270 (!AcceptSizeless && T->isSizelessBuiltinType()));
9272 // Check that any necessary explicit specializations are visible. For an
9273 // enum, we just need the declaration, so don't check this.
9274 if (Def && !isa<EnumDecl>(Def))
9275 checkSpecializationReachability(Loc, Def);
9277 // If we have a complete type, we're done.
9278 if (!Incomplete) {
9279 NamedDecl *Suggested = nullptr;
9280 if (Def &&
9281 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
9282 // If the user is going to see an error here, recover by making the
9283 // definition visible.
9284 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
9285 if (Diagnoser && Suggested)
9286 diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
9287 /*Recover*/ TreatAsComplete);
9288 return !TreatAsComplete;
9289 } else if (Def && !TemplateInstCallbacks.empty()) {
9290 CodeSynthesisContext TempInst;
9291 TempInst.Kind = CodeSynthesisContext::Memoization;
9292 TempInst.Template = Def;
9293 TempInst.Entity = Def;
9294 TempInst.PointOfInstantiation = Loc;
9295 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
9296 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
9299 return false;
9302 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
9303 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
9305 // Give the external source a chance to provide a definition of the type.
9306 // This is kept separate from completing the redeclaration chain so that
9307 // external sources such as LLDB can avoid synthesizing a type definition
9308 // unless it's actually needed.
9309 if (Tag || IFace) {
9310 // Avoid diagnosing invalid decls as incomplete.
9311 if (Def->isInvalidDecl())
9312 return true;
9314 // Give the external AST source a chance to complete the type.
9315 if (auto *Source = Context.getExternalSource()) {
9316 if (Tag && Tag->hasExternalLexicalStorage())
9317 Source->CompleteType(Tag);
9318 if (IFace && IFace->hasExternalLexicalStorage())
9319 Source->CompleteType(IFace);
9320 // If the external source completed the type, go through the motions
9321 // again to ensure we're allowed to use the completed type.
9322 if (!T->isIncompleteType())
9323 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9327 // If we have a class template specialization or a class member of a
9328 // class template specialization, or an array with known size of such,
9329 // try to instantiate it.
9330 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
9331 bool Instantiated = false;
9332 bool Diagnosed = false;
9333 if (RD->isDependentContext()) {
9334 // Don't try to instantiate a dependent class (eg, a member template of
9335 // an instantiated class template specialization).
9336 // FIXME: Can this ever happen?
9337 } else if (auto *ClassTemplateSpec =
9338 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
9339 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
9340 runWithSufficientStackSpace(Loc, [&] {
9341 Diagnosed = InstantiateClassTemplateSpecialization(
9342 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
9343 /*Complain=*/Diagnoser);
9345 Instantiated = true;
9347 } else {
9348 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
9349 if (!RD->isBeingDefined() && Pattern) {
9350 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
9351 assert(MSI && "Missing member specialization information?");
9352 // This record was instantiated from a class within a template.
9353 if (MSI->getTemplateSpecializationKind() !=
9354 TSK_ExplicitSpecialization) {
9355 runWithSufficientStackSpace(Loc, [&] {
9356 Diagnosed = InstantiateClass(Loc, RD, Pattern,
9357 getTemplateInstantiationArgs(RD),
9358 TSK_ImplicitInstantiation,
9359 /*Complain=*/Diagnoser);
9361 Instantiated = true;
9366 if (Instantiated) {
9367 // Instantiate* might have already complained that the template is not
9368 // defined, if we asked it to.
9369 if (Diagnoser && Diagnosed)
9370 return true;
9371 // If we instantiated a definition, check that it's usable, even if
9372 // instantiation produced an error, so that repeated calls to this
9373 // function give consistent answers.
9374 if (!T->isIncompleteType())
9375 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
9379 // FIXME: If we didn't instantiate a definition because of an explicit
9380 // specialization declaration, check that it's visible.
9382 if (!Diagnoser)
9383 return true;
9385 Diagnoser->diagnose(*this, Loc, T);
9387 // If the type was a forward declaration of a class/struct/union
9388 // type, produce a note.
9389 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
9390 Diag(Tag->getLocation(),
9391 Tag->isBeingDefined() ? diag::note_type_being_defined
9392 : diag::note_forward_declaration)
9393 << Context.getTagDeclType(Tag);
9395 // If the Objective-C class was a forward declaration, produce a note.
9396 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
9397 Diag(IFace->getLocation(), diag::note_forward_class);
9399 // If we have external information that we can use to suggest a fix,
9400 // produce a note.
9401 if (ExternalSource)
9402 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
9404 return true;
9407 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9408 CompleteTypeKind Kind, unsigned DiagID) {
9409 BoundTypeDiagnoser<> Diagnoser(DiagID);
9410 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9413 /// Get diagnostic %select index for tag kind for
9414 /// literal type diagnostic message.
9415 /// WARNING: Indexes apply to particular diagnostics only!
9417 /// \returns diagnostic %select index.
9418 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9419 switch (Tag) {
9420 case TTK_Struct: return 0;
9421 case TTK_Interface: return 1;
9422 case TTK_Class: return 2;
9423 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9427 /// Ensure that the type T is a literal type.
9429 /// This routine checks whether the type @p T is a literal type. If @p T is an
9430 /// incomplete type, an attempt is made to complete it. If @p T is a literal
9431 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9432 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9433 /// it the type @p T), along with notes explaining why the type is not a
9434 /// literal type, and returns true.
9436 /// @param Loc The location in the source that the non-literal type
9437 /// diagnostic should refer to.
9439 /// @param T The type that this routine is examining for literalness.
9441 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
9443 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9444 /// @c false otherwise.
9445 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9446 TypeDiagnoser &Diagnoser) {
9447 assert(!T->isDependentType() && "type should not be dependent");
9449 QualType ElemType = Context.getBaseElementType(T);
9450 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9451 T->isLiteralType(Context))
9452 return false;
9454 Diagnoser.diagnose(*this, Loc, T);
9456 if (T->isVariableArrayType())
9457 return true;
9459 const RecordType *RT = ElemType->getAs<RecordType>();
9460 if (!RT)
9461 return true;
9463 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9465 // A partially-defined class type can't be a literal type, because a literal
9466 // class type must have a trivial destructor (which can't be checked until
9467 // the class definition is complete).
9468 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9469 return true;
9471 // [expr.prim.lambda]p3:
9472 // This class type is [not] a literal type.
9473 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9474 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9475 return true;
9478 // If the class has virtual base classes, then it's not an aggregate, and
9479 // cannot have any constexpr constructors or a trivial default constructor,
9480 // so is non-literal. This is better to diagnose than the resulting absence
9481 // of constexpr constructors.
9482 if (RD->getNumVBases()) {
9483 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9484 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9485 for (const auto &I : RD->vbases())
9486 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9487 << I.getSourceRange();
9488 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9489 !RD->hasTrivialDefaultConstructor()) {
9490 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9491 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9492 for (const auto &I : RD->bases()) {
9493 if (!I.getType()->isLiteralType(Context)) {
9494 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9495 << RD << I.getType() << I.getSourceRange();
9496 return true;
9499 for (const auto *I : RD->fields()) {
9500 if (!I->getType()->isLiteralType(Context) ||
9501 I->getType().isVolatileQualified()) {
9502 Diag(I->getLocation(), diag::note_non_literal_field)
9503 << RD << I << I->getType()
9504 << I->getType().isVolatileQualified();
9505 return true;
9508 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9509 : !RD->hasTrivialDestructor()) {
9510 // All fields and bases are of literal types, so have trivial or constexpr
9511 // destructors. If this class's destructor is non-trivial / non-constexpr,
9512 // it must be user-declared.
9513 CXXDestructorDecl *Dtor = RD->getDestructor();
9514 assert(Dtor && "class has literal fields and bases but no dtor?");
9515 if (!Dtor)
9516 return true;
9518 if (getLangOpts().CPlusPlus20) {
9519 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9520 << RD;
9521 } else {
9522 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9523 ? diag::note_non_literal_user_provided_dtor
9524 : diag::note_non_literal_nontrivial_dtor)
9525 << RD;
9526 if (!Dtor->isUserProvided())
9527 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9528 /*Diagnose*/ true);
9532 return true;
9535 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9536 BoundTypeDiagnoser<> Diagnoser(DiagID);
9537 return RequireLiteralType(Loc, T, Diagnoser);
9540 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9541 /// by the nested-name-specifier contained in SS, and that is (re)declared by
9542 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9543 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9544 const CXXScopeSpec &SS, QualType T,
9545 TagDecl *OwnedTagDecl) {
9546 if (T.isNull())
9547 return T;
9548 return Context.getElaboratedType(
9549 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9552 QualType Sema::BuildTypeofExprType(Expr *E, TypeOfKind Kind) {
9553 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9555 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9556 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield)
9557 << (Kind == TypeOfKind::Unqualified ? 3 : 2);
9559 if (!E->isTypeDependent()) {
9560 QualType T = E->getType();
9561 if (const TagType *TT = T->getAs<TagType>())
9562 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9564 return Context.getTypeOfExprType(E, Kind);
9567 /// getDecltypeForExpr - Given an expr, will return the decltype for
9568 /// that expression, according to the rules in C++11
9569 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9570 QualType Sema::getDecltypeForExpr(Expr *E) {
9571 if (E->isTypeDependent())
9572 return Context.DependentTy;
9574 Expr *IDExpr = E;
9575 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9576 IDExpr = ImplCastExpr->getSubExpr();
9578 // C++11 [dcl.type.simple]p4:
9579 // The type denoted by decltype(e) is defined as follows:
9581 // C++20:
9582 // - if E is an unparenthesized id-expression naming a non-type
9583 // template-parameter (13.2), decltype(E) is the type of the
9584 // template-parameter after performing any necessary type deduction
9585 // Note that this does not pick up the implicit 'const' for a template
9586 // parameter object. This rule makes no difference before C++20 so we apply
9587 // it unconditionally.
9588 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9589 return SNTTPE->getParameterType(Context);
9591 // - if e is an unparenthesized id-expression or an unparenthesized class
9592 // member access (5.2.5), decltype(e) is the type of the entity named
9593 // by e. If there is no such entity, or if e names a set of overloaded
9594 // functions, the program is ill-formed;
9596 // We apply the same rules for Objective-C ivar and property references.
9597 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9598 const ValueDecl *VD = DRE->getDecl();
9599 QualType T = VD->getType();
9600 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9602 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9603 if (const auto *VD = ME->getMemberDecl())
9604 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9605 return VD->getType();
9606 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9607 return IR->getDecl()->getType();
9608 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9609 if (PR->isExplicitProperty())
9610 return PR->getExplicitProperty()->getType();
9611 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9612 return PE->getType();
9615 // C++11 [expr.lambda.prim]p18:
9616 // Every occurrence of decltype((x)) where x is a possibly
9617 // parenthesized id-expression that names an entity of automatic
9618 // storage duration is treated as if x were transformed into an
9619 // access to a corresponding data member of the closure type that
9620 // would have been declared if x were an odr-use of the denoted
9621 // entity.
9622 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9623 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9624 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9625 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9626 if (!T.isNull())
9627 return Context.getLValueReferenceType(T);
9632 return Context.getReferenceQualifiedType(E);
9635 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9636 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9638 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9639 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9640 // The expression operand for decltype is in an unevaluated expression
9641 // context, so side effects could result in unintended consequences.
9642 // Exclude instantiation-dependent expressions, because 'decltype' is often
9643 // used to build SFINAE gadgets.
9644 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9646 return Context.getDecltypeType(E, getDecltypeForExpr(E));
9649 static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9650 SourceLocation Loc) {
9651 assert(BaseType->isEnumeralType());
9652 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9653 assert(ED && "EnumType has no EnumDecl");
9655 S.DiagnoseUseOfDecl(ED, Loc);
9657 QualType Underlying = ED->getIntegerType();
9658 assert(!Underlying.isNull());
9660 return Underlying;
9663 QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9664 SourceLocation Loc) {
9665 if (!BaseType->isEnumeralType()) {
9666 Diag(Loc, diag::err_only_enums_have_underlying_types);
9667 return QualType();
9670 // The enum could be incomplete if we're parsing its definition or
9671 // recovering from an error.
9672 NamedDecl *FwdDecl = nullptr;
9673 if (BaseType->isIncompleteType(&FwdDecl)) {
9674 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9675 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9676 return QualType();
9679 return GetEnumUnderlyingType(*this, BaseType, Loc);
9682 QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9683 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9684 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9685 DeclarationName())
9686 : BaseType;
9688 return Pointer.isNull() ? QualType() : Pointer;
9691 QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9692 // We don't want block pointers or ObjectiveC's id type.
9693 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9694 return BaseType;
9696 return BaseType->getPointeeType();
9699 QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9700 QualType Underlying = BaseType.getNonReferenceType();
9701 if (Underlying->isArrayType())
9702 return Context.getDecayedType(Underlying);
9704 if (Underlying->isFunctionType())
9705 return BuiltinAddPointer(BaseType, Loc);
9707 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9708 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9709 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9710 // '__decay(T)' so that it removes all qualifiers.
9711 Split.Quals.removeCVRQualifiers();
9712 return Context.getQualifiedType(Split);
9715 QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9716 SourceLocation Loc) {
9717 assert(LangOpts.CPlusPlus);
9718 QualType Reference =
9719 BaseType.isReferenceable()
9720 ? BuildReferenceType(BaseType,
9721 UKind == UnaryTransformType::AddLvalueReference,
9722 Loc, DeclarationName())
9723 : BaseType;
9724 return Reference.isNull() ? QualType() : Reference;
9727 QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9728 SourceLocation Loc) {
9729 if (UKind == UnaryTransformType::RemoveAllExtents)
9730 return Context.getBaseElementType(BaseType);
9732 if (const auto *AT = Context.getAsArrayType(BaseType))
9733 return AT->getElementType();
9735 return BaseType;
9738 QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9739 SourceLocation Loc) {
9740 assert(LangOpts.CPlusPlus);
9741 QualType T = BaseType.getNonReferenceType();
9742 if (UKind == UTTKind::RemoveCVRef &&
9743 (T.isConstQualified() || T.isVolatileQualified())) {
9744 Qualifiers Quals;
9745 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9746 Quals.removeConst();
9747 Quals.removeVolatile();
9748 T = Context.getQualifiedType(Unqual, Quals);
9750 return T;
9753 QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9754 SourceLocation Loc) {
9755 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9756 BaseType->isFunctionType())
9757 return BaseType;
9759 Qualifiers Quals;
9760 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9762 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9763 Quals.removeConst();
9764 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9765 Quals.removeVolatile();
9766 if (UKind == UTTKind::RemoveRestrict)
9767 Quals.removeRestrict();
9769 return Context.getQualifiedType(Unqual, Quals);
9772 static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9773 bool IsMakeSigned,
9774 SourceLocation Loc) {
9775 if (BaseType->isEnumeralType()) {
9776 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9777 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9778 unsigned int Bits = BitInt->getNumBits();
9779 if (Bits > 1)
9780 return S.Context.getBitIntType(!IsMakeSigned, Bits);
9782 S.Diag(Loc, diag::err_make_signed_integral_only)
9783 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9784 return QualType();
9786 if (Underlying->isBooleanType()) {
9787 S.Diag(Loc, diag::err_make_signed_integral_only)
9788 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9789 << Underlying;
9790 return QualType();
9794 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9795 std::array<CanQualType *, 6> AllSignedIntegers = {
9796 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
9797 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
9798 ArrayRef<CanQualType *> AvailableSignedIntegers(
9799 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9800 std::array<CanQualType *, 6> AllUnsignedIntegers = {
9801 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
9802 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
9803 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9804 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9805 AllUnsignedIntegers.size() -
9806 Int128Unsupported);
9807 ArrayRef<CanQualType *> *Consider =
9808 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9810 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9811 auto *Result =
9812 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9813 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9816 assert(Result != Consider->end());
9817 return QualType((*Result)->getTypePtr(), 0);
9820 QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9821 SourceLocation Loc) {
9822 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9823 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9824 BaseType->isBooleanType() ||
9825 (BaseType->isBitIntType() &&
9826 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9827 Diag(Loc, diag::err_make_signed_integral_only)
9828 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9829 return QualType();
9832 bool IsNonIntIntegral =
9833 BaseType->isChar16Type() || BaseType->isChar32Type() ||
9834 BaseType->isWideCharType() || BaseType->isEnumeralType();
9836 QualType Underlying =
9837 IsNonIntIntegral
9838 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9839 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9840 : Context.getCorrespondingUnsignedType(BaseType);
9841 if (Underlying.isNull())
9842 return Underlying;
9843 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9846 QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9847 SourceLocation Loc) {
9848 if (BaseType->isDependentType())
9849 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9850 QualType Result;
9851 switch (UKind) {
9852 case UnaryTransformType::EnumUnderlyingType: {
9853 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9854 break;
9856 case UnaryTransformType::AddPointer: {
9857 Result = BuiltinAddPointer(BaseType, Loc);
9858 break;
9860 case UnaryTransformType::RemovePointer: {
9861 Result = BuiltinRemovePointer(BaseType, Loc);
9862 break;
9864 case UnaryTransformType::Decay: {
9865 Result = BuiltinDecay(BaseType, Loc);
9866 break;
9868 case UnaryTransformType::AddLvalueReference:
9869 case UnaryTransformType::AddRvalueReference: {
9870 Result = BuiltinAddReference(BaseType, UKind, Loc);
9871 break;
9873 case UnaryTransformType::RemoveAllExtents:
9874 case UnaryTransformType::RemoveExtent: {
9875 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9876 break;
9878 case UnaryTransformType::RemoveCVRef:
9879 case UnaryTransformType::RemoveReference: {
9880 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9881 break;
9883 case UnaryTransformType::RemoveConst:
9884 case UnaryTransformType::RemoveCV:
9885 case UnaryTransformType::RemoveRestrict:
9886 case UnaryTransformType::RemoveVolatile: {
9887 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9888 break;
9890 case UnaryTransformType::MakeSigned:
9891 case UnaryTransformType::MakeUnsigned: {
9892 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9893 break;
9897 return !Result.isNull()
9898 ? Context.getUnaryTransformType(BaseType, Result, UKind)
9899 : Result;
9902 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9903 if (!isDependentOrGNUAutoType(T)) {
9904 // FIXME: It isn't entirely clear whether incomplete atomic types
9905 // are allowed or not; for simplicity, ban them for the moment.
9906 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9907 return QualType();
9909 int DisallowedKind = -1;
9910 if (T->isArrayType())
9911 DisallowedKind = 1;
9912 else if (T->isFunctionType())
9913 DisallowedKind = 2;
9914 else if (T->isReferenceType())
9915 DisallowedKind = 3;
9916 else if (T->isAtomicType())
9917 DisallowedKind = 4;
9918 else if (T.hasQualifiers())
9919 DisallowedKind = 5;
9920 else if (T->isSizelessType())
9921 DisallowedKind = 6;
9922 else if (!T.isTriviallyCopyableType(Context) && getLangOpts().CPlusPlus)
9923 // Some other non-trivially-copyable type (probably a C++ class)
9924 DisallowedKind = 7;
9925 else if (T->isBitIntType())
9926 DisallowedKind = 8;
9927 else if (getLangOpts().C23 && T->isUndeducedAutoType())
9928 // _Atomic auto is prohibited in C23
9929 DisallowedKind = 9;
9931 if (DisallowedKind != -1) {
9932 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9933 return QualType();
9936 // FIXME: Do we need any handling for ARC here?
9939 // Build the pointer type.
9940 return Context.getAtomicType(T);