[docs] Fix build-docs.sh
[llvm-project.git] / clang / lib / Sema / SemaType.cpp
blob04e3b00682a0516e63e87cc63a9cd35893f45f07
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/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/Type.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/SourceLocation.h"
27 #include "clang/Basic/Specifiers.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "clang/Lex/Preprocessor.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ParsedTemplate.h"
34 #include "clang/Sema/ScopeInfo.h"
35 #include "clang/Sema/SemaInternal.h"
36 #include "clang/Sema/Template.h"
37 #include "clang/Sema/TemplateInstCallback.h"
38 #include "llvm/ADT/ArrayRef.h"
39 #include "llvm/ADT/SmallPtrSet.h"
40 #include "llvm/ADT/SmallString.h"
41 #include "llvm/IR/DerivedTypes.h"
42 #include "llvm/Support/ErrorHandling.h"
43 #include <bitset>
45 using namespace clang;
47 enum TypeDiagSelector {
48 TDS_Function,
49 TDS_Pointer,
50 TDS_ObjCObjOrBlock
53 /// isOmittedBlockReturnType - Return true if this declarator is missing a
54 /// return type because this is a omitted return type on a block literal.
55 static bool isOmittedBlockReturnType(const Declarator &D) {
56 if (D.getContext() != DeclaratorContext::BlockLiteral ||
57 D.getDeclSpec().hasTypeSpecifier())
58 return false;
60 if (D.getNumTypeObjects() == 0)
61 return true; // ^{ ... }
63 if (D.getNumTypeObjects() == 1 &&
64 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
65 return true; // ^(int X, float Y) { ... }
67 return false;
70 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
71 /// doesn't apply to the given type.
72 static void diagnoseBadTypeAttribute(Sema &S, const ParsedAttr &attr,
73 QualType type) {
74 TypeDiagSelector WhichType;
75 bool useExpansionLoc = true;
76 switch (attr.getKind()) {
77 case ParsedAttr::AT_ObjCGC:
78 WhichType = TDS_Pointer;
79 break;
80 case ParsedAttr::AT_ObjCOwnership:
81 WhichType = TDS_ObjCObjOrBlock;
82 break;
83 default:
84 // Assume everything else was a function attribute.
85 WhichType = TDS_Function;
86 useExpansionLoc = false;
87 break;
90 SourceLocation loc = attr.getLoc();
91 StringRef name = attr.getAttrName()->getName();
93 // The GC attributes are usually written with macros; special-case them.
94 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
95 : nullptr;
96 if (useExpansionLoc && loc.isMacroID() && II) {
97 if (II->isStr("strong")) {
98 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
99 } else if (II->isStr("weak")) {
100 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
104 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
105 << type;
108 // objc_gc applies to Objective-C pointers or, otherwise, to the
109 // smallest available pointer type (i.e. 'void*' in 'void**').
110 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
111 case ParsedAttr::AT_ObjCGC: \
112 case ParsedAttr::AT_ObjCOwnership
114 // Calling convention attributes.
115 #define CALLING_CONV_ATTRS_CASELIST \
116 case ParsedAttr::AT_CDecl: \
117 case ParsedAttr::AT_FastCall: \
118 case ParsedAttr::AT_StdCall: \
119 case ParsedAttr::AT_ThisCall: \
120 case ParsedAttr::AT_RegCall: \
121 case ParsedAttr::AT_Pascal: \
122 case ParsedAttr::AT_SwiftCall: \
123 case ParsedAttr::AT_SwiftAsyncCall: \
124 case ParsedAttr::AT_VectorCall: \
125 case ParsedAttr::AT_AArch64VectorPcs: \
126 case ParsedAttr::AT_AArch64SVEPcs: \
127 case ParsedAttr::AT_AMDGPUKernelCall: \
128 case ParsedAttr::AT_MSABI: \
129 case ParsedAttr::AT_SysVABI: \
130 case ParsedAttr::AT_Pcs: \
131 case ParsedAttr::AT_IntelOclBicc: \
132 case ParsedAttr::AT_PreserveMost: \
133 case ParsedAttr::AT_PreserveAll
135 // Function type attributes.
136 #define FUNCTION_TYPE_ATTRS_CASELIST \
137 case ParsedAttr::AT_NSReturnsRetained: \
138 case ParsedAttr::AT_NoReturn: \
139 case ParsedAttr::AT_Regparm: \
140 case ParsedAttr::AT_CmseNSCall: \
141 case ParsedAttr::AT_AnyX86NoCallerSavedRegisters: \
142 case ParsedAttr::AT_AnyX86NoCfCheck: \
143 CALLING_CONV_ATTRS_CASELIST
145 // Microsoft-specific type qualifiers.
146 #define MS_TYPE_ATTRS_CASELIST \
147 case ParsedAttr::AT_Ptr32: \
148 case ParsedAttr::AT_Ptr64: \
149 case ParsedAttr::AT_SPtr: \
150 case ParsedAttr::AT_UPtr
152 // Nullability qualifiers.
153 #define NULLABILITY_TYPE_ATTRS_CASELIST \
154 case ParsedAttr::AT_TypeNonNull: \
155 case ParsedAttr::AT_TypeNullable: \
156 case ParsedAttr::AT_TypeNullableResult: \
157 case ParsedAttr::AT_TypeNullUnspecified
159 namespace {
160 /// An object which stores processing state for the entire
161 /// GetTypeForDeclarator process.
162 class TypeProcessingState {
163 Sema &sema;
165 /// The declarator being processed.
166 Declarator &declarator;
168 /// The index of the declarator chunk we're currently processing.
169 /// May be the total number of valid chunks, indicating the
170 /// DeclSpec.
171 unsigned chunkIndex;
173 /// The original set of attributes on the DeclSpec.
174 SmallVector<ParsedAttr *, 2> savedAttrs;
176 /// A list of attributes to diagnose the uselessness of when the
177 /// processing is complete.
178 SmallVector<ParsedAttr *, 2> ignoredTypeAttrs;
180 /// Attributes corresponding to AttributedTypeLocs that we have not yet
181 /// populated.
182 // FIXME: The two-phase mechanism by which we construct Types and fill
183 // their TypeLocs makes it hard to correctly assign these. We keep the
184 // attributes in creation order as an attempt to make them line up
185 // properly.
186 using TypeAttrPair = std::pair<const AttributedType*, const Attr*>;
187 SmallVector<TypeAttrPair, 8> AttrsForTypes;
188 bool AttrsForTypesSorted = true;
190 /// MacroQualifiedTypes mapping to macro expansion locations that will be
191 /// stored in a MacroQualifiedTypeLoc.
192 llvm::DenseMap<const MacroQualifiedType *, SourceLocation> LocsForMacros;
194 /// Flag to indicate we parsed a noderef attribute. This is used for
195 /// validating that noderef was used on a pointer or array.
196 bool parsedNoDeref;
198 public:
199 TypeProcessingState(Sema &sema, Declarator &declarator)
200 : sema(sema), declarator(declarator),
201 chunkIndex(declarator.getNumTypeObjects()), parsedNoDeref(false) {}
203 Sema &getSema() const {
204 return sema;
207 Declarator &getDeclarator() const {
208 return declarator;
211 bool isProcessingDeclSpec() const {
212 return chunkIndex == declarator.getNumTypeObjects();
215 unsigned getCurrentChunkIndex() const {
216 return chunkIndex;
219 void setCurrentChunkIndex(unsigned idx) {
220 assert(idx <= declarator.getNumTypeObjects());
221 chunkIndex = idx;
224 ParsedAttributesView &getCurrentAttributes() const {
225 if (isProcessingDeclSpec())
226 return getMutableDeclSpec().getAttributes();
227 return declarator.getTypeObject(chunkIndex).getAttrs();
230 /// Save the current set of attributes on the DeclSpec.
231 void saveDeclSpecAttrs() {
232 // Don't try to save them multiple times.
233 if (!savedAttrs.empty())
234 return;
236 DeclSpec &spec = getMutableDeclSpec();
237 llvm::append_range(savedAttrs,
238 llvm::make_pointer_range(spec.getAttributes()));
241 /// Record that we had nowhere to put the given type attribute.
242 /// We will diagnose such attributes later.
243 void addIgnoredTypeAttr(ParsedAttr &attr) {
244 ignoredTypeAttrs.push_back(&attr);
247 /// Diagnose all the ignored type attributes, given that the
248 /// declarator worked out to the given type.
249 void diagnoseIgnoredTypeAttrs(QualType type) const {
250 for (auto *Attr : ignoredTypeAttrs)
251 diagnoseBadTypeAttribute(getSema(), *Attr, type);
254 /// Get an attributed type for the given attribute, and remember the Attr
255 /// object so that we can attach it to the AttributedTypeLoc.
256 QualType getAttributedType(Attr *A, QualType ModifiedType,
257 QualType EquivType) {
258 QualType T =
259 sema.Context.getAttributedType(A->getKind(), ModifiedType, EquivType);
260 AttrsForTypes.push_back({cast<AttributedType>(T.getTypePtr()), A});
261 AttrsForTypesSorted = false;
262 return T;
265 /// Get a BTFTagAttributed type for the btf_type_tag attribute.
266 QualType getBTFTagAttributedType(const BTFTypeTagAttr *BTFAttr,
267 QualType WrappedType) {
268 return sema.Context.getBTFTagAttributedType(BTFAttr, WrappedType);
271 /// Completely replace the \c auto in \p TypeWithAuto by
272 /// \p Replacement. Also replace \p TypeWithAuto in \c TypeAttrPair if
273 /// necessary.
274 QualType ReplaceAutoType(QualType TypeWithAuto, QualType Replacement) {
275 QualType T = sema.ReplaceAutoType(TypeWithAuto, Replacement);
276 if (auto *AttrTy = TypeWithAuto->getAs<AttributedType>()) {
277 // Attributed type still should be an attributed type after replacement.
278 auto *NewAttrTy = cast<AttributedType>(T.getTypePtr());
279 for (TypeAttrPair &A : AttrsForTypes) {
280 if (A.first == AttrTy)
281 A.first = NewAttrTy;
283 AttrsForTypesSorted = false;
285 return T;
288 /// Extract and remove the Attr* for a given attributed type.
289 const Attr *takeAttrForAttributedType(const AttributedType *AT) {
290 if (!AttrsForTypesSorted) {
291 llvm::stable_sort(AttrsForTypes, llvm::less_first());
292 AttrsForTypesSorted = true;
295 // FIXME: This is quadratic if we have lots of reuses of the same
296 // attributed type.
297 for (auto It = std::partition_point(
298 AttrsForTypes.begin(), AttrsForTypes.end(),
299 [=](const TypeAttrPair &A) { return A.first < AT; });
300 It != AttrsForTypes.end() && It->first == AT; ++It) {
301 if (It->second) {
302 const Attr *Result = It->second;
303 It->second = nullptr;
304 return Result;
308 llvm_unreachable("no Attr* for AttributedType*");
311 SourceLocation
312 getExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT) const {
313 auto FoundLoc = LocsForMacros.find(MQT);
314 assert(FoundLoc != LocsForMacros.end() &&
315 "Unable to find macro expansion location for MacroQualifedType");
316 return FoundLoc->second;
319 void setExpansionLocForMacroQualifiedType(const MacroQualifiedType *MQT,
320 SourceLocation Loc) {
321 LocsForMacros[MQT] = Loc;
324 void setParsedNoDeref(bool parsed) { parsedNoDeref = parsed; }
326 bool didParseNoDeref() const { return parsedNoDeref; }
328 ~TypeProcessingState() {
329 if (savedAttrs.empty())
330 return;
332 getMutableDeclSpec().getAttributes().clearListOnly();
333 for (ParsedAttr *AL : savedAttrs)
334 getMutableDeclSpec().getAttributes().addAtEnd(AL);
337 private:
338 DeclSpec &getMutableDeclSpec() const {
339 return const_cast<DeclSpec&>(declarator.getDeclSpec());
342 } // end anonymous namespace
344 static void moveAttrFromListToList(ParsedAttr &attr,
345 ParsedAttributesView &fromList,
346 ParsedAttributesView &toList) {
347 fromList.remove(&attr);
348 toList.addAtEnd(&attr);
351 /// The location of a type attribute.
352 enum TypeAttrLocation {
353 /// The attribute is in the decl-specifier-seq.
354 TAL_DeclSpec,
355 /// The attribute is part of a DeclaratorChunk.
356 TAL_DeclChunk,
357 /// The attribute is immediately after the declaration's name.
358 TAL_DeclName
361 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
362 TypeAttrLocation TAL,
363 const ParsedAttributesView &attrs);
365 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
366 QualType &type);
368 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
369 ParsedAttr &attr, QualType &type);
371 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
372 QualType &type);
374 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
375 ParsedAttr &attr, QualType &type);
377 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
378 ParsedAttr &attr, QualType &type) {
379 if (attr.getKind() == ParsedAttr::AT_ObjCGC)
380 return handleObjCGCTypeAttr(state, attr, type);
381 assert(attr.getKind() == ParsedAttr::AT_ObjCOwnership);
382 return handleObjCOwnershipTypeAttr(state, attr, type);
385 /// Given the index of a declarator chunk, check whether that chunk
386 /// directly specifies the return type of a function and, if so, find
387 /// an appropriate place for it.
389 /// \param i - a notional index which the search will start
390 /// immediately inside
392 /// \param onlyBlockPointers Whether we should only look into block
393 /// pointer types (vs. all pointer types).
394 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
395 unsigned i,
396 bool onlyBlockPointers) {
397 assert(i <= declarator.getNumTypeObjects());
399 DeclaratorChunk *result = nullptr;
401 // First, look inwards past parens for a function declarator.
402 for (; i != 0; --i) {
403 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
404 switch (fnChunk.Kind) {
405 case DeclaratorChunk::Paren:
406 continue;
408 // If we find anything except a function, bail out.
409 case DeclaratorChunk::Pointer:
410 case DeclaratorChunk::BlockPointer:
411 case DeclaratorChunk::Array:
412 case DeclaratorChunk::Reference:
413 case DeclaratorChunk::MemberPointer:
414 case DeclaratorChunk::Pipe:
415 return result;
417 // If we do find a function declarator, scan inwards from that,
418 // looking for a (block-)pointer declarator.
419 case DeclaratorChunk::Function:
420 for (--i; i != 0; --i) {
421 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
422 switch (ptrChunk.Kind) {
423 case DeclaratorChunk::Paren:
424 case DeclaratorChunk::Array:
425 case DeclaratorChunk::Function:
426 case DeclaratorChunk::Reference:
427 case DeclaratorChunk::Pipe:
428 continue;
430 case DeclaratorChunk::MemberPointer:
431 case DeclaratorChunk::Pointer:
432 if (onlyBlockPointers)
433 continue;
435 [[fallthrough]];
437 case DeclaratorChunk::BlockPointer:
438 result = &ptrChunk;
439 goto continue_outer;
441 llvm_unreachable("bad declarator chunk kind");
444 // If we run out of declarators doing that, we're done.
445 return result;
447 llvm_unreachable("bad declarator chunk kind");
449 // Okay, reconsider from our new point.
450 continue_outer: ;
453 // Ran out of chunks, bail out.
454 return result;
457 /// Given that an objc_gc attribute was written somewhere on a
458 /// declaration *other* than on the declarator itself (for which, use
459 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
460 /// didn't apply in whatever position it was written in, try to move
461 /// it to a more appropriate position.
462 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
463 ParsedAttr &attr, QualType type) {
464 Declarator &declarator = state.getDeclarator();
466 // Move it to the outermost normal or block pointer declarator.
467 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
468 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
469 switch (chunk.Kind) {
470 case DeclaratorChunk::Pointer:
471 case DeclaratorChunk::BlockPointer: {
472 // But don't move an ARC ownership attribute to the return type
473 // of a block.
474 DeclaratorChunk *destChunk = nullptr;
475 if (state.isProcessingDeclSpec() &&
476 attr.getKind() == ParsedAttr::AT_ObjCOwnership)
477 destChunk = maybeMovePastReturnType(declarator, i - 1,
478 /*onlyBlockPointers=*/true);
479 if (!destChunk) destChunk = &chunk;
481 moveAttrFromListToList(attr, state.getCurrentAttributes(),
482 destChunk->getAttrs());
483 return;
486 case DeclaratorChunk::Paren:
487 case DeclaratorChunk::Array:
488 continue;
490 // We may be starting at the return type of a block.
491 case DeclaratorChunk::Function:
492 if (state.isProcessingDeclSpec() &&
493 attr.getKind() == ParsedAttr::AT_ObjCOwnership) {
494 if (DeclaratorChunk *dest = maybeMovePastReturnType(
495 declarator, i,
496 /*onlyBlockPointers=*/true)) {
497 moveAttrFromListToList(attr, state.getCurrentAttributes(),
498 dest->getAttrs());
499 return;
502 goto error;
504 // Don't walk through these.
505 case DeclaratorChunk::Reference:
506 case DeclaratorChunk::MemberPointer:
507 case DeclaratorChunk::Pipe:
508 goto error;
511 error:
513 diagnoseBadTypeAttribute(state.getSema(), attr, type);
516 /// Distribute an objc_gc type attribute that was written on the
517 /// declarator.
518 static void distributeObjCPointerTypeAttrFromDeclarator(
519 TypeProcessingState &state, ParsedAttr &attr, QualType &declSpecType) {
520 Declarator &declarator = state.getDeclarator();
522 // objc_gc goes on the innermost pointer to something that's not a
523 // pointer.
524 unsigned innermost = -1U;
525 bool considerDeclSpec = true;
526 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
527 DeclaratorChunk &chunk = declarator.getTypeObject(i);
528 switch (chunk.Kind) {
529 case DeclaratorChunk::Pointer:
530 case DeclaratorChunk::BlockPointer:
531 innermost = i;
532 continue;
534 case DeclaratorChunk::Reference:
535 case DeclaratorChunk::MemberPointer:
536 case DeclaratorChunk::Paren:
537 case DeclaratorChunk::Array:
538 case DeclaratorChunk::Pipe:
539 continue;
541 case DeclaratorChunk::Function:
542 considerDeclSpec = false;
543 goto done;
546 done:
548 // That might actually be the decl spec if we weren't blocked by
549 // anything in the declarator.
550 if (considerDeclSpec) {
551 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
552 // Splice the attribute into the decl spec. Prevents the
553 // attribute from being applied multiple times and gives
554 // the source-location-filler something to work with.
555 state.saveDeclSpecAttrs();
556 declarator.getMutableDeclSpec().getAttributes().takeOneFrom(
557 declarator.getAttributes(), &attr);
558 return;
562 // Otherwise, if we found an appropriate chunk, splice the attribute
563 // into it.
564 if (innermost != -1U) {
565 moveAttrFromListToList(attr, declarator.getAttributes(),
566 declarator.getTypeObject(innermost).getAttrs());
567 return;
570 // Otherwise, diagnose when we're done building the type.
571 declarator.getAttributes().remove(&attr);
572 state.addIgnoredTypeAttr(attr);
575 /// A function type attribute was written somewhere in a declaration
576 /// *other* than on the declarator itself or in the decl spec. Given
577 /// that it didn't apply in whatever position it was written in, try
578 /// to move it to a more appropriate position.
579 static void distributeFunctionTypeAttr(TypeProcessingState &state,
580 ParsedAttr &attr, QualType type) {
581 Declarator &declarator = state.getDeclarator();
583 // Try to push the attribute from the return type of a function to
584 // the function itself.
585 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
586 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
587 switch (chunk.Kind) {
588 case DeclaratorChunk::Function:
589 moveAttrFromListToList(attr, state.getCurrentAttributes(),
590 chunk.getAttrs());
591 return;
593 case DeclaratorChunk::Paren:
594 case DeclaratorChunk::Pointer:
595 case DeclaratorChunk::BlockPointer:
596 case DeclaratorChunk::Array:
597 case DeclaratorChunk::Reference:
598 case DeclaratorChunk::MemberPointer:
599 case DeclaratorChunk::Pipe:
600 continue;
604 diagnoseBadTypeAttribute(state.getSema(), attr, type);
607 /// Try to distribute a function type attribute to the innermost
608 /// function chunk or type. Returns true if the attribute was
609 /// distributed, false if no location was found.
610 static bool distributeFunctionTypeAttrToInnermost(
611 TypeProcessingState &state, ParsedAttr &attr,
612 ParsedAttributesView &attrList, QualType &declSpecType) {
613 Declarator &declarator = state.getDeclarator();
615 // Put it on the innermost function chunk, if there is one.
616 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
617 DeclaratorChunk &chunk = declarator.getTypeObject(i);
618 if (chunk.Kind != DeclaratorChunk::Function) continue;
620 moveAttrFromListToList(attr, attrList, chunk.getAttrs());
621 return true;
624 return handleFunctionTypeAttr(state, attr, declSpecType);
627 /// A function type attribute was written in the decl spec. Try to
628 /// apply it somewhere.
629 static void distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
630 ParsedAttr &attr,
631 QualType &declSpecType) {
632 state.saveDeclSpecAttrs();
634 // Try to distribute to the innermost.
635 if (distributeFunctionTypeAttrToInnermost(
636 state, attr, state.getCurrentAttributes(), declSpecType))
637 return;
639 // If that failed, diagnose the bad attribute when the declarator is
640 // fully built.
641 state.addIgnoredTypeAttr(attr);
644 /// A function type attribute was written on the declarator or declaration.
645 /// Try to apply it somewhere.
646 /// `Attrs` is the attribute list containing the declaration (either of the
647 /// declarator or the declaration).
648 static void distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
649 ParsedAttr &attr,
650 QualType &declSpecType) {
651 Declarator &declarator = state.getDeclarator();
653 // Try to distribute to the innermost.
654 if (distributeFunctionTypeAttrToInnermost(
655 state, attr, declarator.getAttributes(), declSpecType))
656 return;
658 // If that failed, diagnose the bad attribute when the declarator is
659 // fully built.
660 declarator.getAttributes().remove(&attr);
661 state.addIgnoredTypeAttr(attr);
664 /// Given that there are attributes written on the declarator or declaration
665 /// itself, try to distribute any type attributes to the appropriate
666 /// declarator chunk.
668 /// These are attributes like the following:
669 /// int f ATTR;
670 /// int (f ATTR)();
671 /// but not necessarily this:
672 /// int f() ATTR;
674 /// `Attrs` is the attribute list containing the declaration (either of the
675 /// declarator or the declaration).
676 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
677 QualType &declSpecType) {
678 // The called functions in this loop actually remove things from the current
679 // list, so iterating over the existing list isn't possible. Instead, make a
680 // non-owning copy and iterate over that.
681 ParsedAttributesView AttrsCopy{state.getDeclarator().getAttributes()};
682 for (ParsedAttr &attr : AttrsCopy) {
683 // Do not distribute [[]] attributes. They have strict rules for what
684 // they appertain to.
685 if (attr.isStandardAttributeSyntax())
686 continue;
688 switch (attr.getKind()) {
689 OBJC_POINTER_TYPE_ATTRS_CASELIST:
690 distributeObjCPointerTypeAttrFromDeclarator(state, attr, declSpecType);
691 break;
693 FUNCTION_TYPE_ATTRS_CASELIST:
694 distributeFunctionTypeAttrFromDeclarator(state, attr, declSpecType);
695 break;
697 MS_TYPE_ATTRS_CASELIST:
698 // Microsoft type attributes cannot go after the declarator-id.
699 continue;
701 NULLABILITY_TYPE_ATTRS_CASELIST:
702 // Nullability specifiers cannot go after the declarator-id.
704 // Objective-C __kindof does not get distributed.
705 case ParsedAttr::AT_ObjCKindOf:
706 continue;
708 default:
709 break;
714 /// Add a synthetic '()' to a block-literal declarator if it is
715 /// required, given the return type.
716 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
717 QualType declSpecType) {
718 Declarator &declarator = state.getDeclarator();
720 // First, check whether the declarator would produce a function,
721 // i.e. whether the innermost semantic chunk is a function.
722 if (declarator.isFunctionDeclarator()) {
723 // If so, make that declarator a prototyped declarator.
724 declarator.getFunctionTypeInfo().hasPrototype = true;
725 return;
728 // If there are any type objects, the type as written won't name a
729 // function, regardless of the decl spec type. This is because a
730 // block signature declarator is always an abstract-declarator, and
731 // abstract-declarators can't just be parentheses chunks. Therefore
732 // we need to build a function chunk unless there are no type
733 // objects and the decl spec type is a function.
734 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
735 return;
737 // Note that there *are* cases with invalid declarators where
738 // declarators consist solely of parentheses. In general, these
739 // occur only in failed efforts to make function declarators, so
740 // faking up the function chunk is still the right thing to do.
742 // Otherwise, we need to fake up a function declarator.
743 SourceLocation loc = declarator.getBeginLoc();
745 // ...and *prepend* it to the declarator.
746 SourceLocation NoLoc;
747 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
748 /*HasProto=*/true,
749 /*IsAmbiguous=*/false,
750 /*LParenLoc=*/NoLoc,
751 /*ArgInfo=*/nullptr,
752 /*NumParams=*/0,
753 /*EllipsisLoc=*/NoLoc,
754 /*RParenLoc=*/NoLoc,
755 /*RefQualifierIsLvalueRef=*/true,
756 /*RefQualifierLoc=*/NoLoc,
757 /*MutableLoc=*/NoLoc, EST_None,
758 /*ESpecRange=*/SourceRange(),
759 /*Exceptions=*/nullptr,
760 /*ExceptionRanges=*/nullptr,
761 /*NumExceptions=*/0,
762 /*NoexceptExpr=*/nullptr,
763 /*ExceptionSpecTokens=*/nullptr,
764 /*DeclsInPrototype=*/None, loc, loc, declarator));
766 // For consistency, make sure the state still has us as processing
767 // the decl spec.
768 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
769 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
772 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
773 unsigned &TypeQuals,
774 QualType TypeSoFar,
775 unsigned RemoveTQs,
776 unsigned DiagID) {
777 // If this occurs outside a template instantiation, warn the user about
778 // it; they probably didn't mean to specify a redundant qualifier.
779 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
780 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
781 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
782 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
783 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
784 if (!(RemoveTQs & Qual.first))
785 continue;
787 if (!S.inTemplateInstantiation()) {
788 if (TypeQuals & Qual.first)
789 S.Diag(Qual.second, DiagID)
790 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
791 << FixItHint::CreateRemoval(Qual.second);
794 TypeQuals &= ~Qual.first;
798 /// Return true if this is omitted block return type. Also check type
799 /// attributes and type qualifiers when returning true.
800 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
801 QualType Result) {
802 if (!isOmittedBlockReturnType(declarator))
803 return false;
805 // Warn if we see type attributes for omitted return type on a block literal.
806 SmallVector<ParsedAttr *, 2> ToBeRemoved;
807 for (ParsedAttr &AL : declarator.getMutableDeclSpec().getAttributes()) {
808 if (AL.isInvalid() || !AL.isTypeAttr())
809 continue;
810 S.Diag(AL.getLoc(),
811 diag::warn_block_literal_attributes_on_omitted_return_type)
812 << AL;
813 ToBeRemoved.push_back(&AL);
815 // Remove bad attributes from the list.
816 for (ParsedAttr *AL : ToBeRemoved)
817 declarator.getMutableDeclSpec().getAttributes().remove(AL);
819 // Warn if we see type qualifiers for omitted return type on a block literal.
820 const DeclSpec &DS = declarator.getDeclSpec();
821 unsigned TypeQuals = DS.getTypeQualifiers();
822 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
823 diag::warn_block_literal_qualifiers_on_omitted_return_type);
824 declarator.getMutableDeclSpec().ClearTypeQualifiers();
826 return true;
829 /// Apply Objective-C type arguments to the given type.
830 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
831 ArrayRef<TypeSourceInfo *> typeArgs,
832 SourceRange typeArgsRange,
833 bool failOnError = false) {
834 // We can only apply type arguments to an Objective-C class type.
835 const auto *objcObjectType = type->getAs<ObjCObjectType>();
836 if (!objcObjectType || !objcObjectType->getInterface()) {
837 S.Diag(loc, diag::err_objc_type_args_non_class)
838 << type
839 << typeArgsRange;
841 if (failOnError)
842 return QualType();
843 return type;
846 // The class type must be parameterized.
847 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
848 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
849 if (!typeParams) {
850 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
851 << objcClass->getDeclName()
852 << FixItHint::CreateRemoval(typeArgsRange);
854 if (failOnError)
855 return QualType();
857 return type;
860 // The type must not already be specialized.
861 if (objcObjectType->isSpecialized()) {
862 S.Diag(loc, diag::err_objc_type_args_specialized_class)
863 << type
864 << FixItHint::CreateRemoval(typeArgsRange);
866 if (failOnError)
867 return QualType();
869 return type;
872 // Check the type arguments.
873 SmallVector<QualType, 4> finalTypeArgs;
874 unsigned numTypeParams = typeParams->size();
875 bool anyPackExpansions = false;
876 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
877 TypeSourceInfo *typeArgInfo = typeArgs[i];
878 QualType typeArg = typeArgInfo->getType();
880 // Type arguments cannot have explicit qualifiers or nullability.
881 // We ignore indirect sources of these, e.g. behind typedefs or
882 // template arguments.
883 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
884 bool diagnosed = false;
885 SourceRange rangeToRemove;
886 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
887 rangeToRemove = attr.getLocalSourceRange();
888 if (attr.getTypePtr()->getImmediateNullability()) {
889 typeArg = attr.getTypePtr()->getModifiedType();
890 S.Diag(attr.getBeginLoc(),
891 diag::err_objc_type_arg_explicit_nullability)
892 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
893 diagnosed = true;
897 if (!diagnosed) {
898 S.Diag(qual.getBeginLoc(), diag::err_objc_type_arg_qualified)
899 << typeArg << typeArg.getQualifiers().getAsString()
900 << FixItHint::CreateRemoval(rangeToRemove);
904 // Remove qualifiers even if they're non-local.
905 typeArg = typeArg.getUnqualifiedType();
907 finalTypeArgs.push_back(typeArg);
909 if (typeArg->getAs<PackExpansionType>())
910 anyPackExpansions = true;
912 // Find the corresponding type parameter, if there is one.
913 ObjCTypeParamDecl *typeParam = nullptr;
914 if (!anyPackExpansions) {
915 if (i < numTypeParams) {
916 typeParam = typeParams->begin()[i];
917 } else {
918 // Too many arguments.
919 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
920 << false
921 << objcClass->getDeclName()
922 << (unsigned)typeArgs.size()
923 << numTypeParams;
924 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
925 << objcClass;
927 if (failOnError)
928 return QualType();
930 return type;
934 // Objective-C object pointer types must be substitutable for the bounds.
935 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
936 // If we don't have a type parameter to match against, assume
937 // everything is fine. There was a prior pack expansion that
938 // means we won't be able to match anything.
939 if (!typeParam) {
940 assert(anyPackExpansions && "Too many arguments?");
941 continue;
944 // Retrieve the bound.
945 QualType bound = typeParam->getUnderlyingType();
946 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
948 // Determine whether the type argument is substitutable for the bound.
949 if (typeArgObjC->isObjCIdType()) {
950 // When the type argument is 'id', the only acceptable type
951 // parameter bound is 'id'.
952 if (boundObjC->isObjCIdType())
953 continue;
954 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
955 // Otherwise, we follow the assignability rules.
956 continue;
959 // Diagnose the mismatch.
960 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
961 diag::err_objc_type_arg_does_not_match_bound)
962 << typeArg << bound << typeParam->getDeclName();
963 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
964 << typeParam->getDeclName();
966 if (failOnError)
967 return QualType();
969 return type;
972 // Block pointer types are permitted for unqualified 'id' bounds.
973 if (typeArg->isBlockPointerType()) {
974 // If we don't have a type parameter to match against, assume
975 // everything is fine. There was a prior pack expansion that
976 // means we won't be able to match anything.
977 if (!typeParam) {
978 assert(anyPackExpansions && "Too many arguments?");
979 continue;
982 // Retrieve the bound.
983 QualType bound = typeParam->getUnderlyingType();
984 if (bound->isBlockCompatibleObjCPointerType(S.Context))
985 continue;
987 // Diagnose the mismatch.
988 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
989 diag::err_objc_type_arg_does_not_match_bound)
990 << typeArg << bound << typeParam->getDeclName();
991 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
992 << typeParam->getDeclName();
994 if (failOnError)
995 return QualType();
997 return type;
1000 // Dependent types will be checked at instantiation time.
1001 if (typeArg->isDependentType()) {
1002 continue;
1005 // Diagnose non-id-compatible type arguments.
1006 S.Diag(typeArgInfo->getTypeLoc().getBeginLoc(),
1007 diag::err_objc_type_arg_not_id_compatible)
1008 << typeArg << typeArgInfo->getTypeLoc().getSourceRange();
1010 if (failOnError)
1011 return QualType();
1013 return type;
1016 // Make sure we didn't have the wrong number of arguments.
1017 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
1018 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
1019 << (typeArgs.size() < typeParams->size())
1020 << objcClass->getDeclName()
1021 << (unsigned)finalTypeArgs.size()
1022 << (unsigned)numTypeParams;
1023 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1024 << objcClass;
1026 if (failOnError)
1027 return QualType();
1029 return type;
1032 // Success. Form the specialized type.
1033 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1036 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1037 SourceLocation ProtocolLAngleLoc,
1038 ArrayRef<ObjCProtocolDecl *> Protocols,
1039 ArrayRef<SourceLocation> ProtocolLocs,
1040 SourceLocation ProtocolRAngleLoc,
1041 bool FailOnError) {
1042 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1043 if (!Protocols.empty()) {
1044 bool HasError;
1045 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1046 HasError);
1047 if (HasError) {
1048 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1049 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1050 if (FailOnError) Result = QualType();
1052 if (FailOnError && Result.isNull())
1053 return QualType();
1056 return Result;
1059 QualType Sema::BuildObjCObjectType(QualType BaseType,
1060 SourceLocation Loc,
1061 SourceLocation TypeArgsLAngleLoc,
1062 ArrayRef<TypeSourceInfo *> TypeArgs,
1063 SourceLocation TypeArgsRAngleLoc,
1064 SourceLocation ProtocolLAngleLoc,
1065 ArrayRef<ObjCProtocolDecl *> Protocols,
1066 ArrayRef<SourceLocation> ProtocolLocs,
1067 SourceLocation ProtocolRAngleLoc,
1068 bool FailOnError) {
1069 QualType Result = BaseType;
1070 if (!TypeArgs.empty()) {
1071 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1072 SourceRange(TypeArgsLAngleLoc,
1073 TypeArgsRAngleLoc),
1074 FailOnError);
1075 if (FailOnError && Result.isNull())
1076 return QualType();
1079 if (!Protocols.empty()) {
1080 bool HasError;
1081 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1082 HasError);
1083 if (HasError) {
1084 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1085 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1086 if (FailOnError) Result = QualType();
1088 if (FailOnError && Result.isNull())
1089 return QualType();
1092 return Result;
1095 TypeResult Sema::actOnObjCProtocolQualifierType(
1096 SourceLocation lAngleLoc,
1097 ArrayRef<Decl *> protocols,
1098 ArrayRef<SourceLocation> protocolLocs,
1099 SourceLocation rAngleLoc) {
1100 // Form id<protocol-list>.
1101 QualType Result = Context.getObjCObjectType(
1102 Context.ObjCBuiltinIdTy, { },
1103 llvm::makeArrayRef(
1104 (ObjCProtocolDecl * const *)protocols.data(),
1105 protocols.size()),
1106 false);
1107 Result = Context.getObjCObjectPointerType(Result);
1109 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1110 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1112 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1113 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1115 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1116 .castAs<ObjCObjectTypeLoc>();
1117 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1118 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1120 // No type arguments.
1121 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1122 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1124 // Fill in protocol qualifiers.
1125 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1126 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1127 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1128 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1130 // We're done. Return the completed type to the parser.
1131 return CreateParsedType(Result, ResultTInfo);
1134 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1135 Scope *S,
1136 SourceLocation Loc,
1137 ParsedType BaseType,
1138 SourceLocation TypeArgsLAngleLoc,
1139 ArrayRef<ParsedType> TypeArgs,
1140 SourceLocation TypeArgsRAngleLoc,
1141 SourceLocation ProtocolLAngleLoc,
1142 ArrayRef<Decl *> Protocols,
1143 ArrayRef<SourceLocation> ProtocolLocs,
1144 SourceLocation ProtocolRAngleLoc) {
1145 TypeSourceInfo *BaseTypeInfo = nullptr;
1146 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1147 if (T.isNull())
1148 return true;
1150 // Handle missing type-source info.
1151 if (!BaseTypeInfo)
1152 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1154 // Extract type arguments.
1155 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1156 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1157 TypeSourceInfo *TypeArgInfo = nullptr;
1158 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1159 if (TypeArg.isNull()) {
1160 ActualTypeArgInfos.clear();
1161 break;
1164 assert(TypeArgInfo && "No type source info?");
1165 ActualTypeArgInfos.push_back(TypeArgInfo);
1168 // Build the object type.
1169 QualType Result = BuildObjCObjectType(
1170 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1171 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1172 ProtocolLAngleLoc,
1173 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1174 Protocols.size()),
1175 ProtocolLocs, ProtocolRAngleLoc,
1176 /*FailOnError=*/false);
1178 if (Result == T)
1179 return BaseType;
1181 // Create source information for this type.
1182 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1183 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1185 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1186 // object pointer type. Fill in source information for it.
1187 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1188 // The '*' is implicit.
1189 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1190 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1193 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1194 // Protocol qualifier information.
1195 if (OTPTL.getNumProtocols() > 0) {
1196 assert(OTPTL.getNumProtocols() == Protocols.size());
1197 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1198 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1199 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1200 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1203 // We're done. Return the completed type to the parser.
1204 return CreateParsedType(Result, ResultTInfo);
1207 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1209 // Type argument information.
1210 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1211 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1212 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1213 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1214 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1215 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1216 } else {
1217 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1218 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1221 // Protocol qualifier information.
1222 if (ObjCObjectTL.getNumProtocols() > 0) {
1223 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1224 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1225 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1226 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1227 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1228 } else {
1229 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1230 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1233 // Base type.
1234 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1235 if (ObjCObjectTL.getType() == T)
1236 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1237 else
1238 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1240 // We're done. Return the completed type to the parser.
1241 return CreateParsedType(Result, ResultTInfo);
1244 static OpenCLAccessAttr::Spelling
1245 getImageAccess(const ParsedAttributesView &Attrs) {
1246 for (const ParsedAttr &AL : Attrs)
1247 if (AL.getKind() == ParsedAttr::AT_OpenCLAccess)
1248 return static_cast<OpenCLAccessAttr::Spelling>(AL.getSemanticSpelling());
1249 return OpenCLAccessAttr::Keyword_read_only;
1252 static UnaryTransformType::UTTKind
1253 TSTToUnaryTransformType(DeclSpec::TST SwitchTST) {
1254 switch (SwitchTST) {
1255 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
1256 case TST_##Trait: \
1257 return UnaryTransformType::Enum;
1258 #include "clang/Basic/TransformTypeTraits.def"
1259 default:
1260 llvm_unreachable("attempted to parse a non-unary transform builtin");
1264 /// Convert the specified declspec to the appropriate type
1265 /// object.
1266 /// \param state Specifies the declarator containing the declaration specifier
1267 /// to be converted, along with other associated processing state.
1268 /// \returns The type described by the declaration specifiers. This function
1269 /// never returns null.
1270 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1271 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1272 // checking.
1274 Sema &S = state.getSema();
1275 Declarator &declarator = state.getDeclarator();
1276 DeclSpec &DS = declarator.getMutableDeclSpec();
1277 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1278 if (DeclLoc.isInvalid())
1279 DeclLoc = DS.getBeginLoc();
1281 ASTContext &Context = S.Context;
1283 QualType Result;
1284 switch (DS.getTypeSpecType()) {
1285 case DeclSpec::TST_void:
1286 Result = Context.VoidTy;
1287 break;
1288 case DeclSpec::TST_char:
1289 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1290 Result = Context.CharTy;
1291 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed)
1292 Result = Context.SignedCharTy;
1293 else {
1294 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1295 "Unknown TSS value");
1296 Result = Context.UnsignedCharTy;
1298 break;
1299 case DeclSpec::TST_wchar:
1300 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified)
1301 Result = Context.WCharTy;
1302 else if (DS.getTypeSpecSign() == TypeSpecifierSign::Signed) {
1303 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1304 << DS.getSpecifierName(DS.getTypeSpecType(),
1305 Context.getPrintingPolicy());
1306 Result = Context.getSignedWCharType();
1307 } else {
1308 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned &&
1309 "Unknown TSS value");
1310 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_wchar_t_sign_spec)
1311 << DS.getSpecifierName(DS.getTypeSpecType(),
1312 Context.getPrintingPolicy());
1313 Result = Context.getUnsignedWCharType();
1315 break;
1316 case DeclSpec::TST_char8:
1317 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1318 "Unknown TSS value");
1319 Result = Context.Char8Ty;
1320 break;
1321 case DeclSpec::TST_char16:
1322 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1323 "Unknown TSS value");
1324 Result = Context.Char16Ty;
1325 break;
1326 case DeclSpec::TST_char32:
1327 assert(DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1328 "Unknown TSS value");
1329 Result = Context.Char32Ty;
1330 break;
1331 case DeclSpec::TST_unspecified:
1332 // If this is a missing declspec in a block literal return context, then it
1333 // is inferred from the return statements inside the block.
1334 // The declspec is always missing in a lambda expr context; it is either
1335 // specified with a trailing return type or inferred.
1336 if (S.getLangOpts().CPlusPlus14 &&
1337 declarator.getContext() == DeclaratorContext::LambdaExpr) {
1338 // In C++1y, a lambda's implicit return type is 'auto'.
1339 Result = Context.getAutoDeductType();
1340 break;
1341 } else if (declarator.getContext() == DeclaratorContext::LambdaExpr ||
1342 checkOmittedBlockReturnType(S, declarator,
1343 Context.DependentTy)) {
1344 Result = Context.DependentTy;
1345 break;
1348 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1349 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1350 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1351 // Note that the one exception to this is function definitions, which are
1352 // allowed to be completely missing a declspec. This is handled in the
1353 // parser already though by it pretending to have seen an 'int' in this
1354 // case.
1355 if (S.getLangOpts().isImplicitIntRequired()) {
1356 S.Diag(DeclLoc, diag::warn_missing_type_specifier)
1357 << DS.getSourceRange()
1358 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1359 } else if (!DS.hasTypeSpecifier()) {
1360 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1361 // "At least one type specifier shall be given in the declaration
1362 // specifiers in each declaration, and in the specifier-qualifier list in
1363 // each struct declaration and type name."
1364 if (!S.getLangOpts().isImplicitIntAllowed() && !DS.isTypeSpecPipe()) {
1365 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1366 << DS.getSourceRange();
1368 // When this occurs, often something is very broken with the value
1369 // being declared, poison it as invalid so we don't get chains of
1370 // errors.
1371 declarator.setInvalidType(true);
1372 } else if (S.getLangOpts().getOpenCLCompatibleVersion() >= 200 &&
1373 DS.isTypeSpecPipe()) {
1374 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1375 << DS.getSourceRange();
1376 declarator.setInvalidType(true);
1377 } else {
1378 assert(S.getLangOpts().isImplicitIntAllowed() &&
1379 "implicit int is disabled?");
1380 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1381 << DS.getSourceRange()
1382 << FixItHint::CreateInsertion(DS.getBeginLoc(), "int");
1386 [[fallthrough]];
1387 case DeclSpec::TST_int: {
1388 if (DS.getTypeSpecSign() != TypeSpecifierSign::Unsigned) {
1389 switch (DS.getTypeSpecWidth()) {
1390 case TypeSpecifierWidth::Unspecified:
1391 Result = Context.IntTy;
1392 break;
1393 case TypeSpecifierWidth::Short:
1394 Result = Context.ShortTy;
1395 break;
1396 case TypeSpecifierWidth::Long:
1397 Result = Context.LongTy;
1398 break;
1399 case TypeSpecifierWidth::LongLong:
1400 Result = Context.LongLongTy;
1402 // 'long long' is a C99 or C++11 feature.
1403 if (!S.getLangOpts().C99) {
1404 if (S.getLangOpts().CPlusPlus)
1405 S.Diag(DS.getTypeSpecWidthLoc(),
1406 S.getLangOpts().CPlusPlus11 ?
1407 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1408 else
1409 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1411 break;
1413 } else {
1414 switch (DS.getTypeSpecWidth()) {
1415 case TypeSpecifierWidth::Unspecified:
1416 Result = Context.UnsignedIntTy;
1417 break;
1418 case TypeSpecifierWidth::Short:
1419 Result = Context.UnsignedShortTy;
1420 break;
1421 case TypeSpecifierWidth::Long:
1422 Result = Context.UnsignedLongTy;
1423 break;
1424 case TypeSpecifierWidth::LongLong:
1425 Result = Context.UnsignedLongLongTy;
1427 // 'long long' is a C99 or C++11 feature.
1428 if (!S.getLangOpts().C99) {
1429 if (S.getLangOpts().CPlusPlus)
1430 S.Diag(DS.getTypeSpecWidthLoc(),
1431 S.getLangOpts().CPlusPlus11 ?
1432 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1433 else
1434 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1436 break;
1439 break;
1441 case DeclSpec::TST_bitint: {
1442 if (!S.Context.getTargetInfo().hasBitIntType())
1443 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "_BitInt";
1444 Result =
1445 S.BuildBitIntType(DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned,
1446 DS.getRepAsExpr(), DS.getBeginLoc());
1447 if (Result.isNull()) {
1448 Result = Context.IntTy;
1449 declarator.setInvalidType(true);
1451 break;
1453 case DeclSpec::TST_accum: {
1454 switch (DS.getTypeSpecWidth()) {
1455 case TypeSpecifierWidth::Short:
1456 Result = Context.ShortAccumTy;
1457 break;
1458 case TypeSpecifierWidth::Unspecified:
1459 Result = Context.AccumTy;
1460 break;
1461 case TypeSpecifierWidth::Long:
1462 Result = Context.LongAccumTy;
1463 break;
1464 case TypeSpecifierWidth::LongLong:
1465 llvm_unreachable("Unable to specify long long as _Accum width");
1468 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1469 Result = Context.getCorrespondingUnsignedType(Result);
1471 if (DS.isTypeSpecSat())
1472 Result = Context.getCorrespondingSaturatedType(Result);
1474 break;
1476 case DeclSpec::TST_fract: {
1477 switch (DS.getTypeSpecWidth()) {
1478 case TypeSpecifierWidth::Short:
1479 Result = Context.ShortFractTy;
1480 break;
1481 case TypeSpecifierWidth::Unspecified:
1482 Result = Context.FractTy;
1483 break;
1484 case TypeSpecifierWidth::Long:
1485 Result = Context.LongFractTy;
1486 break;
1487 case TypeSpecifierWidth::LongLong:
1488 llvm_unreachable("Unable to specify long long as _Fract width");
1491 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1492 Result = Context.getCorrespondingUnsignedType(Result);
1494 if (DS.isTypeSpecSat())
1495 Result = Context.getCorrespondingSaturatedType(Result);
1497 break;
1499 case DeclSpec::TST_int128:
1500 if (!S.Context.getTargetInfo().hasInt128Type() &&
1501 !(S.getLangOpts().SYCLIsDevice || S.getLangOpts().CUDAIsDevice ||
1502 (S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice)))
1503 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1504 << "__int128";
1505 if (DS.getTypeSpecSign() == TypeSpecifierSign::Unsigned)
1506 Result = Context.UnsignedInt128Ty;
1507 else
1508 Result = Context.Int128Ty;
1509 break;
1510 case DeclSpec::TST_float16:
1511 // CUDA host and device may have different _Float16 support, therefore
1512 // do not diagnose _Float16 usage to avoid false alarm.
1513 // ToDo: more precise diagnostics for CUDA.
1514 if (!S.Context.getTargetInfo().hasFloat16Type() && !S.getLangOpts().CUDA &&
1515 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1516 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1517 << "_Float16";
1518 Result = Context.Float16Ty;
1519 break;
1520 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1521 case DeclSpec::TST_BFloat16:
1522 if (!S.Context.getTargetInfo().hasBFloat16Type())
1523 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1524 << "__bf16";
1525 Result = Context.BFloat16Ty;
1526 break;
1527 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1528 case DeclSpec::TST_double:
1529 if (DS.getTypeSpecWidth() == TypeSpecifierWidth::Long)
1530 Result = Context.LongDoubleTy;
1531 else
1532 Result = Context.DoubleTy;
1533 if (S.getLangOpts().OpenCL) {
1534 if (!S.getOpenCLOptions().isSupported("cl_khr_fp64", S.getLangOpts()))
1535 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1536 << 0 << Result
1537 << (S.getLangOpts().getOpenCLCompatibleVersion() == 300
1538 ? "cl_khr_fp64 and __opencl_c_fp64"
1539 : "cl_khr_fp64");
1540 else if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp64", S.getLangOpts()))
1541 S.Diag(DS.getTypeSpecTypeLoc(), diag::ext_opencl_double_without_pragma);
1543 break;
1544 case DeclSpec::TST_float128:
1545 if (!S.Context.getTargetInfo().hasFloat128Type() &&
1546 !S.getLangOpts().SYCLIsDevice &&
1547 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1548 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1549 << "__float128";
1550 Result = Context.Float128Ty;
1551 break;
1552 case DeclSpec::TST_ibm128:
1553 if (!S.Context.getTargetInfo().hasIbm128Type() &&
1554 !S.getLangOpts().SYCLIsDevice &&
1555 !(S.getLangOpts().OpenMP && S.getLangOpts().OpenMPIsDevice))
1556 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported) << "__ibm128";
1557 Result = Context.Ibm128Ty;
1558 break;
1559 case DeclSpec::TST_bool:
1560 Result = Context.BoolTy; // _Bool or bool
1561 break;
1562 case DeclSpec::TST_decimal32: // _Decimal32
1563 case DeclSpec::TST_decimal64: // _Decimal64
1564 case DeclSpec::TST_decimal128: // _Decimal128
1565 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1566 Result = Context.IntTy;
1567 declarator.setInvalidType(true);
1568 break;
1569 case DeclSpec::TST_class:
1570 case DeclSpec::TST_enum:
1571 case DeclSpec::TST_union:
1572 case DeclSpec::TST_struct:
1573 case DeclSpec::TST_interface: {
1574 TagDecl *D = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl());
1575 if (!D) {
1576 // This can happen in C++ with ambiguous lookups.
1577 Result = Context.IntTy;
1578 declarator.setInvalidType(true);
1579 break;
1582 // If the type is deprecated or unavailable, diagnose it.
1583 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1585 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1586 DS.getTypeSpecComplex() == 0 &&
1587 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1588 "No qualifiers on tag names!");
1590 // TypeQuals handled by caller.
1591 Result = Context.getTypeDeclType(D);
1593 // In both C and C++, make an ElaboratedType.
1594 ElaboratedTypeKeyword Keyword
1595 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1596 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result,
1597 DS.isTypeSpecOwned() ? D : nullptr);
1598 break;
1600 case DeclSpec::TST_typename: {
1601 assert(DS.getTypeSpecWidth() == TypeSpecifierWidth::Unspecified &&
1602 DS.getTypeSpecComplex() == 0 &&
1603 DS.getTypeSpecSign() == TypeSpecifierSign::Unspecified &&
1604 "Can't handle qualifiers on typedef names yet!");
1605 Result = S.GetTypeFromParser(DS.getRepAsType());
1606 if (Result.isNull()) {
1607 declarator.setInvalidType(true);
1610 // TypeQuals handled by caller.
1611 break;
1613 case DeclSpec::TST_typeofType:
1614 // FIXME: Preserve type source info.
1615 Result = S.GetTypeFromParser(DS.getRepAsType());
1616 assert(!Result.isNull() && "Didn't get a type for typeof?");
1617 if (!Result->isDependentType())
1618 if (const TagType *TT = Result->getAs<TagType>())
1619 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1620 // TypeQuals handled by caller.
1621 Result = Context.getTypeOfType(Result);
1622 break;
1623 case DeclSpec::TST_typeofExpr: {
1624 Expr *E = DS.getRepAsExpr();
1625 assert(E && "Didn't get an expression for typeof?");
1626 // TypeQuals handled by caller.
1627 Result = S.BuildTypeofExprType(E);
1628 if (Result.isNull()) {
1629 Result = Context.IntTy;
1630 declarator.setInvalidType(true);
1632 break;
1634 case DeclSpec::TST_decltype: {
1635 Expr *E = DS.getRepAsExpr();
1636 assert(E && "Didn't get an expression for decltype?");
1637 // TypeQuals handled by caller.
1638 Result = S.BuildDecltypeType(E);
1639 if (Result.isNull()) {
1640 Result = Context.IntTy;
1641 declarator.setInvalidType(true);
1643 break;
1645 #define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case DeclSpec::TST_##Trait:
1646 #include "clang/Basic/TransformTypeTraits.def"
1647 Result = S.GetTypeFromParser(DS.getRepAsType());
1648 assert(!Result.isNull() && "Didn't get a type for the transformation?");
1649 Result = S.BuildUnaryTransformType(
1650 Result, TSTToUnaryTransformType(DS.getTypeSpecType()),
1651 DS.getTypeSpecTypeLoc());
1652 if (Result.isNull()) {
1653 Result = Context.IntTy;
1654 declarator.setInvalidType(true);
1656 break;
1658 case DeclSpec::TST_auto:
1659 case DeclSpec::TST_decltype_auto: {
1660 auto AutoKW = DS.getTypeSpecType() == DeclSpec::TST_decltype_auto
1661 ? AutoTypeKeyword::DecltypeAuto
1662 : AutoTypeKeyword::Auto;
1664 ConceptDecl *TypeConstraintConcept = nullptr;
1665 llvm::SmallVector<TemplateArgument, 8> TemplateArgs;
1666 if (DS.isConstrainedAuto()) {
1667 if (TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId()) {
1668 TypeConstraintConcept =
1669 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl());
1670 TemplateArgumentListInfo TemplateArgsInfo;
1671 TemplateArgsInfo.setLAngleLoc(TemplateId->LAngleLoc);
1672 TemplateArgsInfo.setRAngleLoc(TemplateId->RAngleLoc);
1673 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
1674 TemplateId->NumArgs);
1675 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
1676 for (const auto &ArgLoc : TemplateArgsInfo.arguments())
1677 TemplateArgs.push_back(ArgLoc.getArgument());
1678 } else {
1679 declarator.setInvalidType(true);
1682 Result = S.Context.getAutoType(QualType(), AutoKW,
1683 /*IsDependent*/ false, /*IsPack=*/false,
1684 TypeConstraintConcept, TemplateArgs);
1685 break;
1688 case DeclSpec::TST_auto_type:
1689 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1690 break;
1692 case DeclSpec::TST_unknown_anytype:
1693 Result = Context.UnknownAnyTy;
1694 break;
1696 case DeclSpec::TST_atomic:
1697 Result = S.GetTypeFromParser(DS.getRepAsType());
1698 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1699 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1700 if (Result.isNull()) {
1701 Result = Context.IntTy;
1702 declarator.setInvalidType(true);
1704 break;
1706 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1707 case DeclSpec::TST_##ImgType##_t: \
1708 switch (getImageAccess(DS.getAttributes())) { \
1709 case OpenCLAccessAttr::Keyword_write_only: \
1710 Result = Context.Id##WOTy; \
1711 break; \
1712 case OpenCLAccessAttr::Keyword_read_write: \
1713 Result = Context.Id##RWTy; \
1714 break; \
1715 case OpenCLAccessAttr::Keyword_read_only: \
1716 Result = Context.Id##ROTy; \
1717 break; \
1718 case OpenCLAccessAttr::SpellingNotCalculated: \
1719 llvm_unreachable("Spelling not yet calculated"); \
1721 break;
1722 #include "clang/Basic/OpenCLImageTypes.def"
1724 case DeclSpec::TST_error:
1725 Result = Context.IntTy;
1726 declarator.setInvalidType(true);
1727 break;
1730 // FIXME: we want resulting declarations to be marked invalid, but claiming
1731 // the type is invalid is too strong - e.g. it causes ActOnTypeName to return
1732 // a null type.
1733 if (Result->containsErrors())
1734 declarator.setInvalidType();
1736 if (S.getLangOpts().OpenCL) {
1737 const auto &OpenCLOptions = S.getOpenCLOptions();
1738 bool IsOpenCLC30Compatible =
1739 S.getLangOpts().getOpenCLCompatibleVersion() == 300;
1740 // OpenCL C v3.0 s6.3.3 - OpenCL image types require __opencl_c_images
1741 // support.
1742 // OpenCL C v3.0 s6.2.1 - OpenCL 3d image write types requires support
1743 // for OpenCL C 2.0, or OpenCL C 3.0 or newer and the
1744 // __opencl_c_3d_image_writes feature. OpenCL C v3.0 API s4.2 - For devices
1745 // that support OpenCL 3.0, cl_khr_3d_image_writes must be returned when and
1746 // only when the optional feature is supported
1747 if ((Result->isImageType() || Result->isSamplerT()) &&
1748 (IsOpenCLC30Compatible &&
1749 !OpenCLOptions.isSupported("__opencl_c_images", S.getLangOpts()))) {
1750 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1751 << 0 << Result << "__opencl_c_images";
1752 declarator.setInvalidType();
1753 } else if (Result->isOCLImage3dWOType() &&
1754 !OpenCLOptions.isSupported("cl_khr_3d_image_writes",
1755 S.getLangOpts())) {
1756 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_opencl_requires_extension)
1757 << 0 << Result
1758 << (IsOpenCLC30Compatible
1759 ? "cl_khr_3d_image_writes and __opencl_c_3d_image_writes"
1760 : "cl_khr_3d_image_writes");
1761 declarator.setInvalidType();
1765 bool IsFixedPointType = DS.getTypeSpecType() == DeclSpec::TST_accum ||
1766 DS.getTypeSpecType() == DeclSpec::TST_fract;
1768 // Only fixed point types can be saturated
1769 if (DS.isTypeSpecSat() && !IsFixedPointType)
1770 S.Diag(DS.getTypeSpecSatLoc(), diag::err_invalid_saturation_spec)
1771 << DS.getSpecifierName(DS.getTypeSpecType(),
1772 Context.getPrintingPolicy());
1774 // Handle complex types.
1775 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1776 if (S.getLangOpts().Freestanding)
1777 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1778 Result = Context.getComplexType(Result);
1779 } else if (DS.isTypeAltiVecVector()) {
1780 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1781 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1782 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1783 if (DS.isTypeAltiVecPixel())
1784 VecKind = VectorType::AltiVecPixel;
1785 else if (DS.isTypeAltiVecBool())
1786 VecKind = VectorType::AltiVecBool;
1787 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1790 // FIXME: Imaginary.
1791 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1792 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1794 // Before we process any type attributes, synthesize a block literal
1795 // function declarator if necessary.
1796 if (declarator.getContext() == DeclaratorContext::BlockLiteral)
1797 maybeSynthesizeBlockSignature(state, Result);
1799 // Apply any type attributes from the decl spec. This may cause the
1800 // list of type attributes to be temporarily saved while the type
1801 // attributes are pushed around.
1802 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1803 if (!DS.isTypeSpecPipe()) {
1804 // We also apply declaration attributes that "slide" to the decl spec.
1805 // Ordering can be important for attributes. The decalaration attributes
1806 // come syntactically before the decl spec attributes, so we process them
1807 // in that order.
1808 ParsedAttributesView SlidingAttrs;
1809 for (ParsedAttr &AL : declarator.getDeclarationAttributes()) {
1810 if (AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
1811 SlidingAttrs.addAtEnd(&AL);
1813 // For standard syntax attributes, which would normally appertain to the
1814 // declaration here, suggest moving them to the type instead. But only
1815 // do this for our own vendor attributes; moving other vendors'
1816 // attributes might hurt portability.
1817 // There's one special case that we need to deal with here: The
1818 // `MatrixType` attribute may only be used in a typedef declaration. If
1819 // it's being used anywhere else, don't output the warning as
1820 // ProcessDeclAttributes() will output an error anyway.
1821 if (AL.isStandardAttributeSyntax() && AL.isClangScope() &&
1822 !(AL.getKind() == ParsedAttr::AT_MatrixType &&
1823 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)) {
1824 S.Diag(AL.getLoc(), diag::warn_type_attribute_deprecated_on_decl)
1825 << AL;
1829 // During this call to processTypeAttrs(),
1830 // TypeProcessingState::getCurrentAttributes() will erroneously return a
1831 // reference to the DeclSpec attributes, rather than the declaration
1832 // attributes. However, this doesn't matter, as getCurrentAttributes()
1833 // is only called when distributing attributes from one attribute list
1834 // to another. Declaration attributes are always C++11 attributes, and these
1835 // are never distributed.
1836 processTypeAttrs(state, Result, TAL_DeclSpec, SlidingAttrs);
1837 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes());
1840 // Apply const/volatile/restrict qualifiers to T.
1841 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1842 // Warn about CV qualifiers on function types.
1843 // C99 6.7.3p8:
1844 // If the specification of a function type includes any type qualifiers,
1845 // the behavior is undefined.
1846 // C++11 [dcl.fct]p7:
1847 // The effect of a cv-qualifier-seq in a function declarator is not the
1848 // same as adding cv-qualification on top of the function type. In the
1849 // latter case, the cv-qualifiers are ignored.
1850 if (Result->isFunctionType()) {
1851 diagnoseAndRemoveTypeQualifiers(
1852 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1853 S.getLangOpts().CPlusPlus
1854 ? diag::warn_typecheck_function_qualifiers_ignored
1855 : diag::warn_typecheck_function_qualifiers_unspecified);
1856 // No diagnostic for 'restrict' or '_Atomic' applied to a
1857 // function type; we'll diagnose those later, in BuildQualifiedType.
1860 // C++11 [dcl.ref]p1:
1861 // Cv-qualified references are ill-formed except when the
1862 // cv-qualifiers are introduced through the use of a typedef-name
1863 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1865 // There don't appear to be any other contexts in which a cv-qualified
1866 // reference type could be formed, so the 'ill-formed' clause here appears
1867 // to never happen.
1868 if (TypeQuals && Result->isReferenceType()) {
1869 diagnoseAndRemoveTypeQualifiers(
1870 S, DS, TypeQuals, Result,
1871 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1872 diag::warn_typecheck_reference_qualifiers);
1875 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1876 // than once in the same specifier-list or qualifier-list, either directly
1877 // or via one or more typedefs."
1878 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1879 && TypeQuals & Result.getCVRQualifiers()) {
1880 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1881 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1882 << "const";
1885 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1886 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1887 << "volatile";
1890 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1891 // produce a warning in this case.
1894 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1896 // If adding qualifiers fails, just use the unqualified type.
1897 if (Qualified.isNull())
1898 declarator.setInvalidType(true);
1899 else
1900 Result = Qualified;
1903 assert(!Result.isNull() && "This function should not return a null type");
1904 return Result;
1907 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1908 if (Entity)
1909 return Entity.getAsString();
1911 return "type name";
1914 static bool isDependentOrGNUAutoType(QualType T) {
1915 if (T->isDependentType())
1916 return true;
1918 const auto *AT = dyn_cast<AutoType>(T);
1919 return AT && AT->isGNUAutoType();
1922 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1923 Qualifiers Qs, const DeclSpec *DS) {
1924 if (T.isNull())
1925 return QualType();
1927 // Ignore any attempt to form a cv-qualified reference.
1928 if (T->isReferenceType()) {
1929 Qs.removeConst();
1930 Qs.removeVolatile();
1933 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1934 // object or incomplete types shall not be restrict-qualified."
1935 if (Qs.hasRestrict()) {
1936 unsigned DiagID = 0;
1937 QualType ProblemTy;
1939 if (T->isAnyPointerType() || T->isReferenceType() ||
1940 T->isMemberPointerType()) {
1941 QualType EltTy;
1942 if (T->isObjCObjectPointerType())
1943 EltTy = T;
1944 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1945 EltTy = PTy->getPointeeType();
1946 else
1947 EltTy = T->getPointeeType();
1949 // If we have a pointer or reference, the pointee must have an object
1950 // incomplete type.
1951 if (!EltTy->isIncompleteOrObjectType()) {
1952 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1953 ProblemTy = EltTy;
1955 } else if (!isDependentOrGNUAutoType(T)) {
1956 // For an __auto_type variable, we may not have seen the initializer yet
1957 // and so have no idea whether the underlying type is a pointer type or
1958 // not.
1959 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1960 ProblemTy = T;
1963 if (DiagID) {
1964 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1965 Qs.removeRestrict();
1969 return Context.getQualifiedType(T, Qs);
1972 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1973 unsigned CVRAU, const DeclSpec *DS) {
1974 if (T.isNull())
1975 return QualType();
1977 // Ignore any attempt to form a cv-qualified reference.
1978 if (T->isReferenceType())
1979 CVRAU &=
1980 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1982 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1983 // TQ_unaligned;
1984 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1986 // C11 6.7.3/5:
1987 // If the same qualifier appears more than once in the same
1988 // specifier-qualifier-list, either directly or via one or more typedefs,
1989 // the behavior is the same as if it appeared only once.
1991 // It's not specified what happens when the _Atomic qualifier is applied to
1992 // a type specified with the _Atomic specifier, but we assume that this
1993 // should be treated as if the _Atomic qualifier appeared multiple times.
1994 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1995 // C11 6.7.3/5:
1996 // If other qualifiers appear along with the _Atomic qualifier in a
1997 // specifier-qualifier-list, the resulting type is the so-qualified
1998 // atomic type.
2000 // Don't need to worry about array types here, since _Atomic can't be
2001 // applied to such types.
2002 SplitQualType Split = T.getSplitUnqualifiedType();
2003 T = BuildAtomicType(QualType(Split.Ty, 0),
2004 DS ? DS->getAtomicSpecLoc() : Loc);
2005 if (T.isNull())
2006 return T;
2007 Split.Quals.addCVRQualifiers(CVR);
2008 return BuildQualifiedType(T, Loc, Split.Quals);
2011 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
2012 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
2013 return BuildQualifiedType(T, Loc, Q, DS);
2016 /// Build a paren type including \p T.
2017 QualType Sema::BuildParenType(QualType T) {
2018 return Context.getParenType(T);
2021 /// Given that we're building a pointer or reference to the given
2022 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
2023 SourceLocation loc,
2024 bool isReference) {
2025 // Bail out if retention is unrequired or already specified.
2026 if (!type->isObjCLifetimeType() ||
2027 type.getObjCLifetime() != Qualifiers::OCL_None)
2028 return type;
2030 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
2032 // If the object type is const-qualified, we can safely use
2033 // __unsafe_unretained. This is safe (because there are no read
2034 // barriers), and it'll be safe to coerce anything but __weak* to
2035 // the resulting type.
2036 if (type.isConstQualified()) {
2037 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2039 // Otherwise, check whether the static type does not require
2040 // retaining. This currently only triggers for Class (possibly
2041 // protocol-qualifed, and arrays thereof).
2042 } else if (type->isObjCARCImplicitlyUnretainedType()) {
2043 implicitLifetime = Qualifiers::OCL_ExplicitNone;
2045 // If we are in an unevaluated context, like sizeof, skip adding a
2046 // qualification.
2047 } else if (S.isUnevaluatedContext()) {
2048 return type;
2050 // If that failed, give an error and recover using __strong. __strong
2051 // is the option most likely to prevent spurious second-order diagnostics,
2052 // like when binding a reference to a field.
2053 } else {
2054 // These types can show up in private ivars in system headers, so
2055 // we need this to not be an error in those cases. Instead we
2056 // want to delay.
2057 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
2058 S.DelayedDiagnostics.add(
2059 sema::DelayedDiagnostic::makeForbiddenType(loc,
2060 diag::err_arc_indirect_no_ownership, type, isReference));
2061 } else {
2062 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
2064 implicitLifetime = Qualifiers::OCL_Strong;
2066 assert(implicitLifetime && "didn't infer any lifetime!");
2068 Qualifiers qs;
2069 qs.addObjCLifetime(implicitLifetime);
2070 return S.Context.getQualifiedType(type, qs);
2073 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2074 std::string Quals = FnTy->getMethodQuals().getAsString();
2076 switch (FnTy->getRefQualifier()) {
2077 case RQ_None:
2078 break;
2080 case RQ_LValue:
2081 if (!Quals.empty())
2082 Quals += ' ';
2083 Quals += '&';
2084 break;
2086 case RQ_RValue:
2087 if (!Quals.empty())
2088 Quals += ' ';
2089 Quals += "&&";
2090 break;
2093 return Quals;
2096 namespace {
2097 /// Kinds of declarator that cannot contain a qualified function type.
2099 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
2100 /// a function type with a cv-qualifier or a ref-qualifier can only appear
2101 /// at the topmost level of a type.
2103 /// Parens and member pointers are permitted. We don't diagnose array and
2104 /// function declarators, because they don't allow function types at all.
2106 /// The values of this enum are used in diagnostics.
2107 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
2108 } // end anonymous namespace
2110 /// Check whether the type T is a qualified function type, and if it is,
2111 /// diagnose that it cannot be contained within the given kind of declarator.
2112 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
2113 QualifiedFunctionKind QFK) {
2114 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2115 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2116 if (!FPT ||
2117 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2118 return false;
2120 S.Diag(Loc, diag::err_compound_qualified_function_type)
2121 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
2122 << getFunctionQualifiersAsString(FPT);
2123 return true;
2126 bool Sema::CheckQualifiedFunctionForTypeId(QualType T, SourceLocation Loc) {
2127 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
2128 if (!FPT ||
2129 (FPT->getMethodQuals().empty() && FPT->getRefQualifier() == RQ_None))
2130 return false;
2132 Diag(Loc, diag::err_qualified_function_typeid)
2133 << T << getFunctionQualifiersAsString(FPT);
2134 return true;
2137 // Helper to deduce addr space of a pointee type in OpenCL mode.
2138 static QualType deduceOpenCLPointeeAddrSpace(Sema &S, QualType PointeeType) {
2139 if (!PointeeType->isUndeducedAutoType() && !PointeeType->isDependentType() &&
2140 !PointeeType->isSamplerT() &&
2141 !PointeeType.hasAddressSpace())
2142 PointeeType = S.getASTContext().getAddrSpaceQualType(
2143 PointeeType, S.getASTContext().getDefaultOpenCLPointeeAddrSpace());
2144 return PointeeType;
2147 /// Build a pointer type.
2149 /// \param T The type to which we'll be building a pointer.
2151 /// \param Loc The location of the entity whose type involves this
2152 /// pointer type or, if there is no such entity, the location of the
2153 /// type that will have pointer type.
2155 /// \param Entity The name of the entity that involves the pointer
2156 /// type, if known.
2158 /// \returns A suitable pointer type, if there are no
2159 /// errors. Otherwise, returns a NULL type.
2160 QualType Sema::BuildPointerType(QualType T,
2161 SourceLocation Loc, DeclarationName Entity) {
2162 if (T->isReferenceType()) {
2163 // C++ 8.3.2p4: There shall be no ... pointers to references ...
2164 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
2165 << getPrintableNameForEntity(Entity) << T;
2166 return QualType();
2169 if (T->isFunctionType() && getLangOpts().OpenCL &&
2170 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2171 getLangOpts())) {
2172 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
2173 return QualType();
2176 if (getLangOpts().HLSL && Loc.isValid()) {
2177 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
2178 return QualType();
2181 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
2182 return QualType();
2184 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
2186 // In ARC, it is forbidden to build pointers to unqualified pointers.
2187 if (getLangOpts().ObjCAutoRefCount)
2188 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
2190 if (getLangOpts().OpenCL)
2191 T = deduceOpenCLPointeeAddrSpace(*this, T);
2193 // Build the pointer type.
2194 return Context.getPointerType(T);
2197 /// Build a reference type.
2199 /// \param T The type to which we'll be building a reference.
2201 /// \param Loc The location of the entity whose type involves this
2202 /// reference type or, if there is no such entity, the location of the
2203 /// type that will have reference type.
2205 /// \param Entity The name of the entity that involves the reference
2206 /// type, if known.
2208 /// \returns A suitable reference type, if there are no
2209 /// errors. Otherwise, returns a NULL type.
2210 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
2211 SourceLocation Loc,
2212 DeclarationName Entity) {
2213 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
2214 "Unresolved overloaded function type");
2216 // C++0x [dcl.ref]p6:
2217 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
2218 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
2219 // type T, an attempt to create the type "lvalue reference to cv TR" creates
2220 // the type "lvalue reference to T", while an attempt to create the type
2221 // "rvalue reference to cv TR" creates the type TR.
2222 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
2224 // C++ [dcl.ref]p4: There shall be no references to references.
2226 // According to C++ DR 106, references to references are only
2227 // diagnosed when they are written directly (e.g., "int & &"),
2228 // but not when they happen via a typedef:
2230 // typedef int& intref;
2231 // typedef intref& intref2;
2233 // Parser::ParseDeclaratorInternal diagnoses the case where
2234 // references are written directly; here, we handle the
2235 // collapsing of references-to-references as described in C++0x.
2236 // DR 106 and 540 introduce reference-collapsing into C++98/03.
2238 // C++ [dcl.ref]p1:
2239 // A declarator that specifies the type "reference to cv void"
2240 // is ill-formed.
2241 if (T->isVoidType()) {
2242 Diag(Loc, diag::err_reference_to_void);
2243 return QualType();
2246 if (getLangOpts().HLSL && Loc.isValid()) {
2247 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 1;
2248 return QualType();
2251 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
2252 return QualType();
2254 if (T->isFunctionType() && getLangOpts().OpenCL &&
2255 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
2256 getLangOpts())) {
2257 Diag(Loc, diag::err_opencl_function_pointer) << /*reference*/ 1;
2258 return QualType();
2261 // In ARC, it is forbidden to build references to unqualified pointers.
2262 if (getLangOpts().ObjCAutoRefCount)
2263 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
2265 if (getLangOpts().OpenCL)
2266 T = deduceOpenCLPointeeAddrSpace(*this, T);
2268 // Handle restrict on references.
2269 if (LValueRef)
2270 return Context.getLValueReferenceType(T, SpelledAsLValue);
2271 return Context.getRValueReferenceType(T);
2274 /// Build a Read-only Pipe type.
2276 /// \param T The type to which we'll be building a Pipe.
2278 /// \param Loc We do not use it for now.
2280 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2281 /// NULL type.
2282 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2283 return Context.getReadPipeType(T);
2286 /// Build a Write-only Pipe type.
2288 /// \param T The type to which we'll be building a Pipe.
2290 /// \param Loc We do not use it for now.
2292 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2293 /// NULL type.
2294 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2295 return Context.getWritePipeType(T);
2298 /// Build a bit-precise integer type.
2300 /// \param IsUnsigned Boolean representing the signedness of the type.
2302 /// \param BitWidth Size of this int type in bits, or an expression representing
2303 /// that.
2305 /// \param Loc Location of the keyword.
2306 QualType Sema::BuildBitIntType(bool IsUnsigned, Expr *BitWidth,
2307 SourceLocation Loc) {
2308 if (BitWidth->isInstantiationDependent())
2309 return Context.getDependentBitIntType(IsUnsigned, BitWidth);
2311 llvm::APSInt Bits(32);
2312 ExprResult ICE =
2313 VerifyIntegerConstantExpression(BitWidth, &Bits, /*FIXME*/ AllowFold);
2315 if (ICE.isInvalid())
2316 return QualType();
2318 size_t NumBits = Bits.getZExtValue();
2319 if (!IsUnsigned && NumBits < 2) {
2320 Diag(Loc, diag::err_bit_int_bad_size) << 0;
2321 return QualType();
2324 if (IsUnsigned && NumBits < 1) {
2325 Diag(Loc, diag::err_bit_int_bad_size) << 1;
2326 return QualType();
2329 const TargetInfo &TI = getASTContext().getTargetInfo();
2330 if (NumBits > TI.getMaxBitIntWidth()) {
2331 Diag(Loc, diag::err_bit_int_max_size)
2332 << IsUnsigned << static_cast<uint64_t>(TI.getMaxBitIntWidth());
2333 return QualType();
2336 return Context.getBitIntType(IsUnsigned, NumBits);
2339 /// Check whether the specified array bound can be evaluated using the relevant
2340 /// language rules. If so, returns the possibly-converted expression and sets
2341 /// SizeVal to the size. If not, but the expression might be a VLA bound,
2342 /// returns ExprResult(). Otherwise, produces a diagnostic and returns
2343 /// ExprError().
2344 static ExprResult checkArraySize(Sema &S, Expr *&ArraySize,
2345 llvm::APSInt &SizeVal, unsigned VLADiag,
2346 bool VLAIsError) {
2347 if (S.getLangOpts().CPlusPlus14 &&
2348 (VLAIsError ||
2349 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType())) {
2350 // C++14 [dcl.array]p1:
2351 // The constant-expression shall be a converted constant expression of
2352 // type std::size_t.
2354 // Don't apply this rule if we might be forming a VLA: in that case, we
2355 // allow non-constant expressions and constant-folding. We only need to use
2356 // the converted constant expression rules (to properly convert the source)
2357 // when the source expression is of class type.
2358 return S.CheckConvertedConstantExpression(
2359 ArraySize, S.Context.getSizeType(), SizeVal, Sema::CCEK_ArrayBound);
2362 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2363 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2364 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2365 public:
2366 unsigned VLADiag;
2367 bool VLAIsError;
2368 bool IsVLA = false;
2370 VLADiagnoser(unsigned VLADiag, bool VLAIsError)
2371 : VLADiag(VLADiag), VLAIsError(VLAIsError) {}
2373 Sema::SemaDiagnosticBuilder diagnoseNotICEType(Sema &S, SourceLocation Loc,
2374 QualType T) override {
2375 return S.Diag(Loc, diag::err_array_size_non_int) << T;
2378 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
2379 SourceLocation Loc) override {
2380 IsVLA = !VLAIsError;
2381 return S.Diag(Loc, VLADiag);
2384 Sema::SemaDiagnosticBuilder diagnoseFold(Sema &S,
2385 SourceLocation Loc) override {
2386 return S.Diag(Loc, diag::ext_vla_folded_to_constant);
2388 } Diagnoser(VLADiag, VLAIsError);
2390 ExprResult R =
2391 S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser);
2392 if (Diagnoser.IsVLA)
2393 return ExprResult();
2394 return R;
2397 /// Build an array type.
2399 /// \param T The type of each element in the array.
2401 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2403 /// \param ArraySize Expression describing the size of the array.
2405 /// \param Brackets The range from the opening '[' to the closing ']'.
2407 /// \param Entity The name of the entity that involves the array
2408 /// type, if known.
2410 /// \returns A suitable array type, if there are no errors. Otherwise,
2411 /// returns a NULL type.
2412 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2413 Expr *ArraySize, unsigned Quals,
2414 SourceRange Brackets, DeclarationName Entity) {
2416 SourceLocation Loc = Brackets.getBegin();
2417 if (getLangOpts().CPlusPlus) {
2418 // C++ [dcl.array]p1:
2419 // T is called the array element type; this type shall not be a reference
2420 // type, the (possibly cv-qualified) type void, a function type or an
2421 // abstract class type.
2423 // C++ [dcl.array]p3:
2424 // When several "array of" specifications are adjacent, [...] only the
2425 // first of the constant expressions that specify the bounds of the arrays
2426 // may be omitted.
2428 // Note: function types are handled in the common path with C.
2429 if (T->isReferenceType()) {
2430 Diag(Loc, diag::err_illegal_decl_array_of_references)
2431 << getPrintableNameForEntity(Entity) << T;
2432 return QualType();
2435 if (T->isVoidType() || T->isIncompleteArrayType()) {
2436 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 0 << T;
2437 return QualType();
2440 if (RequireNonAbstractType(Brackets.getBegin(), T,
2441 diag::err_array_of_abstract_type))
2442 return QualType();
2444 // Mentioning a member pointer type for an array type causes us to lock in
2445 // an inheritance model, even if it's inside an unused typedef.
2446 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2447 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2448 if (!MPTy->getClass()->isDependentType())
2449 (void)isCompleteType(Loc, T);
2451 } else {
2452 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2453 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2454 if (RequireCompleteSizedType(Loc, T,
2455 diag::err_array_incomplete_or_sizeless_type))
2456 return QualType();
2459 if (T->isSizelessType()) {
2460 Diag(Loc, diag::err_array_incomplete_or_sizeless_type) << 1 << T;
2461 return QualType();
2464 if (T->isFunctionType()) {
2465 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2466 << getPrintableNameForEntity(Entity) << T;
2467 return QualType();
2470 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2471 // If the element type is a struct or union that contains a variadic
2472 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2473 if (EltTy->getDecl()->hasFlexibleArrayMember())
2474 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2475 } else if (T->isObjCObjectType()) {
2476 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2477 return QualType();
2480 // Do placeholder conversions on the array size expression.
2481 if (ArraySize && ArraySize->hasPlaceholderType()) {
2482 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2483 if (Result.isInvalid()) return QualType();
2484 ArraySize = Result.get();
2487 // Do lvalue-to-rvalue conversions on the array size expression.
2488 if (ArraySize && !ArraySize->isPRValue()) {
2489 ExprResult Result = DefaultLvalueConversion(ArraySize);
2490 if (Result.isInvalid())
2491 return QualType();
2493 ArraySize = Result.get();
2496 // C99 6.7.5.2p1: The size expression shall have integer type.
2497 // C++11 allows contextual conversions to such types.
2498 if (!getLangOpts().CPlusPlus11 &&
2499 ArraySize && !ArraySize->isTypeDependent() &&
2500 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2501 Diag(ArraySize->getBeginLoc(), diag::err_array_size_non_int)
2502 << ArraySize->getType() << ArraySize->getSourceRange();
2503 return QualType();
2506 // VLAs always produce at least a -Wvla diagnostic, sometimes an error.
2507 unsigned VLADiag;
2508 bool VLAIsError;
2509 if (getLangOpts().OpenCL) {
2510 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2511 VLADiag = diag::err_opencl_vla;
2512 VLAIsError = true;
2513 } else if (getLangOpts().C99) {
2514 VLADiag = diag::warn_vla_used;
2515 VLAIsError = false;
2516 } else if (isSFINAEContext()) {
2517 VLADiag = diag::err_vla_in_sfinae;
2518 VLAIsError = true;
2519 } else if (getLangOpts().OpenMP && isInOpenMPTaskUntiedContext()) {
2520 VLADiag = diag::err_openmp_vla_in_task_untied;
2521 VLAIsError = true;
2522 } else {
2523 VLADiag = diag::ext_vla;
2524 VLAIsError = false;
2527 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2528 if (!ArraySize) {
2529 if (ASM == ArrayType::Star) {
2530 Diag(Loc, VLADiag);
2531 if (VLAIsError)
2532 return QualType();
2534 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2535 } else {
2536 T = Context.getIncompleteArrayType(T, ASM, Quals);
2538 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2539 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2540 } else {
2541 ExprResult R =
2542 checkArraySize(*this, ArraySize, ConstVal, VLADiag, VLAIsError);
2543 if (R.isInvalid())
2544 return QualType();
2546 if (!R.isUsable()) {
2547 // C99: an array with a non-ICE size is a VLA. We accept any expression
2548 // that we can fold to a non-zero positive value as a non-VLA as an
2549 // extension.
2550 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2551 } else if (!T->isDependentType() && !T->isIncompleteType() &&
2552 !T->isConstantSizeType()) {
2553 // C99: an array with an element type that has a non-constant-size is a
2554 // VLA.
2555 // FIXME: Add a note to explain why this isn't a VLA.
2556 Diag(Loc, VLADiag);
2557 if (VLAIsError)
2558 return QualType();
2559 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2560 } else {
2561 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2562 // have a value greater than zero.
2563 // In C++, this follows from narrowing conversions being disallowed.
2564 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2565 if (Entity)
2566 Diag(ArraySize->getBeginLoc(), diag::err_decl_negative_array_size)
2567 << getPrintableNameForEntity(Entity)
2568 << ArraySize->getSourceRange();
2569 else
2570 Diag(ArraySize->getBeginLoc(),
2571 diag::err_typecheck_negative_array_size)
2572 << ArraySize->getSourceRange();
2573 return QualType();
2575 if (ConstVal == 0) {
2576 // GCC accepts zero sized static arrays. We allow them when
2577 // we're not in a SFINAE context.
2578 Diag(ArraySize->getBeginLoc(),
2579 isSFINAEContext() ? diag::err_typecheck_zero_array_size
2580 : diag::ext_typecheck_zero_array_size)
2581 << 0 << ArraySize->getSourceRange();
2584 // Is the array too large?
2585 unsigned ActiveSizeBits =
2586 (!T->isDependentType() && !T->isVariablyModifiedType() &&
2587 !T->isIncompleteType() && !T->isUndeducedType())
2588 ? ConstantArrayType::getNumAddressingBits(Context, T, ConstVal)
2589 : ConstVal.getActiveBits();
2590 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2591 Diag(ArraySize->getBeginLoc(), diag::err_array_too_large)
2592 << toString(ConstVal, 10) << ArraySize->getSourceRange();
2593 return QualType();
2596 T = Context.getConstantArrayType(T, ConstVal, ArraySize, ASM, Quals);
2600 if (T->isVariableArrayType() && !Context.getTargetInfo().isVLASupported()) {
2601 // CUDA device code and some other targets don't support VLAs.
2602 targetDiag(Loc, (getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2603 ? diag::err_cuda_vla
2604 : diag::err_vla_unsupported)
2605 << ((getLangOpts().CUDA && getLangOpts().CUDAIsDevice)
2606 ? CurrentCUDATarget()
2607 : CFT_InvalidTarget);
2610 // If this is not C99, diagnose array size modifiers on non-VLAs.
2611 if (!getLangOpts().C99 && !T->isVariableArrayType() &&
2612 (ASM != ArrayType::Normal || Quals != 0)) {
2613 Diag(Loc, getLangOpts().CPlusPlus ? diag::err_c99_array_usage_cxx
2614 : diag::ext_c99_array_usage)
2615 << ASM;
2618 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2619 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2620 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2621 if (getLangOpts().OpenCL) {
2622 const QualType ArrType = Context.getBaseElementType(T);
2623 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2624 ArrType->isSamplerT() || ArrType->isImageType()) {
2625 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2626 return QualType();
2630 return T;
2633 QualType Sema::BuildVectorType(QualType CurType, Expr *SizeExpr,
2634 SourceLocation AttrLoc) {
2635 // The base type must be integer (not Boolean or enumeration) or float, and
2636 // can't already be a vector.
2637 if ((!CurType->isDependentType() &&
2638 (!CurType->isBuiltinType() || CurType->isBooleanType() ||
2639 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) &&
2640 !CurType->isBitIntType()) ||
2641 CurType->isArrayType()) {
2642 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << CurType;
2643 return QualType();
2645 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2646 if (CurType->isBitIntType()) {
2647 unsigned NumBits = CurType->getAs<BitIntType>()->getNumBits();
2648 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2649 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2650 << (NumBits < 8);
2651 return QualType();
2655 if (SizeExpr->isTypeDependent() || SizeExpr->isValueDependent())
2656 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2657 VectorType::GenericVector);
2659 Optional<llvm::APSInt> VecSize = SizeExpr->getIntegerConstantExpr(Context);
2660 if (!VecSize) {
2661 Diag(AttrLoc, diag::err_attribute_argument_type)
2662 << "vector_size" << AANT_ArgumentIntegerConstant
2663 << SizeExpr->getSourceRange();
2664 return QualType();
2667 if (CurType->isDependentType())
2668 return Context.getDependentVectorType(CurType, SizeExpr, AttrLoc,
2669 VectorType::GenericVector);
2671 // vecSize is specified in bytes - convert to bits.
2672 if (!VecSize->isIntN(61)) {
2673 // Bit size will overflow uint64.
2674 Diag(AttrLoc, diag::err_attribute_size_too_large)
2675 << SizeExpr->getSourceRange() << "vector";
2676 return QualType();
2678 uint64_t VectorSizeBits = VecSize->getZExtValue() * 8;
2679 unsigned TypeSize = static_cast<unsigned>(Context.getTypeSize(CurType));
2681 if (VectorSizeBits == 0) {
2682 Diag(AttrLoc, diag::err_attribute_zero_size)
2683 << SizeExpr->getSourceRange() << "vector";
2684 return QualType();
2687 if (!TypeSize || VectorSizeBits % TypeSize) {
2688 Diag(AttrLoc, diag::err_attribute_invalid_size)
2689 << SizeExpr->getSourceRange();
2690 return QualType();
2693 if (VectorSizeBits / TypeSize > std::numeric_limits<uint32_t>::max()) {
2694 Diag(AttrLoc, diag::err_attribute_size_too_large)
2695 << SizeExpr->getSourceRange() << "vector";
2696 return QualType();
2699 return Context.getVectorType(CurType, VectorSizeBits / TypeSize,
2700 VectorType::GenericVector);
2703 /// Build an ext-vector type.
2705 /// Run the required checks for the extended vector type.
2706 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2707 SourceLocation AttrLoc) {
2708 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2709 // in conjunction with complex types (pointers, arrays, functions, etc.).
2711 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2712 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2713 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2714 // of bool aren't allowed.
2716 // We explictly allow bool elements in ext_vector_type for C/C++.
2717 bool IsNoBoolVecLang = getLangOpts().OpenCL || getLangOpts().OpenCLCPlusPlus;
2718 if ((!T->isDependentType() && !T->isIntegerType() &&
2719 !T->isRealFloatingType()) ||
2720 (IsNoBoolVecLang && T->isBooleanType())) {
2721 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2722 return QualType();
2725 // Only support _BitInt elements with byte-sized power of 2 NumBits.
2726 if (T->isBitIntType()) {
2727 unsigned NumBits = T->getAs<BitIntType>()->getNumBits();
2728 if (!llvm::isPowerOf2_32(NumBits) || NumBits < 8) {
2729 Diag(AttrLoc, diag::err_attribute_invalid_bitint_vector_type)
2730 << (NumBits < 8);
2731 return QualType();
2735 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2736 Optional<llvm::APSInt> vecSize = ArraySize->getIntegerConstantExpr(Context);
2737 if (!vecSize) {
2738 Diag(AttrLoc, diag::err_attribute_argument_type)
2739 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2740 << ArraySize->getSourceRange();
2741 return QualType();
2744 if (!vecSize->isIntN(32)) {
2745 Diag(AttrLoc, diag::err_attribute_size_too_large)
2746 << ArraySize->getSourceRange() << "vector";
2747 return QualType();
2749 // Unlike gcc's vector_size attribute, the size is specified as the
2750 // number of elements, not the number of bytes.
2751 unsigned vectorSize = static_cast<unsigned>(vecSize->getZExtValue());
2753 if (vectorSize == 0) {
2754 Diag(AttrLoc, diag::err_attribute_zero_size)
2755 << ArraySize->getSourceRange() << "vector";
2756 return QualType();
2759 return Context.getExtVectorType(T, vectorSize);
2762 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2765 QualType Sema::BuildMatrixType(QualType ElementTy, Expr *NumRows, Expr *NumCols,
2766 SourceLocation AttrLoc) {
2767 assert(Context.getLangOpts().MatrixTypes &&
2768 "Should never build a matrix type when it is disabled");
2770 // Check element type, if it is not dependent.
2771 if (!ElementTy->isDependentType() &&
2772 !MatrixType::isValidElementType(ElementTy)) {
2773 Diag(AttrLoc, diag::err_attribute_invalid_matrix_type) << ElementTy;
2774 return QualType();
2777 if (NumRows->isTypeDependent() || NumCols->isTypeDependent() ||
2778 NumRows->isValueDependent() || NumCols->isValueDependent())
2779 return Context.getDependentSizedMatrixType(ElementTy, NumRows, NumCols,
2780 AttrLoc);
2782 Optional<llvm::APSInt> ValueRows = NumRows->getIntegerConstantExpr(Context);
2783 Optional<llvm::APSInt> ValueColumns =
2784 NumCols->getIntegerConstantExpr(Context);
2786 auto const RowRange = NumRows->getSourceRange();
2787 auto const ColRange = NumCols->getSourceRange();
2789 // Both are row and column expressions are invalid.
2790 if (!ValueRows && !ValueColumns) {
2791 Diag(AttrLoc, diag::err_attribute_argument_type)
2792 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange
2793 << ColRange;
2794 return QualType();
2797 // Only the row expression is invalid.
2798 if (!ValueRows) {
2799 Diag(AttrLoc, diag::err_attribute_argument_type)
2800 << "matrix_type" << AANT_ArgumentIntegerConstant << RowRange;
2801 return QualType();
2804 // Only the column expression is invalid.
2805 if (!ValueColumns) {
2806 Diag(AttrLoc, diag::err_attribute_argument_type)
2807 << "matrix_type" << AANT_ArgumentIntegerConstant << ColRange;
2808 return QualType();
2811 // Check the matrix dimensions.
2812 unsigned MatrixRows = static_cast<unsigned>(ValueRows->getZExtValue());
2813 unsigned MatrixColumns = static_cast<unsigned>(ValueColumns->getZExtValue());
2814 if (MatrixRows == 0 && MatrixColumns == 0) {
2815 Diag(AttrLoc, diag::err_attribute_zero_size)
2816 << "matrix" << RowRange << ColRange;
2817 return QualType();
2819 if (MatrixRows == 0) {
2820 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << RowRange;
2821 return QualType();
2823 if (MatrixColumns == 0) {
2824 Diag(AttrLoc, diag::err_attribute_zero_size) << "matrix" << ColRange;
2825 return QualType();
2827 if (!ConstantMatrixType::isDimensionValid(MatrixRows)) {
2828 Diag(AttrLoc, diag::err_attribute_size_too_large)
2829 << RowRange << "matrix row";
2830 return QualType();
2832 if (!ConstantMatrixType::isDimensionValid(MatrixColumns)) {
2833 Diag(AttrLoc, diag::err_attribute_size_too_large)
2834 << ColRange << "matrix column";
2835 return QualType();
2837 return Context.getConstantMatrixType(ElementTy, MatrixRows, MatrixColumns);
2840 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2841 if (T->isArrayType() || T->isFunctionType()) {
2842 Diag(Loc, diag::err_func_returning_array_function)
2843 << T->isFunctionType() << T;
2844 return true;
2847 // Functions cannot return half FP.
2848 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2849 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2850 FixItHint::CreateInsertion(Loc, "*");
2851 return true;
2854 // Methods cannot return interface types. All ObjC objects are
2855 // passed by reference.
2856 if (T->isObjCObjectType()) {
2857 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value)
2858 << 0 << T << FixItHint::CreateInsertion(Loc, "*");
2859 return true;
2862 if (T.hasNonTrivialToPrimitiveDestructCUnion() ||
2863 T.hasNonTrivialToPrimitiveCopyCUnion())
2864 checkNonTrivialCUnion(T, Loc, NTCUC_FunctionReturn,
2865 NTCUK_Destruct|NTCUK_Copy);
2867 // C++2a [dcl.fct]p12:
2868 // A volatile-qualified return type is deprecated
2869 if (T.isVolatileQualified() && getLangOpts().CPlusPlus20)
2870 Diag(Loc, diag::warn_deprecated_volatile_return) << T;
2872 return false;
2875 /// Check the extended parameter information. Most of the necessary
2876 /// checking should occur when applying the parameter attribute; the
2877 /// only other checks required are positional restrictions.
2878 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2879 const FunctionProtoType::ExtProtoInfo &EPI,
2880 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2881 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2883 bool emittedError = false;
2884 auto actualCC = EPI.ExtInfo.getCC();
2885 enum class RequiredCC { OnlySwift, SwiftOrSwiftAsync };
2886 auto checkCompatible = [&](unsigned paramIndex, RequiredCC required) {
2887 bool isCompatible =
2888 (required == RequiredCC::OnlySwift)
2889 ? (actualCC == CC_Swift)
2890 : (actualCC == CC_Swift || actualCC == CC_SwiftAsync);
2891 if (isCompatible || emittedError)
2892 return;
2893 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2894 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI())
2895 << (required == RequiredCC::OnlySwift);
2896 emittedError = true;
2898 for (size_t paramIndex = 0, numParams = paramTypes.size();
2899 paramIndex != numParams; ++paramIndex) {
2900 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2901 // Nothing interesting to check for orindary-ABI parameters.
2902 case ParameterABI::Ordinary:
2903 continue;
2905 // swift_indirect_result parameters must be a prefix of the function
2906 // arguments.
2907 case ParameterABI::SwiftIndirectResult:
2908 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2909 if (paramIndex != 0 &&
2910 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2911 != ParameterABI::SwiftIndirectResult) {
2912 S.Diag(getParamLoc(paramIndex),
2913 diag::err_swift_indirect_result_not_first);
2915 continue;
2917 case ParameterABI::SwiftContext:
2918 checkCompatible(paramIndex, RequiredCC::SwiftOrSwiftAsync);
2919 continue;
2921 // SwiftAsyncContext is not limited to swiftasynccall functions.
2922 case ParameterABI::SwiftAsyncContext:
2923 continue;
2925 // swift_error parameters must be preceded by a swift_context parameter.
2926 case ParameterABI::SwiftErrorResult:
2927 checkCompatible(paramIndex, RequiredCC::OnlySwift);
2928 if (paramIndex == 0 ||
2929 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2930 ParameterABI::SwiftContext) {
2931 S.Diag(getParamLoc(paramIndex),
2932 diag::err_swift_error_result_not_after_swift_context);
2934 continue;
2936 llvm_unreachable("bad ABI kind");
2940 QualType Sema::BuildFunctionType(QualType T,
2941 MutableArrayRef<QualType> ParamTypes,
2942 SourceLocation Loc, DeclarationName Entity,
2943 const FunctionProtoType::ExtProtoInfo &EPI) {
2944 bool Invalid = false;
2946 Invalid |= CheckFunctionReturnType(T, Loc);
2948 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2949 // FIXME: Loc is too inprecise here, should use proper locations for args.
2950 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2951 if (ParamType->isVoidType()) {
2952 Diag(Loc, diag::err_param_with_void_type);
2953 Invalid = true;
2954 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2955 // Disallow half FP arguments.
2956 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2957 FixItHint::CreateInsertion(Loc, "*");
2958 Invalid = true;
2961 // C++2a [dcl.fct]p4:
2962 // A parameter with volatile-qualified type is deprecated
2963 if (ParamType.isVolatileQualified() && getLangOpts().CPlusPlus20)
2964 Diag(Loc, diag::warn_deprecated_volatile_param) << ParamType;
2966 ParamTypes[Idx] = ParamType;
2969 if (EPI.ExtParameterInfos) {
2970 checkExtParameterInfos(*this, ParamTypes, EPI,
2971 [=](unsigned i) { return Loc; });
2974 if (EPI.ExtInfo.getProducesResult()) {
2975 // This is just a warning, so we can't fail to build if we see it.
2976 checkNSReturnsRetainedReturnType(Loc, T);
2979 if (Invalid)
2980 return QualType();
2982 return Context.getFunctionType(T, ParamTypes, EPI);
2985 /// Build a member pointer type \c T Class::*.
2987 /// \param T the type to which the member pointer refers.
2988 /// \param Class the class type into which the member pointer points.
2989 /// \param Loc the location where this type begins
2990 /// \param Entity the name of the entity that will have this member pointer type
2992 /// \returns a member pointer type, if successful, or a NULL type if there was
2993 /// an error.
2994 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2995 SourceLocation Loc,
2996 DeclarationName Entity) {
2997 // Verify that we're not building a pointer to pointer to function with
2998 // exception specification.
2999 if (CheckDistantExceptionSpec(T)) {
3000 Diag(Loc, diag::err_distant_exception_spec);
3001 return QualType();
3004 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
3005 // with reference type, or "cv void."
3006 if (T->isReferenceType()) {
3007 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
3008 << getPrintableNameForEntity(Entity) << T;
3009 return QualType();
3012 if (T->isVoidType()) {
3013 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
3014 << getPrintableNameForEntity(Entity);
3015 return QualType();
3018 if (!Class->isDependentType() && !Class->isRecordType()) {
3019 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
3020 return QualType();
3023 if (T->isFunctionType() && getLangOpts().OpenCL &&
3024 !getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
3025 getLangOpts())) {
3026 Diag(Loc, diag::err_opencl_function_pointer) << /*pointer*/ 0;
3027 return QualType();
3030 if (getLangOpts().HLSL && Loc.isValid()) {
3031 Diag(Loc, diag::err_hlsl_pointers_unsupported) << 0;
3032 return QualType();
3035 // Adjust the default free function calling convention to the default method
3036 // calling convention.
3037 bool IsCtorOrDtor =
3038 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
3039 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
3040 if (T->isFunctionType())
3041 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
3043 return Context.getMemberPointerType(T, Class.getTypePtr());
3046 /// Build a block pointer type.
3048 /// \param T The type to which we'll be building a block pointer.
3050 /// \param Loc The source location, used for diagnostics.
3052 /// \param Entity The name of the entity that involves the block pointer
3053 /// type, if known.
3055 /// \returns A suitable block pointer type, if there are no
3056 /// errors. Otherwise, returns a NULL type.
3057 QualType Sema::BuildBlockPointerType(QualType T,
3058 SourceLocation Loc,
3059 DeclarationName Entity) {
3060 if (!T->isFunctionType()) {
3061 Diag(Loc, diag::err_nonfunction_block_type);
3062 return QualType();
3065 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
3066 return QualType();
3068 if (getLangOpts().OpenCL)
3069 T = deduceOpenCLPointeeAddrSpace(*this, T);
3071 return Context.getBlockPointerType(T);
3074 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
3075 QualType QT = Ty.get();
3076 if (QT.isNull()) {
3077 if (TInfo) *TInfo = nullptr;
3078 return QualType();
3081 TypeSourceInfo *DI = nullptr;
3082 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
3083 QT = LIT->getType();
3084 DI = LIT->getTypeSourceInfo();
3087 if (TInfo) *TInfo = DI;
3088 return QT;
3091 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3092 Qualifiers::ObjCLifetime ownership,
3093 unsigned chunkIndex);
3095 /// Given that this is the declaration of a parameter under ARC,
3096 /// attempt to infer attributes and such for pointer-to-whatever
3097 /// types.
3098 static void inferARCWriteback(TypeProcessingState &state,
3099 QualType &declSpecType) {
3100 Sema &S = state.getSema();
3101 Declarator &declarator = state.getDeclarator();
3103 // TODO: should we care about decl qualifiers?
3105 // Check whether the declarator has the expected form. We walk
3106 // from the inside out in order to make the block logic work.
3107 unsigned outermostPointerIndex = 0;
3108 bool isBlockPointer = false;
3109 unsigned numPointers = 0;
3110 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
3111 unsigned chunkIndex = i;
3112 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
3113 switch (chunk.Kind) {
3114 case DeclaratorChunk::Paren:
3115 // Ignore parens.
3116 break;
3118 case DeclaratorChunk::Reference:
3119 case DeclaratorChunk::Pointer:
3120 // Count the number of pointers. Treat references
3121 // interchangeably as pointers; if they're mis-ordered, normal
3122 // type building will discover that.
3123 outermostPointerIndex = chunkIndex;
3124 numPointers++;
3125 break;
3127 case DeclaratorChunk::BlockPointer:
3128 // If we have a pointer to block pointer, that's an acceptable
3129 // indirect reference; anything else is not an application of
3130 // the rules.
3131 if (numPointers != 1) return;
3132 numPointers++;
3133 outermostPointerIndex = chunkIndex;
3134 isBlockPointer = true;
3136 // We don't care about pointer structure in return values here.
3137 goto done;
3139 case DeclaratorChunk::Array: // suppress if written (id[])?
3140 case DeclaratorChunk::Function:
3141 case DeclaratorChunk::MemberPointer:
3142 case DeclaratorChunk::Pipe:
3143 return;
3146 done:
3148 // If we have *one* pointer, then we want to throw the qualifier on
3149 // the declaration-specifiers, which means that it needs to be a
3150 // retainable object type.
3151 if (numPointers == 1) {
3152 // If it's not a retainable object type, the rule doesn't apply.
3153 if (!declSpecType->isObjCRetainableType()) return;
3155 // If it already has lifetime, don't do anything.
3156 if (declSpecType.getObjCLifetime()) return;
3158 // Otherwise, modify the type in-place.
3159 Qualifiers qs;
3161 if (declSpecType->isObjCARCImplicitlyUnretainedType())
3162 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
3163 else
3164 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
3165 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
3167 // If we have *two* pointers, then we want to throw the qualifier on
3168 // the outermost pointer.
3169 } else if (numPointers == 2) {
3170 // If we don't have a block pointer, we need to check whether the
3171 // declaration-specifiers gave us something that will turn into a
3172 // retainable object pointer after we slap the first pointer on it.
3173 if (!isBlockPointer && !declSpecType->isObjCObjectType())
3174 return;
3176 // Look for an explicit lifetime attribute there.
3177 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
3178 if (chunk.Kind != DeclaratorChunk::Pointer &&
3179 chunk.Kind != DeclaratorChunk::BlockPointer)
3180 return;
3181 for (const ParsedAttr &AL : chunk.getAttrs())
3182 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership)
3183 return;
3185 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
3186 outermostPointerIndex);
3188 // Any other number of pointers/references does not trigger the rule.
3189 } else return;
3191 // TODO: mark whether we did this inference?
3194 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
3195 SourceLocation FallbackLoc,
3196 SourceLocation ConstQualLoc,
3197 SourceLocation VolatileQualLoc,
3198 SourceLocation RestrictQualLoc,
3199 SourceLocation AtomicQualLoc,
3200 SourceLocation UnalignedQualLoc) {
3201 if (!Quals)
3202 return;
3204 struct Qual {
3205 const char *Name;
3206 unsigned Mask;
3207 SourceLocation Loc;
3208 } const QualKinds[5] = {
3209 { "const", DeclSpec::TQ_const, ConstQualLoc },
3210 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
3211 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
3212 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
3213 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
3216 SmallString<32> QualStr;
3217 unsigned NumQuals = 0;
3218 SourceLocation Loc;
3219 FixItHint FixIts[5];
3221 // Build a string naming the redundant qualifiers.
3222 for (auto &E : QualKinds) {
3223 if (Quals & E.Mask) {
3224 if (!QualStr.empty()) QualStr += ' ';
3225 QualStr += E.Name;
3227 // If we have a location for the qualifier, offer a fixit.
3228 SourceLocation QualLoc = E.Loc;
3229 if (QualLoc.isValid()) {
3230 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
3231 if (Loc.isInvalid() ||
3232 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
3233 Loc = QualLoc;
3236 ++NumQuals;
3240 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
3241 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
3244 // Diagnose pointless type qualifiers on the return type of a function.
3245 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
3246 Declarator &D,
3247 unsigned FunctionChunkIndex) {
3248 const DeclaratorChunk::FunctionTypeInfo &FTI =
3249 D.getTypeObject(FunctionChunkIndex).Fun;
3250 if (FTI.hasTrailingReturnType()) {
3251 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3252 RetTy.getLocalCVRQualifiers(),
3253 FTI.getTrailingReturnTypeLoc());
3254 return;
3257 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
3258 End = D.getNumTypeObjects();
3259 OuterChunkIndex != End; ++OuterChunkIndex) {
3260 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
3261 switch (OuterChunk.Kind) {
3262 case DeclaratorChunk::Paren:
3263 continue;
3265 case DeclaratorChunk::Pointer: {
3266 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
3267 S.diagnoseIgnoredQualifiers(
3268 diag::warn_qual_return_type,
3269 PTI.TypeQuals,
3270 SourceLocation(),
3271 PTI.ConstQualLoc,
3272 PTI.VolatileQualLoc,
3273 PTI.RestrictQualLoc,
3274 PTI.AtomicQualLoc,
3275 PTI.UnalignedQualLoc);
3276 return;
3279 case DeclaratorChunk::Function:
3280 case DeclaratorChunk::BlockPointer:
3281 case DeclaratorChunk::Reference:
3282 case DeclaratorChunk::Array:
3283 case DeclaratorChunk::MemberPointer:
3284 case DeclaratorChunk::Pipe:
3285 // FIXME: We can't currently provide an accurate source location and a
3286 // fix-it hint for these.
3287 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
3288 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3289 RetTy.getCVRQualifiers() | AtomicQual,
3290 D.getIdentifierLoc());
3291 return;
3294 llvm_unreachable("unknown declarator chunk kind");
3297 // If the qualifiers come from a conversion function type, don't diagnose
3298 // them -- they're not necessarily redundant, since such a conversion
3299 // operator can be explicitly called as "x.operator const int()".
3300 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3301 return;
3303 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
3304 // which are present there.
3305 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
3306 D.getDeclSpec().getTypeQualifiers(),
3307 D.getIdentifierLoc(),
3308 D.getDeclSpec().getConstSpecLoc(),
3309 D.getDeclSpec().getVolatileSpecLoc(),
3310 D.getDeclSpec().getRestrictSpecLoc(),
3311 D.getDeclSpec().getAtomicSpecLoc(),
3312 D.getDeclSpec().getUnalignedSpecLoc());
3315 static std::pair<QualType, TypeSourceInfo *>
3316 InventTemplateParameter(TypeProcessingState &state, QualType T,
3317 TypeSourceInfo *TrailingTSI, AutoType *Auto,
3318 InventedTemplateParameterInfo &Info) {
3319 Sema &S = state.getSema();
3320 Declarator &D = state.getDeclarator();
3322 const unsigned TemplateParameterDepth = Info.AutoTemplateParameterDepth;
3323 const unsigned AutoParameterPosition = Info.TemplateParams.size();
3324 const bool IsParameterPack = D.hasEllipsis();
3326 // If auto is mentioned in a lambda parameter or abbreviated function
3327 // template context, convert it to a template parameter type.
3329 // Create the TemplateTypeParmDecl here to retrieve the corresponding
3330 // template parameter type. Template parameters are temporarily added
3331 // to the TU until the associated TemplateDecl is created.
3332 TemplateTypeParmDecl *InventedTemplateParam =
3333 TemplateTypeParmDecl::Create(
3334 S.Context, S.Context.getTranslationUnitDecl(),
3335 /*KeyLoc=*/D.getDeclSpec().getTypeSpecTypeLoc(),
3336 /*NameLoc=*/D.getIdentifierLoc(),
3337 TemplateParameterDepth, AutoParameterPosition,
3338 S.InventAbbreviatedTemplateParameterTypeName(
3339 D.getIdentifier(), AutoParameterPosition), false,
3340 IsParameterPack, /*HasTypeConstraint=*/Auto->isConstrained());
3341 InventedTemplateParam->setImplicit();
3342 Info.TemplateParams.push_back(InventedTemplateParam);
3344 // Attach type constraints to the new parameter.
3345 if (Auto->isConstrained()) {
3346 if (TrailingTSI) {
3347 // The 'auto' appears in a trailing return type we've already built;
3348 // extract its type constraints to attach to the template parameter.
3349 AutoTypeLoc AutoLoc = TrailingTSI->getTypeLoc().getContainedAutoTypeLoc();
3350 TemplateArgumentListInfo TAL(AutoLoc.getLAngleLoc(), AutoLoc.getRAngleLoc());
3351 bool Invalid = false;
3352 for (unsigned Idx = 0; Idx < AutoLoc.getNumArgs(); ++Idx) {
3353 if (D.getEllipsisLoc().isInvalid() && !Invalid &&
3354 S.DiagnoseUnexpandedParameterPack(AutoLoc.getArgLoc(Idx),
3355 Sema::UPPC_TypeConstraint))
3356 Invalid = true;
3357 TAL.addArgument(AutoLoc.getArgLoc(Idx));
3360 if (!Invalid) {
3361 S.AttachTypeConstraint(
3362 AutoLoc.getNestedNameSpecifierLoc(), AutoLoc.getConceptNameInfo(),
3363 AutoLoc.getNamedConcept(),
3364 AutoLoc.hasExplicitTemplateArgs() ? &TAL : nullptr,
3365 InventedTemplateParam, D.getEllipsisLoc());
3367 } else {
3368 // The 'auto' appears in the decl-specifiers; we've not finished forming
3369 // TypeSourceInfo for it yet.
3370 TemplateIdAnnotation *TemplateId = D.getDeclSpec().getRepAsTemplateId();
3371 TemplateArgumentListInfo TemplateArgsInfo;
3372 bool Invalid = false;
3373 if (TemplateId->LAngleLoc.isValid()) {
3374 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
3375 TemplateId->NumArgs);
3376 S.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
3378 if (D.getEllipsisLoc().isInvalid()) {
3379 for (TemplateArgumentLoc Arg : TemplateArgsInfo.arguments()) {
3380 if (S.DiagnoseUnexpandedParameterPack(Arg,
3381 Sema::UPPC_TypeConstraint)) {
3382 Invalid = true;
3383 break;
3388 if (!Invalid) {
3389 S.AttachTypeConstraint(
3390 D.getDeclSpec().getTypeSpecScope().getWithLocInContext(S.Context),
3391 DeclarationNameInfo(DeclarationName(TemplateId->Name),
3392 TemplateId->TemplateNameLoc),
3393 cast<ConceptDecl>(TemplateId->Template.get().getAsTemplateDecl()),
3394 TemplateId->LAngleLoc.isValid() ? &TemplateArgsInfo : nullptr,
3395 InventedTemplateParam, D.getEllipsisLoc());
3400 // Replace the 'auto' in the function parameter with this invented
3401 // template type parameter.
3402 // FIXME: Retain some type sugar to indicate that this was written
3403 // as 'auto'?
3404 QualType Replacement(InventedTemplateParam->getTypeForDecl(), 0);
3405 QualType NewT = state.ReplaceAutoType(T, Replacement);
3406 TypeSourceInfo *NewTSI =
3407 TrailingTSI ? S.ReplaceAutoTypeSourceInfo(TrailingTSI, Replacement)
3408 : nullptr;
3409 return {NewT, NewTSI};
3412 static TypeSourceInfo *
3413 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
3414 QualType T, TypeSourceInfo *ReturnTypeInfo);
3416 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
3417 TypeSourceInfo *&ReturnTypeInfo) {
3418 Sema &SemaRef = state.getSema();
3419 Declarator &D = state.getDeclarator();
3420 QualType T;
3421 ReturnTypeInfo = nullptr;
3423 // The TagDecl owned by the DeclSpec.
3424 TagDecl *OwnedTagDecl = nullptr;
3426 switch (D.getName().getKind()) {
3427 case UnqualifiedIdKind::IK_ImplicitSelfParam:
3428 case UnqualifiedIdKind::IK_OperatorFunctionId:
3429 case UnqualifiedIdKind::IK_Identifier:
3430 case UnqualifiedIdKind::IK_LiteralOperatorId:
3431 case UnqualifiedIdKind::IK_TemplateId:
3432 T = ConvertDeclSpecToType(state);
3434 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
3435 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3436 // Owned declaration is embedded in declarator.
3437 OwnedTagDecl->setEmbeddedInDeclarator(true);
3439 break;
3441 case UnqualifiedIdKind::IK_ConstructorName:
3442 case UnqualifiedIdKind::IK_ConstructorTemplateId:
3443 case UnqualifiedIdKind::IK_DestructorName:
3444 // Constructors and destructors don't have return types. Use
3445 // "void" instead.
3446 T = SemaRef.Context.VoidTy;
3447 processTypeAttrs(state, T, TAL_DeclSpec,
3448 D.getMutableDeclSpec().getAttributes());
3449 break;
3451 case UnqualifiedIdKind::IK_DeductionGuideName:
3452 // Deduction guides have a trailing return type and no type in their
3453 // decl-specifier sequence. Use a placeholder return type for now.
3454 T = SemaRef.Context.DependentTy;
3455 break;
3457 case UnqualifiedIdKind::IK_ConversionFunctionId:
3458 // The result type of a conversion function is the type that it
3459 // converts to.
3460 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
3461 &ReturnTypeInfo);
3462 break;
3465 // Note: We don't need to distribute declaration attributes (i.e.
3466 // D.getDeclarationAttributes()) because those are always C++11 attributes,
3467 // and those don't get distributed.
3468 distributeTypeAttrsFromDeclarator(state, T);
3470 // Find the deduced type in this type. Look in the trailing return type if we
3471 // have one, otherwise in the DeclSpec type.
3472 // FIXME: The standard wording doesn't currently describe this.
3473 DeducedType *Deduced = T->getContainedDeducedType();
3474 bool DeducedIsTrailingReturnType = false;
3475 if (Deduced && isa<AutoType>(Deduced) && D.hasTrailingReturnType()) {
3476 QualType T = SemaRef.GetTypeFromParser(D.getTrailingReturnType());
3477 Deduced = T.isNull() ? nullptr : T->getContainedDeducedType();
3478 DeducedIsTrailingReturnType = true;
3481 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
3482 if (Deduced) {
3483 AutoType *Auto = dyn_cast<AutoType>(Deduced);
3484 int Error = -1;
3486 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
3487 // class template argument deduction)?
3488 bool IsCXXAutoType =
3489 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
3490 bool IsDeducedReturnType = false;
3492 switch (D.getContext()) {
3493 case DeclaratorContext::LambdaExpr:
3494 // Declared return type of a lambda-declarator is implicit and is always
3495 // 'auto'.
3496 break;
3497 case DeclaratorContext::ObjCParameter:
3498 case DeclaratorContext::ObjCResult:
3499 Error = 0;
3500 break;
3501 case DeclaratorContext::RequiresExpr:
3502 Error = 22;
3503 break;
3504 case DeclaratorContext::Prototype:
3505 case DeclaratorContext::LambdaExprParameter: {
3506 InventedTemplateParameterInfo *Info = nullptr;
3507 if (D.getContext() == DeclaratorContext::Prototype) {
3508 // With concepts we allow 'auto' in function parameters.
3509 if (!SemaRef.getLangOpts().CPlusPlus20 || !Auto ||
3510 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3511 Error = 0;
3512 break;
3513 } else if (!SemaRef.getCurScope()->isFunctionDeclarationScope()) {
3514 Error = 21;
3515 break;
3518 Info = &SemaRef.InventedParameterInfos.back();
3519 } else {
3520 // In C++14, generic lambdas allow 'auto' in their parameters.
3521 if (!SemaRef.getLangOpts().CPlusPlus14 || !Auto ||
3522 Auto->getKeyword() != AutoTypeKeyword::Auto) {
3523 Error = 16;
3524 break;
3526 Info = SemaRef.getCurLambda();
3527 assert(Info && "No LambdaScopeInfo on the stack!");
3530 // We'll deal with inventing template parameters for 'auto' in trailing
3531 // return types when we pick up the trailing return type when processing
3532 // the function chunk.
3533 if (!DeducedIsTrailingReturnType)
3534 T = InventTemplateParameter(state, T, nullptr, Auto, *Info).first;
3535 break;
3537 case DeclaratorContext::Member: {
3538 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
3539 D.isFunctionDeclarator())
3540 break;
3541 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
3542 if (isa<ObjCContainerDecl>(SemaRef.CurContext)) {
3543 Error = 6; // Interface member.
3544 } else {
3545 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
3546 case TTK_Enum: llvm_unreachable("unhandled tag kind");
3547 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
3548 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
3549 case TTK_Class: Error = 5; /* Class member */ break;
3550 case TTK_Interface: Error = 6; /* Interface member */ break;
3553 if (D.getDeclSpec().isFriendSpecified())
3554 Error = 20; // Friend type
3555 break;
3557 case DeclaratorContext::CXXCatch:
3558 case DeclaratorContext::ObjCCatch:
3559 Error = 7; // Exception declaration
3560 break;
3561 case DeclaratorContext::TemplateParam:
3562 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3563 !SemaRef.getLangOpts().CPlusPlus20)
3564 Error = 19; // Template parameter (until C++20)
3565 else if (!SemaRef.getLangOpts().CPlusPlus17)
3566 Error = 8; // Template parameter (until C++17)
3567 break;
3568 case DeclaratorContext::BlockLiteral:
3569 Error = 9; // Block literal
3570 break;
3571 case DeclaratorContext::TemplateArg:
3572 // Within a template argument list, a deduced template specialization
3573 // type will be reinterpreted as a template template argument.
3574 if (isa<DeducedTemplateSpecializationType>(Deduced) &&
3575 !D.getNumTypeObjects() &&
3576 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier)
3577 break;
3578 [[fallthrough]];
3579 case DeclaratorContext::TemplateTypeArg:
3580 Error = 10; // Template type argument
3581 break;
3582 case DeclaratorContext::AliasDecl:
3583 case DeclaratorContext::AliasTemplate:
3584 Error = 12; // Type alias
3585 break;
3586 case DeclaratorContext::TrailingReturn:
3587 case DeclaratorContext::TrailingReturnVar:
3588 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3589 Error = 13; // Function return type
3590 IsDeducedReturnType = true;
3591 break;
3592 case DeclaratorContext::ConversionId:
3593 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
3594 Error = 14; // conversion-type-id
3595 IsDeducedReturnType = true;
3596 break;
3597 case DeclaratorContext::FunctionalCast:
3598 if (isa<DeducedTemplateSpecializationType>(Deduced))
3599 break;
3600 if (SemaRef.getLangOpts().CPlusPlus2b && IsCXXAutoType &&
3601 !Auto->isDecltypeAuto())
3602 break; // auto(x)
3603 [[fallthrough]];
3604 case DeclaratorContext::TypeName:
3605 case DeclaratorContext::Association:
3606 Error = 15; // Generic
3607 break;
3608 case DeclaratorContext::File:
3609 case DeclaratorContext::Block:
3610 case DeclaratorContext::ForInit:
3611 case DeclaratorContext::SelectionInit:
3612 case DeclaratorContext::Condition:
3613 // FIXME: P0091R3 (erroneously) does not permit class template argument
3614 // deduction in conditions, for-init-statements, and other declarations
3615 // that are not simple-declarations.
3616 break;
3617 case DeclaratorContext::CXXNew:
3618 // FIXME: P0091R3 does not permit class template argument deduction here,
3619 // but we follow GCC and allow it anyway.
3620 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
3621 Error = 17; // 'new' type
3622 break;
3623 case DeclaratorContext::KNRTypeList:
3624 Error = 18; // K&R function parameter
3625 break;
3628 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
3629 Error = 11;
3631 // In Objective-C it is an error to use 'auto' on a function declarator
3632 // (and everywhere for '__auto_type').
3633 if (D.isFunctionDeclarator() &&
3634 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
3635 Error = 13;
3637 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
3638 if (D.getName().getKind() == UnqualifiedIdKind::IK_ConversionFunctionId)
3639 AutoRange = D.getName().getSourceRange();
3641 if (Error != -1) {
3642 unsigned Kind;
3643 if (Auto) {
3644 switch (Auto->getKeyword()) {
3645 case AutoTypeKeyword::Auto: Kind = 0; break;
3646 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
3647 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
3649 } else {
3650 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
3651 "unknown auto type");
3652 Kind = 3;
3655 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
3656 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
3658 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
3659 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
3660 << QualType(Deduced, 0) << AutoRange;
3661 if (auto *TD = TN.getAsTemplateDecl())
3662 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
3664 T = SemaRef.Context.IntTy;
3665 D.setInvalidType(true);
3666 } else if (Auto && D.getContext() != DeclaratorContext::LambdaExpr) {
3667 // If there was a trailing return type, we already got
3668 // warn_cxx98_compat_trailing_return_type in the parser.
3669 SemaRef.Diag(AutoRange.getBegin(),
3670 D.getContext() == DeclaratorContext::LambdaExprParameter
3671 ? diag::warn_cxx11_compat_generic_lambda
3672 : IsDeducedReturnType
3673 ? diag::warn_cxx11_compat_deduced_return_type
3674 : diag::warn_cxx98_compat_auto_type_specifier)
3675 << AutoRange;
3679 if (SemaRef.getLangOpts().CPlusPlus &&
3680 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
3681 // Check the contexts where C++ forbids the declaration of a new class
3682 // or enumeration in a type-specifier-seq.
3683 unsigned DiagID = 0;
3684 switch (D.getContext()) {
3685 case DeclaratorContext::TrailingReturn:
3686 case DeclaratorContext::TrailingReturnVar:
3687 // Class and enumeration definitions are syntactically not allowed in
3688 // trailing return types.
3689 llvm_unreachable("parser should not have allowed this");
3690 break;
3691 case DeclaratorContext::File:
3692 case DeclaratorContext::Member:
3693 case DeclaratorContext::Block:
3694 case DeclaratorContext::ForInit:
3695 case DeclaratorContext::SelectionInit:
3696 case DeclaratorContext::BlockLiteral:
3697 case DeclaratorContext::LambdaExpr:
3698 // C++11 [dcl.type]p3:
3699 // A type-specifier-seq shall not define a class or enumeration unless
3700 // it appears in the type-id of an alias-declaration (7.1.3) that is not
3701 // the declaration of a template-declaration.
3702 case DeclaratorContext::AliasDecl:
3703 break;
3704 case DeclaratorContext::AliasTemplate:
3705 DiagID = diag::err_type_defined_in_alias_template;
3706 break;
3707 case DeclaratorContext::TypeName:
3708 case DeclaratorContext::FunctionalCast:
3709 case DeclaratorContext::ConversionId:
3710 case DeclaratorContext::TemplateParam:
3711 case DeclaratorContext::CXXNew:
3712 case DeclaratorContext::CXXCatch:
3713 case DeclaratorContext::ObjCCatch:
3714 case DeclaratorContext::TemplateArg:
3715 case DeclaratorContext::TemplateTypeArg:
3716 case DeclaratorContext::Association:
3717 DiagID = diag::err_type_defined_in_type_specifier;
3718 break;
3719 case DeclaratorContext::Prototype:
3720 case DeclaratorContext::LambdaExprParameter:
3721 case DeclaratorContext::ObjCParameter:
3722 case DeclaratorContext::ObjCResult:
3723 case DeclaratorContext::KNRTypeList:
3724 case DeclaratorContext::RequiresExpr:
3725 // C++ [dcl.fct]p6:
3726 // Types shall not be defined in return or parameter types.
3727 DiagID = diag::err_type_defined_in_param_type;
3728 break;
3729 case DeclaratorContext::Condition:
3730 // C++ 6.4p2:
3731 // The type-specifier-seq shall not contain typedef and shall not declare
3732 // a new class or enumeration.
3733 DiagID = diag::err_type_defined_in_condition;
3734 break;
3737 if (DiagID != 0) {
3738 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
3739 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
3740 D.setInvalidType(true);
3744 assert(!T.isNull() && "This function should not return a null type");
3745 return T;
3748 /// Produce an appropriate diagnostic for an ambiguity between a function
3749 /// declarator and a C++ direct-initializer.
3750 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3751 DeclaratorChunk &DeclType, QualType RT) {
3752 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3753 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3755 // If the return type is void there is no ambiguity.
3756 if (RT->isVoidType())
3757 return;
3759 // An initializer for a non-class type can have at most one argument.
3760 if (!RT->isRecordType() && FTI.NumParams > 1)
3761 return;
3763 // An initializer for a reference must have exactly one argument.
3764 if (RT->isReferenceType() && FTI.NumParams != 1)
3765 return;
3767 // Only warn if this declarator is declaring a function at block scope, and
3768 // doesn't have a storage class (such as 'extern') specified.
3769 if (!D.isFunctionDeclarator() ||
3770 D.getFunctionDefinitionKind() != FunctionDefinitionKind::Declaration ||
3771 !S.CurContext->isFunctionOrMethod() ||
3772 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_unspecified)
3773 return;
3775 // Inside a condition, a direct initializer is not permitted. We allow one to
3776 // be parsed in order to give better diagnostics in condition parsing.
3777 if (D.getContext() == DeclaratorContext::Condition)
3778 return;
3780 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3782 S.Diag(DeclType.Loc,
3783 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3784 : diag::warn_empty_parens_are_function_decl)
3785 << ParenRange;
3787 // If the declaration looks like:
3788 // T var1,
3789 // f();
3790 // and name lookup finds a function named 'f', then the ',' was
3791 // probably intended to be a ';'.
3792 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3793 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3794 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3795 if (Comma.getFileID() != Name.getFileID() ||
3796 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3797 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3798 Sema::LookupOrdinaryName);
3799 if (S.LookupName(Result, S.getCurScope()))
3800 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3801 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3802 << D.getIdentifier();
3803 Result.suppressDiagnostics();
3807 if (FTI.NumParams > 0) {
3808 // For a declaration with parameters, eg. "T var(T());", suggest adding
3809 // parens around the first parameter to turn the declaration into a
3810 // variable declaration.
3811 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3812 SourceLocation B = Range.getBegin();
3813 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3814 // FIXME: Maybe we should suggest adding braces instead of parens
3815 // in C++11 for classes that don't have an initializer_list constructor.
3816 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3817 << FixItHint::CreateInsertion(B, "(")
3818 << FixItHint::CreateInsertion(E, ")");
3819 } else {
3820 // For a declaration without parameters, eg. "T var();", suggest replacing
3821 // the parens with an initializer to turn the declaration into a variable
3822 // declaration.
3823 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3825 // Empty parens mean value-initialization, and no parens mean
3826 // default initialization. These are equivalent if the default
3827 // constructor is user-provided or if zero-initialization is a
3828 // no-op.
3829 if (RD && RD->hasDefinition() &&
3830 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3831 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3832 << FixItHint::CreateRemoval(ParenRange);
3833 else {
3834 std::string Init =
3835 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3836 if (Init.empty() && S.LangOpts.CPlusPlus11)
3837 Init = "{}";
3838 if (!Init.empty())
3839 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3840 << FixItHint::CreateReplacement(ParenRange, Init);
3845 /// Produce an appropriate diagnostic for a declarator with top-level
3846 /// parentheses.
3847 static void warnAboutRedundantParens(Sema &S, Declarator &D, QualType T) {
3848 DeclaratorChunk &Paren = D.getTypeObject(D.getNumTypeObjects() - 1);
3849 assert(Paren.Kind == DeclaratorChunk::Paren &&
3850 "do not have redundant top-level parentheses");
3852 // This is a syntactic check; we're not interested in cases that arise
3853 // during template instantiation.
3854 if (S.inTemplateInstantiation())
3855 return;
3857 // Check whether this could be intended to be a construction of a temporary
3858 // object in C++ via a function-style cast.
3859 bool CouldBeTemporaryObject =
3860 S.getLangOpts().CPlusPlus && D.isExpressionContext() &&
3861 !D.isInvalidType() && D.getIdentifier() &&
3862 D.getDeclSpec().getParsedSpecifiers() == DeclSpec::PQ_TypeSpecifier &&
3863 (T->isRecordType() || T->isDependentType()) &&
3864 D.getDeclSpec().getTypeQualifiers() == 0 && D.isFirstDeclarator();
3866 bool StartsWithDeclaratorId = true;
3867 for (auto &C : D.type_objects()) {
3868 switch (C.Kind) {
3869 case DeclaratorChunk::Paren:
3870 if (&C == &Paren)
3871 continue;
3872 [[fallthrough]];
3873 case DeclaratorChunk::Pointer:
3874 StartsWithDeclaratorId = false;
3875 continue;
3877 case DeclaratorChunk::Array:
3878 if (!C.Arr.NumElts)
3879 CouldBeTemporaryObject = false;
3880 continue;
3882 case DeclaratorChunk::Reference:
3883 // FIXME: Suppress the warning here if there is no initializer; we're
3884 // going to give an error anyway.
3885 // We assume that something like 'T (&x) = y;' is highly likely to not
3886 // be intended to be a temporary object.
3887 CouldBeTemporaryObject = false;
3888 StartsWithDeclaratorId = false;
3889 continue;
3891 case DeclaratorChunk::Function:
3892 // In a new-type-id, function chunks require parentheses.
3893 if (D.getContext() == DeclaratorContext::CXXNew)
3894 return;
3895 // FIXME: "A(f())" deserves a vexing-parse warning, not just a
3896 // redundant-parens warning, but we don't know whether the function
3897 // chunk was syntactically valid as an expression here.
3898 CouldBeTemporaryObject = false;
3899 continue;
3901 case DeclaratorChunk::BlockPointer:
3902 case DeclaratorChunk::MemberPointer:
3903 case DeclaratorChunk::Pipe:
3904 // These cannot appear in expressions.
3905 CouldBeTemporaryObject = false;
3906 StartsWithDeclaratorId = false;
3907 continue;
3911 // FIXME: If there is an initializer, assume that this is not intended to be
3912 // a construction of a temporary object.
3914 // Check whether the name has already been declared; if not, this is not a
3915 // function-style cast.
3916 if (CouldBeTemporaryObject) {
3917 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3918 Sema::LookupOrdinaryName);
3919 if (!S.LookupName(Result, S.getCurScope()))
3920 CouldBeTemporaryObject = false;
3921 Result.suppressDiagnostics();
3924 SourceRange ParenRange(Paren.Loc, Paren.EndLoc);
3926 if (!CouldBeTemporaryObject) {
3927 // If we have A (::B), the parentheses affect the meaning of the program.
3928 // Suppress the warning in that case. Don't bother looking at the DeclSpec
3929 // here: even (e.g.) "int ::x" is visually ambiguous even though it's
3930 // formally unambiguous.
3931 if (StartsWithDeclaratorId && D.getCXXScopeSpec().isValid()) {
3932 for (NestedNameSpecifier *NNS = D.getCXXScopeSpec().getScopeRep(); NNS;
3933 NNS = NNS->getPrefix()) {
3934 if (NNS->getKind() == NestedNameSpecifier::Global)
3935 return;
3939 S.Diag(Paren.Loc, diag::warn_redundant_parens_around_declarator)
3940 << ParenRange << FixItHint::CreateRemoval(Paren.Loc)
3941 << FixItHint::CreateRemoval(Paren.EndLoc);
3942 return;
3945 S.Diag(Paren.Loc, diag::warn_parens_disambiguated_as_variable_declaration)
3946 << ParenRange << D.getIdentifier();
3947 auto *RD = T->getAsCXXRecordDecl();
3948 if (!RD || !RD->hasDefinition() || RD->hasNonTrivialDestructor())
3949 S.Diag(Paren.Loc, diag::note_raii_guard_add_name)
3950 << FixItHint::CreateInsertion(Paren.Loc, " varname") << T
3951 << D.getIdentifier();
3952 // FIXME: A cast to void is probably a better suggestion in cases where it's
3953 // valid (when there is no initializer and we're not in a condition).
3954 S.Diag(D.getBeginLoc(), diag::note_function_style_cast_add_parentheses)
3955 << FixItHint::CreateInsertion(D.getBeginLoc(), "(")
3956 << FixItHint::CreateInsertion(S.getLocForEndOfToken(D.getEndLoc()), ")");
3957 S.Diag(Paren.Loc, diag::note_remove_parens_for_variable_declaration)
3958 << FixItHint::CreateRemoval(Paren.Loc)
3959 << FixItHint::CreateRemoval(Paren.EndLoc);
3962 /// Helper for figuring out the default CC for a function declarator type. If
3963 /// this is the outermost chunk, then we can determine the CC from the
3964 /// declarator context. If not, then this could be either a member function
3965 /// type or normal function type.
3966 static CallingConv getCCForDeclaratorChunk(
3967 Sema &S, Declarator &D, const ParsedAttributesView &AttrList,
3968 const DeclaratorChunk::FunctionTypeInfo &FTI, unsigned ChunkIndex) {
3969 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3971 // Check for an explicit CC attribute.
3972 for (const ParsedAttr &AL : AttrList) {
3973 switch (AL.getKind()) {
3974 CALLING_CONV_ATTRS_CASELIST : {
3975 // Ignore attributes that don't validate or can't apply to the
3976 // function type. We'll diagnose the failure to apply them in
3977 // handleFunctionTypeAttr.
3978 CallingConv CC;
3979 if (!S.CheckCallingConvAttr(AL, CC) &&
3980 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3981 return CC;
3983 break;
3986 default:
3987 break;
3991 bool IsCXXInstanceMethod = false;
3993 if (S.getLangOpts().CPlusPlus) {
3994 // Look inwards through parentheses to see if this chunk will form a
3995 // member pointer type or if we're the declarator. Any type attributes
3996 // between here and there will override the CC we choose here.
3997 unsigned I = ChunkIndex;
3998 bool FoundNonParen = false;
3999 while (I && !FoundNonParen) {
4000 --I;
4001 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
4002 FoundNonParen = true;
4005 if (FoundNonParen) {
4006 // If we're not the declarator, we're a regular function type unless we're
4007 // in a member pointer.
4008 IsCXXInstanceMethod =
4009 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
4010 } else if (D.getContext() == DeclaratorContext::LambdaExpr) {
4011 // This can only be a call operator for a lambda, which is an instance
4012 // method.
4013 IsCXXInstanceMethod = true;
4014 } else {
4015 // We're the innermost decl chunk, so must be a function declarator.
4016 assert(D.isFunctionDeclarator());
4018 // If we're inside a record, we're declaring a method, but it could be
4019 // explicitly or implicitly static.
4020 IsCXXInstanceMethod =
4021 D.isFirstDeclarationOfMember() &&
4022 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
4023 !D.isStaticMember();
4027 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
4028 IsCXXInstanceMethod);
4030 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
4031 // and AMDGPU targets, hence it cannot be treated as a calling
4032 // convention attribute. This is the simplest place to infer
4033 // calling convention for OpenCL kernels.
4034 if (S.getLangOpts().OpenCL) {
4035 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4036 if (AL.getKind() == ParsedAttr::AT_OpenCLKernel) {
4037 CC = CC_OpenCLKernel;
4038 break;
4041 } else if (S.getLangOpts().CUDA) {
4042 // If we're compiling CUDA/HIP code and targeting SPIR-V we need to make
4043 // sure the kernels will be marked with the right calling convention so that
4044 // they will be visible by the APIs that ingest SPIR-V.
4045 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
4046 if (Triple.getArch() == llvm::Triple::spirv32 ||
4047 Triple.getArch() == llvm::Triple::spirv64) {
4048 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
4049 if (AL.getKind() == ParsedAttr::AT_CUDAGlobal) {
4050 CC = CC_OpenCLKernel;
4051 break;
4057 return CC;
4060 namespace {
4061 /// A simple notion of pointer kinds, which matches up with the various
4062 /// pointer declarators.
4063 enum class SimplePointerKind {
4064 Pointer,
4065 BlockPointer,
4066 MemberPointer,
4067 Array,
4069 } // end anonymous namespace
4071 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
4072 switch (nullability) {
4073 case NullabilityKind::NonNull:
4074 if (!Ident__Nonnull)
4075 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
4076 return Ident__Nonnull;
4078 case NullabilityKind::Nullable:
4079 if (!Ident__Nullable)
4080 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
4081 return Ident__Nullable;
4083 case NullabilityKind::NullableResult:
4084 if (!Ident__Nullable_result)
4085 Ident__Nullable_result = PP.getIdentifierInfo("_Nullable_result");
4086 return Ident__Nullable_result;
4088 case NullabilityKind::Unspecified:
4089 if (!Ident__Null_unspecified)
4090 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
4091 return Ident__Null_unspecified;
4093 llvm_unreachable("Unknown nullability kind.");
4096 /// Retrieve the identifier "NSError".
4097 IdentifierInfo *Sema::getNSErrorIdent() {
4098 if (!Ident_NSError)
4099 Ident_NSError = PP.getIdentifierInfo("NSError");
4101 return Ident_NSError;
4104 /// Check whether there is a nullability attribute of any kind in the given
4105 /// attribute list.
4106 static bool hasNullabilityAttr(const ParsedAttributesView &attrs) {
4107 for (const ParsedAttr &AL : attrs) {
4108 if (AL.getKind() == ParsedAttr::AT_TypeNonNull ||
4109 AL.getKind() == ParsedAttr::AT_TypeNullable ||
4110 AL.getKind() == ParsedAttr::AT_TypeNullableResult ||
4111 AL.getKind() == ParsedAttr::AT_TypeNullUnspecified)
4112 return true;
4115 return false;
4118 namespace {
4119 /// Describes the kind of a pointer a declarator describes.
4120 enum class PointerDeclaratorKind {
4121 // Not a pointer.
4122 NonPointer,
4123 // Single-level pointer.
4124 SingleLevelPointer,
4125 // Multi-level pointer (of any pointer kind).
4126 MultiLevelPointer,
4127 // CFFooRef*
4128 MaybePointerToCFRef,
4129 // CFErrorRef*
4130 CFErrorRefPointer,
4131 // NSError**
4132 NSErrorPointerPointer,
4135 /// Describes a declarator chunk wrapping a pointer that marks inference as
4136 /// unexpected.
4137 // These values must be kept in sync with diagnostics.
4138 enum class PointerWrappingDeclaratorKind {
4139 /// Pointer is top-level.
4140 None = -1,
4141 /// Pointer is an array element.
4142 Array = 0,
4143 /// Pointer is the referent type of a C++ reference.
4144 Reference = 1
4146 } // end anonymous namespace
4148 /// Classify the given declarator, whose type-specified is \c type, based on
4149 /// what kind of pointer it refers to.
4151 /// This is used to determine the default nullability.
4152 static PointerDeclaratorKind
4153 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
4154 PointerWrappingDeclaratorKind &wrappingKind) {
4155 unsigned numNormalPointers = 0;
4157 // For any dependent type, we consider it a non-pointer.
4158 if (type->isDependentType())
4159 return PointerDeclaratorKind::NonPointer;
4161 // Look through the declarator chunks to identify pointers.
4162 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
4163 DeclaratorChunk &chunk = declarator.getTypeObject(i);
4164 switch (chunk.Kind) {
4165 case DeclaratorChunk::Array:
4166 if (numNormalPointers == 0)
4167 wrappingKind = PointerWrappingDeclaratorKind::Array;
4168 break;
4170 case DeclaratorChunk::Function:
4171 case DeclaratorChunk::Pipe:
4172 break;
4174 case DeclaratorChunk::BlockPointer:
4175 case DeclaratorChunk::MemberPointer:
4176 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4177 : PointerDeclaratorKind::SingleLevelPointer;
4179 case DeclaratorChunk::Paren:
4180 break;
4182 case DeclaratorChunk::Reference:
4183 if (numNormalPointers == 0)
4184 wrappingKind = PointerWrappingDeclaratorKind::Reference;
4185 break;
4187 case DeclaratorChunk::Pointer:
4188 ++numNormalPointers;
4189 if (numNormalPointers > 2)
4190 return PointerDeclaratorKind::MultiLevelPointer;
4191 break;
4195 // Then, dig into the type specifier itself.
4196 unsigned numTypeSpecifierPointers = 0;
4197 do {
4198 // Decompose normal pointers.
4199 if (auto ptrType = type->getAs<PointerType>()) {
4200 ++numNormalPointers;
4202 if (numNormalPointers > 2)
4203 return PointerDeclaratorKind::MultiLevelPointer;
4205 type = ptrType->getPointeeType();
4206 ++numTypeSpecifierPointers;
4207 continue;
4210 // Decompose block pointers.
4211 if (type->getAs<BlockPointerType>()) {
4212 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4213 : PointerDeclaratorKind::SingleLevelPointer;
4216 // Decompose member pointers.
4217 if (type->getAs<MemberPointerType>()) {
4218 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
4219 : PointerDeclaratorKind::SingleLevelPointer;
4222 // Look at Objective-C object pointers.
4223 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
4224 ++numNormalPointers;
4225 ++numTypeSpecifierPointers;
4227 // If this is NSError**, report that.
4228 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
4229 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
4230 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
4231 return PointerDeclaratorKind::NSErrorPointerPointer;
4235 break;
4238 // Look at Objective-C class types.
4239 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
4240 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
4241 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
4242 return PointerDeclaratorKind::NSErrorPointerPointer;
4245 break;
4248 // If at this point we haven't seen a pointer, we won't see one.
4249 if (numNormalPointers == 0)
4250 return PointerDeclaratorKind::NonPointer;
4252 if (auto recordType = type->getAs<RecordType>()) {
4253 RecordDecl *recordDecl = recordType->getDecl();
4255 // If this is CFErrorRef*, report it as such.
4256 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2 &&
4257 S.isCFError(recordDecl)) {
4258 return PointerDeclaratorKind::CFErrorRefPointer;
4260 break;
4263 break;
4264 } while (true);
4266 switch (numNormalPointers) {
4267 case 0:
4268 return PointerDeclaratorKind::NonPointer;
4270 case 1:
4271 return PointerDeclaratorKind::SingleLevelPointer;
4273 case 2:
4274 return PointerDeclaratorKind::MaybePointerToCFRef;
4276 default:
4277 return PointerDeclaratorKind::MultiLevelPointer;
4281 bool Sema::isCFError(RecordDecl *RD) {
4282 // If we already know about CFError, test it directly.
4283 if (CFError)
4284 return CFError == RD;
4286 // Check whether this is CFError, which we identify based on its bridge to
4287 // NSError. CFErrorRef used to be declared with "objc_bridge" but is now
4288 // declared with "objc_bridge_mutable", so look for either one of the two
4289 // attributes.
4290 if (RD->getTagKind() == TTK_Struct) {
4291 IdentifierInfo *bridgedType = nullptr;
4292 if (auto bridgeAttr = RD->getAttr<ObjCBridgeAttr>())
4293 bridgedType = bridgeAttr->getBridgedType();
4294 else if (auto bridgeAttr = RD->getAttr<ObjCBridgeMutableAttr>())
4295 bridgedType = bridgeAttr->getBridgedType();
4297 if (bridgedType == getNSErrorIdent()) {
4298 CFError = RD;
4299 return true;
4303 return false;
4306 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
4307 SourceLocation loc) {
4308 // If we're anywhere in a function, method, or closure context, don't perform
4309 // completeness checks.
4310 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
4311 if (ctx->isFunctionOrMethod())
4312 return FileID();
4314 if (ctx->isFileContext())
4315 break;
4318 // We only care about the expansion location.
4319 loc = S.SourceMgr.getExpansionLoc(loc);
4320 FileID file = S.SourceMgr.getFileID(loc);
4321 if (file.isInvalid())
4322 return FileID();
4324 // Retrieve file information.
4325 bool invalid = false;
4326 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
4327 if (invalid || !sloc.isFile())
4328 return FileID();
4330 // We don't want to perform completeness checks on the main file or in
4331 // system headers.
4332 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
4333 if (fileInfo.getIncludeLoc().isInvalid())
4334 return FileID();
4335 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
4336 S.Diags.getSuppressSystemWarnings()) {
4337 return FileID();
4340 return file;
4343 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
4344 /// taking into account whitespace before and after.
4345 template <typename DiagBuilderT>
4346 static void fixItNullability(Sema &S, DiagBuilderT &Diag,
4347 SourceLocation PointerLoc,
4348 NullabilityKind Nullability) {
4349 assert(PointerLoc.isValid());
4350 if (PointerLoc.isMacroID())
4351 return;
4353 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
4354 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
4355 return;
4357 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
4358 if (!NextChar)
4359 return;
4361 SmallString<32> InsertionTextBuf{" "};
4362 InsertionTextBuf += getNullabilitySpelling(Nullability);
4363 InsertionTextBuf += " ";
4364 StringRef InsertionText = InsertionTextBuf.str();
4366 if (isWhitespace(*NextChar)) {
4367 InsertionText = InsertionText.drop_back();
4368 } else if (NextChar[-1] == '[') {
4369 if (NextChar[0] == ']')
4370 InsertionText = InsertionText.drop_back().drop_front();
4371 else
4372 InsertionText = InsertionText.drop_front();
4373 } else if (!isAsciiIdentifierContinue(NextChar[0], /*allow dollar*/ true) &&
4374 !isAsciiIdentifierContinue(NextChar[-1], /*allow dollar*/ true)) {
4375 InsertionText = InsertionText.drop_back().drop_front();
4378 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
4381 static void emitNullabilityConsistencyWarning(Sema &S,
4382 SimplePointerKind PointerKind,
4383 SourceLocation PointerLoc,
4384 SourceLocation PointerEndLoc) {
4385 assert(PointerLoc.isValid());
4387 if (PointerKind == SimplePointerKind::Array) {
4388 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
4389 } else {
4390 S.Diag(PointerLoc, diag::warn_nullability_missing)
4391 << static_cast<unsigned>(PointerKind);
4394 auto FixItLoc = PointerEndLoc.isValid() ? PointerEndLoc : PointerLoc;
4395 if (FixItLoc.isMacroID())
4396 return;
4398 auto addFixIt = [&](NullabilityKind Nullability) {
4399 auto Diag = S.Diag(FixItLoc, diag::note_nullability_fix_it);
4400 Diag << static_cast<unsigned>(Nullability);
4401 Diag << static_cast<unsigned>(PointerKind);
4402 fixItNullability(S, Diag, FixItLoc, Nullability);
4404 addFixIt(NullabilityKind::Nullable);
4405 addFixIt(NullabilityKind::NonNull);
4408 /// Complains about missing nullability if the file containing \p pointerLoc
4409 /// has other uses of nullability (either the keywords or the \c assume_nonnull
4410 /// pragma).
4412 /// If the file has \e not seen other uses of nullability, this particular
4413 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
4414 static void
4415 checkNullabilityConsistency(Sema &S, SimplePointerKind pointerKind,
4416 SourceLocation pointerLoc,
4417 SourceLocation pointerEndLoc = SourceLocation()) {
4418 // Determine which file we're performing consistency checking for.
4419 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
4420 if (file.isInvalid())
4421 return;
4423 // If we haven't seen any type nullability in this file, we won't warn now
4424 // about anything.
4425 FileNullability &fileNullability = S.NullabilityMap[file];
4426 if (!fileNullability.SawTypeNullability) {
4427 // If this is the first pointer declarator in the file, and the appropriate
4428 // warning is on, record it in case we need to diagnose it retroactively.
4429 diag::kind diagKind;
4430 if (pointerKind == SimplePointerKind::Array)
4431 diagKind = diag::warn_nullability_missing_array;
4432 else
4433 diagKind = diag::warn_nullability_missing;
4435 if (fileNullability.PointerLoc.isInvalid() &&
4436 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
4437 fileNullability.PointerLoc = pointerLoc;
4438 fileNullability.PointerEndLoc = pointerEndLoc;
4439 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
4442 return;
4445 // Complain about missing nullability.
4446 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc, pointerEndLoc);
4449 /// Marks that a nullability feature has been used in the file containing
4450 /// \p loc.
4452 /// If this file already had pointer types in it that were missing nullability,
4453 /// the first such instance is retroactively diagnosed.
4455 /// \sa checkNullabilityConsistency
4456 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
4457 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
4458 if (file.isInvalid())
4459 return;
4461 FileNullability &fileNullability = S.NullabilityMap[file];
4462 if (fileNullability.SawTypeNullability)
4463 return;
4464 fileNullability.SawTypeNullability = true;
4466 // If we haven't seen any type nullability before, now we have. Retroactively
4467 // diagnose the first unannotated pointer, if there was one.
4468 if (fileNullability.PointerLoc.isInvalid())
4469 return;
4471 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
4472 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc,
4473 fileNullability.PointerEndLoc);
4476 /// Returns true if any of the declarator chunks before \p endIndex include a
4477 /// level of indirection: array, pointer, reference, or pointer-to-member.
4479 /// Because declarator chunks are stored in outer-to-inner order, testing
4480 /// every chunk before \p endIndex is testing all chunks that embed the current
4481 /// chunk as part of their type.
4483 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
4484 /// end index, in which case all chunks are tested.
4485 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
4486 unsigned i = endIndex;
4487 while (i != 0) {
4488 // Walk outwards along the declarator chunks.
4489 --i;
4490 const DeclaratorChunk &DC = D.getTypeObject(i);
4491 switch (DC.Kind) {
4492 case DeclaratorChunk::Paren:
4493 break;
4494 case DeclaratorChunk::Array:
4495 case DeclaratorChunk::Pointer:
4496 case DeclaratorChunk::Reference:
4497 case DeclaratorChunk::MemberPointer:
4498 return true;
4499 case DeclaratorChunk::Function:
4500 case DeclaratorChunk::BlockPointer:
4501 case DeclaratorChunk::Pipe:
4502 // These are invalid anyway, so just ignore.
4503 break;
4506 return false;
4509 static bool IsNoDerefableChunk(DeclaratorChunk Chunk) {
4510 return (Chunk.Kind == DeclaratorChunk::Pointer ||
4511 Chunk.Kind == DeclaratorChunk::Array);
4514 template<typename AttrT>
4515 static AttrT *createSimpleAttr(ASTContext &Ctx, ParsedAttr &AL) {
4516 AL.setUsedAsTypeAttr();
4517 return ::new (Ctx) AttrT(Ctx, AL);
4520 static Attr *createNullabilityAttr(ASTContext &Ctx, ParsedAttr &Attr,
4521 NullabilityKind NK) {
4522 switch (NK) {
4523 case NullabilityKind::NonNull:
4524 return createSimpleAttr<TypeNonNullAttr>(Ctx, Attr);
4526 case NullabilityKind::Nullable:
4527 return createSimpleAttr<TypeNullableAttr>(Ctx, Attr);
4529 case NullabilityKind::NullableResult:
4530 return createSimpleAttr<TypeNullableResultAttr>(Ctx, Attr);
4532 case NullabilityKind::Unspecified:
4533 return createSimpleAttr<TypeNullUnspecifiedAttr>(Ctx, Attr);
4535 llvm_unreachable("unknown NullabilityKind");
4538 // Diagnose whether this is a case with the multiple addr spaces.
4539 // Returns true if this is an invalid case.
4540 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified
4541 // by qualifiers for two or more different address spaces."
4542 static bool DiagnoseMultipleAddrSpaceAttributes(Sema &S, LangAS ASOld,
4543 LangAS ASNew,
4544 SourceLocation AttrLoc) {
4545 if (ASOld != LangAS::Default) {
4546 if (ASOld != ASNew) {
4547 S.Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
4548 return true;
4550 // Emit a warning if they are identical; it's likely unintended.
4551 S.Diag(AttrLoc,
4552 diag::warn_attribute_address_multiple_identical_qualifiers);
4554 return false;
4557 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
4558 QualType declSpecType,
4559 TypeSourceInfo *TInfo) {
4560 // The TypeSourceInfo that this function returns will not be a null type.
4561 // If there is an error, this function will fill in a dummy type as fallback.
4562 QualType T = declSpecType;
4563 Declarator &D = state.getDeclarator();
4564 Sema &S = state.getSema();
4565 ASTContext &Context = S.Context;
4566 const LangOptions &LangOpts = S.getLangOpts();
4568 // The name we're declaring, if any.
4569 DeclarationName Name;
4570 if (D.getIdentifier())
4571 Name = D.getIdentifier();
4573 // Does this declaration declare a typedef-name?
4574 bool IsTypedefName =
4575 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
4576 D.getContext() == DeclaratorContext::AliasDecl ||
4577 D.getContext() == DeclaratorContext::AliasTemplate;
4579 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
4580 bool IsQualifiedFunction = T->isFunctionProtoType() &&
4581 (!T->castAs<FunctionProtoType>()->getMethodQuals().empty() ||
4582 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
4584 // If T is 'decltype(auto)', the only declarators we can have are parens
4585 // and at most one function declarator if this is a function declaration.
4586 // If T is a deduced class template specialization type, we can have no
4587 // declarator chunks at all.
4588 if (auto *DT = T->getAs<DeducedType>()) {
4589 const AutoType *AT = T->getAs<AutoType>();
4590 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
4591 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
4592 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
4593 unsigned Index = E - I - 1;
4594 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
4595 unsigned DiagId = IsClassTemplateDeduction
4596 ? diag::err_deduced_class_template_compound_type
4597 : diag::err_decltype_auto_compound_type;
4598 unsigned DiagKind = 0;
4599 switch (DeclChunk.Kind) {
4600 case DeclaratorChunk::Paren:
4601 // FIXME: Rejecting this is a little silly.
4602 if (IsClassTemplateDeduction) {
4603 DiagKind = 4;
4604 break;
4606 continue;
4607 case DeclaratorChunk::Function: {
4608 if (IsClassTemplateDeduction) {
4609 DiagKind = 3;
4610 break;
4612 unsigned FnIndex;
4613 if (D.isFunctionDeclarationContext() &&
4614 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
4615 continue;
4616 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
4617 break;
4619 case DeclaratorChunk::Pointer:
4620 case DeclaratorChunk::BlockPointer:
4621 case DeclaratorChunk::MemberPointer:
4622 DiagKind = 0;
4623 break;
4624 case DeclaratorChunk::Reference:
4625 DiagKind = 1;
4626 break;
4627 case DeclaratorChunk::Array:
4628 DiagKind = 2;
4629 break;
4630 case DeclaratorChunk::Pipe:
4631 break;
4634 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
4635 D.setInvalidType(true);
4636 break;
4641 // Determine whether we should infer _Nonnull on pointer types.
4642 Optional<NullabilityKind> inferNullability;
4643 bool inferNullabilityCS = false;
4644 bool inferNullabilityInnerOnly = false;
4645 bool inferNullabilityInnerOnlyComplete = false;
4647 // Are we in an assume-nonnull region?
4648 bool inAssumeNonNullRegion = false;
4649 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
4650 if (assumeNonNullLoc.isValid()) {
4651 inAssumeNonNullRegion = true;
4652 recordNullabilitySeen(S, assumeNonNullLoc);
4655 // Whether to complain about missing nullability specifiers or not.
4656 enum {
4657 /// Never complain.
4658 CAMN_No,
4659 /// Complain on the inner pointers (but not the outermost
4660 /// pointer).
4661 CAMN_InnerPointers,
4662 /// Complain about any pointers that don't have nullability
4663 /// specified or inferred.
4664 CAMN_Yes
4665 } complainAboutMissingNullability = CAMN_No;
4666 unsigned NumPointersRemaining = 0;
4667 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
4669 if (IsTypedefName) {
4670 // For typedefs, we do not infer any nullability (the default),
4671 // and we only complain about missing nullability specifiers on
4672 // inner pointers.
4673 complainAboutMissingNullability = CAMN_InnerPointers;
4675 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4676 !T->getNullability(S.Context)) {
4677 // Note that we allow but don't require nullability on dependent types.
4678 ++NumPointersRemaining;
4681 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
4682 DeclaratorChunk &chunk = D.getTypeObject(i);
4683 switch (chunk.Kind) {
4684 case DeclaratorChunk::Array:
4685 case DeclaratorChunk::Function:
4686 case DeclaratorChunk::Pipe:
4687 break;
4689 case DeclaratorChunk::BlockPointer:
4690 case DeclaratorChunk::MemberPointer:
4691 ++NumPointersRemaining;
4692 break;
4694 case DeclaratorChunk::Paren:
4695 case DeclaratorChunk::Reference:
4696 continue;
4698 case DeclaratorChunk::Pointer:
4699 ++NumPointersRemaining;
4700 continue;
4703 } else {
4704 bool isFunctionOrMethod = false;
4705 switch (auto context = state.getDeclarator().getContext()) {
4706 case DeclaratorContext::ObjCParameter:
4707 case DeclaratorContext::ObjCResult:
4708 case DeclaratorContext::Prototype:
4709 case DeclaratorContext::TrailingReturn:
4710 case DeclaratorContext::TrailingReturnVar:
4711 isFunctionOrMethod = true;
4712 [[fallthrough]];
4714 case DeclaratorContext::Member:
4715 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
4716 complainAboutMissingNullability = CAMN_No;
4717 break;
4720 // Weak properties are inferred to be nullable.
4721 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
4722 inferNullability = NullabilityKind::Nullable;
4723 break;
4726 [[fallthrough]];
4728 case DeclaratorContext::File:
4729 case DeclaratorContext::KNRTypeList: {
4730 complainAboutMissingNullability = CAMN_Yes;
4732 // Nullability inference depends on the type and declarator.
4733 auto wrappingKind = PointerWrappingDeclaratorKind::None;
4734 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
4735 case PointerDeclaratorKind::NonPointer:
4736 case PointerDeclaratorKind::MultiLevelPointer:
4737 // Cannot infer nullability.
4738 break;
4740 case PointerDeclaratorKind::SingleLevelPointer:
4741 // Infer _Nonnull if we are in an assumes-nonnull region.
4742 if (inAssumeNonNullRegion) {
4743 complainAboutInferringWithinChunk = wrappingKind;
4744 inferNullability = NullabilityKind::NonNull;
4745 inferNullabilityCS = (context == DeclaratorContext::ObjCParameter ||
4746 context == DeclaratorContext::ObjCResult);
4748 break;
4750 case PointerDeclaratorKind::CFErrorRefPointer:
4751 case PointerDeclaratorKind::NSErrorPointerPointer:
4752 // Within a function or method signature, infer _Nullable at both
4753 // levels.
4754 if (isFunctionOrMethod && inAssumeNonNullRegion)
4755 inferNullability = NullabilityKind::Nullable;
4756 break;
4758 case PointerDeclaratorKind::MaybePointerToCFRef:
4759 if (isFunctionOrMethod) {
4760 // On pointer-to-pointer parameters marked cf_returns_retained or
4761 // cf_returns_not_retained, if the outer pointer is explicit then
4762 // infer the inner pointer as _Nullable.
4763 auto hasCFReturnsAttr =
4764 [](const ParsedAttributesView &AttrList) -> bool {
4765 return AttrList.hasAttribute(ParsedAttr::AT_CFReturnsRetained) ||
4766 AttrList.hasAttribute(ParsedAttr::AT_CFReturnsNotRetained);
4768 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
4769 if (hasCFReturnsAttr(D.getDeclarationAttributes()) ||
4770 hasCFReturnsAttr(D.getAttributes()) ||
4771 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
4772 hasCFReturnsAttr(D.getDeclSpec().getAttributes())) {
4773 inferNullability = NullabilityKind::Nullable;
4774 inferNullabilityInnerOnly = true;
4778 break;
4780 break;
4783 case DeclaratorContext::ConversionId:
4784 complainAboutMissingNullability = CAMN_Yes;
4785 break;
4787 case DeclaratorContext::AliasDecl:
4788 case DeclaratorContext::AliasTemplate:
4789 case DeclaratorContext::Block:
4790 case DeclaratorContext::BlockLiteral:
4791 case DeclaratorContext::Condition:
4792 case DeclaratorContext::CXXCatch:
4793 case DeclaratorContext::CXXNew:
4794 case DeclaratorContext::ForInit:
4795 case DeclaratorContext::SelectionInit:
4796 case DeclaratorContext::LambdaExpr:
4797 case DeclaratorContext::LambdaExprParameter:
4798 case DeclaratorContext::ObjCCatch:
4799 case DeclaratorContext::TemplateParam:
4800 case DeclaratorContext::TemplateArg:
4801 case DeclaratorContext::TemplateTypeArg:
4802 case DeclaratorContext::TypeName:
4803 case DeclaratorContext::FunctionalCast:
4804 case DeclaratorContext::RequiresExpr:
4805 case DeclaratorContext::Association:
4806 // Don't infer in these contexts.
4807 break;
4811 // Local function that returns true if its argument looks like a va_list.
4812 auto isVaList = [&S](QualType T) -> bool {
4813 auto *typedefTy = T->getAs<TypedefType>();
4814 if (!typedefTy)
4815 return false;
4816 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
4817 do {
4818 if (typedefTy->getDecl() == vaListTypedef)
4819 return true;
4820 if (auto *name = typedefTy->getDecl()->getIdentifier())
4821 if (name->isStr("va_list"))
4822 return true;
4823 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
4824 } while (typedefTy);
4825 return false;
4828 // Local function that checks the nullability for a given pointer declarator.
4829 // Returns true if _Nonnull was inferred.
4830 auto inferPointerNullability =
4831 [&](SimplePointerKind pointerKind, SourceLocation pointerLoc,
4832 SourceLocation pointerEndLoc,
4833 ParsedAttributesView &attrs, AttributePool &Pool) -> ParsedAttr * {
4834 // We've seen a pointer.
4835 if (NumPointersRemaining > 0)
4836 --NumPointersRemaining;
4838 // If a nullability attribute is present, there's nothing to do.
4839 if (hasNullabilityAttr(attrs))
4840 return nullptr;
4842 // If we're supposed to infer nullability, do so now.
4843 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
4844 ParsedAttr::Syntax syntax = inferNullabilityCS
4845 ? ParsedAttr::AS_ContextSensitiveKeyword
4846 : ParsedAttr::AS_Keyword;
4847 ParsedAttr *nullabilityAttr = Pool.create(
4848 S.getNullabilityKeyword(*inferNullability), SourceRange(pointerLoc),
4849 nullptr, SourceLocation(), nullptr, 0, syntax);
4851 attrs.addAtEnd(nullabilityAttr);
4853 if (inferNullabilityCS) {
4854 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
4855 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
4858 if (pointerLoc.isValid() &&
4859 complainAboutInferringWithinChunk !=
4860 PointerWrappingDeclaratorKind::None) {
4861 auto Diag =
4862 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
4863 Diag << static_cast<int>(complainAboutInferringWithinChunk);
4864 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
4867 if (inferNullabilityInnerOnly)
4868 inferNullabilityInnerOnlyComplete = true;
4869 return nullabilityAttr;
4872 // If we're supposed to complain about missing nullability, do so
4873 // now if it's truly missing.
4874 switch (complainAboutMissingNullability) {
4875 case CAMN_No:
4876 break;
4878 case CAMN_InnerPointers:
4879 if (NumPointersRemaining == 0)
4880 break;
4881 [[fallthrough]];
4883 case CAMN_Yes:
4884 checkNullabilityConsistency(S, pointerKind, pointerLoc, pointerEndLoc);
4886 return nullptr;
4889 // If the type itself could have nullability but does not, infer pointer
4890 // nullability and perform consistency checking.
4891 if (S.CodeSynthesisContexts.empty()) {
4892 if (T->canHaveNullability(/*ResultIfUnknown*/false) &&
4893 !T->getNullability(S.Context)) {
4894 if (isVaList(T)) {
4895 // Record that we've seen a pointer, but do nothing else.
4896 if (NumPointersRemaining > 0)
4897 --NumPointersRemaining;
4898 } else {
4899 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
4900 if (T->isBlockPointerType())
4901 pointerKind = SimplePointerKind::BlockPointer;
4902 else if (T->isMemberPointerType())
4903 pointerKind = SimplePointerKind::MemberPointer;
4905 if (auto *attr = inferPointerNullability(
4906 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
4907 D.getDeclSpec().getEndLoc(),
4908 D.getMutableDeclSpec().getAttributes(),
4909 D.getMutableDeclSpec().getAttributePool())) {
4910 T = state.getAttributedType(
4911 createNullabilityAttr(Context, *attr, *inferNullability), T, T);
4916 if (complainAboutMissingNullability == CAMN_Yes &&
4917 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
4918 D.isPrototypeContext() &&
4919 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
4920 checkNullabilityConsistency(S, SimplePointerKind::Array,
4921 D.getDeclSpec().getTypeSpecTypeLoc());
4925 bool ExpectNoDerefChunk =
4926 state.getCurrentAttributes().hasAttribute(ParsedAttr::AT_NoDeref);
4928 // Walk the DeclTypeInfo, building the recursive type as we go.
4929 // DeclTypeInfos are ordered from the identifier out, which is
4930 // opposite of what we want :).
4931 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4932 unsigned chunkIndex = e - i - 1;
4933 state.setCurrentChunkIndex(chunkIndex);
4934 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4935 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4936 switch (DeclType.Kind) {
4937 case DeclaratorChunk::Paren:
4938 if (i == 0)
4939 warnAboutRedundantParens(S, D, T);
4940 T = S.BuildParenType(T);
4941 break;
4942 case DeclaratorChunk::BlockPointer:
4943 // If blocks are disabled, emit an error.
4944 if (!LangOpts.Blocks)
4945 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4947 // Handle pointer nullability.
4948 inferPointerNullability(SimplePointerKind::BlockPointer, DeclType.Loc,
4949 DeclType.EndLoc, DeclType.getAttrs(),
4950 state.getDeclarator().getAttributePool());
4952 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4953 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4954 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4955 // qualified with const.
4956 if (LangOpts.OpenCL)
4957 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4958 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4960 break;
4961 case DeclaratorChunk::Pointer:
4962 // Verify that we're not building a pointer to pointer to function with
4963 // exception specification.
4964 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4965 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4966 D.setInvalidType(true);
4967 // Build the type anyway.
4970 // Handle pointer nullability
4971 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4972 DeclType.EndLoc, DeclType.getAttrs(),
4973 state.getDeclarator().getAttributePool());
4975 if (LangOpts.ObjC && T->getAs<ObjCObjectType>()) {
4976 T = Context.getObjCObjectPointerType(T);
4977 if (DeclType.Ptr.TypeQuals)
4978 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4979 break;
4982 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4983 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4984 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4985 if (LangOpts.OpenCL) {
4986 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4987 T->isBlockPointerType()) {
4988 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4989 D.setInvalidType(true);
4993 T = S.BuildPointerType(T, DeclType.Loc, Name);
4994 if (DeclType.Ptr.TypeQuals)
4995 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4996 break;
4997 case DeclaratorChunk::Reference: {
4998 // Verify that we're not building a reference to pointer to function with
4999 // exception specification.
5000 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5001 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5002 D.setInvalidType(true);
5003 // Build the type anyway.
5005 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
5007 if (DeclType.Ref.HasRestrict)
5008 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
5009 break;
5011 case DeclaratorChunk::Array: {
5012 // Verify that we're not building an array of pointers to function with
5013 // exception specification.
5014 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
5015 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
5016 D.setInvalidType(true);
5017 // Build the type anyway.
5019 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
5020 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
5021 ArrayType::ArraySizeModifier ASM;
5022 if (ATI.isStar)
5023 ASM = ArrayType::Star;
5024 else if (ATI.hasStatic)
5025 ASM = ArrayType::Static;
5026 else
5027 ASM = ArrayType::Normal;
5028 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
5029 // FIXME: This check isn't quite right: it allows star in prototypes
5030 // for function definitions, and disallows some edge cases detailed
5031 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
5032 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
5033 ASM = ArrayType::Normal;
5034 D.setInvalidType(true);
5037 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
5038 // shall appear only in a declaration of a function parameter with an
5039 // array type, ...
5040 if (ASM == ArrayType::Static || ATI.TypeQuals) {
5041 if (!(D.isPrototypeContext() ||
5042 D.getContext() == DeclaratorContext::KNRTypeList)) {
5043 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
5044 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5045 // Remove the 'static' and the type qualifiers.
5046 if (ASM == ArrayType::Static)
5047 ASM = ArrayType::Normal;
5048 ATI.TypeQuals = 0;
5049 D.setInvalidType(true);
5052 // C99 6.7.5.2p1: ... and then only in the outermost array type
5053 // derivation.
5054 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
5055 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
5056 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
5057 if (ASM == ArrayType::Static)
5058 ASM = ArrayType::Normal;
5059 ATI.TypeQuals = 0;
5060 D.setInvalidType(true);
5063 const AutoType *AT = T->getContainedAutoType();
5064 // Allow arrays of auto if we are a generic lambda parameter.
5065 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
5066 if (AT && D.getContext() != DeclaratorContext::LambdaExprParameter) {
5067 // We've already diagnosed this for decltype(auto).
5068 if (!AT->isDecltypeAuto())
5069 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
5070 << getPrintableNameForEntity(Name) << T;
5071 T = QualType();
5072 break;
5075 // Array parameters can be marked nullable as well, although it's not
5076 // necessary if they're marked 'static'.
5077 if (complainAboutMissingNullability == CAMN_Yes &&
5078 !hasNullabilityAttr(DeclType.getAttrs()) &&
5079 ASM != ArrayType::Static &&
5080 D.isPrototypeContext() &&
5081 !hasOuterPointerLikeChunk(D, chunkIndex)) {
5082 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
5085 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
5086 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
5087 break;
5089 case DeclaratorChunk::Function: {
5090 // If the function declarator has a prototype (i.e. it is not () and
5091 // does not have a K&R-style identifier list), then the arguments are part
5092 // of the type, otherwise the argument list is ().
5093 DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5094 IsQualifiedFunction =
5095 FTI.hasMethodTypeQualifiers() || FTI.hasRefQualifier();
5097 // Check for auto functions and trailing return type and adjust the
5098 // return type accordingly.
5099 if (!D.isInvalidType()) {
5100 // trailing-return-type is only required if we're declaring a function,
5101 // and not, for instance, a pointer to a function.
5102 if (D.getDeclSpec().hasAutoTypeSpec() &&
5103 !FTI.hasTrailingReturnType() && chunkIndex == 0) {
5104 if (!S.getLangOpts().CPlusPlus14) {
5105 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5106 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
5107 ? diag::err_auto_missing_trailing_return
5108 : diag::err_deduced_return_type);
5109 T = Context.IntTy;
5110 D.setInvalidType(true);
5111 } else {
5112 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5113 diag::warn_cxx11_compat_deduced_return_type);
5115 } else if (FTI.hasTrailingReturnType()) {
5116 // T must be exactly 'auto' at this point. See CWG issue 681.
5117 if (isa<ParenType>(T)) {
5118 S.Diag(D.getBeginLoc(), diag::err_trailing_return_in_parens)
5119 << T << D.getSourceRange();
5120 D.setInvalidType(true);
5121 } else if (D.getName().getKind() ==
5122 UnqualifiedIdKind::IK_DeductionGuideName) {
5123 if (T != Context.DependentTy) {
5124 S.Diag(D.getDeclSpec().getBeginLoc(),
5125 diag::err_deduction_guide_with_complex_decl)
5126 << D.getSourceRange();
5127 D.setInvalidType(true);
5129 } else if (D.getContext() != DeclaratorContext::LambdaExpr &&
5130 (T.hasQualifiers() || !isa<AutoType>(T) ||
5131 cast<AutoType>(T)->getKeyword() !=
5132 AutoTypeKeyword::Auto ||
5133 cast<AutoType>(T)->isConstrained())) {
5134 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
5135 diag::err_trailing_return_without_auto)
5136 << T << D.getDeclSpec().getSourceRange();
5137 D.setInvalidType(true);
5139 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
5140 if (T.isNull()) {
5141 // An error occurred parsing the trailing return type.
5142 T = Context.IntTy;
5143 D.setInvalidType(true);
5144 } else if (AutoType *Auto = T->getContainedAutoType()) {
5145 // If the trailing return type contains an `auto`, we may need to
5146 // invent a template parameter for it, for cases like
5147 // `auto f() -> C auto` or `[](auto (*p) -> auto) {}`.
5148 InventedTemplateParameterInfo *InventedParamInfo = nullptr;
5149 if (D.getContext() == DeclaratorContext::Prototype)
5150 InventedParamInfo = &S.InventedParameterInfos.back();
5151 else if (D.getContext() == DeclaratorContext::LambdaExprParameter)
5152 InventedParamInfo = S.getCurLambda();
5153 if (InventedParamInfo) {
5154 std::tie(T, TInfo) = InventTemplateParameter(
5155 state, T, TInfo, Auto, *InventedParamInfo);
5158 } else {
5159 // This function type is not the type of the entity being declared,
5160 // so checking the 'auto' is not the responsibility of this chunk.
5164 // C99 6.7.5.3p1: The return type may not be a function or array type.
5165 // For conversion functions, we'll diagnose this particular error later.
5166 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
5167 (D.getName().getKind() !=
5168 UnqualifiedIdKind::IK_ConversionFunctionId)) {
5169 unsigned diagID = diag::err_func_returning_array_function;
5170 // Last processing chunk in block context means this function chunk
5171 // represents the block.
5172 if (chunkIndex == 0 &&
5173 D.getContext() == DeclaratorContext::BlockLiteral)
5174 diagID = diag::err_block_returning_array_function;
5175 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
5176 T = Context.IntTy;
5177 D.setInvalidType(true);
5180 // Do not allow returning half FP value.
5181 // FIXME: This really should be in BuildFunctionType.
5182 if (T->isHalfType()) {
5183 if (S.getLangOpts().OpenCL) {
5184 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5185 S.getLangOpts())) {
5186 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5187 << T << 0 /*pointer hint*/;
5188 D.setInvalidType(true);
5190 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5191 S.Diag(D.getIdentifierLoc(),
5192 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
5193 D.setInvalidType(true);
5197 if (LangOpts.OpenCL) {
5198 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
5199 // function.
5200 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
5201 T->isPipeType()) {
5202 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
5203 << T << 1 /*hint off*/;
5204 D.setInvalidType(true);
5206 // OpenCL doesn't support variadic functions and blocks
5207 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
5208 // We also allow here any toolchain reserved identifiers.
5209 if (FTI.isVariadic &&
5210 !S.getOpenCLOptions().isAvailableOption(
5211 "__cl_clang_variadic_functions", S.getLangOpts()) &&
5212 !(D.getIdentifier() &&
5213 ((D.getIdentifier()->getName() == "printf" &&
5214 LangOpts.getOpenCLCompatibleVersion() >= 120) ||
5215 D.getIdentifier()->getName().startswith("__")))) {
5216 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
5217 D.setInvalidType(true);
5221 // Methods cannot return interface types. All ObjC objects are
5222 // passed by reference.
5223 if (T->isObjCObjectType()) {
5224 SourceLocation DiagLoc, FixitLoc;
5225 if (TInfo) {
5226 DiagLoc = TInfo->getTypeLoc().getBeginLoc();
5227 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getEndLoc());
5228 } else {
5229 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
5230 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getEndLoc());
5232 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
5233 << 0 << T
5234 << FixItHint::CreateInsertion(FixitLoc, "*");
5236 T = Context.getObjCObjectPointerType(T);
5237 if (TInfo) {
5238 TypeLocBuilder TLB;
5239 TLB.pushFullCopy(TInfo->getTypeLoc());
5240 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
5241 TLoc.setStarLoc(FixitLoc);
5242 TInfo = TLB.getTypeSourceInfo(Context, T);
5245 D.setInvalidType(true);
5248 // cv-qualifiers on return types are pointless except when the type is a
5249 // class type in C++.
5250 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
5251 !(S.getLangOpts().CPlusPlus &&
5252 (T->isDependentType() || T->isRecordType()))) {
5253 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
5254 D.getFunctionDefinitionKind() ==
5255 FunctionDefinitionKind::Definition) {
5256 // [6.9.1/3] qualified void return is invalid on a C
5257 // function definition. Apparently ok on declarations and
5258 // in C++ though (!)
5259 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
5260 } else
5261 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
5263 // C++2a [dcl.fct]p12:
5264 // A volatile-qualified return type is deprecated
5265 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20)
5266 S.Diag(DeclType.Loc, diag::warn_deprecated_volatile_return) << T;
5269 // Objective-C ARC ownership qualifiers are ignored on the function
5270 // return type (by type canonicalization). Complain if this attribute
5271 // was written here.
5272 if (T.getQualifiers().hasObjCLifetime()) {
5273 SourceLocation AttrLoc;
5274 if (chunkIndex + 1 < D.getNumTypeObjects()) {
5275 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
5276 for (const ParsedAttr &AL : ReturnTypeChunk.getAttrs()) {
5277 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5278 AttrLoc = AL.getLoc();
5279 break;
5283 if (AttrLoc.isInvalid()) {
5284 for (const ParsedAttr &AL : D.getDeclSpec().getAttributes()) {
5285 if (AL.getKind() == ParsedAttr::AT_ObjCOwnership) {
5286 AttrLoc = AL.getLoc();
5287 break;
5292 if (AttrLoc.isValid()) {
5293 // The ownership attributes are almost always written via
5294 // the predefined
5295 // __strong/__weak/__autoreleasing/__unsafe_unretained.
5296 if (AttrLoc.isMacroID())
5297 AttrLoc =
5298 S.SourceMgr.getImmediateExpansionRange(AttrLoc).getBegin();
5300 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
5301 << T.getQualifiers().getObjCLifetime();
5305 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
5306 // C++ [dcl.fct]p6:
5307 // Types shall not be defined in return or parameter types.
5308 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
5309 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
5310 << Context.getTypeDeclType(Tag);
5313 // Exception specs are not allowed in typedefs. Complain, but add it
5314 // anyway.
5315 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus17)
5316 S.Diag(FTI.getExceptionSpecLocBeg(),
5317 diag::err_exception_spec_in_typedef)
5318 << (D.getContext() == DeclaratorContext::AliasDecl ||
5319 D.getContext() == DeclaratorContext::AliasTemplate);
5321 // If we see "T var();" or "T var(T());" at block scope, it is probably
5322 // an attempt to initialize a variable, not a function declaration.
5323 if (FTI.isAmbiguous)
5324 warnAboutAmbiguousFunction(S, D, DeclType, T);
5326 FunctionType::ExtInfo EI(
5327 getCCForDeclaratorChunk(S, D, DeclType.getAttrs(), FTI, chunkIndex));
5329 // OpenCL disallows functions without a prototype, but it doesn't enforce
5330 // strict prototypes as in C2x because it allows a function definition to
5331 // have an identifier list. See OpenCL 3.0 6.11/g for more details.
5332 if (!FTI.NumParams && !FTI.isVariadic &&
5333 !LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL) {
5334 // Simple void foo(), where the incoming T is the result type.
5335 T = Context.getFunctionNoProtoType(T, EI);
5336 } else {
5337 // We allow a zero-parameter variadic function in C if the
5338 // function is marked with the "overloadable" attribute. Scan
5339 // for this attribute now.
5340 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus)
5341 if (!D.getDeclarationAttributes().hasAttribute(
5342 ParsedAttr::AT_Overloadable) &&
5343 !D.getAttributes().hasAttribute(ParsedAttr::AT_Overloadable) &&
5344 !D.getDeclSpec().getAttributes().hasAttribute(
5345 ParsedAttr::AT_Overloadable))
5346 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
5348 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
5349 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
5350 // definition.
5351 S.Diag(FTI.Params[0].IdentLoc,
5352 diag::err_ident_list_in_fn_declaration);
5353 D.setInvalidType(true);
5354 // Recover by creating a K&R-style function type, if possible.
5355 T = (!LangOpts.requiresStrictPrototypes() && !LangOpts.OpenCL)
5356 ? Context.getFunctionNoProtoType(T, EI)
5357 : Context.IntTy;
5358 break;
5361 FunctionProtoType::ExtProtoInfo EPI;
5362 EPI.ExtInfo = EI;
5363 EPI.Variadic = FTI.isVariadic;
5364 EPI.EllipsisLoc = FTI.getEllipsisLoc();
5365 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
5366 EPI.TypeQuals.addCVRUQualifiers(
5367 FTI.MethodQualifiers ? FTI.MethodQualifiers->getTypeQualifiers()
5368 : 0);
5369 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
5370 : FTI.RefQualifierIsLValueRef? RQ_LValue
5371 : RQ_RValue;
5373 // Otherwise, we have a function with a parameter list that is
5374 // potentially variadic.
5375 SmallVector<QualType, 16> ParamTys;
5376 ParamTys.reserve(FTI.NumParams);
5378 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
5379 ExtParameterInfos(FTI.NumParams);
5380 bool HasAnyInterestingExtParameterInfos = false;
5382 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
5383 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5384 QualType ParamTy = Param->getType();
5385 assert(!ParamTy.isNull() && "Couldn't parse type?");
5387 // Look for 'void'. void is allowed only as a single parameter to a
5388 // function with no other parameters (C99 6.7.5.3p10). We record
5389 // int(void) as a FunctionProtoType with an empty parameter list.
5390 if (ParamTy->isVoidType()) {
5391 // If this is something like 'float(int, void)', reject it. 'void'
5392 // is an incomplete type (C99 6.2.5p19) and function decls cannot
5393 // have parameters of incomplete type.
5394 if (FTI.NumParams != 1 || FTI.isVariadic) {
5395 S.Diag(FTI.Params[i].IdentLoc, diag::err_void_only_param);
5396 ParamTy = Context.IntTy;
5397 Param->setType(ParamTy);
5398 } else if (FTI.Params[i].Ident) {
5399 // Reject, but continue to parse 'int(void abc)'.
5400 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
5401 ParamTy = Context.IntTy;
5402 Param->setType(ParamTy);
5403 } else {
5404 // Reject, but continue to parse 'float(const void)'.
5405 if (ParamTy.hasQualifiers())
5406 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
5408 // Do not add 'void' to the list.
5409 break;
5411 } else if (ParamTy->isHalfType()) {
5412 // Disallow half FP parameters.
5413 // FIXME: This really should be in BuildFunctionType.
5414 if (S.getLangOpts().OpenCL) {
5415 if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
5416 S.getLangOpts())) {
5417 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5418 << ParamTy << 0;
5419 D.setInvalidType();
5420 Param->setInvalidDecl();
5422 } else if (!S.getLangOpts().HalfArgsAndReturns) {
5423 S.Diag(Param->getLocation(),
5424 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
5425 D.setInvalidType();
5427 } else if (!FTI.hasPrototype) {
5428 if (ParamTy->isPromotableIntegerType()) {
5429 ParamTy = Context.getPromotedIntegerType(ParamTy);
5430 Param->setKNRPromoted(true);
5431 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
5432 if (BTy->getKind() == BuiltinType::Float) {
5433 ParamTy = Context.DoubleTy;
5434 Param->setKNRPromoted(true);
5437 } else if (S.getLangOpts().OpenCL && ParamTy->isBlockPointerType()) {
5438 // OpenCL 2.0 s6.12.5: A block cannot be a parameter of a function.
5439 S.Diag(Param->getLocation(), diag::err_opencl_invalid_param)
5440 << ParamTy << 1 /*hint off*/;
5441 D.setInvalidType();
5444 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
5445 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
5446 HasAnyInterestingExtParameterInfos = true;
5449 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
5450 ExtParameterInfos[i] =
5451 ExtParameterInfos[i].withABI(attr->getABI());
5452 HasAnyInterestingExtParameterInfos = true;
5455 if (Param->hasAttr<PassObjectSizeAttr>()) {
5456 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
5457 HasAnyInterestingExtParameterInfos = true;
5460 if (Param->hasAttr<NoEscapeAttr>()) {
5461 ExtParameterInfos[i] = ExtParameterInfos[i].withIsNoEscape(true);
5462 HasAnyInterestingExtParameterInfos = true;
5465 ParamTys.push_back(ParamTy);
5468 if (HasAnyInterestingExtParameterInfos) {
5469 EPI.ExtParameterInfos = ExtParameterInfos.data();
5470 checkExtParameterInfos(S, ParamTys, EPI,
5471 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
5474 SmallVector<QualType, 4> Exceptions;
5475 SmallVector<ParsedType, 2> DynamicExceptions;
5476 SmallVector<SourceRange, 2> DynamicExceptionRanges;
5477 Expr *NoexceptExpr = nullptr;
5479 if (FTI.getExceptionSpecType() == EST_Dynamic) {
5480 // FIXME: It's rather inefficient to have to split into two vectors
5481 // here.
5482 unsigned N = FTI.getNumExceptions();
5483 DynamicExceptions.reserve(N);
5484 DynamicExceptionRanges.reserve(N);
5485 for (unsigned I = 0; I != N; ++I) {
5486 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
5487 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
5489 } else if (isComputedNoexcept(FTI.getExceptionSpecType())) {
5490 NoexceptExpr = FTI.NoexceptExpr;
5493 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
5494 FTI.getExceptionSpecType(),
5495 DynamicExceptions,
5496 DynamicExceptionRanges,
5497 NoexceptExpr,
5498 Exceptions,
5499 EPI.ExceptionSpec);
5501 // FIXME: Set address space from attrs for C++ mode here.
5502 // OpenCLCPlusPlus: A class member function has an address space.
5503 auto IsClassMember = [&]() {
5504 return (!state.getDeclarator().getCXXScopeSpec().isEmpty() &&
5505 state.getDeclarator()
5506 .getCXXScopeSpec()
5507 .getScopeRep()
5508 ->getKind() == NestedNameSpecifier::TypeSpec) ||
5509 state.getDeclarator().getContext() ==
5510 DeclaratorContext::Member ||
5511 state.getDeclarator().getContext() ==
5512 DeclaratorContext::LambdaExpr;
5515 if (state.getSema().getLangOpts().OpenCLCPlusPlus && IsClassMember()) {
5516 LangAS ASIdx = LangAS::Default;
5517 // Take address space attr if any and mark as invalid to avoid adding
5518 // them later while creating QualType.
5519 if (FTI.MethodQualifiers)
5520 for (ParsedAttr &attr : FTI.MethodQualifiers->getAttributes()) {
5521 LangAS ASIdxNew = attr.asOpenCLLangAS();
5522 if (DiagnoseMultipleAddrSpaceAttributes(S, ASIdx, ASIdxNew,
5523 attr.getLoc()))
5524 D.setInvalidType(true);
5525 else
5526 ASIdx = ASIdxNew;
5528 // If a class member function's address space is not set, set it to
5529 // __generic.
5530 LangAS AS =
5531 (ASIdx == LangAS::Default ? S.getDefaultCXXMethodAddrSpace()
5532 : ASIdx);
5533 EPI.TypeQuals.addAddressSpace(AS);
5535 T = Context.getFunctionType(T, ParamTys, EPI);
5537 break;
5539 case DeclaratorChunk::MemberPointer: {
5540 // The scope spec must refer to a class, or be dependent.
5541 CXXScopeSpec &SS = DeclType.Mem.Scope();
5542 QualType ClsType;
5544 // Handle pointer nullability.
5545 inferPointerNullability(SimplePointerKind::MemberPointer, DeclType.Loc,
5546 DeclType.EndLoc, DeclType.getAttrs(),
5547 state.getDeclarator().getAttributePool());
5549 if (SS.isInvalid()) {
5550 // Avoid emitting extra errors if we already errored on the scope.
5551 D.setInvalidType(true);
5552 } else if (S.isDependentScopeSpecifier(SS) ||
5553 isa_and_nonnull<CXXRecordDecl>(S.computeDeclContext(SS))) {
5554 NestedNameSpecifier *NNS = SS.getScopeRep();
5555 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
5556 switch (NNS->getKind()) {
5557 case NestedNameSpecifier::Identifier:
5558 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
5559 NNS->getAsIdentifier());
5560 break;
5562 case NestedNameSpecifier::Namespace:
5563 case NestedNameSpecifier::NamespaceAlias:
5564 case NestedNameSpecifier::Global:
5565 case NestedNameSpecifier::Super:
5566 llvm_unreachable("Nested-name-specifier must name a type");
5568 case NestedNameSpecifier::TypeSpec:
5569 case NestedNameSpecifier::TypeSpecWithTemplate:
5570 ClsType = QualType(NNS->getAsType(), 0);
5571 // Note: if the NNS has a prefix and ClsType is a nondependent
5572 // TemplateSpecializationType, then the NNS prefix is NOT included
5573 // in ClsType; hence we wrap ClsType into an ElaboratedType.
5574 // NOTE: in particular, no wrap occurs if ClsType already is an
5575 // Elaborated, DependentName, or DependentTemplateSpecialization.
5576 if (isa<TemplateSpecializationType>(NNS->getAsType()))
5577 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
5578 break;
5580 } else {
5581 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
5582 diag::err_illegal_decl_mempointer_in_nonclass)
5583 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
5584 << DeclType.Mem.Scope().getRange();
5585 D.setInvalidType(true);
5588 if (!ClsType.isNull())
5589 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
5590 D.getIdentifier());
5591 if (T.isNull()) {
5592 T = Context.IntTy;
5593 D.setInvalidType(true);
5594 } else if (DeclType.Mem.TypeQuals) {
5595 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
5597 break;
5600 case DeclaratorChunk::Pipe: {
5601 T = S.BuildReadPipeType(T, DeclType.Loc);
5602 processTypeAttrs(state, T, TAL_DeclSpec,
5603 D.getMutableDeclSpec().getAttributes());
5604 break;
5608 if (T.isNull()) {
5609 D.setInvalidType(true);
5610 T = Context.IntTy;
5613 // See if there are any attributes on this declarator chunk.
5614 processTypeAttrs(state, T, TAL_DeclChunk, DeclType.getAttrs());
5616 if (DeclType.Kind != DeclaratorChunk::Paren) {
5617 if (ExpectNoDerefChunk && !IsNoDerefableChunk(DeclType))
5618 S.Diag(DeclType.Loc, diag::warn_noderef_on_non_pointer_or_array);
5620 ExpectNoDerefChunk = state.didParseNoDeref();
5624 if (ExpectNoDerefChunk)
5625 S.Diag(state.getDeclarator().getBeginLoc(),
5626 diag::warn_noderef_on_non_pointer_or_array);
5628 // GNU warning -Wstrict-prototypes
5629 // Warn if a function declaration or definition is without a prototype.
5630 // This warning is issued for all kinds of unprototyped function
5631 // declarations (i.e. function type typedef, function pointer etc.)
5632 // C99 6.7.5.3p14:
5633 // The empty list in a function declarator that is not part of a definition
5634 // of that function specifies that no information about the number or types
5635 // of the parameters is supplied.
5636 // See ActOnFinishFunctionBody() and MergeFunctionDecl() for handling of
5637 // function declarations whose behavior changes in C2x.
5638 if (!LangOpts.requiresStrictPrototypes()) {
5639 bool IsBlock = false;
5640 for (const DeclaratorChunk &DeclType : D.type_objects()) {
5641 switch (DeclType.Kind) {
5642 case DeclaratorChunk::BlockPointer:
5643 IsBlock = true;
5644 break;
5645 case DeclaratorChunk::Function: {
5646 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
5647 // We suppress the warning when there's no LParen location, as this
5648 // indicates the declaration was an implicit declaration, which gets
5649 // warned about separately via -Wimplicit-function-declaration. We also
5650 // suppress the warning when we know the function has a prototype.
5651 if (!FTI.hasPrototype && FTI.NumParams == 0 && !FTI.isVariadic &&
5652 FTI.getLParenLoc().isValid())
5653 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
5654 << IsBlock
5655 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
5656 IsBlock = false;
5657 break;
5659 default:
5660 break;
5665 assert(!T.isNull() && "T must not be null after this point");
5667 if (LangOpts.CPlusPlus && T->isFunctionType()) {
5668 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
5669 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
5671 // C++ 8.3.5p4:
5672 // A cv-qualifier-seq shall only be part of the function type
5673 // for a nonstatic member function, the function type to which a pointer
5674 // to member refers, or the top-level function type of a function typedef
5675 // declaration.
5677 // Core issue 547 also allows cv-qualifiers on function types that are
5678 // top-level template type arguments.
5679 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
5680 if (D.getName().getKind() == UnqualifiedIdKind::IK_DeductionGuideName)
5681 Kind = DeductionGuide;
5682 else if (!D.getCXXScopeSpec().isSet()) {
5683 if ((D.getContext() == DeclaratorContext::Member ||
5684 D.getContext() == DeclaratorContext::LambdaExpr) &&
5685 !D.getDeclSpec().isFriendSpecified())
5686 Kind = Member;
5687 } else {
5688 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
5689 if (!DC || DC->isRecord())
5690 Kind = Member;
5693 // C++11 [dcl.fct]p6 (w/DR1417):
5694 // An attempt to specify a function type with a cv-qualifier-seq or a
5695 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
5696 // - the function type for a non-static member function,
5697 // - the function type to which a pointer to member refers,
5698 // - the top-level function type of a function typedef declaration or
5699 // alias-declaration,
5700 // - the type-id in the default argument of a type-parameter, or
5701 // - the type-id of a template-argument for a type-parameter
5703 // FIXME: Checking this here is insufficient. We accept-invalid on:
5705 // template<typename T> struct S { void f(T); };
5706 // S<int() const> s;
5708 // ... for instance.
5709 if (IsQualifiedFunction &&
5710 !(Kind == Member &&
5711 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
5712 !IsTypedefName && D.getContext() != DeclaratorContext::TemplateArg &&
5713 D.getContext() != DeclaratorContext::TemplateTypeArg) {
5714 SourceLocation Loc = D.getBeginLoc();
5715 SourceRange RemovalRange;
5716 unsigned I;
5717 if (D.isFunctionDeclarator(I)) {
5718 SmallVector<SourceLocation, 4> RemovalLocs;
5719 const DeclaratorChunk &Chunk = D.getTypeObject(I);
5720 assert(Chunk.Kind == DeclaratorChunk::Function);
5722 if (Chunk.Fun.hasRefQualifier())
5723 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
5725 if (Chunk.Fun.hasMethodTypeQualifiers())
5726 Chunk.Fun.MethodQualifiers->forEachQualifier(
5727 [&](DeclSpec::TQ TypeQual, StringRef QualName,
5728 SourceLocation SL) { RemovalLocs.push_back(SL); });
5730 if (!RemovalLocs.empty()) {
5731 llvm::sort(RemovalLocs,
5732 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
5733 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
5734 Loc = RemovalLocs.front();
5738 S.Diag(Loc, diag::err_invalid_qualified_function_type)
5739 << Kind << D.isFunctionDeclarator() << T
5740 << getFunctionQualifiersAsString(FnTy)
5741 << FixItHint::CreateRemoval(RemovalRange);
5743 // Strip the cv-qualifiers and ref-qualifiers from the type.
5744 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
5745 EPI.TypeQuals.removeCVRQualifiers();
5746 EPI.RefQualifier = RQ_None;
5748 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
5749 EPI);
5750 // Rebuild any parens around the identifier in the function type.
5751 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5752 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
5753 break;
5754 T = S.BuildParenType(T);
5759 // Apply any undistributed attributes from the declaration or declarator.
5760 ParsedAttributesView NonSlidingAttrs;
5761 for (ParsedAttr &AL : D.getDeclarationAttributes()) {
5762 if (!AL.slidesFromDeclToDeclSpecLegacyBehavior()) {
5763 NonSlidingAttrs.addAtEnd(&AL);
5766 processTypeAttrs(state, T, TAL_DeclName, NonSlidingAttrs);
5767 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
5769 // Diagnose any ignored type attributes.
5770 state.diagnoseIgnoredTypeAttrs(T);
5772 // C++0x [dcl.constexpr]p9:
5773 // A constexpr specifier used in an object declaration declares the object
5774 // as const.
5775 if (D.getDeclSpec().getConstexprSpecifier() == ConstexprSpecKind::Constexpr &&
5776 T->isObjectType())
5777 T.addConst();
5779 // C++2a [dcl.fct]p4:
5780 // A parameter with volatile-qualified type is deprecated
5781 if (T.isVolatileQualified() && S.getLangOpts().CPlusPlus20 &&
5782 (D.getContext() == DeclaratorContext::Prototype ||
5783 D.getContext() == DeclaratorContext::LambdaExprParameter))
5784 S.Diag(D.getIdentifierLoc(), diag::warn_deprecated_volatile_param) << T;
5786 // If there was an ellipsis in the declarator, the declaration declares a
5787 // parameter pack whose type may be a pack expansion type.
5788 if (D.hasEllipsis()) {
5789 // C++0x [dcl.fct]p13:
5790 // A declarator-id or abstract-declarator containing an ellipsis shall
5791 // only be used in a parameter-declaration. Such a parameter-declaration
5792 // is a parameter pack (14.5.3). [...]
5793 switch (D.getContext()) {
5794 case DeclaratorContext::Prototype:
5795 case DeclaratorContext::LambdaExprParameter:
5796 case DeclaratorContext::RequiresExpr:
5797 // C++0x [dcl.fct]p13:
5798 // [...] When it is part of a parameter-declaration-clause, the
5799 // parameter pack is a function parameter pack (14.5.3). The type T
5800 // of the declarator-id of the function parameter pack shall contain
5801 // a template parameter pack; each template parameter pack in T is
5802 // expanded by the function parameter pack.
5804 // We represent function parameter packs as function parameters whose
5805 // type is a pack expansion.
5806 if (!T->containsUnexpandedParameterPack() &&
5807 (!LangOpts.CPlusPlus20 || !T->getContainedAutoType())) {
5808 S.Diag(D.getEllipsisLoc(),
5809 diag::err_function_parameter_pack_without_parameter_packs)
5810 << T << D.getSourceRange();
5811 D.setEllipsisLoc(SourceLocation());
5812 } else {
5813 T = Context.getPackExpansionType(T, None, /*ExpectPackInType=*/false);
5815 break;
5816 case DeclaratorContext::TemplateParam:
5817 // C++0x [temp.param]p15:
5818 // If a template-parameter is a [...] is a parameter-declaration that
5819 // declares a parameter pack (8.3.5), then the template-parameter is a
5820 // template parameter pack (14.5.3).
5822 // Note: core issue 778 clarifies that, if there are any unexpanded
5823 // parameter packs in the type of the non-type template parameter, then
5824 // it expands those parameter packs.
5825 if (T->containsUnexpandedParameterPack())
5826 T = Context.getPackExpansionType(T, None);
5827 else
5828 S.Diag(D.getEllipsisLoc(),
5829 LangOpts.CPlusPlus11
5830 ? diag::warn_cxx98_compat_variadic_templates
5831 : diag::ext_variadic_templates);
5832 break;
5834 case DeclaratorContext::File:
5835 case DeclaratorContext::KNRTypeList:
5836 case DeclaratorContext::ObjCParameter: // FIXME: special diagnostic here?
5837 case DeclaratorContext::ObjCResult: // FIXME: special diagnostic here?
5838 case DeclaratorContext::TypeName:
5839 case DeclaratorContext::FunctionalCast:
5840 case DeclaratorContext::CXXNew:
5841 case DeclaratorContext::AliasDecl:
5842 case DeclaratorContext::AliasTemplate:
5843 case DeclaratorContext::Member:
5844 case DeclaratorContext::Block:
5845 case DeclaratorContext::ForInit:
5846 case DeclaratorContext::SelectionInit:
5847 case DeclaratorContext::Condition:
5848 case DeclaratorContext::CXXCatch:
5849 case DeclaratorContext::ObjCCatch:
5850 case DeclaratorContext::BlockLiteral:
5851 case DeclaratorContext::LambdaExpr:
5852 case DeclaratorContext::ConversionId:
5853 case DeclaratorContext::TrailingReturn:
5854 case DeclaratorContext::TrailingReturnVar:
5855 case DeclaratorContext::TemplateArg:
5856 case DeclaratorContext::TemplateTypeArg:
5857 case DeclaratorContext::Association:
5858 // FIXME: We may want to allow parameter packs in block-literal contexts
5859 // in the future.
5860 S.Diag(D.getEllipsisLoc(),
5861 diag::err_ellipsis_in_declarator_not_parameter);
5862 D.setEllipsisLoc(SourceLocation());
5863 break;
5867 assert(!T.isNull() && "T must not be null at the end of this function");
5868 if (D.isInvalidType())
5869 return Context.getTrivialTypeSourceInfo(T);
5871 return GetTypeSourceInfoForDeclarator(state, T, TInfo);
5874 /// GetTypeForDeclarator - Convert the type for the specified
5875 /// declarator to Type instances.
5877 /// The result of this call will never be null, but the associated
5878 /// type may be a null type if there's an unrecoverable error.
5879 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
5880 // Determine the type of the declarator. Not all forms of declarator
5881 // have a type.
5883 TypeProcessingState state(*this, D);
5885 TypeSourceInfo *ReturnTypeInfo = nullptr;
5886 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5887 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
5888 inferARCWriteback(state, T);
5890 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
5893 static void transferARCOwnershipToDeclSpec(Sema &S,
5894 QualType &declSpecTy,
5895 Qualifiers::ObjCLifetime ownership) {
5896 if (declSpecTy->isObjCRetainableType() &&
5897 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
5898 Qualifiers qs;
5899 qs.addObjCLifetime(ownership);
5900 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
5904 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
5905 Qualifiers::ObjCLifetime ownership,
5906 unsigned chunkIndex) {
5907 Sema &S = state.getSema();
5908 Declarator &D = state.getDeclarator();
5910 // Look for an explicit lifetime attribute.
5911 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
5912 if (chunk.getAttrs().hasAttribute(ParsedAttr::AT_ObjCOwnership))
5913 return;
5915 const char *attrStr = nullptr;
5916 switch (ownership) {
5917 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
5918 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
5919 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
5920 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
5921 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
5924 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
5925 Arg->Ident = &S.Context.Idents.get(attrStr);
5926 Arg->Loc = SourceLocation();
5928 ArgsUnion Args(Arg);
5930 // If there wasn't one, add one (with an invalid source location
5931 // so that we don't make an AttributedType for it).
5932 ParsedAttr *attr = D.getAttributePool().create(
5933 &S.Context.Idents.get("objc_ownership"), SourceLocation(),
5934 /*scope*/ nullptr, SourceLocation(),
5935 /*args*/ &Args, 1, ParsedAttr::AS_GNU);
5936 chunk.getAttrs().addAtEnd(attr);
5937 // TODO: mark whether we did this inference?
5940 /// Used for transferring ownership in casts resulting in l-values.
5941 static void transferARCOwnership(TypeProcessingState &state,
5942 QualType &declSpecTy,
5943 Qualifiers::ObjCLifetime ownership) {
5944 Sema &S = state.getSema();
5945 Declarator &D = state.getDeclarator();
5947 int inner = -1;
5948 bool hasIndirection = false;
5949 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5950 DeclaratorChunk &chunk = D.getTypeObject(i);
5951 switch (chunk.Kind) {
5952 case DeclaratorChunk::Paren:
5953 // Ignore parens.
5954 break;
5956 case DeclaratorChunk::Array:
5957 case DeclaratorChunk::Reference:
5958 case DeclaratorChunk::Pointer:
5959 if (inner != -1)
5960 hasIndirection = true;
5961 inner = i;
5962 break;
5964 case DeclaratorChunk::BlockPointer:
5965 if (inner != -1)
5966 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
5967 return;
5969 case DeclaratorChunk::Function:
5970 case DeclaratorChunk::MemberPointer:
5971 case DeclaratorChunk::Pipe:
5972 return;
5976 if (inner == -1)
5977 return;
5979 DeclaratorChunk &chunk = D.getTypeObject(inner);
5980 if (chunk.Kind == DeclaratorChunk::Pointer) {
5981 if (declSpecTy->isObjCRetainableType())
5982 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5983 if (declSpecTy->isObjCObjectType() && hasIndirection)
5984 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
5985 } else {
5986 assert(chunk.Kind == DeclaratorChunk::Array ||
5987 chunk.Kind == DeclaratorChunk::Reference);
5988 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
5992 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
5993 TypeProcessingState state(*this, D);
5995 TypeSourceInfo *ReturnTypeInfo = nullptr;
5996 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
5998 if (getLangOpts().ObjC) {
5999 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
6000 if (ownership != Qualifiers::OCL_None)
6001 transferARCOwnership(state, declSpecTy, ownership);
6004 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
6007 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
6008 TypeProcessingState &State) {
6009 TL.setAttr(State.takeAttrForAttributedType(TL.getTypePtr()));
6012 namespace {
6013 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
6014 Sema &SemaRef;
6015 ASTContext &Context;
6016 TypeProcessingState &State;
6017 const DeclSpec &DS;
6019 public:
6020 TypeSpecLocFiller(Sema &S, ASTContext &Context, TypeProcessingState &State,
6021 const DeclSpec &DS)
6022 : SemaRef(S), Context(Context), State(State), DS(DS) {}
6024 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6025 Visit(TL.getModifiedLoc());
6026 fillAttributedTypeLoc(TL, State);
6028 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6029 Visit(TL.getWrappedLoc());
6031 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6032 Visit(TL.getInnerLoc());
6033 TL.setExpansionLoc(
6034 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6036 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6037 Visit(TL.getUnqualifiedLoc());
6039 // Allow to fill pointee's type locations, e.g.,
6040 // int __attr * __attr * __attr *p;
6041 void VisitPointerTypeLoc(PointerTypeLoc TL) { Visit(TL.getNextTypeLoc()); }
6042 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
6043 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6045 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
6046 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6047 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
6048 // addition field. What we have is good enough for display of location
6049 // of 'fixit' on interface name.
6050 TL.setNameEndLoc(DS.getEndLoc());
6052 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
6053 TypeSourceInfo *RepTInfo = nullptr;
6054 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6055 TL.copy(RepTInfo->getTypeLoc());
6057 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6058 TypeSourceInfo *RepTInfo = nullptr;
6059 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
6060 TL.copy(RepTInfo->getTypeLoc());
6062 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
6063 TypeSourceInfo *TInfo = nullptr;
6064 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6066 // If we got no declarator info from previous Sema routines,
6067 // just fill with the typespec loc.
6068 if (!TInfo) {
6069 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
6070 return;
6073 TypeLoc OldTL = TInfo->getTypeLoc();
6074 if (TInfo->getType()->getAs<ElaboratedType>()) {
6075 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
6076 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
6077 .castAs<TemplateSpecializationTypeLoc>();
6078 TL.copy(NamedTL);
6079 } else {
6080 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
6081 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
6085 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
6086 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
6087 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6088 TL.setParensRange(DS.getTypeofParensRange());
6090 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
6091 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
6092 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
6093 TL.setParensRange(DS.getTypeofParensRange());
6094 assert(DS.getRepAsType());
6095 TypeSourceInfo *TInfo = nullptr;
6096 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6097 TL.setUnderlyingTInfo(TInfo);
6099 void VisitDecltypeTypeLoc(DecltypeTypeLoc TL) {
6100 assert(DS.getTypeSpecType() == DeclSpec::TST_decltype);
6101 TL.setDecltypeLoc(DS.getTypeSpecTypeLoc());
6102 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6104 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
6105 assert(DS.isTransformTypeTrait(DS.getTypeSpecType()));
6106 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6107 TL.setParensRange(DS.getTypeofParensRange());
6108 assert(DS.getRepAsType());
6109 TypeSourceInfo *TInfo = nullptr;
6110 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6111 TL.setUnderlyingTInfo(TInfo);
6113 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
6114 // By default, use the source location of the type specifier.
6115 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
6116 if (TL.needsExtraLocalData()) {
6117 // Set info for the written builtin specifiers.
6118 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
6119 // Try to have a meaningful source location.
6120 if (TL.getWrittenSignSpec() != TypeSpecifierSign::Unspecified)
6121 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
6122 if (TL.getWrittenWidthSpec() != TypeSpecifierWidth::Unspecified)
6123 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
6126 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
6127 if (DS.getTypeSpecType() == TST_typename) {
6128 TypeSourceInfo *TInfo = nullptr;
6129 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6130 if (TInfo)
6131 if (auto ETL = TInfo->getTypeLoc().getAs<ElaboratedTypeLoc>()) {
6132 TL.copy(ETL);
6133 return;
6136 const ElaboratedType *T = TL.getTypePtr();
6137 TL.setElaboratedKeywordLoc(T->getKeyword() != ETK_None
6138 ? DS.getTypeSpecTypeLoc()
6139 : SourceLocation());
6140 const CXXScopeSpec& SS = DS.getTypeSpecScope();
6141 TL.setQualifierLoc(SS.getWithLocInContext(Context));
6142 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
6144 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
6145 assert(DS.getTypeSpecType() == TST_typename);
6146 TypeSourceInfo *TInfo = nullptr;
6147 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6148 assert(TInfo);
6149 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
6151 void VisitDependentTemplateSpecializationTypeLoc(
6152 DependentTemplateSpecializationTypeLoc TL) {
6153 assert(DS.getTypeSpecType() == TST_typename);
6154 TypeSourceInfo *TInfo = nullptr;
6155 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6156 assert(TInfo);
6157 TL.copy(
6158 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
6160 void VisitAutoTypeLoc(AutoTypeLoc TL) {
6161 assert(DS.getTypeSpecType() == TST_auto ||
6162 DS.getTypeSpecType() == TST_decltype_auto ||
6163 DS.getTypeSpecType() == TST_auto_type ||
6164 DS.getTypeSpecType() == TST_unspecified);
6165 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6166 if (DS.getTypeSpecType() == TST_decltype_auto)
6167 TL.setRParenLoc(DS.getTypeofParensRange().getEnd());
6168 if (!DS.isConstrainedAuto())
6169 return;
6170 TemplateIdAnnotation *TemplateId = DS.getRepAsTemplateId();
6171 if (!TemplateId)
6172 return;
6173 if (DS.getTypeSpecScope().isNotEmpty())
6174 TL.setNestedNameSpecifierLoc(
6175 DS.getTypeSpecScope().getWithLocInContext(Context));
6176 else
6177 TL.setNestedNameSpecifierLoc(NestedNameSpecifierLoc());
6178 TL.setTemplateKWLoc(TemplateId->TemplateKWLoc);
6179 TL.setConceptNameLoc(TemplateId->TemplateNameLoc);
6180 TL.setFoundDecl(nullptr);
6181 TL.setLAngleLoc(TemplateId->LAngleLoc);
6182 TL.setRAngleLoc(TemplateId->RAngleLoc);
6183 if (TemplateId->NumArgs == 0)
6184 return;
6185 TemplateArgumentListInfo TemplateArgsInfo;
6186 ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
6187 TemplateId->NumArgs);
6188 SemaRef.translateTemplateArguments(TemplateArgsPtr, TemplateArgsInfo);
6189 for (unsigned I = 0; I < TemplateId->NumArgs; ++I)
6190 TL.setArgLocInfo(I, TemplateArgsInfo.arguments()[I].getLocInfo());
6192 void VisitTagTypeLoc(TagTypeLoc TL) {
6193 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
6195 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
6196 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
6197 // or an _Atomic qualifier.
6198 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
6199 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6200 TL.setParensRange(DS.getTypeofParensRange());
6202 TypeSourceInfo *TInfo = nullptr;
6203 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6204 assert(TInfo);
6205 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6206 } else {
6207 TL.setKWLoc(DS.getAtomicSpecLoc());
6208 // No parens, to indicate this was spelled as an _Atomic qualifier.
6209 TL.setParensRange(SourceRange());
6210 Visit(TL.getValueLoc());
6214 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6215 TL.setKWLoc(DS.getTypeSpecTypeLoc());
6217 TypeSourceInfo *TInfo = nullptr;
6218 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
6219 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
6222 void VisitExtIntTypeLoc(BitIntTypeLoc TL) {
6223 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6226 void VisitDependentExtIntTypeLoc(DependentBitIntTypeLoc TL) {
6227 TL.setNameLoc(DS.getTypeSpecTypeLoc());
6230 void VisitTypeLoc(TypeLoc TL) {
6231 // FIXME: add other typespec types and change this to an assert.
6232 TL.initialize(Context, DS.getTypeSpecTypeLoc());
6236 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
6237 ASTContext &Context;
6238 TypeProcessingState &State;
6239 const DeclaratorChunk &Chunk;
6241 public:
6242 DeclaratorLocFiller(ASTContext &Context, TypeProcessingState &State,
6243 const DeclaratorChunk &Chunk)
6244 : Context(Context), State(State), Chunk(Chunk) {}
6246 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
6247 llvm_unreachable("qualified type locs not expected here!");
6249 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
6250 llvm_unreachable("decayed type locs not expected here!");
6253 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
6254 fillAttributedTypeLoc(TL, State);
6256 void VisitBTFTagAttributedTypeLoc(BTFTagAttributedTypeLoc TL) {
6257 // nothing
6259 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
6260 // nothing
6262 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
6263 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
6264 TL.setCaretLoc(Chunk.Loc);
6266 void VisitPointerTypeLoc(PointerTypeLoc TL) {
6267 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6268 TL.setStarLoc(Chunk.Loc);
6270 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
6271 assert(Chunk.Kind == DeclaratorChunk::Pointer);
6272 TL.setStarLoc(Chunk.Loc);
6274 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
6275 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
6276 const CXXScopeSpec& SS = Chunk.Mem.Scope();
6277 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
6279 const Type* ClsTy = TL.getClass();
6280 QualType ClsQT = QualType(ClsTy, 0);
6281 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
6282 // Now copy source location info into the type loc component.
6283 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
6284 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
6285 case NestedNameSpecifier::Identifier:
6286 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
6288 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
6289 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
6290 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
6291 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
6293 break;
6295 case NestedNameSpecifier::TypeSpec:
6296 case NestedNameSpecifier::TypeSpecWithTemplate:
6297 if (isa<ElaboratedType>(ClsTy)) {
6298 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
6299 ETLoc.setElaboratedKeywordLoc(SourceLocation());
6300 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
6301 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
6302 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
6303 } else {
6304 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
6306 break;
6308 case NestedNameSpecifier::Namespace:
6309 case NestedNameSpecifier::NamespaceAlias:
6310 case NestedNameSpecifier::Global:
6311 case NestedNameSpecifier::Super:
6312 llvm_unreachable("Nested-name-specifier must name a type");
6315 // Finally fill in MemberPointerLocInfo fields.
6316 TL.setStarLoc(Chunk.Mem.StarLoc);
6317 TL.setClassTInfo(ClsTInfo);
6319 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
6320 assert(Chunk.Kind == DeclaratorChunk::Reference);
6321 // 'Amp' is misleading: this might have been originally
6322 /// spelled with AmpAmp.
6323 TL.setAmpLoc(Chunk.Loc);
6325 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
6326 assert(Chunk.Kind == DeclaratorChunk::Reference);
6327 assert(!Chunk.Ref.LValueRef);
6328 TL.setAmpAmpLoc(Chunk.Loc);
6330 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
6331 assert(Chunk.Kind == DeclaratorChunk::Array);
6332 TL.setLBracketLoc(Chunk.Loc);
6333 TL.setRBracketLoc(Chunk.EndLoc);
6334 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
6336 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
6337 assert(Chunk.Kind == DeclaratorChunk::Function);
6338 TL.setLocalRangeBegin(Chunk.Loc);
6339 TL.setLocalRangeEnd(Chunk.EndLoc);
6341 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
6342 TL.setLParenLoc(FTI.getLParenLoc());
6343 TL.setRParenLoc(FTI.getRParenLoc());
6344 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
6345 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
6346 TL.setParam(tpi++, Param);
6348 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
6350 void VisitParenTypeLoc(ParenTypeLoc TL) {
6351 assert(Chunk.Kind == DeclaratorChunk::Paren);
6352 TL.setLParenLoc(Chunk.Loc);
6353 TL.setRParenLoc(Chunk.EndLoc);
6355 void VisitPipeTypeLoc(PipeTypeLoc TL) {
6356 assert(Chunk.Kind == DeclaratorChunk::Pipe);
6357 TL.setKWLoc(Chunk.Loc);
6359 void VisitBitIntTypeLoc(BitIntTypeLoc TL) {
6360 TL.setNameLoc(Chunk.Loc);
6362 void VisitMacroQualifiedTypeLoc(MacroQualifiedTypeLoc TL) {
6363 TL.setExpansionLoc(Chunk.Loc);
6365 void VisitVectorTypeLoc(VectorTypeLoc TL) { TL.setNameLoc(Chunk.Loc); }
6366 void VisitDependentVectorTypeLoc(DependentVectorTypeLoc TL) {
6367 TL.setNameLoc(Chunk.Loc);
6369 void VisitExtVectorTypeLoc(ExtVectorTypeLoc TL) {
6370 TL.setNameLoc(Chunk.Loc);
6372 void
6373 VisitDependentSizedExtVectorTypeLoc(DependentSizedExtVectorTypeLoc TL) {
6374 TL.setNameLoc(Chunk.Loc);
6377 void VisitTypeLoc(TypeLoc TL) {
6378 llvm_unreachable("unsupported TypeLoc kind in declarator!");
6381 } // end anonymous namespace
6383 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
6384 SourceLocation Loc;
6385 switch (Chunk.Kind) {
6386 case DeclaratorChunk::Function:
6387 case DeclaratorChunk::Array:
6388 case DeclaratorChunk::Paren:
6389 case DeclaratorChunk::Pipe:
6390 llvm_unreachable("cannot be _Atomic qualified");
6392 case DeclaratorChunk::Pointer:
6393 Loc = Chunk.Ptr.AtomicQualLoc;
6394 break;
6396 case DeclaratorChunk::BlockPointer:
6397 case DeclaratorChunk::Reference:
6398 case DeclaratorChunk::MemberPointer:
6399 // FIXME: Provide a source location for the _Atomic keyword.
6400 break;
6403 ATL.setKWLoc(Loc);
6404 ATL.setParensRange(SourceRange());
6407 static void
6408 fillDependentAddressSpaceTypeLoc(DependentAddressSpaceTypeLoc DASTL,
6409 const ParsedAttributesView &Attrs) {
6410 for (const ParsedAttr &AL : Attrs) {
6411 if (AL.getKind() == ParsedAttr::AT_AddressSpace) {
6412 DASTL.setAttrNameLoc(AL.getLoc());
6413 DASTL.setAttrExprOperand(AL.getArgAsExpr(0));
6414 DASTL.setAttrOperandParensRange(SourceRange());
6415 return;
6419 llvm_unreachable(
6420 "no address_space attribute found at the expected location!");
6423 static void fillMatrixTypeLoc(MatrixTypeLoc MTL,
6424 const ParsedAttributesView &Attrs) {
6425 for (const ParsedAttr &AL : Attrs) {
6426 if (AL.getKind() == ParsedAttr::AT_MatrixType) {
6427 MTL.setAttrNameLoc(AL.getLoc());
6428 MTL.setAttrRowOperand(AL.getArgAsExpr(0));
6429 MTL.setAttrColumnOperand(AL.getArgAsExpr(1));
6430 MTL.setAttrOperandParensRange(SourceRange());
6431 return;
6435 llvm_unreachable("no matrix_type attribute found at the expected location!");
6438 /// Create and instantiate a TypeSourceInfo with type source information.
6440 /// \param T QualType referring to the type as written in source code.
6442 /// \param ReturnTypeInfo For declarators whose return type does not show
6443 /// up in the normal place in the declaration specifiers (such as a C++
6444 /// conversion function), this pointer will refer to a type source information
6445 /// for that return type.
6446 static TypeSourceInfo *
6447 GetTypeSourceInfoForDeclarator(TypeProcessingState &State,
6448 QualType T, TypeSourceInfo *ReturnTypeInfo) {
6449 Sema &S = State.getSema();
6450 Declarator &D = State.getDeclarator();
6452 TypeSourceInfo *TInfo = S.Context.CreateTypeSourceInfo(T);
6453 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
6455 // Handle parameter packs whose type is a pack expansion.
6456 if (isa<PackExpansionType>(T)) {
6457 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
6458 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6461 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
6462 // An AtomicTypeLoc might be produced by an atomic qualifier in this
6463 // declarator chunk.
6464 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
6465 fillAtomicQualLoc(ATL, D.getTypeObject(i));
6466 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
6469 while (MacroQualifiedTypeLoc TL = CurrTL.getAs<MacroQualifiedTypeLoc>()) {
6470 TL.setExpansionLoc(
6471 State.getExpansionLocForMacroQualifiedType(TL.getTypePtr()));
6472 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6475 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
6476 fillAttributedTypeLoc(TL, State);
6477 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6480 while (DependentAddressSpaceTypeLoc TL =
6481 CurrTL.getAs<DependentAddressSpaceTypeLoc>()) {
6482 fillDependentAddressSpaceTypeLoc(TL, D.getTypeObject(i).getAttrs());
6483 CurrTL = TL.getPointeeTypeLoc().getUnqualifiedLoc();
6486 if (MatrixTypeLoc TL = CurrTL.getAs<MatrixTypeLoc>())
6487 fillMatrixTypeLoc(TL, D.getTypeObject(i).getAttrs());
6489 // FIXME: Ordering here?
6490 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
6491 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
6493 DeclaratorLocFiller(S.Context, State, D.getTypeObject(i)).Visit(CurrTL);
6494 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
6497 // If we have different source information for the return type, use
6498 // that. This really only applies to C++ conversion functions.
6499 if (ReturnTypeInfo) {
6500 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
6501 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
6502 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
6503 } else {
6504 TypeSpecLocFiller(S, S.Context, State, D.getDeclSpec()).Visit(CurrTL);
6507 return TInfo;
6510 /// Create a LocInfoType to hold the given QualType and TypeSourceInfo.
6511 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
6512 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
6513 // and Sema during declaration parsing. Try deallocating/caching them when
6514 // it's appropriate, instead of allocating them and keeping them around.
6515 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
6516 TypeAlignment);
6517 new (LocT) LocInfoType(T, TInfo);
6518 assert(LocT->getTypeClass() != T->getTypeClass() &&
6519 "LocInfoType's TypeClass conflicts with an existing Type class");
6520 return ParsedType::make(QualType(LocT, 0));
6523 void LocInfoType::getAsStringInternal(std::string &Str,
6524 const PrintingPolicy &Policy) const {
6525 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
6526 " was used directly instead of getting the QualType through"
6527 " GetTypeFromParser");
6530 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
6531 // C99 6.7.6: Type names have no identifier. This is already validated by
6532 // the parser.
6533 assert(D.getIdentifier() == nullptr &&
6534 "Type name should have no identifier!");
6536 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6537 QualType T = TInfo->getType();
6538 if (D.isInvalidType())
6539 return true;
6541 // Make sure there are no unused decl attributes on the declarator.
6542 // We don't want to do this for ObjC parameters because we're going
6543 // to apply them to the actual parameter declaration.
6544 // Likewise, we don't want to do this for alias declarations, because
6545 // we are actually going to build a declaration from this eventually.
6546 if (D.getContext() != DeclaratorContext::ObjCParameter &&
6547 D.getContext() != DeclaratorContext::AliasDecl &&
6548 D.getContext() != DeclaratorContext::AliasTemplate)
6549 checkUnusedDeclAttributes(D);
6551 if (getLangOpts().CPlusPlus) {
6552 // Check that there are no default arguments (C++ only).
6553 CheckExtraCXXDefaultArguments(D);
6556 return CreateParsedType(T, TInfo);
6559 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
6560 QualType T = Context.getObjCInstanceType();
6561 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
6562 return CreateParsedType(T, TInfo);
6565 //===----------------------------------------------------------------------===//
6566 // Type Attribute Processing
6567 //===----------------------------------------------------------------------===//
6569 /// Build an AddressSpace index from a constant expression and diagnose any
6570 /// errors related to invalid address_spaces. Returns true on successfully
6571 /// building an AddressSpace index.
6572 static bool BuildAddressSpaceIndex(Sema &S, LangAS &ASIdx,
6573 const Expr *AddrSpace,
6574 SourceLocation AttrLoc) {
6575 if (!AddrSpace->isValueDependent()) {
6576 Optional<llvm::APSInt> OptAddrSpace =
6577 AddrSpace->getIntegerConstantExpr(S.Context);
6578 if (!OptAddrSpace) {
6579 S.Diag(AttrLoc, diag::err_attribute_argument_type)
6580 << "'address_space'" << AANT_ArgumentIntegerConstant
6581 << AddrSpace->getSourceRange();
6582 return false;
6584 llvm::APSInt &addrSpace = *OptAddrSpace;
6586 // Bounds checking.
6587 if (addrSpace.isSigned()) {
6588 if (addrSpace.isNegative()) {
6589 S.Diag(AttrLoc, diag::err_attribute_address_space_negative)
6590 << AddrSpace->getSourceRange();
6591 return false;
6593 addrSpace.setIsSigned(false);
6596 llvm::APSInt max(addrSpace.getBitWidth());
6597 max =
6598 Qualifiers::MaxAddressSpace - (unsigned)LangAS::FirstTargetAddressSpace;
6600 if (addrSpace > max) {
6601 S.Diag(AttrLoc, diag::err_attribute_address_space_too_high)
6602 << (unsigned)max.getZExtValue() << AddrSpace->getSourceRange();
6603 return false;
6606 ASIdx =
6607 getLangASFromTargetAS(static_cast<unsigned>(addrSpace.getZExtValue()));
6608 return true;
6611 // Default value for DependentAddressSpaceTypes
6612 ASIdx = LangAS::Default;
6613 return true;
6616 /// BuildAddressSpaceAttr - Builds a DependentAddressSpaceType if an expression
6617 /// is uninstantiated. If instantiated it will apply the appropriate address
6618 /// space to the type. This function allows dependent template variables to be
6619 /// used in conjunction with the address_space attribute
6620 QualType Sema::BuildAddressSpaceAttr(QualType &T, LangAS ASIdx, Expr *AddrSpace,
6621 SourceLocation AttrLoc) {
6622 if (!AddrSpace->isValueDependent()) {
6623 if (DiagnoseMultipleAddrSpaceAttributes(*this, T.getAddressSpace(), ASIdx,
6624 AttrLoc))
6625 return QualType();
6627 return Context.getAddrSpaceQualType(T, ASIdx);
6630 // A check with similar intentions as checking if a type already has an
6631 // address space except for on a dependent types, basically if the
6632 // current type is already a DependentAddressSpaceType then its already
6633 // lined up to have another address space on it and we can't have
6634 // multiple address spaces on the one pointer indirection
6635 if (T->getAs<DependentAddressSpaceType>()) {
6636 Diag(AttrLoc, diag::err_attribute_address_multiple_qualifiers);
6637 return QualType();
6640 return Context.getDependentAddressSpaceType(T, AddrSpace, AttrLoc);
6643 QualType Sema::BuildAddressSpaceAttr(QualType &T, Expr *AddrSpace,
6644 SourceLocation AttrLoc) {
6645 LangAS ASIdx;
6646 if (!BuildAddressSpaceIndex(*this, ASIdx, AddrSpace, AttrLoc))
6647 return QualType();
6648 return BuildAddressSpaceAttr(T, ASIdx, AddrSpace, AttrLoc);
6651 static void HandleBTFTypeTagAttribute(QualType &Type, const ParsedAttr &Attr,
6652 TypeProcessingState &State) {
6653 Sema &S = State.getSema();
6655 // Check the number of attribute arguments.
6656 if (Attr.getNumArgs() != 1) {
6657 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6658 << Attr << 1;
6659 Attr.setInvalid();
6660 return;
6663 // Ensure the argument is a string.
6664 auto *StrLiteral = dyn_cast<StringLiteral>(Attr.getArgAsExpr(0));
6665 if (!StrLiteral) {
6666 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6667 << Attr << AANT_ArgumentString;
6668 Attr.setInvalid();
6669 return;
6672 ASTContext &Ctx = S.Context;
6673 StringRef BTFTypeTag = StrLiteral->getString();
6674 Type = State.getBTFTagAttributedType(
6675 ::new (Ctx) BTFTypeTagAttr(Ctx, Attr, BTFTypeTag), Type);
6678 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
6679 /// specified type. The attribute contains 1 argument, the id of the address
6680 /// space for the type.
6681 static void HandleAddressSpaceTypeAttribute(QualType &Type,
6682 const ParsedAttr &Attr,
6683 TypeProcessingState &State) {
6684 Sema &S = State.getSema();
6686 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
6687 // qualified by an address-space qualifier."
6688 if (Type->isFunctionType()) {
6689 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
6690 Attr.setInvalid();
6691 return;
6694 LangAS ASIdx;
6695 if (Attr.getKind() == ParsedAttr::AT_AddressSpace) {
6697 // Check the attribute arguments.
6698 if (Attr.getNumArgs() != 1) {
6699 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
6700 << 1;
6701 Attr.setInvalid();
6702 return;
6705 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6706 LangAS ASIdx;
6707 if (!BuildAddressSpaceIndex(S, ASIdx, ASArgExpr, Attr.getLoc())) {
6708 Attr.setInvalid();
6709 return;
6712 ASTContext &Ctx = S.Context;
6713 auto *ASAttr =
6714 ::new (Ctx) AddressSpaceAttr(Ctx, Attr, static_cast<unsigned>(ASIdx));
6716 // If the expression is not value dependent (not templated), then we can
6717 // apply the address space qualifiers just to the equivalent type.
6718 // Otherwise, we make an AttributedType with the modified and equivalent
6719 // type the same, and wrap it in a DependentAddressSpaceType. When this
6720 // dependent type is resolved, the qualifier is added to the equivalent type
6721 // later.
6722 QualType T;
6723 if (!ASArgExpr->isValueDependent()) {
6724 QualType EquivType =
6725 S.BuildAddressSpaceAttr(Type, ASIdx, ASArgExpr, Attr.getLoc());
6726 if (EquivType.isNull()) {
6727 Attr.setInvalid();
6728 return;
6730 T = State.getAttributedType(ASAttr, Type, EquivType);
6731 } else {
6732 T = State.getAttributedType(ASAttr, Type, Type);
6733 T = S.BuildAddressSpaceAttr(T, ASIdx, ASArgExpr, Attr.getLoc());
6736 if (!T.isNull())
6737 Type = T;
6738 else
6739 Attr.setInvalid();
6740 } else {
6741 // The keyword-based type attributes imply which address space to use.
6742 ASIdx = S.getLangOpts().SYCLIsDevice ? Attr.asSYCLLangAS()
6743 : Attr.asOpenCLLangAS();
6745 if (ASIdx == LangAS::Default)
6746 llvm_unreachable("Invalid address space");
6748 if (DiagnoseMultipleAddrSpaceAttributes(S, Type.getAddressSpace(), ASIdx,
6749 Attr.getLoc())) {
6750 Attr.setInvalid();
6751 return;
6754 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
6758 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
6759 /// attribute on the specified type.
6761 /// Returns 'true' if the attribute was handled.
6762 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
6763 ParsedAttr &attr, QualType &type) {
6764 bool NonObjCPointer = false;
6766 if (!type->isDependentType() && !type->isUndeducedType()) {
6767 if (const PointerType *ptr = type->getAs<PointerType>()) {
6768 QualType pointee = ptr->getPointeeType();
6769 if (pointee->isObjCRetainableType() || pointee->isPointerType())
6770 return false;
6771 // It is important not to lose the source info that there was an attribute
6772 // applied to non-objc pointer. We will create an attributed type but
6773 // its type will be the same as the original type.
6774 NonObjCPointer = true;
6775 } else if (!type->isObjCRetainableType()) {
6776 return false;
6779 // Don't accept an ownership attribute in the declspec if it would
6780 // just be the return type of a block pointer.
6781 if (state.isProcessingDeclSpec()) {
6782 Declarator &D = state.getDeclarator();
6783 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
6784 /*onlyBlockPointers=*/true))
6785 return false;
6789 Sema &S = state.getSema();
6790 SourceLocation AttrLoc = attr.getLoc();
6791 if (AttrLoc.isMacroID())
6792 AttrLoc =
6793 S.getSourceManager().getImmediateExpansionRange(AttrLoc).getBegin();
6795 if (!attr.isArgIdent(0)) {
6796 S.Diag(AttrLoc, diag::err_attribute_argument_type) << attr
6797 << AANT_ArgumentString;
6798 attr.setInvalid();
6799 return true;
6802 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6803 Qualifiers::ObjCLifetime lifetime;
6804 if (II->isStr("none"))
6805 lifetime = Qualifiers::OCL_ExplicitNone;
6806 else if (II->isStr("strong"))
6807 lifetime = Qualifiers::OCL_Strong;
6808 else if (II->isStr("weak"))
6809 lifetime = Qualifiers::OCL_Weak;
6810 else if (II->isStr("autoreleasing"))
6811 lifetime = Qualifiers::OCL_Autoreleasing;
6812 else {
6813 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported) << attr << II;
6814 attr.setInvalid();
6815 return true;
6818 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
6819 // outside of ARC mode.
6820 if (!S.getLangOpts().ObjCAutoRefCount &&
6821 lifetime != Qualifiers::OCL_Weak &&
6822 lifetime != Qualifiers::OCL_ExplicitNone) {
6823 return true;
6826 SplitQualType underlyingType = type.split();
6828 // Check for redundant/conflicting ownership qualifiers.
6829 if (Qualifiers::ObjCLifetime previousLifetime
6830 = type.getQualifiers().getObjCLifetime()) {
6831 // If it's written directly, that's an error.
6832 if (S.Context.hasDirectOwnershipQualifier(type)) {
6833 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
6834 << type;
6835 return true;
6838 // Otherwise, if the qualifiers actually conflict, pull sugar off
6839 // and remove the ObjCLifetime qualifiers.
6840 if (previousLifetime != lifetime) {
6841 // It's possible to have multiple local ObjCLifetime qualifiers. We
6842 // can't stop after we reach a type that is directly qualified.
6843 const Type *prevTy = nullptr;
6844 while (!prevTy || prevTy != underlyingType.Ty) {
6845 prevTy = underlyingType.Ty;
6846 underlyingType = underlyingType.getSingleStepDesugaredType();
6848 underlyingType.Quals.removeObjCLifetime();
6852 underlyingType.Quals.addObjCLifetime(lifetime);
6854 if (NonObjCPointer) {
6855 StringRef name = attr.getAttrName()->getName();
6856 switch (lifetime) {
6857 case Qualifiers::OCL_None:
6858 case Qualifiers::OCL_ExplicitNone:
6859 break;
6860 case Qualifiers::OCL_Strong: name = "__strong"; break;
6861 case Qualifiers::OCL_Weak: name = "__weak"; break;
6862 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
6864 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
6865 << TDS_ObjCObjOrBlock << type;
6868 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
6869 // because having both 'T' and '__unsafe_unretained T' exist in the type
6870 // system causes unfortunate widespread consistency problems. (For example,
6871 // they're not considered compatible types, and we mangle them identicially
6872 // as template arguments.) These problems are all individually fixable,
6873 // but it's easier to just not add the qualifier and instead sniff it out
6874 // in specific places using isObjCInertUnsafeUnretainedType().
6876 // Doing this does means we miss some trivial consistency checks that
6877 // would've triggered in ARC, but that's better than trying to solve all
6878 // the coexistence problems with __unsafe_unretained.
6879 if (!S.getLangOpts().ObjCAutoRefCount &&
6880 lifetime == Qualifiers::OCL_ExplicitNone) {
6881 type = state.getAttributedType(
6882 createSimpleAttr<ObjCInertUnsafeUnretainedAttr>(S.Context, attr),
6883 type, type);
6884 return true;
6887 QualType origType = type;
6888 if (!NonObjCPointer)
6889 type = S.Context.getQualifiedType(underlyingType);
6891 // If we have a valid source location for the attribute, use an
6892 // AttributedType instead.
6893 if (AttrLoc.isValid()) {
6894 type = state.getAttributedType(::new (S.Context)
6895 ObjCOwnershipAttr(S.Context, attr, II),
6896 origType, type);
6899 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
6900 unsigned diagnostic, QualType type) {
6901 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
6902 S.DelayedDiagnostics.add(
6903 sema::DelayedDiagnostic::makeForbiddenType(
6904 S.getSourceManager().getExpansionLoc(loc),
6905 diagnostic, type, /*ignored*/ 0));
6906 } else {
6907 S.Diag(loc, diagnostic);
6911 // Sometimes, __weak isn't allowed.
6912 if (lifetime == Qualifiers::OCL_Weak &&
6913 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
6915 // Use a specialized diagnostic if the runtime just doesn't support them.
6916 unsigned diagnostic =
6917 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
6918 : diag::err_arc_weak_no_runtime);
6920 // In any case, delay the diagnostic until we know what we're parsing.
6921 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
6923 attr.setInvalid();
6924 return true;
6927 // Forbid __weak for class objects marked as
6928 // objc_arc_weak_reference_unavailable
6929 if (lifetime == Qualifiers::OCL_Weak) {
6930 if (const ObjCObjectPointerType *ObjT =
6931 type->getAs<ObjCObjectPointerType>()) {
6932 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
6933 if (Class->isArcWeakrefUnavailable()) {
6934 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
6935 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
6936 diag::note_class_declared);
6942 return true;
6945 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
6946 /// attribute on the specified type. Returns true to indicate that
6947 /// the attribute was handled, false to indicate that the type does
6948 /// not permit the attribute.
6949 static bool handleObjCGCTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
6950 QualType &type) {
6951 Sema &S = state.getSema();
6953 // Delay if this isn't some kind of pointer.
6954 if (!type->isPointerType() &&
6955 !type->isObjCObjectPointerType() &&
6956 !type->isBlockPointerType())
6957 return false;
6959 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
6960 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
6961 attr.setInvalid();
6962 return true;
6965 // Check the attribute arguments.
6966 if (!attr.isArgIdent(0)) {
6967 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
6968 << attr << AANT_ArgumentString;
6969 attr.setInvalid();
6970 return true;
6972 Qualifiers::GC GCAttr;
6973 if (attr.getNumArgs() > 1) {
6974 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << attr
6975 << 1;
6976 attr.setInvalid();
6977 return true;
6980 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
6981 if (II->isStr("weak"))
6982 GCAttr = Qualifiers::Weak;
6983 else if (II->isStr("strong"))
6984 GCAttr = Qualifiers::Strong;
6985 else {
6986 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
6987 << attr << II;
6988 attr.setInvalid();
6989 return true;
6992 QualType origType = type;
6993 type = S.Context.getObjCGCQualType(origType, GCAttr);
6995 // Make an attributed type to preserve the source information.
6996 if (attr.getLoc().isValid())
6997 type = state.getAttributedType(
6998 ::new (S.Context) ObjCGCAttr(S.Context, attr, II), origType, type);
7000 return true;
7003 namespace {
7004 /// A helper class to unwrap a type down to a function for the
7005 /// purposes of applying attributes there.
7007 /// Use:
7008 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
7009 /// if (unwrapped.isFunctionType()) {
7010 /// const FunctionType *fn = unwrapped.get();
7011 /// // change fn somehow
7012 /// T = unwrapped.wrap(fn);
7013 /// }
7014 struct FunctionTypeUnwrapper {
7015 enum WrapKind {
7016 Desugar,
7017 Attributed,
7018 Parens,
7019 Array,
7020 Pointer,
7021 BlockPointer,
7022 Reference,
7023 MemberPointer,
7024 MacroQualified,
7027 QualType Original;
7028 const FunctionType *Fn;
7029 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
7031 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
7032 while (true) {
7033 const Type *Ty = T.getTypePtr();
7034 if (isa<FunctionType>(Ty)) {
7035 Fn = cast<FunctionType>(Ty);
7036 return;
7037 } else if (isa<ParenType>(Ty)) {
7038 T = cast<ParenType>(Ty)->getInnerType();
7039 Stack.push_back(Parens);
7040 } else if (isa<ConstantArrayType>(Ty) || isa<VariableArrayType>(Ty) ||
7041 isa<IncompleteArrayType>(Ty)) {
7042 T = cast<ArrayType>(Ty)->getElementType();
7043 Stack.push_back(Array);
7044 } else if (isa<PointerType>(Ty)) {
7045 T = cast<PointerType>(Ty)->getPointeeType();
7046 Stack.push_back(Pointer);
7047 } else if (isa<BlockPointerType>(Ty)) {
7048 T = cast<BlockPointerType>(Ty)->getPointeeType();
7049 Stack.push_back(BlockPointer);
7050 } else if (isa<MemberPointerType>(Ty)) {
7051 T = cast<MemberPointerType>(Ty)->getPointeeType();
7052 Stack.push_back(MemberPointer);
7053 } else if (isa<ReferenceType>(Ty)) {
7054 T = cast<ReferenceType>(Ty)->getPointeeType();
7055 Stack.push_back(Reference);
7056 } else if (isa<AttributedType>(Ty)) {
7057 T = cast<AttributedType>(Ty)->getEquivalentType();
7058 Stack.push_back(Attributed);
7059 } else if (isa<MacroQualifiedType>(Ty)) {
7060 T = cast<MacroQualifiedType>(Ty)->getUnderlyingType();
7061 Stack.push_back(MacroQualified);
7062 } else {
7063 const Type *DTy = Ty->getUnqualifiedDesugaredType();
7064 if (Ty == DTy) {
7065 Fn = nullptr;
7066 return;
7069 T = QualType(DTy, 0);
7070 Stack.push_back(Desugar);
7075 bool isFunctionType() const { return (Fn != nullptr); }
7076 const FunctionType *get() const { return Fn; }
7078 QualType wrap(Sema &S, const FunctionType *New) {
7079 // If T wasn't modified from the unwrapped type, do nothing.
7080 if (New == get()) return Original;
7082 Fn = New;
7083 return wrap(S.Context, Original, 0);
7086 private:
7087 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
7088 if (I == Stack.size())
7089 return C.getQualifiedType(Fn, Old.getQualifiers());
7091 // Build up the inner type, applying the qualifiers from the old
7092 // type to the new type.
7093 SplitQualType SplitOld = Old.split();
7095 // As a special case, tail-recurse if there are no qualifiers.
7096 if (SplitOld.Quals.empty())
7097 return wrap(C, SplitOld.Ty, I);
7098 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
7101 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
7102 if (I == Stack.size()) return QualType(Fn, 0);
7104 switch (static_cast<WrapKind>(Stack[I++])) {
7105 case Desugar:
7106 // This is the point at which we potentially lose source
7107 // information.
7108 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
7110 case Attributed:
7111 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
7113 case Parens: {
7114 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
7115 return C.getParenType(New);
7118 case MacroQualified:
7119 return wrap(C, cast<MacroQualifiedType>(Old)->getUnderlyingType(), I);
7121 case Array: {
7122 if (const auto *CAT = dyn_cast<ConstantArrayType>(Old)) {
7123 QualType New = wrap(C, CAT->getElementType(), I);
7124 return C.getConstantArrayType(New, CAT->getSize(), CAT->getSizeExpr(),
7125 CAT->getSizeModifier(),
7126 CAT->getIndexTypeCVRQualifiers());
7129 if (const auto *VAT = dyn_cast<VariableArrayType>(Old)) {
7130 QualType New = wrap(C, VAT->getElementType(), I);
7131 return C.getVariableArrayType(
7132 New, VAT->getSizeExpr(), VAT->getSizeModifier(),
7133 VAT->getIndexTypeCVRQualifiers(), VAT->getBracketsRange());
7136 const auto *IAT = cast<IncompleteArrayType>(Old);
7137 QualType New = wrap(C, IAT->getElementType(), I);
7138 return C.getIncompleteArrayType(New, IAT->getSizeModifier(),
7139 IAT->getIndexTypeCVRQualifiers());
7142 case Pointer: {
7143 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
7144 return C.getPointerType(New);
7147 case BlockPointer: {
7148 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
7149 return C.getBlockPointerType(New);
7152 case MemberPointer: {
7153 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
7154 QualType New = wrap(C, OldMPT->getPointeeType(), I);
7155 return C.getMemberPointerType(New, OldMPT->getClass());
7158 case Reference: {
7159 const ReferenceType *OldRef = cast<ReferenceType>(Old);
7160 QualType New = wrap(C, OldRef->getPointeeType(), I);
7161 if (isa<LValueReferenceType>(OldRef))
7162 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
7163 else
7164 return C.getRValueReferenceType(New);
7168 llvm_unreachable("unknown wrapping kind");
7171 } // end anonymous namespace
7173 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
7174 ParsedAttr &PAttr, QualType &Type) {
7175 Sema &S = State.getSema();
7177 Attr *A;
7178 switch (PAttr.getKind()) {
7179 default: llvm_unreachable("Unknown attribute kind");
7180 case ParsedAttr::AT_Ptr32:
7181 A = createSimpleAttr<Ptr32Attr>(S.Context, PAttr);
7182 break;
7183 case ParsedAttr::AT_Ptr64:
7184 A = createSimpleAttr<Ptr64Attr>(S.Context, PAttr);
7185 break;
7186 case ParsedAttr::AT_SPtr:
7187 A = createSimpleAttr<SPtrAttr>(S.Context, PAttr);
7188 break;
7189 case ParsedAttr::AT_UPtr:
7190 A = createSimpleAttr<UPtrAttr>(S.Context, PAttr);
7191 break;
7194 std::bitset<attr::LastAttr> Attrs;
7195 QualType Desugared = Type;
7196 for (;;) {
7197 if (const TypedefType *TT = dyn_cast<TypedefType>(Desugared)) {
7198 Desugared = TT->desugar();
7199 continue;
7200 } else if (const ElaboratedType *ET = dyn_cast<ElaboratedType>(Desugared)) {
7201 Desugared = ET->desugar();
7202 continue;
7204 const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
7205 if (!AT)
7206 break;
7207 Attrs[AT->getAttrKind()] = true;
7208 Desugared = AT->getModifiedType();
7211 // You cannot specify duplicate type attributes, so if the attribute has
7212 // already been applied, flag it.
7213 attr::Kind NewAttrKind = A->getKind();
7214 if (Attrs[NewAttrKind]) {
7215 S.Diag(PAttr.getLoc(), diag::warn_duplicate_attribute_exact) << PAttr;
7216 return true;
7218 Attrs[NewAttrKind] = true;
7220 // You cannot have both __sptr and __uptr on the same type, nor can you
7221 // have __ptr32 and __ptr64.
7222 if (Attrs[attr::Ptr32] && Attrs[attr::Ptr64]) {
7223 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7224 << "'__ptr32'"
7225 << "'__ptr64'";
7226 return true;
7227 } else if (Attrs[attr::SPtr] && Attrs[attr::UPtr]) {
7228 S.Diag(PAttr.getLoc(), diag::err_attributes_are_not_compatible)
7229 << "'__sptr'"
7230 << "'__uptr'";
7231 return true;
7234 // Check the raw (i.e., desugared) Canonical type to see if it
7235 // is a pointer type.
7236 if (!isa<PointerType>(Desugared)) {
7237 // Pointer type qualifiers can only operate on pointer types, but not
7238 // pointer-to-member types.
7239 if (Type->isMemberPointerType())
7240 S.Diag(PAttr.getLoc(), diag::err_attribute_no_member_pointers) << PAttr;
7241 else
7242 S.Diag(PAttr.getLoc(), diag::err_attribute_pointers_only) << PAttr << 0;
7243 return true;
7246 // Add address space to type based on its attributes.
7247 LangAS ASIdx = LangAS::Default;
7248 uint64_t PtrWidth = S.Context.getTargetInfo().getPointerWidth(0);
7249 if (PtrWidth == 32) {
7250 if (Attrs[attr::Ptr64])
7251 ASIdx = LangAS::ptr64;
7252 else if (Attrs[attr::UPtr])
7253 ASIdx = LangAS::ptr32_uptr;
7254 } else if (PtrWidth == 64 && Attrs[attr::Ptr32]) {
7255 if (Attrs[attr::UPtr])
7256 ASIdx = LangAS::ptr32_uptr;
7257 else
7258 ASIdx = LangAS::ptr32_sptr;
7261 QualType Pointee = Type->getPointeeType();
7262 if (ASIdx != LangAS::Default)
7263 Pointee = S.Context.getAddrSpaceQualType(
7264 S.Context.removeAddrSpaceQualType(Pointee), ASIdx);
7265 Type = State.getAttributedType(A, Type, S.Context.getPointerType(Pointee));
7266 return false;
7269 /// Map a nullability attribute kind to a nullability kind.
7270 static NullabilityKind mapNullabilityAttrKind(ParsedAttr::Kind kind) {
7271 switch (kind) {
7272 case ParsedAttr::AT_TypeNonNull:
7273 return NullabilityKind::NonNull;
7275 case ParsedAttr::AT_TypeNullable:
7276 return NullabilityKind::Nullable;
7278 case ParsedAttr::AT_TypeNullableResult:
7279 return NullabilityKind::NullableResult;
7281 case ParsedAttr::AT_TypeNullUnspecified:
7282 return NullabilityKind::Unspecified;
7284 default:
7285 llvm_unreachable("not a nullability attribute kind");
7289 /// Applies a nullability type specifier to the given type, if possible.
7291 /// \param state The type processing state.
7293 /// \param type The type to which the nullability specifier will be
7294 /// added. On success, this type will be updated appropriately.
7296 /// \param attr The attribute as written on the type.
7298 /// \param allowOnArrayType Whether to accept nullability specifiers on an
7299 /// array type (e.g., because it will decay to a pointer).
7301 /// \returns true if a problem has been diagnosed, false on success.
7302 static bool checkNullabilityTypeSpecifier(TypeProcessingState &state,
7303 QualType &type,
7304 ParsedAttr &attr,
7305 bool allowOnArrayType) {
7306 Sema &S = state.getSema();
7308 NullabilityKind nullability = mapNullabilityAttrKind(attr.getKind());
7309 SourceLocation nullabilityLoc = attr.getLoc();
7310 bool isContextSensitive = attr.isContextSensitiveKeywordAttribute();
7312 recordNullabilitySeen(S, nullabilityLoc);
7314 // Check for existing nullability attributes on the type.
7315 QualType desugared = type;
7316 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
7317 // Check whether there is already a null
7318 if (auto existingNullability = attributed->getImmediateNullability()) {
7319 // Duplicated nullability.
7320 if (nullability == *existingNullability) {
7321 S.Diag(nullabilityLoc, diag::warn_nullability_duplicate)
7322 << DiagNullabilityKind(nullability, isContextSensitive)
7323 << FixItHint::CreateRemoval(nullabilityLoc);
7325 break;
7328 // Conflicting nullability.
7329 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7330 << DiagNullabilityKind(nullability, isContextSensitive)
7331 << DiagNullabilityKind(*existingNullability, false);
7332 return true;
7335 desugared = attributed->getModifiedType();
7338 // If there is already a different nullability specifier, complain.
7339 // This (unlike the code above) looks through typedefs that might
7340 // have nullability specifiers on them, which means we cannot
7341 // provide a useful Fix-It.
7342 if (auto existingNullability = desugared->getNullability(S.Context)) {
7343 if (nullability != *existingNullability) {
7344 S.Diag(nullabilityLoc, diag::err_nullability_conflicting)
7345 << DiagNullabilityKind(nullability, isContextSensitive)
7346 << DiagNullabilityKind(*existingNullability, false);
7348 // Try to find the typedef with the existing nullability specifier.
7349 if (auto typedefType = desugared->getAs<TypedefType>()) {
7350 TypedefNameDecl *typedefDecl = typedefType->getDecl();
7351 QualType underlyingType = typedefDecl->getUnderlyingType();
7352 if (auto typedefNullability
7353 = AttributedType::stripOuterNullability(underlyingType)) {
7354 if (*typedefNullability == *existingNullability) {
7355 S.Diag(typedefDecl->getLocation(), diag::note_nullability_here)
7356 << DiagNullabilityKind(*existingNullability, false);
7361 return true;
7365 // If this definitely isn't a pointer type, reject the specifier.
7366 if (!desugared->canHaveNullability() &&
7367 !(allowOnArrayType && desugared->isArrayType())) {
7368 S.Diag(nullabilityLoc, diag::err_nullability_nonpointer)
7369 << DiagNullabilityKind(nullability, isContextSensitive) << type;
7370 return true;
7373 // For the context-sensitive keywords/Objective-C property
7374 // attributes, require that the type be a single-level pointer.
7375 if (isContextSensitive) {
7376 // Make sure that the pointee isn't itself a pointer type.
7377 const Type *pointeeType = nullptr;
7378 if (desugared->isArrayType())
7379 pointeeType = desugared->getArrayElementTypeNoTypeQual();
7380 else if (desugared->isAnyPointerType())
7381 pointeeType = desugared->getPointeeType().getTypePtr();
7383 if (pointeeType && (pointeeType->isAnyPointerType() ||
7384 pointeeType->isObjCObjectPointerType() ||
7385 pointeeType->isMemberPointerType())) {
7386 S.Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
7387 << DiagNullabilityKind(nullability, true)
7388 << type;
7389 S.Diag(nullabilityLoc, diag::note_nullability_type_specifier)
7390 << DiagNullabilityKind(nullability, false)
7391 << type
7392 << FixItHint::CreateReplacement(nullabilityLoc,
7393 getNullabilitySpelling(nullability));
7394 return true;
7398 // Form the attributed type.
7399 type = state.getAttributedType(
7400 createNullabilityAttr(S.Context, attr, nullability), type, type);
7401 return false;
7404 /// Check the application of the Objective-C '__kindof' qualifier to
7405 /// the given type.
7406 static bool checkObjCKindOfType(TypeProcessingState &state, QualType &type,
7407 ParsedAttr &attr) {
7408 Sema &S = state.getSema();
7410 if (isa<ObjCTypeParamType>(type)) {
7411 // Build the attributed type to record where __kindof occurred.
7412 type = state.getAttributedType(
7413 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, type);
7414 return false;
7417 // Find out if it's an Objective-C object or object pointer type;
7418 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
7419 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
7420 : type->getAs<ObjCObjectType>();
7422 // If not, we can't apply __kindof.
7423 if (!objType) {
7424 // FIXME: Handle dependent types that aren't yet object types.
7425 S.Diag(attr.getLoc(), diag::err_objc_kindof_nonobject)
7426 << type;
7427 return true;
7430 // Rebuild the "equivalent" type, which pushes __kindof down into
7431 // the object type.
7432 // There is no need to apply kindof on an unqualified id type.
7433 QualType equivType = S.Context.getObjCObjectType(
7434 objType->getBaseType(), objType->getTypeArgsAsWritten(),
7435 objType->getProtocols(),
7436 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
7438 // If we started with an object pointer type, rebuild it.
7439 if (ptrType) {
7440 equivType = S.Context.getObjCObjectPointerType(equivType);
7441 if (auto nullability = type->getNullability(S.Context)) {
7442 // We create a nullability attribute from the __kindof attribute.
7443 // Make sure that will make sense.
7444 assert(attr.getAttributeSpellingListIndex() == 0 &&
7445 "multiple spellings for __kindof?");
7446 Attr *A = createNullabilityAttr(S.Context, attr, *nullability);
7447 A->setImplicit(true);
7448 equivType = state.getAttributedType(A, equivType, equivType);
7452 // Build the attributed type to record where __kindof occurred.
7453 type = state.getAttributedType(
7454 createSimpleAttr<ObjCKindOfAttr>(S.Context, attr), type, equivType);
7455 return false;
7458 /// Distribute a nullability type attribute that cannot be applied to
7459 /// the type specifier to a pointer, block pointer, or member pointer
7460 /// declarator, complaining if necessary.
7462 /// \returns true if the nullability annotation was distributed, false
7463 /// otherwise.
7464 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
7465 QualType type, ParsedAttr &attr) {
7466 Declarator &declarator = state.getDeclarator();
7468 /// Attempt to move the attribute to the specified chunk.
7469 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
7470 // If there is already a nullability attribute there, don't add
7471 // one.
7472 if (hasNullabilityAttr(chunk.getAttrs()))
7473 return false;
7475 // Complain about the nullability qualifier being in the wrong
7476 // place.
7477 enum {
7478 PK_Pointer,
7479 PK_BlockPointer,
7480 PK_MemberPointer,
7481 PK_FunctionPointer,
7482 PK_MemberFunctionPointer,
7483 } pointerKind
7484 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
7485 : PK_Pointer)
7486 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
7487 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
7489 auto diag = state.getSema().Diag(attr.getLoc(),
7490 diag::warn_nullability_declspec)
7491 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
7492 attr.isContextSensitiveKeywordAttribute())
7493 << type
7494 << static_cast<unsigned>(pointerKind);
7496 // FIXME: MemberPointer chunks don't carry the location of the *.
7497 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
7498 diag << FixItHint::CreateRemoval(attr.getLoc())
7499 << FixItHint::CreateInsertion(
7500 state.getSema().getPreprocessor().getLocForEndOfToken(
7501 chunk.Loc),
7502 " " + attr.getAttrName()->getName().str() + " ");
7505 moveAttrFromListToList(attr, state.getCurrentAttributes(),
7506 chunk.getAttrs());
7507 return true;
7510 // Move it to the outermost pointer, member pointer, or block
7511 // pointer declarator.
7512 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
7513 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
7514 switch (chunk.Kind) {
7515 case DeclaratorChunk::Pointer:
7516 case DeclaratorChunk::BlockPointer:
7517 case DeclaratorChunk::MemberPointer:
7518 return moveToChunk(chunk, false);
7520 case DeclaratorChunk::Paren:
7521 case DeclaratorChunk::Array:
7522 continue;
7524 case DeclaratorChunk::Function:
7525 // Try to move past the return type to a function/block/member
7526 // function pointer.
7527 if (DeclaratorChunk *dest = maybeMovePastReturnType(
7528 declarator, i,
7529 /*onlyBlockPointers=*/false)) {
7530 return moveToChunk(*dest, true);
7533 return false;
7535 // Don't walk through these.
7536 case DeclaratorChunk::Reference:
7537 case DeclaratorChunk::Pipe:
7538 return false;
7542 return false;
7545 static Attr *getCCTypeAttr(ASTContext &Ctx, ParsedAttr &Attr) {
7546 assert(!Attr.isInvalid());
7547 switch (Attr.getKind()) {
7548 default:
7549 llvm_unreachable("not a calling convention attribute");
7550 case ParsedAttr::AT_CDecl:
7551 return createSimpleAttr<CDeclAttr>(Ctx, Attr);
7552 case ParsedAttr::AT_FastCall:
7553 return createSimpleAttr<FastCallAttr>(Ctx, Attr);
7554 case ParsedAttr::AT_StdCall:
7555 return createSimpleAttr<StdCallAttr>(Ctx, Attr);
7556 case ParsedAttr::AT_ThisCall:
7557 return createSimpleAttr<ThisCallAttr>(Ctx, Attr);
7558 case ParsedAttr::AT_RegCall:
7559 return createSimpleAttr<RegCallAttr>(Ctx, Attr);
7560 case ParsedAttr::AT_Pascal:
7561 return createSimpleAttr<PascalAttr>(Ctx, Attr);
7562 case ParsedAttr::AT_SwiftCall:
7563 return createSimpleAttr<SwiftCallAttr>(Ctx, Attr);
7564 case ParsedAttr::AT_SwiftAsyncCall:
7565 return createSimpleAttr<SwiftAsyncCallAttr>(Ctx, Attr);
7566 case ParsedAttr::AT_VectorCall:
7567 return createSimpleAttr<VectorCallAttr>(Ctx, Attr);
7568 case ParsedAttr::AT_AArch64VectorPcs:
7569 return createSimpleAttr<AArch64VectorPcsAttr>(Ctx, Attr);
7570 case ParsedAttr::AT_AArch64SVEPcs:
7571 return createSimpleAttr<AArch64SVEPcsAttr>(Ctx, Attr);
7572 case ParsedAttr::AT_AMDGPUKernelCall:
7573 return createSimpleAttr<AMDGPUKernelCallAttr>(Ctx, Attr);
7574 case ParsedAttr::AT_Pcs: {
7575 // The attribute may have had a fixit applied where we treated an
7576 // identifier as a string literal. The contents of the string are valid,
7577 // but the form may not be.
7578 StringRef Str;
7579 if (Attr.isArgExpr(0))
7580 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
7581 else
7582 Str = Attr.getArgAsIdent(0)->Ident->getName();
7583 PcsAttr::PCSType Type;
7584 if (!PcsAttr::ConvertStrToPCSType(Str, Type))
7585 llvm_unreachable("already validated the attribute");
7586 return ::new (Ctx) PcsAttr(Ctx, Attr, Type);
7588 case ParsedAttr::AT_IntelOclBicc:
7589 return createSimpleAttr<IntelOclBiccAttr>(Ctx, Attr);
7590 case ParsedAttr::AT_MSABI:
7591 return createSimpleAttr<MSABIAttr>(Ctx, Attr);
7592 case ParsedAttr::AT_SysVABI:
7593 return createSimpleAttr<SysVABIAttr>(Ctx, Attr);
7594 case ParsedAttr::AT_PreserveMost:
7595 return createSimpleAttr<PreserveMostAttr>(Ctx, Attr);
7596 case ParsedAttr::AT_PreserveAll:
7597 return createSimpleAttr<PreserveAllAttr>(Ctx, Attr);
7599 llvm_unreachable("unexpected attribute kind!");
7602 /// Process an individual function attribute. Returns true to
7603 /// indicate that the attribute was handled, false if it wasn't.
7604 static bool handleFunctionTypeAttr(TypeProcessingState &state, ParsedAttr &attr,
7605 QualType &type) {
7606 Sema &S = state.getSema();
7608 FunctionTypeUnwrapper unwrapped(S, type);
7610 if (attr.getKind() == ParsedAttr::AT_NoReturn) {
7611 if (S.CheckAttrNoArgs(attr))
7612 return true;
7614 // Delay if this is not a function type.
7615 if (!unwrapped.isFunctionType())
7616 return false;
7618 // Otherwise we can process right away.
7619 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
7620 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7621 return true;
7624 if (attr.getKind() == ParsedAttr::AT_CmseNSCall) {
7625 // Delay if this is not a function type.
7626 if (!unwrapped.isFunctionType())
7627 return false;
7629 // Ignore if we don't have CMSE enabled.
7630 if (!S.getLangOpts().Cmse) {
7631 S.Diag(attr.getLoc(), diag::warn_attribute_ignored) << attr;
7632 attr.setInvalid();
7633 return true;
7636 // Otherwise we can process right away.
7637 FunctionType::ExtInfo EI =
7638 unwrapped.get()->getExtInfo().withCmseNSCall(true);
7639 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7640 return true;
7643 // ns_returns_retained is not always a type attribute, but if we got
7644 // here, we're treating it as one right now.
7645 if (attr.getKind() == ParsedAttr::AT_NSReturnsRetained) {
7646 if (attr.getNumArgs()) return true;
7648 // Delay if this is not a function type.
7649 if (!unwrapped.isFunctionType())
7650 return false;
7652 // Check whether the return type is reasonable.
7653 if (S.checkNSReturnsRetainedReturnType(attr.getLoc(),
7654 unwrapped.get()->getReturnType()))
7655 return true;
7657 // Only actually change the underlying type in ARC builds.
7658 QualType origType = type;
7659 if (state.getSema().getLangOpts().ObjCAutoRefCount) {
7660 FunctionType::ExtInfo EI
7661 = unwrapped.get()->getExtInfo().withProducesResult(true);
7662 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7664 type = state.getAttributedType(
7665 createSimpleAttr<NSReturnsRetainedAttr>(S.Context, attr),
7666 origType, type);
7667 return true;
7670 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCallerSavedRegisters) {
7671 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7672 return true;
7674 // Delay if this is not a function type.
7675 if (!unwrapped.isFunctionType())
7676 return false;
7678 FunctionType::ExtInfo EI =
7679 unwrapped.get()->getExtInfo().withNoCallerSavedRegs(true);
7680 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7681 return true;
7684 if (attr.getKind() == ParsedAttr::AT_AnyX86NoCfCheck) {
7685 if (!S.getLangOpts().CFProtectionBranch) {
7686 S.Diag(attr.getLoc(), diag::warn_nocf_check_attribute_ignored);
7687 attr.setInvalid();
7688 return true;
7691 if (S.CheckAttrTarget(attr) || S.CheckAttrNoArgs(attr))
7692 return true;
7694 // If this is not a function type, warning will be asserted by subject
7695 // check.
7696 if (!unwrapped.isFunctionType())
7697 return true;
7699 FunctionType::ExtInfo EI =
7700 unwrapped.get()->getExtInfo().withNoCfCheck(true);
7701 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7702 return true;
7705 if (attr.getKind() == ParsedAttr::AT_Regparm) {
7706 unsigned value;
7707 if (S.CheckRegparmAttr(attr, value))
7708 return true;
7710 // Delay if this is not a function type.
7711 if (!unwrapped.isFunctionType())
7712 return false;
7714 // Diagnose regparm with fastcall.
7715 const FunctionType *fn = unwrapped.get();
7716 CallingConv CC = fn->getCallConv();
7717 if (CC == CC_X86FastCall) {
7718 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7719 << FunctionType::getNameForCallConv(CC)
7720 << "regparm";
7721 attr.setInvalid();
7722 return true;
7725 FunctionType::ExtInfo EI =
7726 unwrapped.get()->getExtInfo().withRegParm(value);
7727 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7728 return true;
7731 if (attr.getKind() == ParsedAttr::AT_NoThrow) {
7732 // Delay if this is not a function type.
7733 if (!unwrapped.isFunctionType())
7734 return false;
7736 if (S.CheckAttrNoArgs(attr)) {
7737 attr.setInvalid();
7738 return true;
7741 // Otherwise we can process right away.
7742 auto *Proto = unwrapped.get()->castAs<FunctionProtoType>();
7744 // MSVC ignores nothrow if it is in conflict with an explicit exception
7745 // specification.
7746 if (Proto->hasExceptionSpec()) {
7747 switch (Proto->getExceptionSpecType()) {
7748 case EST_None:
7749 llvm_unreachable("This doesn't have an exception spec!");
7751 case EST_DynamicNone:
7752 case EST_BasicNoexcept:
7753 case EST_NoexceptTrue:
7754 case EST_NoThrow:
7755 // Exception spec doesn't conflict with nothrow, so don't warn.
7756 [[fallthrough]];
7757 case EST_Unparsed:
7758 case EST_Uninstantiated:
7759 case EST_DependentNoexcept:
7760 case EST_Unevaluated:
7761 // We don't have enough information to properly determine if there is a
7762 // conflict, so suppress the warning.
7763 break;
7764 case EST_Dynamic:
7765 case EST_MSAny:
7766 case EST_NoexceptFalse:
7767 S.Diag(attr.getLoc(), diag::warn_nothrow_attribute_ignored);
7768 break;
7770 return true;
7773 type = unwrapped.wrap(
7774 S, S.Context
7775 .getFunctionTypeWithExceptionSpec(
7776 QualType{Proto, 0},
7777 FunctionProtoType::ExceptionSpecInfo{EST_NoThrow})
7778 ->getAs<FunctionType>());
7779 return true;
7782 // Delay if the type didn't work out to a function.
7783 if (!unwrapped.isFunctionType()) return false;
7785 // Otherwise, a calling convention.
7786 CallingConv CC;
7787 if (S.CheckCallingConvAttr(attr, CC))
7788 return true;
7790 const FunctionType *fn = unwrapped.get();
7791 CallingConv CCOld = fn->getCallConv();
7792 Attr *CCAttr = getCCTypeAttr(S.Context, attr);
7794 if (CCOld != CC) {
7795 // Error out on when there's already an attribute on the type
7796 // and the CCs don't match.
7797 if (S.getCallingConvAttributedType(type)) {
7798 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7799 << FunctionType::getNameForCallConv(CC)
7800 << FunctionType::getNameForCallConv(CCOld);
7801 attr.setInvalid();
7802 return true;
7806 // Diagnose use of variadic functions with calling conventions that
7807 // don't support them (e.g. because they're callee-cleanup).
7808 // We delay warning about this on unprototyped function declarations
7809 // until after redeclaration checking, just in case we pick up a
7810 // prototype that way. And apparently we also "delay" warning about
7811 // unprototyped function types in general, despite not necessarily having
7812 // much ability to diagnose it later.
7813 if (!supportsVariadicCall(CC)) {
7814 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
7815 if (FnP && FnP->isVariadic()) {
7816 // stdcall and fastcall are ignored with a warning for GCC and MS
7817 // compatibility.
7818 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
7819 return S.Diag(attr.getLoc(), diag::warn_cconv_unsupported)
7820 << FunctionType::getNameForCallConv(CC)
7821 << (int)Sema::CallingConventionIgnoredReason::VariadicFunction;
7823 attr.setInvalid();
7824 return S.Diag(attr.getLoc(), diag::err_cconv_varargs)
7825 << FunctionType::getNameForCallConv(CC);
7829 // Also diagnose fastcall with regparm.
7830 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
7831 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
7832 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
7833 attr.setInvalid();
7834 return true;
7837 // Modify the CC from the wrapped function type, wrap it all back, and then
7838 // wrap the whole thing in an AttributedType as written. The modified type
7839 // might have a different CC if we ignored the attribute.
7840 QualType Equivalent;
7841 if (CCOld == CC) {
7842 Equivalent = type;
7843 } else {
7844 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
7845 Equivalent =
7846 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
7848 type = state.getAttributedType(CCAttr, type, Equivalent);
7849 return true;
7852 bool Sema::hasExplicitCallingConv(QualType T) {
7853 const AttributedType *AT;
7855 // Stop if we'd be stripping off a typedef sugar node to reach the
7856 // AttributedType.
7857 while ((AT = T->getAs<AttributedType>()) &&
7858 AT->getAs<TypedefType>() == T->getAs<TypedefType>()) {
7859 if (AT->isCallingConv())
7860 return true;
7861 T = AT->getModifiedType();
7863 return false;
7866 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
7867 SourceLocation Loc) {
7868 FunctionTypeUnwrapper Unwrapped(*this, T);
7869 const FunctionType *FT = Unwrapped.get();
7870 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
7871 cast<FunctionProtoType>(FT)->isVariadic());
7872 CallingConv CurCC = FT->getCallConv();
7873 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
7875 if (CurCC == ToCC)
7876 return;
7878 // MS compiler ignores explicit calling convention attributes on structors. We
7879 // should do the same.
7880 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
7881 // Issue a warning on ignored calling convention -- except of __stdcall.
7882 // Again, this is what MS compiler does.
7883 if (CurCC != CC_X86StdCall)
7884 Diag(Loc, diag::warn_cconv_unsupported)
7885 << FunctionType::getNameForCallConv(CurCC)
7886 << (int)Sema::CallingConventionIgnoredReason::ConstructorDestructor;
7887 // Default adjustment.
7888 } else {
7889 // Only adjust types with the default convention. For example, on Windows
7890 // we should adjust a __cdecl type to __thiscall for instance methods, and a
7891 // __thiscall type to __cdecl for static methods.
7892 CallingConv DefaultCC =
7893 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
7895 if (CurCC != DefaultCC || DefaultCC == ToCC)
7896 return;
7898 if (hasExplicitCallingConv(T))
7899 return;
7902 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
7903 QualType Wrapped = Unwrapped.wrap(*this, FT);
7904 T = Context.getAdjustedType(T, Wrapped);
7907 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
7908 /// and float scalars, although arrays, pointers, and function return values are
7909 /// allowed in conjunction with this construct. Aggregates with this attribute
7910 /// are invalid, even if they are of the same size as a corresponding scalar.
7911 /// The raw attribute should contain precisely 1 argument, the vector size for
7912 /// the variable, measured in bytes. If curType and rawAttr are well formed,
7913 /// this routine will return a new vector type.
7914 static void HandleVectorSizeAttr(QualType &CurType, const ParsedAttr &Attr,
7915 Sema &S) {
7916 // Check the attribute arguments.
7917 if (Attr.getNumArgs() != 1) {
7918 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7919 << 1;
7920 Attr.setInvalid();
7921 return;
7924 Expr *SizeExpr = Attr.getArgAsExpr(0);
7925 QualType T = S.BuildVectorType(CurType, SizeExpr, Attr.getLoc());
7926 if (!T.isNull())
7927 CurType = T;
7928 else
7929 Attr.setInvalid();
7932 /// Process the OpenCL-like ext_vector_type attribute when it occurs on
7933 /// a type.
7934 static void HandleExtVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
7935 Sema &S) {
7936 // check the attribute arguments.
7937 if (Attr.getNumArgs() != 1) {
7938 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
7939 << 1;
7940 return;
7943 Expr *SizeExpr = Attr.getArgAsExpr(0);
7944 QualType T = S.BuildExtVectorType(CurType, SizeExpr, Attr.getLoc());
7945 if (!T.isNull())
7946 CurType = T;
7949 static bool isPermittedNeonBaseType(QualType &Ty,
7950 VectorType::VectorKind VecKind, Sema &S) {
7951 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
7952 if (!BTy)
7953 return false;
7955 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
7957 // Signed poly is mathematically wrong, but has been baked into some ABIs by
7958 // now.
7959 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
7960 Triple.getArch() == llvm::Triple::aarch64_32 ||
7961 Triple.getArch() == llvm::Triple::aarch64_be;
7962 if (VecKind == VectorType::NeonPolyVector) {
7963 if (IsPolyUnsigned) {
7964 // AArch64 polynomial vectors are unsigned.
7965 return BTy->getKind() == BuiltinType::UChar ||
7966 BTy->getKind() == BuiltinType::UShort ||
7967 BTy->getKind() == BuiltinType::ULong ||
7968 BTy->getKind() == BuiltinType::ULongLong;
7969 } else {
7970 // AArch32 polynomial vectors are signed.
7971 return BTy->getKind() == BuiltinType::SChar ||
7972 BTy->getKind() == BuiltinType::Short ||
7973 BTy->getKind() == BuiltinType::LongLong;
7977 // Non-polynomial vector types: the usual suspects are allowed, as well as
7978 // float64_t on AArch64.
7979 if ((Triple.isArch64Bit() || Triple.getArch() == llvm::Triple::aarch64_32) &&
7980 BTy->getKind() == BuiltinType::Double)
7981 return true;
7983 return BTy->getKind() == BuiltinType::SChar ||
7984 BTy->getKind() == BuiltinType::UChar ||
7985 BTy->getKind() == BuiltinType::Short ||
7986 BTy->getKind() == BuiltinType::UShort ||
7987 BTy->getKind() == BuiltinType::Int ||
7988 BTy->getKind() == BuiltinType::UInt ||
7989 BTy->getKind() == BuiltinType::Long ||
7990 BTy->getKind() == BuiltinType::ULong ||
7991 BTy->getKind() == BuiltinType::LongLong ||
7992 BTy->getKind() == BuiltinType::ULongLong ||
7993 BTy->getKind() == BuiltinType::Float ||
7994 BTy->getKind() == BuiltinType::Half ||
7995 BTy->getKind() == BuiltinType::BFloat16;
7998 static bool verifyValidIntegerConstantExpr(Sema &S, const ParsedAttr &Attr,
7999 llvm::APSInt &Result) {
8000 const auto *AttrExpr = Attr.getArgAsExpr(0);
8001 if (!AttrExpr->isTypeDependent()) {
8002 if (Optional<llvm::APSInt> Res =
8003 AttrExpr->getIntegerConstantExpr(S.Context)) {
8004 Result = *Res;
8005 return true;
8008 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
8009 << Attr << AANT_ArgumentIntegerConstant << AttrExpr->getSourceRange();
8010 Attr.setInvalid();
8011 return false;
8014 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
8015 /// "neon_polyvector_type" attributes are used to create vector types that
8016 /// are mangled according to ARM's ABI. Otherwise, these types are identical
8017 /// to those created with the "vector_size" attribute. Unlike "vector_size"
8018 /// the argument to these Neon attributes is the number of vector elements,
8019 /// not the vector size in bytes. The vector width and element type must
8020 /// match one of the standard Neon vector types.
8021 static void HandleNeonVectorTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8022 Sema &S, VectorType::VectorKind VecKind) {
8023 // Target must have NEON (or MVE, whose vectors are similar enough
8024 // not to need a separate attribute)
8025 if (!S.Context.getTargetInfo().hasFeature("neon") &&
8026 !S.Context.getTargetInfo().hasFeature("mve")) {
8027 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported)
8028 << Attr << "'neon' or 'mve'";
8029 Attr.setInvalid();
8030 return;
8032 // Check the attribute arguments.
8033 if (Attr.getNumArgs() != 1) {
8034 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << Attr
8035 << 1;
8036 Attr.setInvalid();
8037 return;
8039 // The number of elements must be an ICE.
8040 llvm::APSInt numEltsInt(32);
8041 if (!verifyValidIntegerConstantExpr(S, Attr, numEltsInt))
8042 return;
8044 // Only certain element types are supported for Neon vectors.
8045 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
8046 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
8047 Attr.setInvalid();
8048 return;
8051 // The total size of the vector must be 64 or 128 bits.
8052 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
8053 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
8054 unsigned vecSize = typeSize * numElts;
8055 if (vecSize != 64 && vecSize != 128) {
8056 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
8057 Attr.setInvalid();
8058 return;
8061 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
8064 /// HandleArmSveVectorBitsTypeAttr - The "arm_sve_vector_bits" attribute is
8065 /// used to create fixed-length versions of sizeless SVE types defined by
8066 /// the ACLE, such as svint32_t and svbool_t.
8067 static void HandleArmSveVectorBitsTypeAttr(QualType &CurType, ParsedAttr &Attr,
8068 Sema &S) {
8069 // Target must have SVE.
8070 if (!S.Context.getTargetInfo().hasFeature("sve")) {
8071 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr << "'sve'";
8072 Attr.setInvalid();
8073 return;
8076 // Attribute is unsupported if '-msve-vector-bits=<bits>' isn't specified, or
8077 // if <bits>+ syntax is used.
8078 if (!S.getLangOpts().VScaleMin ||
8079 S.getLangOpts().VScaleMin != S.getLangOpts().VScaleMax) {
8080 S.Diag(Attr.getLoc(), diag::err_attribute_arm_feature_sve_bits_unsupported)
8081 << Attr;
8082 Attr.setInvalid();
8083 return;
8086 // Check the attribute arguments.
8087 if (Attr.getNumArgs() != 1) {
8088 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8089 << Attr << 1;
8090 Attr.setInvalid();
8091 return;
8094 // The vector size must be an integer constant expression.
8095 llvm::APSInt SveVectorSizeInBits(32);
8096 if (!verifyValidIntegerConstantExpr(S, Attr, SveVectorSizeInBits))
8097 return;
8099 unsigned VecSize = static_cast<unsigned>(SveVectorSizeInBits.getZExtValue());
8101 // The attribute vector size must match -msve-vector-bits.
8102 if (VecSize != S.getLangOpts().VScaleMin * 128) {
8103 S.Diag(Attr.getLoc(), diag::err_attribute_bad_sve_vector_size)
8104 << VecSize << S.getLangOpts().VScaleMin * 128;
8105 Attr.setInvalid();
8106 return;
8109 // Attribute can only be attached to a single SVE vector or predicate type.
8110 if (!CurType->isVLSTBuiltinType()) {
8111 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_sve_type)
8112 << Attr << CurType;
8113 Attr.setInvalid();
8114 return;
8117 const auto *BT = CurType->castAs<BuiltinType>();
8119 QualType EltType = CurType->getSveEltType(S.Context);
8120 unsigned TypeSize = S.Context.getTypeSize(EltType);
8121 VectorType::VectorKind VecKind = VectorType::SveFixedLengthDataVector;
8122 if (BT->getKind() == BuiltinType::SveBool) {
8123 // Predicates are represented as i8.
8124 VecSize /= S.Context.getCharWidth() * S.Context.getCharWidth();
8125 VecKind = VectorType::SveFixedLengthPredicateVector;
8126 } else
8127 VecSize /= TypeSize;
8128 CurType = S.Context.getVectorType(EltType, VecSize, VecKind);
8131 static void HandleArmMveStrictPolymorphismAttr(TypeProcessingState &State,
8132 QualType &CurType,
8133 ParsedAttr &Attr) {
8134 const VectorType *VT = dyn_cast<VectorType>(CurType);
8135 if (!VT || VT->getVectorKind() != VectorType::NeonVector) {
8136 State.getSema().Diag(Attr.getLoc(),
8137 diag::err_attribute_arm_mve_polymorphism);
8138 Attr.setInvalid();
8139 return;
8142 CurType =
8143 State.getAttributedType(createSimpleAttr<ArmMveStrictPolymorphismAttr>(
8144 State.getSema().Context, Attr),
8145 CurType, CurType);
8148 /// Handle OpenCL Access Qualifier Attribute.
8149 static void HandleOpenCLAccessAttr(QualType &CurType, const ParsedAttr &Attr,
8150 Sema &S) {
8151 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
8152 if (!(CurType->isImageType() || CurType->isPipeType())) {
8153 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
8154 Attr.setInvalid();
8155 return;
8158 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
8159 QualType BaseTy = TypedefTy->desugar();
8161 std::string PrevAccessQual;
8162 if (BaseTy->isPipeType()) {
8163 if (TypedefTy->getDecl()->hasAttr<OpenCLAccessAttr>()) {
8164 OpenCLAccessAttr *Attr =
8165 TypedefTy->getDecl()->getAttr<OpenCLAccessAttr>();
8166 PrevAccessQual = Attr->getSpelling();
8167 } else {
8168 PrevAccessQual = "read_only";
8170 } else if (const BuiltinType* ImgType = BaseTy->getAs<BuiltinType>()) {
8172 switch (ImgType->getKind()) {
8173 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
8174 case BuiltinType::Id: \
8175 PrevAccessQual = #Access; \
8176 break;
8177 #include "clang/Basic/OpenCLImageTypes.def"
8178 default:
8179 llvm_unreachable("Unable to find corresponding image type.");
8181 } else {
8182 llvm_unreachable("unexpected type");
8184 StringRef AttrName = Attr.getAttrName()->getName();
8185 if (PrevAccessQual == AttrName.ltrim("_")) {
8186 // Duplicated qualifiers
8187 S.Diag(Attr.getLoc(), diag::warn_duplicate_declspec)
8188 << AttrName << Attr.getRange();
8189 } else {
8190 // Contradicting qualifiers
8191 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
8194 S.Diag(TypedefTy->getDecl()->getBeginLoc(),
8195 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
8196 } else if (CurType->isPipeType()) {
8197 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
8198 QualType ElemType = CurType->castAs<PipeType>()->getElementType();
8199 CurType = S.Context.getWritePipeType(ElemType);
8204 /// HandleMatrixTypeAttr - "matrix_type" attribute, like ext_vector_type
8205 static void HandleMatrixTypeAttr(QualType &CurType, const ParsedAttr &Attr,
8206 Sema &S) {
8207 if (!S.getLangOpts().MatrixTypes) {
8208 S.Diag(Attr.getLoc(), diag::err_builtin_matrix_disabled);
8209 return;
8212 if (Attr.getNumArgs() != 2) {
8213 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
8214 << Attr << 2;
8215 return;
8218 Expr *RowsExpr = Attr.getArgAsExpr(0);
8219 Expr *ColsExpr = Attr.getArgAsExpr(1);
8220 QualType T = S.BuildMatrixType(CurType, RowsExpr, ColsExpr, Attr.getLoc());
8221 if (!T.isNull())
8222 CurType = T;
8225 static void HandleAnnotateTypeAttr(TypeProcessingState &State,
8226 QualType &CurType, const ParsedAttr &PA) {
8227 Sema &S = State.getSema();
8229 if (PA.getNumArgs() < 1) {
8230 S.Diag(PA.getLoc(), diag::err_attribute_too_few_arguments) << PA << 1;
8231 return;
8234 // Make sure that there is a string literal as the annotation's first
8235 // argument.
8236 StringRef Str;
8237 if (!S.checkStringLiteralArgumentAttr(PA, 0, Str))
8238 return;
8240 llvm::SmallVector<Expr *, 4> Args;
8241 Args.reserve(PA.getNumArgs() - 1);
8242 for (unsigned Idx = 1; Idx < PA.getNumArgs(); Idx++) {
8243 assert(!PA.isArgIdent(Idx));
8244 Args.push_back(PA.getArgAsExpr(Idx));
8246 if (!S.ConstantFoldAttrArgs(PA, Args))
8247 return;
8248 auto *AnnotateTypeAttr =
8249 AnnotateTypeAttr::Create(S.Context, Str, Args.data(), Args.size(), PA);
8250 CurType = State.getAttributedType(AnnotateTypeAttr, CurType, CurType);
8253 static void HandleLifetimeBoundAttr(TypeProcessingState &State,
8254 QualType &CurType,
8255 ParsedAttr &Attr) {
8256 if (State.getDeclarator().isDeclarationOfFunction()) {
8257 CurType = State.getAttributedType(
8258 createSimpleAttr<LifetimeBoundAttr>(State.getSema().Context, Attr),
8259 CurType, CurType);
8263 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
8264 TypeAttrLocation TAL,
8265 const ParsedAttributesView &attrs) {
8267 state.setParsedNoDeref(false);
8268 if (attrs.empty())
8269 return;
8271 // Scan through and apply attributes to this type where it makes sense. Some
8272 // attributes (such as __address_space__, __vector_size__, etc) apply to the
8273 // type, but others can be present in the type specifiers even though they
8274 // apply to the decl. Here we apply type attributes and ignore the rest.
8276 // This loop modifies the list pretty frequently, but we still need to make
8277 // sure we visit every element once. Copy the attributes list, and iterate
8278 // over that.
8279 ParsedAttributesView AttrsCopy{attrs};
8280 for (ParsedAttr &attr : AttrsCopy) {
8282 // Skip attributes that were marked to be invalid.
8283 if (attr.isInvalid())
8284 continue;
8286 if (attr.isStandardAttributeSyntax()) {
8287 // [[gnu::...]] attributes are treated as declaration attributes, so may
8288 // not appertain to a DeclaratorChunk. If we handle them as type
8289 // attributes, accept them in that position and diagnose the GCC
8290 // incompatibility.
8291 if (attr.isGNUScope()) {
8292 bool IsTypeAttr = attr.isTypeAttr();
8293 if (TAL == TAL_DeclChunk) {
8294 state.getSema().Diag(attr.getLoc(),
8295 IsTypeAttr
8296 ? diag::warn_gcc_ignores_type_attr
8297 : diag::warn_cxx11_gnu_attribute_on_type)
8298 << attr;
8299 if (!IsTypeAttr)
8300 continue;
8302 } else if (TAL != TAL_DeclSpec && TAL != TAL_DeclChunk &&
8303 !attr.isTypeAttr()) {
8304 // Otherwise, only consider type processing for a C++11 attribute if
8305 // - it has actually been applied to a type (decl-specifier-seq or
8306 // declarator chunk), or
8307 // - it is a type attribute, irrespective of where it was applied (so
8308 // that we can support the legacy behavior of some type attributes
8309 // that can be applied to the declaration name).
8310 continue;
8314 // If this is an attribute we can handle, do so now,
8315 // otherwise, add it to the FnAttrs list for rechaining.
8316 switch (attr.getKind()) {
8317 default:
8318 // A [[]] attribute on a declarator chunk must appertain to a type.
8319 if (attr.isStandardAttributeSyntax() && TAL == TAL_DeclChunk) {
8320 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
8321 << attr;
8322 attr.setUsedAsTypeAttr();
8324 break;
8326 case ParsedAttr::UnknownAttribute:
8327 if (attr.isStandardAttributeSyntax()) {
8328 state.getSema().Diag(attr.getLoc(),
8329 diag::warn_unknown_attribute_ignored)
8330 << attr << attr.getRange();
8331 // Mark the attribute as invalid so we don't emit the same diagnostic
8332 // multiple times.
8333 attr.setInvalid();
8335 break;
8337 case ParsedAttr::IgnoredAttribute:
8338 break;
8340 case ParsedAttr::AT_BTFTypeTag:
8341 HandleBTFTypeTagAttribute(type, attr, state);
8342 attr.setUsedAsTypeAttr();
8343 break;
8345 case ParsedAttr::AT_MayAlias:
8346 // FIXME: This attribute needs to actually be handled, but if we ignore
8347 // it it breaks large amounts of Linux software.
8348 attr.setUsedAsTypeAttr();
8349 break;
8350 case ParsedAttr::AT_OpenCLPrivateAddressSpace:
8351 case ParsedAttr::AT_OpenCLGlobalAddressSpace:
8352 case ParsedAttr::AT_OpenCLGlobalDeviceAddressSpace:
8353 case ParsedAttr::AT_OpenCLGlobalHostAddressSpace:
8354 case ParsedAttr::AT_OpenCLLocalAddressSpace:
8355 case ParsedAttr::AT_OpenCLConstantAddressSpace:
8356 case ParsedAttr::AT_OpenCLGenericAddressSpace:
8357 case ParsedAttr::AT_AddressSpace:
8358 HandleAddressSpaceTypeAttribute(type, attr, state);
8359 attr.setUsedAsTypeAttr();
8360 break;
8361 OBJC_POINTER_TYPE_ATTRS_CASELIST:
8362 if (!handleObjCPointerTypeAttr(state, attr, type))
8363 distributeObjCPointerTypeAttr(state, attr, type);
8364 attr.setUsedAsTypeAttr();
8365 break;
8366 case ParsedAttr::AT_VectorSize:
8367 HandleVectorSizeAttr(type, attr, state.getSema());
8368 attr.setUsedAsTypeAttr();
8369 break;
8370 case ParsedAttr::AT_ExtVectorType:
8371 HandleExtVectorTypeAttr(type, attr, state.getSema());
8372 attr.setUsedAsTypeAttr();
8373 break;
8374 case ParsedAttr::AT_NeonVectorType:
8375 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8376 VectorType::NeonVector);
8377 attr.setUsedAsTypeAttr();
8378 break;
8379 case ParsedAttr::AT_NeonPolyVectorType:
8380 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
8381 VectorType::NeonPolyVector);
8382 attr.setUsedAsTypeAttr();
8383 break;
8384 case ParsedAttr::AT_ArmSveVectorBits:
8385 HandleArmSveVectorBitsTypeAttr(type, attr, state.getSema());
8386 attr.setUsedAsTypeAttr();
8387 break;
8388 case ParsedAttr::AT_ArmMveStrictPolymorphism: {
8389 HandleArmMveStrictPolymorphismAttr(state, type, attr);
8390 attr.setUsedAsTypeAttr();
8391 break;
8393 case ParsedAttr::AT_OpenCLAccess:
8394 HandleOpenCLAccessAttr(type, attr, state.getSema());
8395 attr.setUsedAsTypeAttr();
8396 break;
8397 case ParsedAttr::AT_LifetimeBound:
8398 if (TAL == TAL_DeclChunk)
8399 HandleLifetimeBoundAttr(state, type, attr);
8400 break;
8402 case ParsedAttr::AT_NoDeref: {
8403 // FIXME: `noderef` currently doesn't work correctly in [[]] syntax.
8404 // See https://github.com/llvm/llvm-project/issues/55790 for details.
8405 // For the time being, we simply emit a warning that the attribute is
8406 // ignored.
8407 if (attr.isStandardAttributeSyntax()) {
8408 state.getSema().Diag(attr.getLoc(), diag::warn_attribute_ignored)
8409 << attr;
8410 break;
8412 ASTContext &Ctx = state.getSema().Context;
8413 type = state.getAttributedType(createSimpleAttr<NoDerefAttr>(Ctx, attr),
8414 type, type);
8415 attr.setUsedAsTypeAttr();
8416 state.setParsedNoDeref(true);
8417 break;
8420 case ParsedAttr::AT_MatrixType:
8421 HandleMatrixTypeAttr(type, attr, state.getSema());
8422 attr.setUsedAsTypeAttr();
8423 break;
8425 MS_TYPE_ATTRS_CASELIST:
8426 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
8427 attr.setUsedAsTypeAttr();
8428 break;
8431 NULLABILITY_TYPE_ATTRS_CASELIST:
8432 // Either add nullability here or try to distribute it. We
8433 // don't want to distribute the nullability specifier past any
8434 // dependent type, because that complicates the user model.
8435 if (type->canHaveNullability() || type->isDependentType() ||
8436 type->isArrayType() ||
8437 !distributeNullabilityTypeAttr(state, type, attr)) {
8438 unsigned endIndex;
8439 if (TAL == TAL_DeclChunk)
8440 endIndex = state.getCurrentChunkIndex();
8441 else
8442 endIndex = state.getDeclarator().getNumTypeObjects();
8443 bool allowOnArrayType =
8444 state.getDeclarator().isPrototypeContext() &&
8445 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
8446 if (checkNullabilityTypeSpecifier(
8447 state,
8448 type,
8449 attr,
8450 allowOnArrayType)) {
8451 attr.setInvalid();
8454 attr.setUsedAsTypeAttr();
8456 break;
8458 case ParsedAttr::AT_ObjCKindOf:
8459 // '__kindof' must be part of the decl-specifiers.
8460 switch (TAL) {
8461 case TAL_DeclSpec:
8462 break;
8464 case TAL_DeclChunk:
8465 case TAL_DeclName:
8466 state.getSema().Diag(attr.getLoc(),
8467 diag::err_objc_kindof_wrong_position)
8468 << FixItHint::CreateRemoval(attr.getLoc())
8469 << FixItHint::CreateInsertion(
8470 state.getDeclarator().getDeclSpec().getBeginLoc(),
8471 "__kindof ");
8472 break;
8475 // Apply it regardless.
8476 if (checkObjCKindOfType(state, type, attr))
8477 attr.setInvalid();
8478 break;
8480 case ParsedAttr::AT_NoThrow:
8481 // Exception Specifications aren't generally supported in C mode throughout
8482 // clang, so revert to attribute-based handling for C.
8483 if (!state.getSema().getLangOpts().CPlusPlus)
8484 break;
8485 [[fallthrough]];
8486 FUNCTION_TYPE_ATTRS_CASELIST:
8487 attr.setUsedAsTypeAttr();
8489 // Attributes with standard syntax have strict rules for what they
8490 // appertain to and hence should not use the "distribution" logic below.
8491 if (attr.isStandardAttributeSyntax()) {
8492 if (!handleFunctionTypeAttr(state, attr, type)) {
8493 diagnoseBadTypeAttribute(state.getSema(), attr, type);
8494 attr.setInvalid();
8496 break;
8499 // Never process function type attributes as part of the
8500 // declaration-specifiers.
8501 if (TAL == TAL_DeclSpec)
8502 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
8504 // Otherwise, handle the possible delays.
8505 else if (!handleFunctionTypeAttr(state, attr, type))
8506 distributeFunctionTypeAttr(state, attr, type);
8507 break;
8508 case ParsedAttr::AT_AcquireHandle: {
8509 if (!type->isFunctionType())
8510 return;
8512 if (attr.getNumArgs() != 1) {
8513 state.getSema().Diag(attr.getLoc(),
8514 diag::err_attribute_wrong_number_arguments)
8515 << attr << 1;
8516 attr.setInvalid();
8517 return;
8520 StringRef HandleType;
8521 if (!state.getSema().checkStringLiteralArgumentAttr(attr, 0, HandleType))
8522 return;
8523 type = state.getAttributedType(
8524 AcquireHandleAttr::Create(state.getSema().Context, HandleType, attr),
8525 type, type);
8526 attr.setUsedAsTypeAttr();
8527 break;
8529 case ParsedAttr::AT_AnnotateType: {
8530 HandleAnnotateTypeAttr(state, type, attr);
8531 attr.setUsedAsTypeAttr();
8532 break;
8536 // Handle attributes that are defined in a macro. We do not want this to be
8537 // applied to ObjC builtin attributes.
8538 if (isa<AttributedType>(type) && attr.hasMacroIdentifier() &&
8539 !type.getQualifiers().hasObjCLifetime() &&
8540 !type.getQualifiers().hasObjCGCAttr() &&
8541 attr.getKind() != ParsedAttr::AT_ObjCGC &&
8542 attr.getKind() != ParsedAttr::AT_ObjCOwnership) {
8543 const IdentifierInfo *MacroII = attr.getMacroIdentifier();
8544 type = state.getSema().Context.getMacroQualifiedType(type, MacroII);
8545 state.setExpansionLocForMacroQualifiedType(
8546 cast<MacroQualifiedType>(type.getTypePtr()),
8547 attr.getMacroExpansionLoc());
8552 void Sema::completeExprArrayBound(Expr *E) {
8553 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
8554 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
8555 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
8556 auto *Def = Var->getDefinition();
8557 if (!Def) {
8558 SourceLocation PointOfInstantiation = E->getExprLoc();
8559 runWithSufficientStackSpace(PointOfInstantiation, [&] {
8560 InstantiateVariableDefinition(PointOfInstantiation, Var);
8562 Def = Var->getDefinition();
8564 // If we don't already have a point of instantiation, and we managed
8565 // to instantiate a definition, this is the point of instantiation.
8566 // Otherwise, we don't request an end-of-TU instantiation, so this is
8567 // not a point of instantiation.
8568 // FIXME: Is this really the right behavior?
8569 if (Var->getPointOfInstantiation().isInvalid() && Def) {
8570 assert(Var->getTemplateSpecializationKind() ==
8571 TSK_ImplicitInstantiation &&
8572 "explicit instantiation with no point of instantiation");
8573 Var->setTemplateSpecializationKind(
8574 Var->getTemplateSpecializationKind(), PointOfInstantiation);
8578 // Update the type to the definition's type both here and within the
8579 // expression.
8580 if (Def) {
8581 DRE->setDecl(Def);
8582 QualType T = Def->getType();
8583 DRE->setType(T);
8584 // FIXME: Update the type on all intervening expressions.
8585 E->setType(T);
8588 // We still go on to try to complete the type independently, as it
8589 // may also require instantiations or diagnostics if it remains
8590 // incomplete.
8596 QualType Sema::getCompletedType(Expr *E) {
8597 // Incomplete array types may be completed by the initializer attached to
8598 // their definitions. For static data members of class templates and for
8599 // variable templates, we need to instantiate the definition to get this
8600 // initializer and complete the type.
8601 if (E->getType()->isIncompleteArrayType())
8602 completeExprArrayBound(E);
8604 // FIXME: Are there other cases which require instantiating something other
8605 // than the type to complete the type of an expression?
8607 return E->getType();
8610 /// Ensure that the type of the given expression is complete.
8612 /// This routine checks whether the expression \p E has a complete type. If the
8613 /// expression refers to an instantiable construct, that instantiation is
8614 /// performed as needed to complete its type. Furthermore
8615 /// Sema::RequireCompleteType is called for the expression's type (or in the
8616 /// case of a reference type, the referred-to type).
8618 /// \param E The expression whose type is required to be complete.
8619 /// \param Kind Selects which completeness rules should be applied.
8620 /// \param Diagnoser The object that will emit a diagnostic if the type is
8621 /// incomplete.
8623 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
8624 /// otherwise.
8625 bool Sema::RequireCompleteExprType(Expr *E, CompleteTypeKind Kind,
8626 TypeDiagnoser &Diagnoser) {
8627 return RequireCompleteType(E->getExprLoc(), getCompletedType(E), Kind,
8628 Diagnoser);
8631 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
8632 BoundTypeDiagnoser<> Diagnoser(DiagID);
8633 return RequireCompleteExprType(E, CompleteTypeKind::Default, Diagnoser);
8636 /// Ensure that the type T is a complete type.
8638 /// This routine checks whether the type @p T is complete in any
8639 /// context where a complete type is required. If @p T is a complete
8640 /// type, returns false. If @p T is a class template specialization,
8641 /// this routine then attempts to perform class template
8642 /// instantiation. If instantiation fails, or if @p T is incomplete
8643 /// and cannot be completed, issues the diagnostic @p diag (giving it
8644 /// the type @p T) and returns true.
8646 /// @param Loc The location in the source that the incomplete type
8647 /// diagnostic should refer to.
8649 /// @param T The type that this routine is examining for completeness.
8651 /// @param Kind Selects which completeness rules should be applied.
8653 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
8654 /// @c false otherwise.
8655 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
8656 CompleteTypeKind Kind,
8657 TypeDiagnoser &Diagnoser) {
8658 if (RequireCompleteTypeImpl(Loc, T, Kind, &Diagnoser))
8659 return true;
8660 if (const TagType *Tag = T->getAs<TagType>()) {
8661 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
8662 Tag->getDecl()->setCompleteDefinitionRequired();
8663 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
8666 return false;
8669 bool Sema::hasStructuralCompatLayout(Decl *D, Decl *Suggested) {
8670 llvm::DenseSet<std::pair<Decl *, Decl *>> NonEquivalentDecls;
8671 if (!Suggested)
8672 return false;
8674 // FIXME: Add a specific mode for C11 6.2.7/1 in StructuralEquivalenceContext
8675 // and isolate from other C++ specific checks.
8676 StructuralEquivalenceContext Ctx(
8677 D->getASTContext(), Suggested->getASTContext(), NonEquivalentDecls,
8678 StructuralEquivalenceKind::Default,
8679 false /*StrictTypeSpelling*/, true /*Complain*/,
8680 true /*ErrorOnTagTypeMismatch*/);
8681 return Ctx.IsEquivalent(D, Suggested);
8684 bool Sema::hasAcceptableDefinition(NamedDecl *D, NamedDecl **Suggested,
8685 AcceptableKind Kind, bool OnlyNeedComplete) {
8686 // Easy case: if we don't have modules, all declarations are visible.
8687 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
8688 return true;
8690 // If this definition was instantiated from a template, map back to the
8691 // pattern from which it was instantiated.
8692 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
8693 // We're in the middle of defining it; this definition should be treated
8694 // as visible.
8695 return true;
8696 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
8697 if (auto *Pattern = RD->getTemplateInstantiationPattern())
8698 RD = Pattern;
8699 D = RD->getDefinition();
8700 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
8701 if (auto *Pattern = ED->getTemplateInstantiationPattern())
8702 ED = Pattern;
8703 if (OnlyNeedComplete && (ED->isFixed() || getLangOpts().MSVCCompat)) {
8704 // If the enum has a fixed underlying type, it may have been forward
8705 // declared. In -fms-compatibility, `enum Foo;` will also forward declare
8706 // the enum and assign it the underlying type of `int`. Since we're only
8707 // looking for a complete type (not a definition), any visible declaration
8708 // of it will do.
8709 *Suggested = nullptr;
8710 for (auto *Redecl : ED->redecls()) {
8711 if (isAcceptable(Redecl, Kind))
8712 return true;
8713 if (Redecl->isThisDeclarationADefinition() ||
8714 (Redecl->isCanonicalDecl() && !*Suggested))
8715 *Suggested = Redecl;
8718 return false;
8720 D = ED->getDefinition();
8721 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
8722 if (auto *Pattern = FD->getTemplateInstantiationPattern())
8723 FD = Pattern;
8724 D = FD->getDefinition();
8725 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
8726 if (auto *Pattern = VD->getTemplateInstantiationPattern())
8727 VD = Pattern;
8728 D = VD->getDefinition();
8731 assert(D && "missing definition for pattern of instantiated definition");
8733 *Suggested = D;
8735 auto DefinitionIsAcceptable = [&] {
8736 // The (primary) definition might be in a visible module.
8737 if (isAcceptable(D, Kind))
8738 return true;
8740 // A visible module might have a merged definition instead.
8741 if (D->isModulePrivate() ? hasMergedDefinitionInCurrentModule(D)
8742 : hasVisibleMergedDefinition(D)) {
8743 if (CodeSynthesisContexts.empty() &&
8744 !getLangOpts().ModulesLocalVisibility) {
8745 // Cache the fact that this definition is implicitly visible because
8746 // there is a visible merged definition.
8747 D->setVisibleDespiteOwningModule();
8749 return true;
8752 return false;
8755 if (DefinitionIsAcceptable())
8756 return true;
8758 // The external source may have additional definitions of this entity that are
8759 // visible, so complete the redeclaration chain now and ask again.
8760 if (auto *Source = Context.getExternalSource()) {
8761 Source->CompleteRedeclChain(D);
8762 return DefinitionIsAcceptable();
8765 return false;
8768 /// Determine whether there is any declaration of \p D that was ever a
8769 /// definition (perhaps before module merging) and is currently visible.
8770 /// \param D The definition of the entity.
8771 /// \param Suggested Filled in with the declaration that should be made visible
8772 /// in order to provide a definition of this entity.
8773 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8774 /// not defined. This only matters for enums with a fixed underlying
8775 /// type, since in all other cases, a type is complete if and only if it
8776 /// is defined.
8777 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
8778 bool OnlyNeedComplete) {
8779 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Visible,
8780 OnlyNeedComplete);
8783 /// Determine whether there is any declaration of \p D that was ever a
8784 /// definition (perhaps before module merging) and is currently
8785 /// reachable.
8786 /// \param D The definition of the entity.
8787 /// \param Suggested Filled in with the declaration that should be made
8788 /// reachable
8789 /// in order to provide a definition of this entity.
8790 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
8791 /// not defined. This only matters for enums with a fixed underlying
8792 /// type, since in all other cases, a type is complete if and only if it
8793 /// is defined.
8794 bool Sema::hasReachableDefinition(NamedDecl *D, NamedDecl **Suggested,
8795 bool OnlyNeedComplete) {
8796 return hasAcceptableDefinition(D, Suggested, Sema::AcceptableKind::Reachable,
8797 OnlyNeedComplete);
8800 /// Locks in the inheritance model for the given class and all of its bases.
8801 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
8802 RD = RD->getMostRecentNonInjectedDecl();
8803 if (!RD->hasAttr<MSInheritanceAttr>()) {
8804 MSInheritanceModel IM;
8805 bool BestCase = false;
8806 switch (S.MSPointerToMemberRepresentationMethod) {
8807 case LangOptions::PPTMK_BestCase:
8808 BestCase = true;
8809 IM = RD->calculateInheritanceModel();
8810 break;
8811 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
8812 IM = MSInheritanceModel::Single;
8813 break;
8814 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
8815 IM = MSInheritanceModel::Multiple;
8816 break;
8817 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
8818 IM = MSInheritanceModel::Unspecified;
8819 break;
8822 SourceRange Loc = S.ImplicitMSInheritanceAttrLoc.isValid()
8823 ? S.ImplicitMSInheritanceAttrLoc
8824 : RD->getSourceRange();
8825 RD->addAttr(MSInheritanceAttr::CreateImplicit(
8826 S.getASTContext(), BestCase, Loc, AttributeCommonInfo::AS_Microsoft,
8827 MSInheritanceAttr::Spelling(IM)));
8828 S.Consumer.AssignInheritanceModel(RD);
8832 /// The implementation of RequireCompleteType
8833 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
8834 CompleteTypeKind Kind,
8835 TypeDiagnoser *Diagnoser) {
8836 // FIXME: Add this assertion to make sure we always get instantiation points.
8837 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
8838 // FIXME: Add this assertion to help us flush out problems with
8839 // checking for dependent types and type-dependent expressions.
8841 // assert(!T->isDependentType() &&
8842 // "Can't ask whether a dependent type is complete");
8844 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
8845 if (!MPTy->getClass()->isDependentType()) {
8846 if (getLangOpts().CompleteMemberPointers &&
8847 !MPTy->getClass()->getAsCXXRecordDecl()->isBeingDefined() &&
8848 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), Kind,
8849 diag::err_memptr_incomplete))
8850 return true;
8852 // We lock in the inheritance model once somebody has asked us to ensure
8853 // that a pointer-to-member type is complete.
8854 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
8855 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
8856 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
8861 NamedDecl *Def = nullptr;
8862 bool AcceptSizeless = (Kind == CompleteTypeKind::AcceptSizeless);
8863 bool Incomplete = (T->isIncompleteType(&Def) ||
8864 (!AcceptSizeless && T->isSizelessBuiltinType()));
8866 // Check that any necessary explicit specializations are visible. For an
8867 // enum, we just need the declaration, so don't check this.
8868 if (Def && !isa<EnumDecl>(Def))
8869 checkSpecializationReachability(Loc, Def);
8871 // If we have a complete type, we're done.
8872 if (!Incomplete) {
8873 NamedDecl *Suggested = nullptr;
8874 if (Def &&
8875 !hasReachableDefinition(Def, &Suggested, /*OnlyNeedComplete=*/true)) {
8876 // If the user is going to see an error here, recover by making the
8877 // definition visible.
8878 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
8879 if (Diagnoser && Suggested)
8880 diagnoseMissingImport(Loc, Suggested, MissingImportKind::Definition,
8881 /*Recover*/ TreatAsComplete);
8882 return !TreatAsComplete;
8883 } else if (Def && !TemplateInstCallbacks.empty()) {
8884 CodeSynthesisContext TempInst;
8885 TempInst.Kind = CodeSynthesisContext::Memoization;
8886 TempInst.Template = Def;
8887 TempInst.Entity = Def;
8888 TempInst.PointOfInstantiation = Loc;
8889 atTemplateBegin(TemplateInstCallbacks, *this, TempInst);
8890 atTemplateEnd(TemplateInstCallbacks, *this, TempInst);
8893 return false;
8896 TagDecl *Tag = dyn_cast_or_null<TagDecl>(Def);
8897 ObjCInterfaceDecl *IFace = dyn_cast_or_null<ObjCInterfaceDecl>(Def);
8899 // Give the external source a chance to provide a definition of the type.
8900 // This is kept separate from completing the redeclaration chain so that
8901 // external sources such as LLDB can avoid synthesizing a type definition
8902 // unless it's actually needed.
8903 if (Tag || IFace) {
8904 // Avoid diagnosing invalid decls as incomplete.
8905 if (Def->isInvalidDecl())
8906 return true;
8908 // Give the external AST source a chance to complete the type.
8909 if (auto *Source = Context.getExternalSource()) {
8910 if (Tag && Tag->hasExternalLexicalStorage())
8911 Source->CompleteType(Tag);
8912 if (IFace && IFace->hasExternalLexicalStorage())
8913 Source->CompleteType(IFace);
8914 // If the external source completed the type, go through the motions
8915 // again to ensure we're allowed to use the completed type.
8916 if (!T->isIncompleteType())
8917 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8921 // If we have a class template specialization or a class member of a
8922 // class template specialization, or an array with known size of such,
8923 // try to instantiate it.
8924 if (auto *RD = dyn_cast_or_null<CXXRecordDecl>(Tag)) {
8925 bool Instantiated = false;
8926 bool Diagnosed = false;
8927 if (RD->isDependentContext()) {
8928 // Don't try to instantiate a dependent class (eg, a member template of
8929 // an instantiated class template specialization).
8930 // FIXME: Can this ever happen?
8931 } else if (auto *ClassTemplateSpec =
8932 dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
8933 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
8934 runWithSufficientStackSpace(Loc, [&] {
8935 Diagnosed = InstantiateClassTemplateSpecialization(
8936 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
8937 /*Complain=*/Diagnoser);
8939 Instantiated = true;
8941 } else {
8942 CXXRecordDecl *Pattern = RD->getInstantiatedFromMemberClass();
8943 if (!RD->isBeingDefined() && Pattern) {
8944 MemberSpecializationInfo *MSI = RD->getMemberSpecializationInfo();
8945 assert(MSI && "Missing member specialization information?");
8946 // This record was instantiated from a class within a template.
8947 if (MSI->getTemplateSpecializationKind() !=
8948 TSK_ExplicitSpecialization) {
8949 runWithSufficientStackSpace(Loc, [&] {
8950 Diagnosed = InstantiateClass(Loc, RD, Pattern,
8951 getTemplateInstantiationArgs(RD),
8952 TSK_ImplicitInstantiation,
8953 /*Complain=*/Diagnoser);
8955 Instantiated = true;
8960 if (Instantiated) {
8961 // Instantiate* might have already complained that the template is not
8962 // defined, if we asked it to.
8963 if (Diagnoser && Diagnosed)
8964 return true;
8965 // If we instantiated a definition, check that it's usable, even if
8966 // instantiation produced an error, so that repeated calls to this
8967 // function give consistent answers.
8968 if (!T->isIncompleteType())
8969 return RequireCompleteTypeImpl(Loc, T, Kind, Diagnoser);
8973 // FIXME: If we didn't instantiate a definition because of an explicit
8974 // specialization declaration, check that it's visible.
8976 if (!Diagnoser)
8977 return true;
8979 Diagnoser->diagnose(*this, Loc, T);
8981 // If the type was a forward declaration of a class/struct/union
8982 // type, produce a note.
8983 if (Tag && !Tag->isInvalidDecl() && !Tag->getLocation().isInvalid())
8984 Diag(Tag->getLocation(),
8985 Tag->isBeingDefined() ? diag::note_type_being_defined
8986 : diag::note_forward_declaration)
8987 << Context.getTagDeclType(Tag);
8989 // If the Objective-C class was a forward declaration, produce a note.
8990 if (IFace && !IFace->isInvalidDecl() && !IFace->getLocation().isInvalid())
8991 Diag(IFace->getLocation(), diag::note_forward_class);
8993 // If we have external information that we can use to suggest a fix,
8994 // produce a note.
8995 if (ExternalSource)
8996 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
8998 return true;
9001 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
9002 CompleteTypeKind Kind, unsigned DiagID) {
9003 BoundTypeDiagnoser<> Diagnoser(DiagID);
9004 return RequireCompleteType(Loc, T, Kind, Diagnoser);
9007 /// Get diagnostic %select index for tag kind for
9008 /// literal type diagnostic message.
9009 /// WARNING: Indexes apply to particular diagnostics only!
9011 /// \returns diagnostic %select index.
9012 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
9013 switch (Tag) {
9014 case TTK_Struct: return 0;
9015 case TTK_Interface: return 1;
9016 case TTK_Class: return 2;
9017 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
9021 /// Ensure that the type T is a literal type.
9023 /// This routine checks whether the type @p T is a literal type. If @p T is an
9024 /// incomplete type, an attempt is made to complete it. If @p T is a literal
9025 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
9026 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
9027 /// it the type @p T), along with notes explaining why the type is not a
9028 /// literal type, and returns true.
9030 /// @param Loc The location in the source that the non-literal type
9031 /// diagnostic should refer to.
9033 /// @param T The type that this routine is examining for literalness.
9035 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
9037 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
9038 /// @c false otherwise.
9039 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
9040 TypeDiagnoser &Diagnoser) {
9041 assert(!T->isDependentType() && "type should not be dependent");
9043 QualType ElemType = Context.getBaseElementType(T);
9044 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
9045 T->isLiteralType(Context))
9046 return false;
9048 Diagnoser.diagnose(*this, Loc, T);
9050 if (T->isVariableArrayType())
9051 return true;
9053 const RecordType *RT = ElemType->getAs<RecordType>();
9054 if (!RT)
9055 return true;
9057 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
9059 // A partially-defined class type can't be a literal type, because a literal
9060 // class type must have a trivial destructor (which can't be checked until
9061 // the class definition is complete).
9062 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
9063 return true;
9065 // [expr.prim.lambda]p3:
9066 // This class type is [not] a literal type.
9067 if (RD->isLambda() && !getLangOpts().CPlusPlus17) {
9068 Diag(RD->getLocation(), diag::note_non_literal_lambda);
9069 return true;
9072 // If the class has virtual base classes, then it's not an aggregate, and
9073 // cannot have any constexpr constructors or a trivial default constructor,
9074 // so is non-literal. This is better to diagnose than the resulting absence
9075 // of constexpr constructors.
9076 if (RD->getNumVBases()) {
9077 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
9078 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
9079 for (const auto &I : RD->vbases())
9080 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
9081 << I.getSourceRange();
9082 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
9083 !RD->hasTrivialDefaultConstructor()) {
9084 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
9085 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
9086 for (const auto &I : RD->bases()) {
9087 if (!I.getType()->isLiteralType(Context)) {
9088 Diag(I.getBeginLoc(), diag::note_non_literal_base_class)
9089 << RD << I.getType() << I.getSourceRange();
9090 return true;
9093 for (const auto *I : RD->fields()) {
9094 if (!I->getType()->isLiteralType(Context) ||
9095 I->getType().isVolatileQualified()) {
9096 Diag(I->getLocation(), diag::note_non_literal_field)
9097 << RD << I << I->getType()
9098 << I->getType().isVolatileQualified();
9099 return true;
9102 } else if (getLangOpts().CPlusPlus20 ? !RD->hasConstexprDestructor()
9103 : !RD->hasTrivialDestructor()) {
9104 // All fields and bases are of literal types, so have trivial or constexpr
9105 // destructors. If this class's destructor is non-trivial / non-constexpr,
9106 // it must be user-declared.
9107 CXXDestructorDecl *Dtor = RD->getDestructor();
9108 assert(Dtor && "class has literal fields and bases but no dtor?");
9109 if (!Dtor)
9110 return true;
9112 if (getLangOpts().CPlusPlus20) {
9113 Diag(Dtor->getLocation(), diag::note_non_literal_non_constexpr_dtor)
9114 << RD;
9115 } else {
9116 Diag(Dtor->getLocation(), Dtor->isUserProvided()
9117 ? diag::note_non_literal_user_provided_dtor
9118 : diag::note_non_literal_nontrivial_dtor)
9119 << RD;
9120 if (!Dtor->isUserProvided())
9121 SpecialMemberIsTrivial(Dtor, CXXDestructor, TAH_IgnoreTrivialABI,
9122 /*Diagnose*/ true);
9126 return true;
9129 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
9130 BoundTypeDiagnoser<> Diagnoser(DiagID);
9131 return RequireLiteralType(Loc, T, Diagnoser);
9134 /// Retrieve a version of the type 'T' that is elaborated by Keyword, qualified
9135 /// by the nested-name-specifier contained in SS, and that is (re)declared by
9136 /// OwnedTagDecl, which is nullptr if this is not a (re)declaration.
9137 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
9138 const CXXScopeSpec &SS, QualType T,
9139 TagDecl *OwnedTagDecl) {
9140 if (T.isNull())
9141 return T;
9142 return Context.getElaboratedType(
9143 Keyword, SS.isValid() ? SS.getScopeRep() : nullptr, T, OwnedTagDecl);
9146 QualType Sema::BuildTypeofExprType(Expr *E) {
9147 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9149 if (!getLangOpts().CPlusPlus && E->refersToBitField())
9150 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
9152 if (!E->isTypeDependent()) {
9153 QualType T = E->getType();
9154 if (const TagType *TT = T->getAs<TagType>())
9155 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
9157 return Context.getTypeOfExprType(E);
9160 /// getDecltypeForExpr - Given an expr, will return the decltype for
9161 /// that expression, according to the rules in C++11
9162 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
9163 QualType Sema::getDecltypeForExpr(Expr *E) {
9164 if (E->isTypeDependent())
9165 return Context.DependentTy;
9167 Expr *IDExpr = E;
9168 if (auto *ImplCastExpr = dyn_cast<ImplicitCastExpr>(E))
9169 IDExpr = ImplCastExpr->getSubExpr();
9171 // C++11 [dcl.type.simple]p4:
9172 // The type denoted by decltype(e) is defined as follows:
9174 // C++20:
9175 // - if E is an unparenthesized id-expression naming a non-type
9176 // template-parameter (13.2), decltype(E) is the type of the
9177 // template-parameter after performing any necessary type deduction
9178 // Note that this does not pick up the implicit 'const' for a template
9179 // parameter object. This rule makes no difference before C++20 so we apply
9180 // it unconditionally.
9181 if (const auto *SNTTPE = dyn_cast<SubstNonTypeTemplateParmExpr>(IDExpr))
9182 return SNTTPE->getParameterType(Context);
9184 // - if e is an unparenthesized id-expression or an unparenthesized class
9185 // member access (5.2.5), decltype(e) is the type of the entity named
9186 // by e. If there is no such entity, or if e names a set of overloaded
9187 // functions, the program is ill-formed;
9189 // We apply the same rules for Objective-C ivar and property references.
9190 if (const auto *DRE = dyn_cast<DeclRefExpr>(IDExpr)) {
9191 const ValueDecl *VD = DRE->getDecl();
9192 QualType T = VD->getType();
9193 return isa<TemplateParamObjectDecl>(VD) ? T.getUnqualifiedType() : T;
9195 if (const auto *ME = dyn_cast<MemberExpr>(IDExpr)) {
9196 if (const auto *VD = ME->getMemberDecl())
9197 if (isa<FieldDecl>(VD) || isa<VarDecl>(VD))
9198 return VD->getType();
9199 } else if (const auto *IR = dyn_cast<ObjCIvarRefExpr>(IDExpr)) {
9200 return IR->getDecl()->getType();
9201 } else if (const auto *PR = dyn_cast<ObjCPropertyRefExpr>(IDExpr)) {
9202 if (PR->isExplicitProperty())
9203 return PR->getExplicitProperty()->getType();
9204 } else if (const auto *PE = dyn_cast<PredefinedExpr>(IDExpr)) {
9205 return PE->getType();
9208 // C++11 [expr.lambda.prim]p18:
9209 // Every occurrence of decltype((x)) where x is a possibly
9210 // parenthesized id-expression that names an entity of automatic
9211 // storage duration is treated as if x were transformed into an
9212 // access to a corresponding data member of the closure type that
9213 // would have been declared if x were an odr-use of the denoted
9214 // entity.
9215 if (getCurLambda() && isa<ParenExpr>(IDExpr)) {
9216 if (auto *DRE = dyn_cast<DeclRefExpr>(IDExpr->IgnoreParens())) {
9217 if (auto *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
9218 QualType T = getCapturedDeclRefType(Var, DRE->getLocation());
9219 if (!T.isNull())
9220 return Context.getLValueReferenceType(T);
9225 return Context.getReferenceQualifiedType(E);
9228 QualType Sema::BuildDecltypeType(Expr *E, bool AsUnevaluated) {
9229 assert(!E->hasPlaceholderType() && "unexpected placeholder");
9231 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
9232 !E->isInstantiationDependent() && E->HasSideEffects(Context, false)) {
9233 // The expression operand for decltype is in an unevaluated expression
9234 // context, so side effects could result in unintended consequences.
9235 // Exclude instantiation-dependent expressions, because 'decltype' is often
9236 // used to build SFINAE gadgets.
9237 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
9239 return Context.getDecltypeType(E, getDecltypeForExpr(E));
9242 static QualType GetEnumUnderlyingType(Sema &S, QualType BaseType,
9243 SourceLocation Loc) {
9244 assert(BaseType->isEnumeralType());
9245 EnumDecl *ED = BaseType->castAs<EnumType>()->getDecl();
9246 assert(ED && "EnumType has no EnumDecl");
9248 S.DiagnoseUseOfDecl(ED, Loc);
9250 QualType Underlying = ED->getIntegerType();
9251 assert(!Underlying.isNull());
9253 return Underlying;
9256 QualType Sema::BuiltinEnumUnderlyingType(QualType BaseType,
9257 SourceLocation Loc) {
9258 if (!BaseType->isEnumeralType()) {
9259 Diag(Loc, diag::err_only_enums_have_underlying_types);
9260 return QualType();
9263 // The enum could be incomplete if we're parsing its definition or
9264 // recovering from an error.
9265 NamedDecl *FwdDecl = nullptr;
9266 if (BaseType->isIncompleteType(&FwdDecl)) {
9267 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
9268 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
9269 return QualType();
9272 return GetEnumUnderlyingType(*this, BaseType, Loc);
9275 QualType Sema::BuiltinAddPointer(QualType BaseType, SourceLocation Loc) {
9276 QualType Pointer = BaseType.isReferenceable() || BaseType->isVoidType()
9277 ? BuildPointerType(BaseType.getNonReferenceType(), Loc,
9278 DeclarationName())
9279 : BaseType;
9281 return Pointer.isNull() ? QualType() : Pointer;
9284 QualType Sema::BuiltinRemovePointer(QualType BaseType, SourceLocation Loc) {
9285 // We don't want block pointers or ObjectiveC's id type.
9286 if (!BaseType->isAnyPointerType() || BaseType->isObjCIdType())
9287 return BaseType;
9289 return BaseType->getPointeeType();
9292 QualType Sema::BuiltinDecay(QualType BaseType, SourceLocation Loc) {
9293 QualType Underlying = BaseType.getNonReferenceType();
9294 if (Underlying->isArrayType())
9295 return Context.getDecayedType(Underlying);
9297 if (Underlying->isFunctionType())
9298 return BuiltinAddPointer(BaseType, Loc);
9300 SplitQualType Split = Underlying.getSplitUnqualifiedType();
9301 // std::decay is supposed to produce 'std::remove_cv', but since 'restrict' is
9302 // in the same group of qualifiers as 'const' and 'volatile', we're extending
9303 // '__decay(T)' so that it removes all qualifiers.
9304 Split.Quals.removeCVRQualifiers();
9305 return Context.getQualifiedType(Split);
9308 QualType Sema::BuiltinAddReference(QualType BaseType, UTTKind UKind,
9309 SourceLocation Loc) {
9310 assert(LangOpts.CPlusPlus);
9311 QualType Reference =
9312 BaseType.isReferenceable()
9313 ? BuildReferenceType(BaseType,
9314 UKind == UnaryTransformType::AddLvalueReference,
9315 Loc, DeclarationName())
9316 : BaseType;
9317 return Reference.isNull() ? QualType() : Reference;
9320 QualType Sema::BuiltinRemoveExtent(QualType BaseType, UTTKind UKind,
9321 SourceLocation Loc) {
9322 if (UKind == UnaryTransformType::RemoveAllExtents)
9323 return Context.getBaseElementType(BaseType);
9325 if (const auto *AT = Context.getAsArrayType(BaseType))
9326 return AT->getElementType();
9328 return BaseType;
9331 QualType Sema::BuiltinRemoveReference(QualType BaseType, UTTKind UKind,
9332 SourceLocation Loc) {
9333 assert(LangOpts.CPlusPlus);
9334 QualType T = BaseType.getNonReferenceType();
9335 if (UKind == UTTKind::RemoveCVRef &&
9336 (T.isConstQualified() || T.isVolatileQualified())) {
9337 Qualifiers Quals;
9338 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
9339 Quals.removeConst();
9340 Quals.removeVolatile();
9341 T = Context.getQualifiedType(Unqual, Quals);
9343 return T;
9346 QualType Sema::BuiltinChangeCVRQualifiers(QualType BaseType, UTTKind UKind,
9347 SourceLocation Loc) {
9348 if ((BaseType->isReferenceType() && UKind != UTTKind::RemoveRestrict) ||
9349 BaseType->isFunctionType())
9350 return BaseType;
9352 Qualifiers Quals;
9353 QualType Unqual = Context.getUnqualifiedArrayType(BaseType, Quals);
9355 if (UKind == UTTKind::RemoveConst || UKind == UTTKind::RemoveCV)
9356 Quals.removeConst();
9357 if (UKind == UTTKind::RemoveVolatile || UKind == UTTKind::RemoveCV)
9358 Quals.removeVolatile();
9359 if (UKind == UTTKind::RemoveRestrict)
9360 Quals.removeRestrict();
9362 return Context.getQualifiedType(Unqual, Quals);
9365 static QualType ChangeIntegralSignedness(Sema &S, QualType BaseType,
9366 bool IsMakeSigned,
9367 SourceLocation Loc) {
9368 if (BaseType->isEnumeralType()) {
9369 QualType Underlying = GetEnumUnderlyingType(S, BaseType, Loc);
9370 if (auto *BitInt = dyn_cast<BitIntType>(Underlying)) {
9371 unsigned int Bits = BitInt->getNumBits();
9372 if (Bits > 1)
9373 return S.Context.getBitIntType(!IsMakeSigned, Bits);
9375 S.Diag(Loc, diag::err_make_signed_integral_only)
9376 << IsMakeSigned << /*_BitInt(1)*/ true << BaseType << 1 << Underlying;
9377 return QualType();
9379 if (Underlying->isBooleanType()) {
9380 S.Diag(Loc, diag::err_make_signed_integral_only)
9381 << IsMakeSigned << /*_BitInt(1)*/ false << BaseType << 1
9382 << Underlying;
9383 return QualType();
9387 bool Int128Unsupported = !S.Context.getTargetInfo().hasInt128Type();
9388 std::array<CanQualType *, 6> AllSignedIntegers = {
9389 &S.Context.SignedCharTy, &S.Context.ShortTy, &S.Context.IntTy,
9390 &S.Context.LongTy, &S.Context.LongLongTy, &S.Context.Int128Ty};
9391 ArrayRef<CanQualType *> AvailableSignedIntegers(
9392 AllSignedIntegers.data(), AllSignedIntegers.size() - Int128Unsupported);
9393 std::array<CanQualType *, 6> AllUnsignedIntegers = {
9394 &S.Context.UnsignedCharTy, &S.Context.UnsignedShortTy,
9395 &S.Context.UnsignedIntTy, &S.Context.UnsignedLongTy,
9396 &S.Context.UnsignedLongLongTy, &S.Context.UnsignedInt128Ty};
9397 ArrayRef<CanQualType *> AvailableUnsignedIntegers(AllUnsignedIntegers.data(),
9398 AllUnsignedIntegers.size() -
9399 Int128Unsupported);
9400 ArrayRef<CanQualType *> *Consider =
9401 IsMakeSigned ? &AvailableSignedIntegers : &AvailableUnsignedIntegers;
9403 uint64_t BaseSize = S.Context.getTypeSize(BaseType);
9404 auto *Result =
9405 llvm::find_if(*Consider, [&S, BaseSize](const CanQual<Type> *T) {
9406 return BaseSize == S.Context.getTypeSize(T->getTypePtr());
9409 assert(Result != Consider->end());
9410 return QualType((*Result)->getTypePtr(), 0);
9413 QualType Sema::BuiltinChangeSignedness(QualType BaseType, UTTKind UKind,
9414 SourceLocation Loc) {
9415 bool IsMakeSigned = UKind == UnaryTransformType::MakeSigned;
9416 if ((!BaseType->isIntegerType() && !BaseType->isEnumeralType()) ||
9417 BaseType->isBooleanType() ||
9418 (BaseType->isBitIntType() &&
9419 BaseType->getAs<BitIntType>()->getNumBits() < 2)) {
9420 Diag(Loc, diag::err_make_signed_integral_only)
9421 << IsMakeSigned << BaseType->isBitIntType() << BaseType << 0;
9422 return QualType();
9425 bool IsNonIntIntegral =
9426 BaseType->isChar16Type() || BaseType->isChar32Type() ||
9427 BaseType->isWideCharType() || BaseType->isEnumeralType();
9429 QualType Underlying =
9430 IsNonIntIntegral
9431 ? ChangeIntegralSignedness(*this, BaseType, IsMakeSigned, Loc)
9432 : IsMakeSigned ? Context.getCorrespondingSignedType(BaseType)
9433 : Context.getCorrespondingUnsignedType(BaseType);
9434 if (Underlying.isNull())
9435 return Underlying;
9436 return Context.getQualifiedType(Underlying, BaseType.getQualifiers());
9439 QualType Sema::BuildUnaryTransformType(QualType BaseType, UTTKind UKind,
9440 SourceLocation Loc) {
9441 if (BaseType->isDependentType())
9442 return Context.getUnaryTransformType(BaseType, BaseType, UKind);
9443 QualType Result;
9444 switch (UKind) {
9445 case UnaryTransformType::EnumUnderlyingType: {
9446 Result = BuiltinEnumUnderlyingType(BaseType, Loc);
9447 break;
9449 case UnaryTransformType::AddPointer: {
9450 Result = BuiltinAddPointer(BaseType, Loc);
9451 break;
9453 case UnaryTransformType::RemovePointer: {
9454 Result = BuiltinRemovePointer(BaseType, Loc);
9455 break;
9457 case UnaryTransformType::Decay: {
9458 Result = BuiltinDecay(BaseType, Loc);
9459 break;
9461 case UnaryTransformType::AddLvalueReference:
9462 case UnaryTransformType::AddRvalueReference: {
9463 Result = BuiltinAddReference(BaseType, UKind, Loc);
9464 break;
9466 case UnaryTransformType::RemoveAllExtents:
9467 case UnaryTransformType::RemoveExtent: {
9468 Result = BuiltinRemoveExtent(BaseType, UKind, Loc);
9469 break;
9471 case UnaryTransformType::RemoveCVRef:
9472 case UnaryTransformType::RemoveReference: {
9473 Result = BuiltinRemoveReference(BaseType, UKind, Loc);
9474 break;
9476 case UnaryTransformType::RemoveConst:
9477 case UnaryTransformType::RemoveCV:
9478 case UnaryTransformType::RemoveRestrict:
9479 case UnaryTransformType::RemoveVolatile: {
9480 Result = BuiltinChangeCVRQualifiers(BaseType, UKind, Loc);
9481 break;
9483 case UnaryTransformType::MakeSigned:
9484 case UnaryTransformType::MakeUnsigned: {
9485 Result = BuiltinChangeSignedness(BaseType, UKind, Loc);
9486 break;
9490 return !Result.isNull()
9491 ? Context.getUnaryTransformType(BaseType, Result, UKind)
9492 : Result;
9495 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
9496 if (!isDependentOrGNUAutoType(T)) {
9497 // FIXME: It isn't entirely clear whether incomplete atomic types
9498 // are allowed or not; for simplicity, ban them for the moment.
9499 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
9500 return QualType();
9502 int DisallowedKind = -1;
9503 if (T->isArrayType())
9504 DisallowedKind = 1;
9505 else if (T->isFunctionType())
9506 DisallowedKind = 2;
9507 else if (T->isReferenceType())
9508 DisallowedKind = 3;
9509 else if (T->isAtomicType())
9510 DisallowedKind = 4;
9511 else if (T.hasQualifiers())
9512 DisallowedKind = 5;
9513 else if (T->isSizelessType())
9514 DisallowedKind = 6;
9515 else if (!T.isTriviallyCopyableType(Context))
9516 // Some other non-trivially-copyable type (probably a C++ class)
9517 DisallowedKind = 7;
9518 else if (T->isBitIntType())
9519 DisallowedKind = 8;
9521 if (DisallowedKind != -1) {
9522 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
9523 return QualType();
9526 // FIXME: Do we need any handling for ARC here?
9529 // Build the pointer type.
9530 return Context.getAtomicType(T);