1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/ParseDiagnostic.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Template.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/Support/ErrorHandling.h"
39 using namespace clang;
41 enum TypeDiagSelector {
47 /// isOmittedBlockReturnType - Return true if this declarator is missing a
48 /// return type because this is a omitted return type on a block literal.
49 static bool isOmittedBlockReturnType(const Declarator &D) {
50 if (D.getContext() != Declarator::BlockLiteralContext ||
51 D.getDeclSpec().hasTypeSpecifier())
54 if (D.getNumTypeObjects() == 0)
55 return true; // ^{ ... }
57 if (D.getNumTypeObjects() == 1 &&
58 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
59 return true; // ^(int X, float Y) { ... }
64 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
65 /// doesn't apply to the given type.
66 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
68 TypeDiagSelector WhichType;
69 bool useExpansionLoc = true;
70 switch (attr.getKind()) {
71 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
72 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
74 // Assume everything else was a function attribute.
75 WhichType = TDS_Function;
76 useExpansionLoc = false;
80 SourceLocation loc = attr.getLoc();
81 StringRef name = attr.getName()->getName();
83 // The GC attributes are usually written with macros; special-case them.
84 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
86 if (useExpansionLoc && loc.isMacroID() && II) {
87 if (II->isStr("strong")) {
88 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
89 } else if (II->isStr("weak")) {
90 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
94 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
98 // objc_gc applies to Objective-C pointers or, otherwise, to the
99 // smallest available pointer type (i.e. 'void*' in 'void**').
100 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
101 case AttributeList::AT_ObjCGC: \
102 case AttributeList::AT_ObjCOwnership
104 // Function type attributes.
105 #define FUNCTION_TYPE_ATTRS_CASELIST \
106 case AttributeList::AT_NoReturn: \
107 case AttributeList::AT_CDecl: \
108 case AttributeList::AT_FastCall: \
109 case AttributeList::AT_StdCall: \
110 case AttributeList::AT_ThisCall: \
111 case AttributeList::AT_Pascal: \
112 case AttributeList::AT_VectorCall: \
113 case AttributeList::AT_MSABI: \
114 case AttributeList::AT_SysVABI: \
115 case AttributeList::AT_Regparm: \
116 case AttributeList::AT_Pcs: \
117 case AttributeList::AT_IntelOclBicc
119 // Microsoft-specific type qualifiers.
120 #define MS_TYPE_ATTRS_CASELIST \
121 case AttributeList::AT_Ptr32: \
122 case AttributeList::AT_Ptr64: \
123 case AttributeList::AT_SPtr: \
124 case AttributeList::AT_UPtr
126 // Nullability qualifiers.
127 #define NULLABILITY_TYPE_ATTRS_CASELIST \
128 case AttributeList::AT_TypeNonNull: \
129 case AttributeList::AT_TypeNullable: \
130 case AttributeList::AT_TypeNullUnspecified
133 /// An object which stores processing state for the entire
134 /// GetTypeForDeclarator process.
135 class TypeProcessingState {
138 /// The declarator being processed.
139 Declarator &declarator;
141 /// The index of the declarator chunk we're currently processing.
142 /// May be the total number of valid chunks, indicating the
146 /// Whether there are non-trivial modifications to the decl spec.
149 /// Whether we saved the attributes in the decl spec.
152 /// The original set of attributes on the DeclSpec.
153 SmallVector<AttributeList*, 2> savedAttrs;
155 /// A list of attributes to diagnose the uselessness of when the
156 /// processing is complete.
157 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
160 TypeProcessingState(Sema &sema, Declarator &declarator)
161 : sema(sema), declarator(declarator),
162 chunkIndex(declarator.getNumTypeObjects()),
163 trivial(true), hasSavedAttrs(false) {}
165 Sema &getSema() const {
169 Declarator &getDeclarator() const {
173 bool isProcessingDeclSpec() const {
174 return chunkIndex == declarator.getNumTypeObjects();
177 unsigned getCurrentChunkIndex() const {
181 void setCurrentChunkIndex(unsigned idx) {
182 assert(idx <= declarator.getNumTypeObjects());
186 AttributeList *&getCurrentAttrListRef() const {
187 if (isProcessingDeclSpec())
188 return getMutableDeclSpec().getAttributes().getListRef();
189 return declarator.getTypeObject(chunkIndex).getAttrListRef();
192 /// Save the current set of attributes on the DeclSpec.
193 void saveDeclSpecAttrs() {
194 // Don't try to save them multiple times.
195 if (hasSavedAttrs) return;
197 DeclSpec &spec = getMutableDeclSpec();
198 for (AttributeList *attr = spec.getAttributes().getList(); attr;
199 attr = attr->getNext())
200 savedAttrs.push_back(attr);
201 trivial &= savedAttrs.empty();
202 hasSavedAttrs = true;
205 /// Record that we had nowhere to put the given type attribute.
206 /// We will diagnose such attributes later.
207 void addIgnoredTypeAttr(AttributeList &attr) {
208 ignoredTypeAttrs.push_back(&attr);
211 /// Diagnose all the ignored type attributes, given that the
212 /// declarator worked out to the given type.
213 void diagnoseIgnoredTypeAttrs(QualType type) const {
214 for (SmallVectorImpl<AttributeList*>::const_iterator
215 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
217 diagnoseBadTypeAttribute(getSema(), **i, type);
220 ~TypeProcessingState() {
223 restoreDeclSpecAttrs();
227 DeclSpec &getMutableDeclSpec() const {
228 return const_cast<DeclSpec&>(declarator.getDeclSpec());
231 void restoreDeclSpecAttrs() {
232 assert(hasSavedAttrs);
234 if (savedAttrs.empty()) {
235 getMutableDeclSpec().getAttributes().set(nullptr);
239 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
240 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
241 savedAttrs[i]->setNext(savedAttrs[i+1]);
242 savedAttrs.back()->setNext(nullptr);
247 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
252 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
254 head = attr.getNext();
258 AttributeList *cur = head;
260 assert(cur && cur->getNext() && "ran out of attrs?");
261 if (cur->getNext() == &attr) {
262 cur->setNext(attr.getNext());
265 cur = cur->getNext();
269 static void moveAttrFromListToList(AttributeList &attr,
270 AttributeList *&fromList,
271 AttributeList *&toList) {
272 spliceAttrOutOfList(attr, fromList);
273 spliceAttrIntoList(attr, toList);
276 /// The location of a type attribute.
277 enum TypeAttrLocation {
278 /// The attribute is in the decl-specifier-seq.
280 /// The attribute is part of a DeclaratorChunk.
282 /// The attribute is immediately after the declaration's name.
286 static void processTypeAttrs(TypeProcessingState &state,
287 QualType &type, TypeAttrLocation TAL,
288 AttributeList *attrs);
290 static bool handleFunctionTypeAttr(TypeProcessingState &state,
294 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
298 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
299 AttributeList &attr, QualType &type);
301 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
302 AttributeList &attr, QualType &type);
304 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
305 AttributeList &attr, QualType &type) {
306 if (attr.getKind() == AttributeList::AT_ObjCGC)
307 return handleObjCGCTypeAttr(state, attr, type);
308 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
309 return handleObjCOwnershipTypeAttr(state, attr, type);
312 /// Given the index of a declarator chunk, check whether that chunk
313 /// directly specifies the return type of a function and, if so, find
314 /// an appropriate place for it.
316 /// \param i - a notional index which the search will start
317 /// immediately inside
319 /// \param onlyBlockPointers Whether we should only look into block
320 /// pointer types (vs. all pointer types).
321 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
323 bool onlyBlockPointers) {
324 assert(i <= declarator.getNumTypeObjects());
326 DeclaratorChunk *result = nullptr;
328 // First, look inwards past parens for a function declarator.
329 for (; i != 0; --i) {
330 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
331 switch (fnChunk.Kind) {
332 case DeclaratorChunk::Paren:
335 // If we find anything except a function, bail out.
336 case DeclaratorChunk::Pointer:
337 case DeclaratorChunk::BlockPointer:
338 case DeclaratorChunk::Array:
339 case DeclaratorChunk::Reference:
340 case DeclaratorChunk::MemberPointer:
343 // If we do find a function declarator, scan inwards from that,
344 // looking for a (block-)pointer declarator.
345 case DeclaratorChunk::Function:
346 for (--i; i != 0; --i) {
347 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
348 switch (ptrChunk.Kind) {
349 case DeclaratorChunk::Paren:
350 case DeclaratorChunk::Array:
351 case DeclaratorChunk::Function:
352 case DeclaratorChunk::Reference:
355 case DeclaratorChunk::MemberPointer:
356 case DeclaratorChunk::Pointer:
357 if (onlyBlockPointers)
362 case DeclaratorChunk::BlockPointer:
366 llvm_unreachable("bad declarator chunk kind");
369 // If we run out of declarators doing that, we're done.
372 llvm_unreachable("bad declarator chunk kind");
374 // Okay, reconsider from our new point.
378 // Ran out of chunks, bail out.
382 /// Given that an objc_gc attribute was written somewhere on a
383 /// declaration *other* than on the declarator itself (for which, use
384 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
385 /// didn't apply in whatever position it was written in, try to move
386 /// it to a more appropriate position.
387 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
390 Declarator &declarator = state.getDeclarator();
392 // Move it to the outermost normal or block pointer declarator.
393 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
394 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
395 switch (chunk.Kind) {
396 case DeclaratorChunk::Pointer:
397 case DeclaratorChunk::BlockPointer: {
398 // But don't move an ARC ownership attribute to the return type
400 DeclaratorChunk *destChunk = nullptr;
401 if (state.isProcessingDeclSpec() &&
402 attr.getKind() == AttributeList::AT_ObjCOwnership)
403 destChunk = maybeMovePastReturnType(declarator, i - 1,
404 /*onlyBlockPointers=*/true);
405 if (!destChunk) destChunk = &chunk;
407 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
408 destChunk->getAttrListRef());
412 case DeclaratorChunk::Paren:
413 case DeclaratorChunk::Array:
416 // We may be starting at the return type of a block.
417 case DeclaratorChunk::Function:
418 if (state.isProcessingDeclSpec() &&
419 attr.getKind() == AttributeList::AT_ObjCOwnership) {
420 if (DeclaratorChunk *dest = maybeMovePastReturnType(
422 /*onlyBlockPointers=*/true)) {
423 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
424 dest->getAttrListRef());
430 // Don't walk through these.
431 case DeclaratorChunk::Reference:
432 case DeclaratorChunk::MemberPointer:
438 diagnoseBadTypeAttribute(state.getSema(), attr, type);
441 /// Distribute an objc_gc type attribute that was written on the
444 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
446 QualType &declSpecType) {
447 Declarator &declarator = state.getDeclarator();
449 // objc_gc goes on the innermost pointer to something that's not a
451 unsigned innermost = -1U;
452 bool considerDeclSpec = true;
453 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
454 DeclaratorChunk &chunk = declarator.getTypeObject(i);
455 switch (chunk.Kind) {
456 case DeclaratorChunk::Pointer:
457 case DeclaratorChunk::BlockPointer:
461 case DeclaratorChunk::Reference:
462 case DeclaratorChunk::MemberPointer:
463 case DeclaratorChunk::Paren:
464 case DeclaratorChunk::Array:
467 case DeclaratorChunk::Function:
468 considerDeclSpec = false;
474 // That might actually be the decl spec if we weren't blocked by
475 // anything in the declarator.
476 if (considerDeclSpec) {
477 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
478 // Splice the attribute into the decl spec. Prevents the
479 // attribute from being applied multiple times and gives
480 // the source-location-filler something to work with.
481 state.saveDeclSpecAttrs();
482 moveAttrFromListToList(attr, declarator.getAttrListRef(),
483 declarator.getMutableDeclSpec().getAttributes().getListRef());
488 // Otherwise, if we found an appropriate chunk, splice the attribute
490 if (innermost != -1U) {
491 moveAttrFromListToList(attr, declarator.getAttrListRef(),
492 declarator.getTypeObject(innermost).getAttrListRef());
496 // Otherwise, diagnose when we're done building the type.
497 spliceAttrOutOfList(attr, declarator.getAttrListRef());
498 state.addIgnoredTypeAttr(attr);
501 /// A function type attribute was written somewhere in a declaration
502 /// *other* than on the declarator itself or in the decl spec. Given
503 /// that it didn't apply in whatever position it was written in, try
504 /// to move it to a more appropriate position.
505 static void distributeFunctionTypeAttr(TypeProcessingState &state,
508 Declarator &declarator = state.getDeclarator();
510 // Try to push the attribute from the return type of a function to
511 // the function itself.
512 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
513 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
514 switch (chunk.Kind) {
515 case DeclaratorChunk::Function:
516 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
517 chunk.getAttrListRef());
520 case DeclaratorChunk::Paren:
521 case DeclaratorChunk::Pointer:
522 case DeclaratorChunk::BlockPointer:
523 case DeclaratorChunk::Array:
524 case DeclaratorChunk::Reference:
525 case DeclaratorChunk::MemberPointer:
530 diagnoseBadTypeAttribute(state.getSema(), attr, type);
533 /// Try to distribute a function type attribute to the innermost
534 /// function chunk or type. Returns true if the attribute was
535 /// distributed, false if no location was found.
537 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
539 AttributeList *&attrList,
540 QualType &declSpecType) {
541 Declarator &declarator = state.getDeclarator();
543 // Put it on the innermost function chunk, if there is one.
544 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
545 DeclaratorChunk &chunk = declarator.getTypeObject(i);
546 if (chunk.Kind != DeclaratorChunk::Function) continue;
548 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
552 return handleFunctionTypeAttr(state, attr, declSpecType);
555 /// A function type attribute was written in the decl spec. Try to
556 /// apply it somewhere.
558 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
560 QualType &declSpecType) {
561 state.saveDeclSpecAttrs();
563 // C++11 attributes before the decl specifiers actually appertain to
564 // the declarators. Move them straight there. We don't support the
565 // 'put them wherever you like' semantics we allow for GNU attributes.
566 if (attr.isCXX11Attribute()) {
567 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
568 state.getDeclarator().getAttrListRef());
572 // Try to distribute to the innermost.
573 if (distributeFunctionTypeAttrToInnermost(state, attr,
574 state.getCurrentAttrListRef(),
578 // If that failed, diagnose the bad attribute when the declarator is
580 state.addIgnoredTypeAttr(attr);
583 /// A function type attribute was written on the declarator. Try to
584 /// apply it somewhere.
586 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
588 QualType &declSpecType) {
589 Declarator &declarator = state.getDeclarator();
591 // Try to distribute to the innermost.
592 if (distributeFunctionTypeAttrToInnermost(state, attr,
593 declarator.getAttrListRef(),
597 // If that failed, diagnose the bad attribute when the declarator is
599 spliceAttrOutOfList(attr, declarator.getAttrListRef());
600 state.addIgnoredTypeAttr(attr);
603 /// \brief Given that there are attributes written on the declarator
604 /// itself, try to distribute any type attributes to the appropriate
605 /// declarator chunk.
607 /// These are attributes like the following:
610 /// but not necessarily this:
612 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
613 QualType &declSpecType) {
614 // Collect all the type attributes from the declarator itself.
615 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
616 AttributeList *attr = state.getDeclarator().getAttributes();
619 next = attr->getNext();
621 // Do not distribute C++11 attributes. They have strict rules for what
622 // they appertain to.
623 if (attr->isCXX11Attribute())
626 switch (attr->getKind()) {
627 OBJC_POINTER_TYPE_ATTRS_CASELIST:
628 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
631 case AttributeList::AT_NSReturnsRetained:
632 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
636 FUNCTION_TYPE_ATTRS_CASELIST:
637 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
640 MS_TYPE_ATTRS_CASELIST:
641 // Microsoft type attributes cannot go after the declarator-id.
644 NULLABILITY_TYPE_ATTRS_CASELIST:
645 // Nullability specifiers cannot go after the declarator-id.
647 // Objective-C __kindof does not get distributed.
648 case AttributeList::AT_ObjCKindOf:
654 } while ((attr = next));
657 /// Add a synthetic '()' to a block-literal declarator if it is
658 /// required, given the return type.
659 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
660 QualType declSpecType) {
661 Declarator &declarator = state.getDeclarator();
663 // First, check whether the declarator would produce a function,
664 // i.e. whether the innermost semantic chunk is a function.
665 if (declarator.isFunctionDeclarator()) {
666 // If so, make that declarator a prototyped declarator.
667 declarator.getFunctionTypeInfo().hasPrototype = true;
671 // If there are any type objects, the type as written won't name a
672 // function, regardless of the decl spec type. This is because a
673 // block signature declarator is always an abstract-declarator, and
674 // abstract-declarators can't just be parentheses chunks. Therefore
675 // we need to build a function chunk unless there are no type
676 // objects and the decl spec type is a function.
677 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
680 // Note that there *are* cases with invalid declarators where
681 // declarators consist solely of parentheses. In general, these
682 // occur only in failed efforts to make function declarators, so
683 // faking up the function chunk is still the right thing to do.
685 // Otherwise, we need to fake up a function declarator.
686 SourceLocation loc = declarator.getLocStart();
688 // ...and *prepend* it to the declarator.
689 SourceLocation NoLoc;
690 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
692 /*IsAmbiguous=*/false,
696 /*EllipsisLoc=*/NoLoc,
699 /*RefQualifierIsLvalueRef=*/true,
700 /*RefQualifierLoc=*/NoLoc,
701 /*ConstQualifierLoc=*/NoLoc,
702 /*VolatileQualifierLoc=*/NoLoc,
703 /*RestrictQualifierLoc=*/NoLoc,
704 /*MutableLoc=*/NoLoc, EST_None,
706 /*Exceptions=*/nullptr,
707 /*ExceptionRanges=*/nullptr,
709 /*NoexceptExpr=*/nullptr,
710 /*ExceptionSpecTokens=*/nullptr,
711 loc, loc, declarator));
713 // For consistency, make sure the state still has us as processing
715 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
716 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
719 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
724 // If this occurs outside a template instantiation, warn the user about
725 // it; they probably didn't mean to specify a redundant qualifier.
726 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
727 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
728 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
729 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
730 if (!(RemoveTQs & Qual.first))
733 if (S.ActiveTemplateInstantiations.empty()) {
734 if (TypeQuals & Qual.first)
735 S.Diag(Qual.second, DiagID)
736 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
737 << FixItHint::CreateRemoval(Qual.second);
740 TypeQuals &= ~Qual.first;
744 /// Apply Objective-C type arguments to the given type.
745 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
746 ArrayRef<TypeSourceInfo *> typeArgs,
747 SourceRange typeArgsRange,
748 bool failOnError = false) {
749 // We can only apply type arguments to an Objective-C class type.
750 const auto *objcObjectType = type->getAs<ObjCObjectType>();
751 if (!objcObjectType || !objcObjectType->getInterface()) {
752 S.Diag(loc, diag::err_objc_type_args_non_class)
761 // The class type must be parameterized.
762 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
763 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
765 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
766 << objcClass->getDeclName()
767 << FixItHint::CreateRemoval(typeArgsRange);
775 // The type must not already be specialized.
776 if (objcObjectType->isSpecialized()) {
777 S.Diag(loc, diag::err_objc_type_args_specialized_class)
779 << FixItHint::CreateRemoval(typeArgsRange);
787 // Check the type arguments.
788 SmallVector<QualType, 4> finalTypeArgs;
789 unsigned numTypeParams = typeParams->size();
790 bool anyPackExpansions = false;
791 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
792 TypeSourceInfo *typeArgInfo = typeArgs[i];
793 QualType typeArg = typeArgInfo->getType();
795 // Type arguments cannot explicitly specify nullability.
796 if (auto nullability = AttributedType::stripOuterNullability(typeArg)) {
797 SourceLocation nullabilityLoc
798 = typeArgInfo->getTypeLoc().findNullabilityLoc();
799 SourceLocation diagLoc = nullabilityLoc.isValid()? nullabilityLoc
800 : typeArgInfo->getTypeLoc().getLocStart();
802 diag::err_type_arg_explicit_nullability)
804 << FixItHint::CreateRemoval(nullabilityLoc);
807 finalTypeArgs.push_back(typeArg);
809 if (typeArg->getAs<PackExpansionType>())
810 anyPackExpansions = true;
812 // Find the corresponding type parameter, if there is one.
813 ObjCTypeParamDecl *typeParam = nullptr;
814 if (!anyPackExpansions) {
815 if (i < numTypeParams) {
816 typeParam = typeParams->begin()[i];
818 // Too many arguments.
819 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
821 << objcClass->getDeclName()
822 << (unsigned)typeArgs.size()
824 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
834 // Objective-C object pointer types must be substitutable for the bounds.
835 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
836 // If we don't have a type parameter to match against, assume
837 // everything is fine. There was a prior pack expansion that
838 // means we won't be able to match anything.
840 assert(anyPackExpansions && "Too many arguments?");
844 // Retrieve the bound.
845 QualType bound = typeParam->getUnderlyingType();
846 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
848 // Determine whether the type argument is substitutable for the bound.
849 if (typeArgObjC->isObjCIdType()) {
850 // When the type argument is 'id', the only acceptable type
851 // parameter bound is 'id'.
852 if (boundObjC->isObjCIdType())
854 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
855 // Otherwise, we follow the assignability rules.
859 // Diagnose the mismatch.
860 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
861 diag::err_objc_type_arg_does_not_match_bound)
862 << typeArg << bound << typeParam->getDeclName();
863 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
864 << typeParam->getDeclName();
872 // Block pointer types are permitted for unqualified 'id' bounds.
873 if (typeArg->isBlockPointerType()) {
874 // If we don't have a type parameter to match against, assume
875 // everything is fine. There was a prior pack expansion that
876 // means we won't be able to match anything.
878 assert(anyPackExpansions && "Too many arguments?");
882 // Retrieve the bound.
883 QualType bound = typeParam->getUnderlyingType();
884 if (bound->isBlockCompatibleObjCPointerType(S.Context))
887 // Diagnose the mismatch.
888 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
889 diag::err_objc_type_arg_does_not_match_bound)
890 << typeArg << bound << typeParam->getDeclName();
891 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
892 << typeParam->getDeclName();
900 // Dependent types will be checked at instantiation time.
901 if (typeArg->isDependentType()) {
905 // Diagnose non-id-compatible type arguments.
906 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
907 diag::err_objc_type_arg_not_id_compatible)
909 << typeArgInfo->getTypeLoc().getSourceRange();
917 // Make sure we didn't have the wrong number of arguments.
918 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
919 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
920 << (typeArgs.size() < typeParams->size())
921 << objcClass->getDeclName()
922 << (unsigned)finalTypeArgs.size()
923 << (unsigned)numTypeParams;
924 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
933 // Success. Form the specialized type.
934 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
937 /// Apply Objective-C protocol qualifiers to the given type.
938 static QualType applyObjCProtocolQualifiers(
939 Sema &S, SourceLocation loc, SourceRange range, QualType type,
940 ArrayRef<ObjCProtocolDecl *> protocols,
941 const SourceLocation *protocolLocs,
942 bool failOnError = false) {
943 ASTContext &ctx = S.Context;
944 if (const ObjCObjectType *objT = dyn_cast<ObjCObjectType>(type.getTypePtr())){
945 // FIXME: Check for protocols to which the class type is already
948 return ctx.getObjCObjectType(objT->getBaseType(),
949 objT->getTypeArgsAsWritten(),
951 objT->isKindOfTypeAsWritten());
954 if (type->isObjCObjectType()) {
955 // Silently overwrite any existing protocol qualifiers.
956 // TODO: determine whether that's the right thing to do.
958 // FIXME: Check for protocols to which the class type is already
960 return ctx.getObjCObjectType(type, { }, protocols, false);
964 if (type->isObjCIdType()) {
965 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
966 type = ctx.getObjCObjectType(ctx.ObjCBuiltinIdTy, { }, protocols,
967 objPtr->isKindOfType());
968 return ctx.getObjCObjectPointerType(type);
971 // Class<protocol-list>
972 if (type->isObjCClassType()) {
973 const ObjCObjectPointerType *objPtr = type->castAs<ObjCObjectPointerType>();
974 type = ctx.getObjCObjectType(ctx.ObjCBuiltinClassTy, { }, protocols,
975 objPtr->isKindOfType());
976 return ctx.getObjCObjectPointerType(type);
979 S.Diag(loc, diag::err_invalid_protocol_qualifiers)
988 QualType Sema::BuildObjCObjectType(QualType BaseType,
990 SourceLocation TypeArgsLAngleLoc,
991 ArrayRef<TypeSourceInfo *> TypeArgs,
992 SourceLocation TypeArgsRAngleLoc,
993 SourceLocation ProtocolLAngleLoc,
994 ArrayRef<ObjCProtocolDecl *> Protocols,
995 ArrayRef<SourceLocation> ProtocolLocs,
996 SourceLocation ProtocolRAngleLoc,
998 QualType Result = BaseType;
999 if (!TypeArgs.empty()) {
1000 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1001 SourceRange(TypeArgsLAngleLoc,
1004 if (FailOnError && Result.isNull())
1008 if (!Protocols.empty()) {
1009 Result = applyObjCProtocolQualifiers(*this, Loc,
1010 SourceRange(ProtocolLAngleLoc,
1013 ProtocolLocs.data(),
1015 if (FailOnError && Result.isNull())
1022 TypeResult Sema::actOnObjCProtocolQualifierType(
1023 SourceLocation lAngleLoc,
1024 ArrayRef<Decl *> protocols,
1025 ArrayRef<SourceLocation> protocolLocs,
1026 SourceLocation rAngleLoc) {
1027 // Form id<protocol-list>.
1028 QualType Result = Context.getObjCObjectType(
1029 Context.ObjCBuiltinIdTy, { },
1031 (ObjCProtocolDecl * const *)protocols.data(),
1034 Result = Context.getObjCObjectPointerType(Result);
1036 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1037 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1039 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1040 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1042 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1043 .castAs<ObjCObjectTypeLoc>();
1044 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1045 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1047 // No type arguments.
1048 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1049 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1051 // Fill in protocol qualifiers.
1052 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1053 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1054 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1055 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1057 // We're done. Return the completed type to the parser.
1058 return CreateParsedType(Result, ResultTInfo);
1061 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1064 ParsedType BaseType,
1065 SourceLocation TypeArgsLAngleLoc,
1066 ArrayRef<ParsedType> TypeArgs,
1067 SourceLocation TypeArgsRAngleLoc,
1068 SourceLocation ProtocolLAngleLoc,
1069 ArrayRef<Decl *> Protocols,
1070 ArrayRef<SourceLocation> ProtocolLocs,
1071 SourceLocation ProtocolRAngleLoc) {
1072 TypeSourceInfo *BaseTypeInfo = nullptr;
1073 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1077 // Handle missing type-source info.
1079 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1081 // Extract type arguments.
1082 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1083 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1084 TypeSourceInfo *TypeArgInfo = nullptr;
1085 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1086 if (TypeArg.isNull()) {
1087 ActualTypeArgInfos.clear();
1091 assert(TypeArgInfo && "No type source info?");
1092 ActualTypeArgInfos.push_back(TypeArgInfo);
1095 // Build the object type.
1096 QualType Result = BuildObjCObjectType(
1097 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1098 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1100 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1102 ProtocolLocs, ProtocolRAngleLoc,
1103 /*FailOnError=*/false);
1108 // Create source information for this type.
1109 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1110 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1112 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1113 // object pointer type. Fill in source information for it.
1114 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1115 // The '*' is implicit.
1116 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1117 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1120 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1122 // Type argument information.
1123 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1124 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1125 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1126 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1127 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1128 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1130 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1131 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1134 // Protocol qualifier information.
1135 if (ObjCObjectTL.getNumProtocols() > 0) {
1136 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1137 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1138 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1139 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1140 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1142 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1143 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1147 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1148 if (ObjCObjectTL.getType() == T)
1149 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1151 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1153 // We're done. Return the completed type to the parser.
1154 return CreateParsedType(Result, ResultTInfo);
1157 /// \brief Convert the specified declspec to the appropriate type
1159 /// \param state Specifies the declarator containing the declaration specifier
1160 /// to be converted, along with other associated processing state.
1161 /// \returns The type described by the declaration specifiers. This function
1162 /// never returns null.
1163 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1164 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1167 Sema &S = state.getSema();
1168 Declarator &declarator = state.getDeclarator();
1169 const DeclSpec &DS = declarator.getDeclSpec();
1170 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1171 if (DeclLoc.isInvalid())
1172 DeclLoc = DS.getLocStart();
1174 ASTContext &Context = S.Context;
1177 switch (DS.getTypeSpecType()) {
1178 case DeclSpec::TST_void:
1179 Result = Context.VoidTy;
1181 case DeclSpec::TST_char:
1182 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1183 Result = Context.CharTy;
1184 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1185 Result = Context.SignedCharTy;
1187 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1188 "Unknown TSS value");
1189 Result = Context.UnsignedCharTy;
1192 case DeclSpec::TST_wchar:
1193 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1194 Result = Context.WCharTy;
1195 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1196 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1197 << DS.getSpecifierName(DS.getTypeSpecType(),
1198 Context.getPrintingPolicy());
1199 Result = Context.getSignedWCharType();
1201 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1202 "Unknown TSS value");
1203 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1204 << DS.getSpecifierName(DS.getTypeSpecType(),
1205 Context.getPrintingPolicy());
1206 Result = Context.getUnsignedWCharType();
1209 case DeclSpec::TST_char16:
1210 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1211 "Unknown TSS value");
1212 Result = Context.Char16Ty;
1214 case DeclSpec::TST_char32:
1215 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1216 "Unknown TSS value");
1217 Result = Context.Char32Ty;
1219 case DeclSpec::TST_unspecified:
1220 // If this is a missing declspec in a block literal return context, then it
1221 // is inferred from the return statements inside the block.
1222 // The declspec is always missing in a lambda expr context; it is either
1223 // specified with a trailing return type or inferred.
1224 if (S.getLangOpts().CPlusPlus14 &&
1225 declarator.getContext() == Declarator::LambdaExprContext) {
1226 // In C++1y, a lambda's implicit return type is 'auto'.
1227 Result = Context.getAutoDeductType();
1229 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1230 isOmittedBlockReturnType(declarator)) {
1231 Result = Context.DependentTy;
1235 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1236 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1237 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1238 // Note that the one exception to this is function definitions, which are
1239 // allowed to be completely missing a declspec. This is handled in the
1240 // parser already though by it pretending to have seen an 'int' in this
1242 if (S.getLangOpts().ImplicitInt) {
1243 // In C89 mode, we only warn if there is a completely missing declspec
1244 // when one is not allowed.
1246 S.Diag(DeclLoc, diag::ext_missing_declspec)
1247 << DS.getSourceRange()
1248 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1250 } else if (!DS.hasTypeSpecifier()) {
1251 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1252 // "At least one type specifier shall be given in the declaration
1253 // specifiers in each declaration, and in the specifier-qualifier list in
1254 // each struct declaration and type name."
1255 if (S.getLangOpts().CPlusPlus) {
1256 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1257 << DS.getSourceRange();
1259 // When this occurs in C++ code, often something is very broken with the
1260 // value being declared, poison it as invalid so we don't get chains of
1262 declarator.setInvalidType(true);
1264 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1265 << DS.getSourceRange();
1270 case DeclSpec::TST_int: {
1271 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1272 switch (DS.getTypeSpecWidth()) {
1273 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1274 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1275 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1276 case DeclSpec::TSW_longlong:
1277 Result = Context.LongLongTy;
1279 // 'long long' is a C99 or C++11 feature.
1280 if (!S.getLangOpts().C99) {
1281 if (S.getLangOpts().CPlusPlus)
1282 S.Diag(DS.getTypeSpecWidthLoc(),
1283 S.getLangOpts().CPlusPlus11 ?
1284 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1286 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1291 switch (DS.getTypeSpecWidth()) {
1292 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1293 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1294 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1295 case DeclSpec::TSW_longlong:
1296 Result = Context.UnsignedLongLongTy;
1298 // 'long long' is a C99 or C++11 feature.
1299 if (!S.getLangOpts().C99) {
1300 if (S.getLangOpts().CPlusPlus)
1301 S.Diag(DS.getTypeSpecWidthLoc(),
1302 S.getLangOpts().CPlusPlus11 ?
1303 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1305 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1312 case DeclSpec::TST_int128:
1313 if (!S.Context.getTargetInfo().hasInt128Type())
1314 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
1315 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1316 Result = Context.UnsignedInt128Ty;
1318 Result = Context.Int128Ty;
1320 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1321 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1322 case DeclSpec::TST_double:
1323 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1324 Result = Context.LongDoubleTy;
1326 Result = Context.DoubleTy;
1328 if (S.getLangOpts().OpenCL &&
1329 !((S.getLangOpts().OpenCLVersion >= 120) ||
1330 S.getOpenCLOptions().cl_khr_fp64)) {
1331 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1332 << Result << "cl_khr_fp64";
1333 declarator.setInvalidType(true);
1336 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1337 case DeclSpec::TST_decimal32: // _Decimal32
1338 case DeclSpec::TST_decimal64: // _Decimal64
1339 case DeclSpec::TST_decimal128: // _Decimal128
1340 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1341 Result = Context.IntTy;
1342 declarator.setInvalidType(true);
1344 case DeclSpec::TST_class:
1345 case DeclSpec::TST_enum:
1346 case DeclSpec::TST_union:
1347 case DeclSpec::TST_struct:
1348 case DeclSpec::TST_interface: {
1349 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1351 // This can happen in C++ with ambiguous lookups.
1352 Result = Context.IntTy;
1353 declarator.setInvalidType(true);
1357 // If the type is deprecated or unavailable, diagnose it.
1358 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1360 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1361 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1363 // TypeQuals handled by caller.
1364 Result = Context.getTypeDeclType(D);
1366 // In both C and C++, make an ElaboratedType.
1367 ElaboratedTypeKeyword Keyword
1368 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1369 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1372 case DeclSpec::TST_typename: {
1373 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1374 DS.getTypeSpecSign() == 0 &&
1375 "Can't handle qualifiers on typedef names yet!");
1376 Result = S.GetTypeFromParser(DS.getRepAsType());
1377 if (Result.isNull()) {
1378 declarator.setInvalidType(true);
1379 } else if (S.getLangOpts().OpenCL) {
1380 if (const AtomicType *AT = Result->getAs<AtomicType>()) {
1381 const BuiltinType *BT = AT->getValueType()->getAs<BuiltinType>();
1382 bool NoExtTypes = BT && (BT->getKind() == BuiltinType::Int ||
1383 BT->getKind() == BuiltinType::UInt ||
1384 BT->getKind() == BuiltinType::Float);
1385 if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1386 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1387 << Result << "cl_khr_int64_base_atomics";
1388 declarator.setInvalidType(true);
1390 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1392 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1393 << Result << "cl_khr_int64_extended_atomics";
1394 declarator.setInvalidType(true);
1396 if (!S.getOpenCLOptions().cl_khr_fp64 && BT &&
1397 BT->getKind() == BuiltinType::Double) {
1398 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1399 << Result << "cl_khr_fp64";
1400 declarator.setInvalidType(true);
1405 // TypeQuals handled by caller.
1408 case DeclSpec::TST_typeofType:
1409 // FIXME: Preserve type source info.
1410 Result = S.GetTypeFromParser(DS.getRepAsType());
1411 assert(!Result.isNull() && "Didn't get a type for typeof?");
1412 if (!Result->isDependentType())
1413 if (const TagType *TT = Result->getAs<TagType>())
1414 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1415 // TypeQuals handled by caller.
1416 Result = Context.getTypeOfType(Result);
1418 case DeclSpec::TST_typeofExpr: {
1419 Expr *E = DS.getRepAsExpr();
1420 assert(E && "Didn't get an expression for typeof?");
1421 // TypeQuals handled by caller.
1422 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1423 if (Result.isNull()) {
1424 Result = Context.IntTy;
1425 declarator.setInvalidType(true);
1429 case DeclSpec::TST_decltype: {
1430 Expr *E = DS.getRepAsExpr();
1431 assert(E && "Didn't get an expression for decltype?");
1432 // TypeQuals handled by caller.
1433 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1434 if (Result.isNull()) {
1435 Result = Context.IntTy;
1436 declarator.setInvalidType(true);
1440 case DeclSpec::TST_underlyingType:
1441 Result = S.GetTypeFromParser(DS.getRepAsType());
1442 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1443 Result = S.BuildUnaryTransformType(Result,
1444 UnaryTransformType::EnumUnderlyingType,
1445 DS.getTypeSpecTypeLoc());
1446 if (Result.isNull()) {
1447 Result = Context.IntTy;
1448 declarator.setInvalidType(true);
1452 case DeclSpec::TST_auto:
1453 // TypeQuals handled by caller.
1454 // If auto is mentioned in a lambda parameter context, convert it to a
1455 // template parameter type immediately, with the appropriate depth and
1456 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1457 // being analyzed (which tracks the invented type template parameter).
1458 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1459 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1460 assert(LSI && "No LambdaScopeInfo on the stack!");
1461 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1462 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1463 const bool IsParameterPack = declarator.hasEllipsis();
1465 // Turns out we must create the TemplateTypeParmDecl here to
1466 // retrieve the corresponding template parameter type.
1467 TemplateTypeParmDecl *CorrespondingTemplateParam =
1468 TemplateTypeParmDecl::Create(Context,
1469 // Temporarily add to the TranslationUnit DeclContext. When the
1470 // associated TemplateParameterList is attached to a template
1471 // declaration (such as FunctionTemplateDecl), the DeclContext
1472 // for each template parameter gets updated appropriately via
1473 // a call to AdoptTemplateParameterList.
1474 Context.getTranslationUnitDecl(),
1475 /*KeyLoc*/ SourceLocation(),
1476 /*NameLoc*/ declarator.getLocStart(),
1477 TemplateParameterDepth,
1478 AutoParameterPosition, // our template param index
1479 /* Identifier*/ nullptr, false, IsParameterPack);
1480 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1481 // Replace the 'auto' in the function parameter with this invented
1482 // template type parameter.
1483 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1485 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1489 case DeclSpec::TST_decltype_auto:
1490 Result = Context.getAutoType(QualType(),
1491 /*decltype(auto)*/true,
1492 /*IsDependent*/ false);
1495 case DeclSpec::TST_unknown_anytype:
1496 Result = Context.UnknownAnyTy;
1499 case DeclSpec::TST_atomic:
1500 Result = S.GetTypeFromParser(DS.getRepAsType());
1501 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1502 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1503 if (Result.isNull()) {
1504 Result = Context.IntTy;
1505 declarator.setInvalidType(true);
1509 case DeclSpec::TST_error:
1510 Result = Context.IntTy;
1511 declarator.setInvalidType(true);
1515 // Handle complex types.
1516 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1517 if (S.getLangOpts().Freestanding)
1518 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1519 Result = Context.getComplexType(Result);
1520 } else if (DS.isTypeAltiVecVector()) {
1521 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1522 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1523 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1524 if (DS.isTypeAltiVecPixel())
1525 VecKind = VectorType::AltiVecPixel;
1526 else if (DS.isTypeAltiVecBool())
1527 VecKind = VectorType::AltiVecBool;
1528 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1531 // FIXME: Imaginary.
1532 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1533 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1535 // Before we process any type attributes, synthesize a block literal
1536 // function declarator if necessary.
1537 if (declarator.getContext() == Declarator::BlockLiteralContext)
1538 maybeSynthesizeBlockSignature(state, Result);
1540 // Apply any type attributes from the decl spec. This may cause the
1541 // list of type attributes to be temporarily saved while the type
1542 // attributes are pushed around.
1543 if (AttributeList *attrs = DS.getAttributes().getList())
1544 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1546 // Apply const/volatile/restrict qualifiers to T.
1547 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1548 // Warn about CV qualifiers on function types.
1550 // If the specification of a function type includes any type qualifiers,
1551 // the behavior is undefined.
1552 // C++11 [dcl.fct]p7:
1553 // The effect of a cv-qualifier-seq in a function declarator is not the
1554 // same as adding cv-qualification on top of the function type. In the
1555 // latter case, the cv-qualifiers are ignored.
1556 if (TypeQuals && Result->isFunctionType()) {
1557 diagnoseAndRemoveTypeQualifiers(
1558 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1559 S.getLangOpts().CPlusPlus
1560 ? diag::warn_typecheck_function_qualifiers_ignored
1561 : diag::warn_typecheck_function_qualifiers_unspecified);
1562 // No diagnostic for 'restrict' or '_Atomic' applied to a
1563 // function type; we'll diagnose those later, in BuildQualifiedType.
1566 // C++11 [dcl.ref]p1:
1567 // Cv-qualified references are ill-formed except when the
1568 // cv-qualifiers are introduced through the use of a typedef-name
1569 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1571 // There don't appear to be any other contexts in which a cv-qualified
1572 // reference type could be formed, so the 'ill-formed' clause here appears
1574 if (TypeQuals && Result->isReferenceType()) {
1575 diagnoseAndRemoveTypeQualifiers(
1576 S, DS, TypeQuals, Result,
1577 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1578 diag::warn_typecheck_reference_qualifiers);
1581 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1582 // than once in the same specifier-list or qualifier-list, either directly
1583 // or via one or more typedefs."
1584 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1585 && TypeQuals & Result.getCVRQualifiers()) {
1586 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1587 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1591 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1592 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1596 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1597 // produce a warning in this case.
1600 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1602 // If adding qualifiers fails, just use the unqualified type.
1603 if (Qualified.isNull())
1604 declarator.setInvalidType(true);
1609 assert(!Result.isNull() && "This function should not return a null type");
1613 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1615 return Entity.getAsString();
1620 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1621 Qualifiers Qs, const DeclSpec *DS) {
1625 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1626 // object or incomplete types shall not be restrict-qualified."
1627 if (Qs.hasRestrict()) {
1628 unsigned DiagID = 0;
1631 if (T->isAnyPointerType() || T->isReferenceType() ||
1632 T->isMemberPointerType()) {
1634 if (T->isObjCObjectPointerType())
1636 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1637 EltTy = PTy->getPointeeType();
1639 EltTy = T->getPointeeType();
1641 // If we have a pointer or reference, the pointee must have an object
1643 if (!EltTy->isIncompleteOrObjectType()) {
1644 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1647 } else if (!T->isDependentType()) {
1648 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1653 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1654 Qs.removeRestrict();
1658 return Context.getQualifiedType(T, Qs);
1661 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1662 unsigned CVRA, const DeclSpec *DS) {
1666 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1667 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1670 // If the same qualifier appears more than once in the same
1671 // specifier-qualifier-list, either directly or via one or more typedefs,
1672 // the behavior is the same as if it appeared only once.
1674 // It's not specified what happens when the _Atomic qualifier is applied to
1675 // a type specified with the _Atomic specifier, but we assume that this
1676 // should be treated as if the _Atomic qualifier appeared multiple times.
1677 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1679 // If other qualifiers appear along with the _Atomic qualifier in a
1680 // specifier-qualifier-list, the resulting type is the so-qualified
1683 // Don't need to worry about array types here, since _Atomic can't be
1684 // applied to such types.
1685 SplitQualType Split = T.getSplitUnqualifiedType();
1686 T = BuildAtomicType(QualType(Split.Ty, 0),
1687 DS ? DS->getAtomicSpecLoc() : Loc);
1690 Split.Quals.addCVRQualifiers(CVR);
1691 return BuildQualifiedType(T, Loc, Split.Quals);
1694 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1697 /// \brief Build a paren type including \p T.
1698 QualType Sema::BuildParenType(QualType T) {
1699 return Context.getParenType(T);
1702 /// Given that we're building a pointer or reference to the given
1703 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1706 // Bail out if retention is unrequired or already specified.
1707 if (!type->isObjCLifetimeType() ||
1708 type.getObjCLifetime() != Qualifiers::OCL_None)
1711 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1713 // If the object type is const-qualified, we can safely use
1714 // __unsafe_unretained. This is safe (because there are no read
1715 // barriers), and it'll be safe to coerce anything but __weak* to
1716 // the resulting type.
1717 if (type.isConstQualified()) {
1718 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1720 // Otherwise, check whether the static type does not require
1721 // retaining. This currently only triggers for Class (possibly
1722 // protocol-qualifed, and arrays thereof).
1723 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1724 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1726 // If we are in an unevaluated context, like sizeof, skip adding a
1728 } else if (S.isUnevaluatedContext()) {
1731 // If that failed, give an error and recover using __strong. __strong
1732 // is the option most likely to prevent spurious second-order diagnostics,
1733 // like when binding a reference to a field.
1735 // These types can show up in private ivars in system headers, so
1736 // we need this to not be an error in those cases. Instead we
1738 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1739 S.DelayedDiagnostics.add(
1740 sema::DelayedDiagnostic::makeForbiddenType(loc,
1741 diag::err_arc_indirect_no_ownership, type, isReference));
1743 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1745 implicitLifetime = Qualifiers::OCL_Strong;
1747 assert(implicitLifetime && "didn't infer any lifetime!");
1750 qs.addObjCLifetime(implicitLifetime);
1751 return S.Context.getQualifiedType(type, qs);
1754 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1756 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1758 switch (FnTy->getRefQualifier()) {
1779 /// Kinds of declarator that cannot contain a qualified function type.
1781 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1782 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1783 /// at the topmost level of a type.
1785 /// Parens and member pointers are permitted. We don't diagnose array and
1786 /// function declarators, because they don't allow function types at all.
1788 /// The values of this enum are used in diagnostics.
1789 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1792 /// Check whether the type T is a qualified function type, and if it is,
1793 /// diagnose that it cannot be contained within the given kind of declarator.
1794 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1795 QualifiedFunctionKind QFK) {
1796 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1797 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1798 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1801 S.Diag(Loc, diag::err_compound_qualified_function_type)
1802 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1803 << getFunctionQualifiersAsString(FPT);
1807 /// \brief Build a pointer type.
1809 /// \param T The type to which we'll be building a pointer.
1811 /// \param Loc The location of the entity whose type involves this
1812 /// pointer type or, if there is no such entity, the location of the
1813 /// type that will have pointer type.
1815 /// \param Entity The name of the entity that involves the pointer
1818 /// \returns A suitable pointer type, if there are no
1819 /// errors. Otherwise, returns a NULL type.
1820 QualType Sema::BuildPointerType(QualType T,
1821 SourceLocation Loc, DeclarationName Entity) {
1822 if (T->isReferenceType()) {
1823 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1824 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1825 << getPrintableNameForEntity(Entity) << T;
1829 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1832 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1834 // In ARC, it is forbidden to build pointers to unqualified pointers.
1835 if (getLangOpts().ObjCAutoRefCount)
1836 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1838 // Build the pointer type.
1839 return Context.getPointerType(T);
1842 /// \brief Build a reference type.
1844 /// \param T The type to which we'll be building a reference.
1846 /// \param Loc The location of the entity whose type involves this
1847 /// reference type or, if there is no such entity, the location of the
1848 /// type that will have reference type.
1850 /// \param Entity The name of the entity that involves the reference
1853 /// \returns A suitable reference type, if there are no
1854 /// errors. Otherwise, returns a NULL type.
1855 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1857 DeclarationName Entity) {
1858 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1859 "Unresolved overloaded function type");
1861 // C++0x [dcl.ref]p6:
1862 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1863 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1864 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1865 // the type "lvalue reference to T", while an attempt to create the type
1866 // "rvalue reference to cv TR" creates the type TR.
1867 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1869 // C++ [dcl.ref]p4: There shall be no references to references.
1871 // According to C++ DR 106, references to references are only
1872 // diagnosed when they are written directly (e.g., "int & &"),
1873 // but not when they happen via a typedef:
1875 // typedef int& intref;
1876 // typedef intref& intref2;
1878 // Parser::ParseDeclaratorInternal diagnoses the case where
1879 // references are written directly; here, we handle the
1880 // collapsing of references-to-references as described in C++0x.
1881 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1884 // A declarator that specifies the type "reference to cv void"
1886 if (T->isVoidType()) {
1887 Diag(Loc, diag::err_reference_to_void);
1891 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1894 // In ARC, it is forbidden to build references to unqualified pointers.
1895 if (getLangOpts().ObjCAutoRefCount)
1896 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1898 // Handle restrict on references.
1900 return Context.getLValueReferenceType(T, SpelledAsLValue);
1901 return Context.getRValueReferenceType(T);
1904 /// Check whether the specified array size makes the array type a VLA. If so,
1905 /// return true, if not, return the size of the array in SizeVal.
1906 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1907 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1908 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1909 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1911 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1913 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1916 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1917 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1921 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1922 S.LangOpts.GNUMode).isInvalid();
1926 /// \brief Build an array type.
1928 /// \param T The type of each element in the array.
1930 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1932 /// \param ArraySize Expression describing the size of the array.
1934 /// \param Brackets The range from the opening '[' to the closing ']'.
1936 /// \param Entity The name of the entity that involves the array
1939 /// \returns A suitable array type, if there are no errors. Otherwise,
1940 /// returns a NULL type.
1941 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1942 Expr *ArraySize, unsigned Quals,
1943 SourceRange Brackets, DeclarationName Entity) {
1945 SourceLocation Loc = Brackets.getBegin();
1946 if (getLangOpts().CPlusPlus) {
1947 // C++ [dcl.array]p1:
1948 // T is called the array element type; this type shall not be a reference
1949 // type, the (possibly cv-qualified) type void, a function type or an
1950 // abstract class type.
1952 // C++ [dcl.array]p3:
1953 // When several "array of" specifications are adjacent, [...] only the
1954 // first of the constant expressions that specify the bounds of the arrays
1957 // Note: function types are handled in the common path with C.
1958 if (T->isReferenceType()) {
1959 Diag(Loc, diag::err_illegal_decl_array_of_references)
1960 << getPrintableNameForEntity(Entity) << T;
1964 if (T->isVoidType() || T->isIncompleteArrayType()) {
1965 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1969 if (RequireNonAbstractType(Brackets.getBegin(), T,
1970 diag::err_array_of_abstract_type))
1973 // Mentioning a member pointer type for an array type causes us to lock in
1974 // an inheritance model, even if it's inside an unused typedef.
1975 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1976 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1977 if (!MPTy->getClass()->isDependentType())
1978 RequireCompleteType(Loc, T, 0);
1981 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1982 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1983 if (RequireCompleteType(Loc, T,
1984 diag::err_illegal_decl_array_incomplete_type))
1988 if (T->isFunctionType()) {
1989 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1990 << getPrintableNameForEntity(Entity) << T;
1994 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1995 // If the element type is a struct or union that contains a variadic
1996 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1997 if (EltTy->getDecl()->hasFlexibleArrayMember())
1998 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1999 } else if (T->isObjCObjectType()) {
2000 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2004 // Do placeholder conversions on the array size expression.
2005 if (ArraySize && ArraySize->hasPlaceholderType()) {
2006 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2007 if (Result.isInvalid()) return QualType();
2008 ArraySize = Result.get();
2011 // Do lvalue-to-rvalue conversions on the array size expression.
2012 if (ArraySize && !ArraySize->isRValue()) {
2013 ExprResult Result = DefaultLvalueConversion(ArraySize);
2014 if (Result.isInvalid())
2017 ArraySize = Result.get();
2020 // C99 6.7.5.2p1: The size expression shall have integer type.
2021 // C++11 allows contextual conversions to such types.
2022 if (!getLangOpts().CPlusPlus11 &&
2023 ArraySize && !ArraySize->isTypeDependent() &&
2024 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2025 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2026 << ArraySize->getType() << ArraySize->getSourceRange();
2030 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2032 if (ASM == ArrayType::Star)
2033 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2035 T = Context.getIncompleteArrayType(T, ASM, Quals);
2036 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2037 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2038 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2039 !T->isConstantSizeType()) ||
2040 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2041 // Even in C++11, don't allow contextual conversions in the array bound
2043 if (getLangOpts().CPlusPlus11 &&
2044 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2045 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2046 << ArraySize->getType() << ArraySize->getSourceRange();
2050 // C99: an array with an element type that has a non-constant-size is a VLA.
2051 // C99: an array with a non-ICE size is a VLA. We accept any expression
2052 // that we can fold to a non-zero positive value as an extension.
2053 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2055 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2056 // have a value greater than zero.
2057 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2059 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2060 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2062 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2063 << ArraySize->getSourceRange();
2066 if (ConstVal == 0) {
2067 // GCC accepts zero sized static arrays. We allow them when
2068 // we're not in a SFINAE context.
2069 Diag(ArraySize->getLocStart(),
2070 isSFINAEContext()? diag::err_typecheck_zero_array_size
2071 : diag::ext_typecheck_zero_array_size)
2072 << ArraySize->getSourceRange();
2074 if (ASM == ArrayType::Static) {
2075 Diag(ArraySize->getLocStart(),
2076 diag::warn_typecheck_zero_static_array_size)
2077 << ArraySize->getSourceRange();
2078 ASM = ArrayType::Normal;
2080 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2081 !T->isIncompleteType() && !T->isUndeducedType()) {
2082 // Is the array too large?
2083 unsigned ActiveSizeBits
2084 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2085 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2086 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2087 << ConstVal.toString(10)
2088 << ArraySize->getSourceRange();
2093 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2096 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2097 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2098 Diag(Loc, diag::err_opencl_vla);
2101 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2102 if (!getLangOpts().C99) {
2103 if (T->isVariableArrayType()) {
2104 // Prohibit the use of non-POD types in VLAs.
2105 QualType BaseT = Context.getBaseElementType(T);
2106 if (!T->isDependentType() &&
2107 !RequireCompleteType(Loc, BaseT, 0) &&
2108 !BaseT.isPODType(Context) &&
2109 !BaseT->isObjCLifetimeType()) {
2110 Diag(Loc, diag::err_vla_non_pod)
2114 // Prohibit the use of VLAs during template argument deduction.
2115 else if (isSFINAEContext()) {
2116 Diag(Loc, diag::err_vla_in_sfinae);
2119 // Just extwarn about VLAs.
2121 Diag(Loc, diag::ext_vla);
2122 } else if (ASM != ArrayType::Normal || Quals != 0)
2124 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2125 : diag::ext_c99_array_usage) << ASM;
2128 if (T->isVariableArrayType()) {
2129 // Warn about VLAs for -Wvla.
2130 Diag(Loc, diag::warn_vla_used);
2136 /// \brief Build an ext-vector type.
2138 /// Run the required checks for the extended vector type.
2139 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2140 SourceLocation AttrLoc) {
2141 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
2142 // in conjunction with complex types (pointers, arrays, functions, etc.).
2143 if (!T->isDependentType() &&
2144 !T->isIntegerType() && !T->isRealFloatingType()) {
2145 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2149 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2150 llvm::APSInt vecSize(32);
2151 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2152 Diag(AttrLoc, diag::err_attribute_argument_type)
2153 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2154 << ArraySize->getSourceRange();
2158 // unlike gcc's vector_size attribute, the size is specified as the
2159 // number of elements, not the number of bytes.
2160 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2162 if (vectorSize == 0) {
2163 Diag(AttrLoc, diag::err_attribute_zero_size)
2164 << ArraySize->getSourceRange();
2168 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2169 Diag(AttrLoc, diag::err_attribute_size_too_large)
2170 << ArraySize->getSourceRange();
2174 return Context.getExtVectorType(T, vectorSize);
2177 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2180 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2181 if (T->isArrayType() || T->isFunctionType()) {
2182 Diag(Loc, diag::err_func_returning_array_function)
2183 << T->isFunctionType() << T;
2187 // Functions cannot return half FP.
2188 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2189 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2190 FixItHint::CreateInsertion(Loc, "*");
2194 // Methods cannot return interface types. All ObjC objects are
2195 // passed by reference.
2196 if (T->isObjCObjectType()) {
2197 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2204 QualType Sema::BuildFunctionType(QualType T,
2205 MutableArrayRef<QualType> ParamTypes,
2206 SourceLocation Loc, DeclarationName Entity,
2207 const FunctionProtoType::ExtProtoInfo &EPI) {
2208 bool Invalid = false;
2210 Invalid |= CheckFunctionReturnType(T, Loc);
2212 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2213 // FIXME: Loc is too inprecise here, should use proper locations for args.
2214 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2215 if (ParamType->isVoidType()) {
2216 Diag(Loc, diag::err_param_with_void_type);
2218 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2219 // Disallow half FP arguments.
2220 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2221 FixItHint::CreateInsertion(Loc, "*");
2225 ParamTypes[Idx] = ParamType;
2231 return Context.getFunctionType(T, ParamTypes, EPI);
2234 /// \brief Build a member pointer type \c T Class::*.
2236 /// \param T the type to which the member pointer refers.
2237 /// \param Class the class type into which the member pointer points.
2238 /// \param Loc the location where this type begins
2239 /// \param Entity the name of the entity that will have this member pointer type
2241 /// \returns a member pointer type, if successful, or a NULL type if there was
2243 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2245 DeclarationName Entity) {
2246 // Verify that we're not building a pointer to pointer to function with
2247 // exception specification.
2248 if (CheckDistantExceptionSpec(T)) {
2249 Diag(Loc, diag::err_distant_exception_spec);
2253 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2254 // with reference type, or "cv void."
2255 if (T->isReferenceType()) {
2256 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2257 << getPrintableNameForEntity(Entity) << T;
2261 if (T->isVoidType()) {
2262 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2263 << getPrintableNameForEntity(Entity);
2267 if (!Class->isDependentType() && !Class->isRecordType()) {
2268 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2272 // Adjust the default free function calling convention to the default method
2273 // calling convention.
2274 if (T->isFunctionType())
2275 adjustMemberFunctionCC(T, /*IsStatic=*/false);
2277 return Context.getMemberPointerType(T, Class.getTypePtr());
2280 /// \brief Build a block pointer type.
2282 /// \param T The type to which we'll be building a block pointer.
2284 /// \param Loc The source location, used for diagnostics.
2286 /// \param Entity The name of the entity that involves the block pointer
2289 /// \returns A suitable block pointer type, if there are no
2290 /// errors. Otherwise, returns a NULL type.
2291 QualType Sema::BuildBlockPointerType(QualType T,
2293 DeclarationName Entity) {
2294 if (!T->isFunctionType()) {
2295 Diag(Loc, diag::err_nonfunction_block_type);
2299 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2302 return Context.getBlockPointerType(T);
2305 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2306 QualType QT = Ty.get();
2308 if (TInfo) *TInfo = nullptr;
2312 TypeSourceInfo *DI = nullptr;
2313 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2314 QT = LIT->getType();
2315 DI = LIT->getTypeSourceInfo();
2318 if (TInfo) *TInfo = DI;
2322 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2323 Qualifiers::ObjCLifetime ownership,
2324 unsigned chunkIndex);
2326 /// Given that this is the declaration of a parameter under ARC,
2327 /// attempt to infer attributes and such for pointer-to-whatever
2329 static void inferARCWriteback(TypeProcessingState &state,
2330 QualType &declSpecType) {
2331 Sema &S = state.getSema();
2332 Declarator &declarator = state.getDeclarator();
2334 // TODO: should we care about decl qualifiers?
2336 // Check whether the declarator has the expected form. We walk
2337 // from the inside out in order to make the block logic work.
2338 unsigned outermostPointerIndex = 0;
2339 bool isBlockPointer = false;
2340 unsigned numPointers = 0;
2341 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2342 unsigned chunkIndex = i;
2343 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2344 switch (chunk.Kind) {
2345 case DeclaratorChunk::Paren:
2349 case DeclaratorChunk::Reference:
2350 case DeclaratorChunk::Pointer:
2351 // Count the number of pointers. Treat references
2352 // interchangeably as pointers; if they're mis-ordered, normal
2353 // type building will discover that.
2354 outermostPointerIndex = chunkIndex;
2358 case DeclaratorChunk::BlockPointer:
2359 // If we have a pointer to block pointer, that's an acceptable
2360 // indirect reference; anything else is not an application of
2362 if (numPointers != 1) return;
2364 outermostPointerIndex = chunkIndex;
2365 isBlockPointer = true;
2367 // We don't care about pointer structure in return values here.
2370 case DeclaratorChunk::Array: // suppress if written (id[])?
2371 case DeclaratorChunk::Function:
2372 case DeclaratorChunk::MemberPointer:
2378 // If we have *one* pointer, then we want to throw the qualifier on
2379 // the declaration-specifiers, which means that it needs to be a
2380 // retainable object type.
2381 if (numPointers == 1) {
2382 // If it's not a retainable object type, the rule doesn't apply.
2383 if (!declSpecType->isObjCRetainableType()) return;
2385 // If it already has lifetime, don't do anything.
2386 if (declSpecType.getObjCLifetime()) return;
2388 // Otherwise, modify the type in-place.
2391 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2392 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2394 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2395 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2397 // If we have *two* pointers, then we want to throw the qualifier on
2398 // the outermost pointer.
2399 } else if (numPointers == 2) {
2400 // If we don't have a block pointer, we need to check whether the
2401 // declaration-specifiers gave us something that will turn into a
2402 // retainable object pointer after we slap the first pointer on it.
2403 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2406 // Look for an explicit lifetime attribute there.
2407 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2408 if (chunk.Kind != DeclaratorChunk::Pointer &&
2409 chunk.Kind != DeclaratorChunk::BlockPointer)
2411 for (const AttributeList *attr = chunk.getAttrs(); attr;
2412 attr = attr->getNext())
2413 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2416 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2417 outermostPointerIndex);
2419 // Any other number of pointers/references does not trigger the rule.
2422 // TODO: mark whether we did this inference?
2425 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2426 SourceLocation FallbackLoc,
2427 SourceLocation ConstQualLoc,
2428 SourceLocation VolatileQualLoc,
2429 SourceLocation RestrictQualLoc,
2430 SourceLocation AtomicQualLoc) {
2438 } const QualKinds[4] = {
2439 { DeclSpec::TQ_const, "const", ConstQualLoc },
2440 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2441 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2442 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2445 SmallString<32> QualStr;
2446 unsigned NumQuals = 0;
2448 FixItHint FixIts[4];
2450 // Build a string naming the redundant qualifiers.
2451 for (unsigned I = 0; I != 4; ++I) {
2452 if (Quals & QualKinds[I].Mask) {
2453 if (!QualStr.empty()) QualStr += ' ';
2454 QualStr += QualKinds[I].Name;
2456 // If we have a location for the qualifier, offer a fixit.
2457 SourceLocation QualLoc = QualKinds[I].Loc;
2458 if (!QualLoc.isInvalid()) {
2459 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2460 if (Loc.isInvalid() ||
2461 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2469 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2470 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2473 // Diagnose pointless type qualifiers on the return type of a function.
2474 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2476 unsigned FunctionChunkIndex) {
2477 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2478 // FIXME: TypeSourceInfo doesn't preserve location information for
2480 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2481 RetTy.getLocalCVRQualifiers(),
2482 D.getIdentifierLoc());
2486 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2487 End = D.getNumTypeObjects();
2488 OuterChunkIndex != End; ++OuterChunkIndex) {
2489 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2490 switch (OuterChunk.Kind) {
2491 case DeclaratorChunk::Paren:
2494 case DeclaratorChunk::Pointer: {
2495 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2496 S.diagnoseIgnoredQualifiers(
2497 diag::warn_qual_return_type,
2500 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2501 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2502 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2503 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2507 case DeclaratorChunk::Function:
2508 case DeclaratorChunk::BlockPointer:
2509 case DeclaratorChunk::Reference:
2510 case DeclaratorChunk::Array:
2511 case DeclaratorChunk::MemberPointer:
2512 // FIXME: We can't currently provide an accurate source location and a
2513 // fix-it hint for these.
2514 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2515 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2516 RetTy.getCVRQualifiers() | AtomicQual,
2517 D.getIdentifierLoc());
2521 llvm_unreachable("unknown declarator chunk kind");
2524 // If the qualifiers come from a conversion function type, don't diagnose
2525 // them -- they're not necessarily redundant, since such a conversion
2526 // operator can be explicitly called as "x.operator const int()".
2527 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2530 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2531 // which are present there.
2532 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2533 D.getDeclSpec().getTypeQualifiers(),
2534 D.getIdentifierLoc(),
2535 D.getDeclSpec().getConstSpecLoc(),
2536 D.getDeclSpec().getVolatileSpecLoc(),
2537 D.getDeclSpec().getRestrictSpecLoc(),
2538 D.getDeclSpec().getAtomicSpecLoc());
2541 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2542 TypeSourceInfo *&ReturnTypeInfo) {
2543 Sema &SemaRef = state.getSema();
2544 Declarator &D = state.getDeclarator();
2546 ReturnTypeInfo = nullptr;
2548 // The TagDecl owned by the DeclSpec.
2549 TagDecl *OwnedTagDecl = nullptr;
2551 bool ContainsPlaceholderType = false;
2553 switch (D.getName().getKind()) {
2554 case UnqualifiedId::IK_ImplicitSelfParam:
2555 case UnqualifiedId::IK_OperatorFunctionId:
2556 case UnqualifiedId::IK_Identifier:
2557 case UnqualifiedId::IK_LiteralOperatorId:
2558 case UnqualifiedId::IK_TemplateId:
2559 T = ConvertDeclSpecToType(state);
2560 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2562 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2563 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2564 // Owned declaration is embedded in declarator.
2565 OwnedTagDecl->setEmbeddedInDeclarator(true);
2569 case UnqualifiedId::IK_ConstructorName:
2570 case UnqualifiedId::IK_ConstructorTemplateId:
2571 case UnqualifiedId::IK_DestructorName:
2572 // Constructors and destructors don't have return types. Use
2574 T = SemaRef.Context.VoidTy;
2575 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2576 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2579 case UnqualifiedId::IK_ConversionFunctionId:
2580 // The result type of a conversion function is the type that it
2582 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2584 ContainsPlaceholderType = T->getContainedAutoType();
2588 if (D.getAttributes())
2589 distributeTypeAttrsFromDeclarator(state, T);
2591 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2592 // In C++11, a function declarator using 'auto' must have a trailing return
2593 // type (this is checked later) and we can skip this. In other languages
2594 // using auto, we need to check regardless.
2595 // C++14 In generic lambdas allow 'auto' in their parameters.
2596 if (ContainsPlaceholderType &&
2597 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2600 switch (D.getContext()) {
2601 case Declarator::KNRTypeListContext:
2602 llvm_unreachable("K&R type lists aren't allowed in C++");
2603 case Declarator::LambdaExprContext:
2604 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2605 case Declarator::ObjCParameterContext:
2606 case Declarator::ObjCResultContext:
2607 case Declarator::PrototypeContext:
2610 case Declarator::LambdaExprParameterContext:
2611 if (!(SemaRef.getLangOpts().CPlusPlus14
2612 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2615 case Declarator::MemberContext:
2616 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2618 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2619 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2620 case TTK_Struct: Error = 1; /* Struct member */ break;
2621 case TTK_Union: Error = 2; /* Union member */ break;
2622 case TTK_Class: Error = 3; /* Class member */ break;
2623 case TTK_Interface: Error = 4; /* Interface member */ break;
2626 case Declarator::CXXCatchContext:
2627 case Declarator::ObjCCatchContext:
2628 Error = 5; // Exception declaration
2630 case Declarator::TemplateParamContext:
2631 Error = 6; // Template parameter
2633 case Declarator::BlockLiteralContext:
2634 Error = 7; // Block literal
2636 case Declarator::TemplateTypeArgContext:
2637 Error = 8; // Template type argument
2639 case Declarator::AliasDeclContext:
2640 case Declarator::AliasTemplateContext:
2641 Error = 10; // Type alias
2643 case Declarator::TrailingReturnContext:
2644 if (!SemaRef.getLangOpts().CPlusPlus14)
2645 Error = 11; // Function return type
2647 case Declarator::ConversionIdContext:
2648 if (!SemaRef.getLangOpts().CPlusPlus14)
2649 Error = 12; // conversion-type-id
2651 case Declarator::TypeNameContext:
2652 Error = 13; // Generic
2654 case Declarator::FileContext:
2655 case Declarator::BlockContext:
2656 case Declarator::ForContext:
2657 case Declarator::ConditionContext:
2658 case Declarator::CXXNewContext:
2662 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2665 // In Objective-C it is an error to use 'auto' on a function declarator.
2666 if (D.isFunctionDeclarator())
2669 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2670 // contains a trailing return type. That is only legal at the outermost
2671 // level. Check all declarator chunks (outermost first) anyway, to give
2672 // better diagnostics.
2673 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2674 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2675 unsigned chunkIndex = e - i - 1;
2676 state.setCurrentChunkIndex(chunkIndex);
2677 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2678 if (DeclType.Kind == DeclaratorChunk::Function) {
2679 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2680 if (FTI.hasTrailingReturnType()) {
2688 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2689 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2690 AutoRange = D.getName().getSourceRange();
2693 const bool IsDeclTypeAuto =
2694 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2695 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2696 << IsDeclTypeAuto << Error << AutoRange;
2697 T = SemaRef.Context.IntTy;
2698 D.setInvalidType(true);
2700 SemaRef.Diag(AutoRange.getBegin(),
2701 diag::warn_cxx98_compat_auto_type_specifier)
2705 if (SemaRef.getLangOpts().CPlusPlus &&
2706 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2707 // Check the contexts where C++ forbids the declaration of a new class
2708 // or enumeration in a type-specifier-seq.
2709 switch (D.getContext()) {
2710 case Declarator::TrailingReturnContext:
2711 // Class and enumeration definitions are syntactically not allowed in
2712 // trailing return types.
2713 llvm_unreachable("parser should not have allowed this");
2715 case Declarator::FileContext:
2716 case Declarator::MemberContext:
2717 case Declarator::BlockContext:
2718 case Declarator::ForContext:
2719 case Declarator::BlockLiteralContext:
2720 case Declarator::LambdaExprContext:
2721 // C++11 [dcl.type]p3:
2722 // A type-specifier-seq shall not define a class or enumeration unless
2723 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2724 // the declaration of a template-declaration.
2725 case Declarator::AliasDeclContext:
2727 case Declarator::AliasTemplateContext:
2728 SemaRef.Diag(OwnedTagDecl->getLocation(),
2729 diag::err_type_defined_in_alias_template)
2730 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2731 D.setInvalidType(true);
2733 case Declarator::TypeNameContext:
2734 case Declarator::ConversionIdContext:
2735 case Declarator::TemplateParamContext:
2736 case Declarator::CXXNewContext:
2737 case Declarator::CXXCatchContext:
2738 case Declarator::ObjCCatchContext:
2739 case Declarator::TemplateTypeArgContext:
2740 SemaRef.Diag(OwnedTagDecl->getLocation(),
2741 diag::err_type_defined_in_type_specifier)
2742 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2743 D.setInvalidType(true);
2745 case Declarator::PrototypeContext:
2746 case Declarator::LambdaExprParameterContext:
2747 case Declarator::ObjCParameterContext:
2748 case Declarator::ObjCResultContext:
2749 case Declarator::KNRTypeListContext:
2751 // Types shall not be defined in return or parameter types.
2752 SemaRef.Diag(OwnedTagDecl->getLocation(),
2753 diag::err_type_defined_in_param_type)
2754 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2755 D.setInvalidType(true);
2757 case Declarator::ConditionContext:
2759 // The type-specifier-seq shall not contain typedef and shall not declare
2760 // a new class or enumeration.
2761 SemaRef.Diag(OwnedTagDecl->getLocation(),
2762 diag::err_type_defined_in_condition);
2763 D.setInvalidType(true);
2768 assert(!T.isNull() && "This function should not return a null type");
2772 /// Produce an appropriate diagnostic for an ambiguity between a function
2773 /// declarator and a C++ direct-initializer.
2774 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2775 DeclaratorChunk &DeclType, QualType RT) {
2776 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2777 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2779 // If the return type is void there is no ambiguity.
2780 if (RT->isVoidType())
2783 // An initializer for a non-class type can have at most one argument.
2784 if (!RT->isRecordType() && FTI.NumParams > 1)
2787 // An initializer for a reference must have exactly one argument.
2788 if (RT->isReferenceType() && FTI.NumParams != 1)
2791 // Only warn if this declarator is declaring a function at block scope, and
2792 // doesn't have a storage class (such as 'extern') specified.
2793 if (!D.isFunctionDeclarator() ||
2794 D.getFunctionDefinitionKind() != FDK_Declaration ||
2795 !S.CurContext->isFunctionOrMethod() ||
2796 D.getDeclSpec().getStorageClassSpec()
2797 != DeclSpec::SCS_unspecified)
2800 // Inside a condition, a direct initializer is not permitted. We allow one to
2801 // be parsed in order to give better diagnostics in condition parsing.
2802 if (D.getContext() == Declarator::ConditionContext)
2805 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2807 S.Diag(DeclType.Loc,
2808 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2809 : diag::warn_empty_parens_are_function_decl)
2812 // If the declaration looks like:
2815 // and name lookup finds a function named 'f', then the ',' was
2816 // probably intended to be a ';'.
2817 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2818 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2819 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2820 if (Comma.getFileID() != Name.getFileID() ||
2821 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2822 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2823 Sema::LookupOrdinaryName);
2824 if (S.LookupName(Result, S.getCurScope()))
2825 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2826 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2827 << D.getIdentifier();
2831 if (FTI.NumParams > 0) {
2832 // For a declaration with parameters, eg. "T var(T());", suggest adding
2833 // parens around the first parameter to turn the declaration into a
2834 // variable declaration.
2835 SourceRange Range = FTI.Params[0].Param->getSourceRange();
2836 SourceLocation B = Range.getBegin();
2837 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2838 // FIXME: Maybe we should suggest adding braces instead of parens
2839 // in C++11 for classes that don't have an initializer_list constructor.
2840 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2841 << FixItHint::CreateInsertion(B, "(")
2842 << FixItHint::CreateInsertion(E, ")");
2844 // For a declaration without parameters, eg. "T var();", suggest replacing
2845 // the parens with an initializer to turn the declaration into a variable
2847 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2849 // Empty parens mean value-initialization, and no parens mean
2850 // default initialization. These are equivalent if the default
2851 // constructor is user-provided or if zero-initialization is a
2853 if (RD && RD->hasDefinition() &&
2854 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2855 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2856 << FixItHint::CreateRemoval(ParenRange);
2859 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2860 if (Init.empty() && S.LangOpts.CPlusPlus11)
2863 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2864 << FixItHint::CreateReplacement(ParenRange, Init);
2869 /// Helper for figuring out the default CC for a function declarator type. If
2870 /// this is the outermost chunk, then we can determine the CC from the
2871 /// declarator context. If not, then this could be either a member function
2872 /// type or normal function type.
2874 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2875 const DeclaratorChunk::FunctionTypeInfo &FTI,
2876 unsigned ChunkIndex) {
2877 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2879 bool IsCXXInstanceMethod = false;
2881 if (S.getLangOpts().CPlusPlus) {
2882 // Look inwards through parentheses to see if this chunk will form a
2883 // member pointer type or if we're the declarator. Any type attributes
2884 // between here and there will override the CC we choose here.
2885 unsigned I = ChunkIndex;
2886 bool FoundNonParen = false;
2887 while (I && !FoundNonParen) {
2889 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2890 FoundNonParen = true;
2893 if (FoundNonParen) {
2894 // If we're not the declarator, we're a regular function type unless we're
2895 // in a member pointer.
2896 IsCXXInstanceMethod =
2897 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2898 } else if (D.getContext() == Declarator::LambdaExprContext) {
2899 // This can only be a call operator for a lambda, which is an instance
2901 IsCXXInstanceMethod = true;
2903 // We're the innermost decl chunk, so must be a function declarator.
2904 assert(D.isFunctionDeclarator());
2906 // If we're inside a record, we're declaring a method, but it could be
2907 // explicitly or implicitly static.
2908 IsCXXInstanceMethod =
2909 D.isFirstDeclarationOfMember() &&
2910 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2911 !D.isStaticMember();
2915 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2916 IsCXXInstanceMethod);
2918 // Attribute AT_OpenCLKernel affects the calling convention only on
2919 // the SPIR target, hence it cannot be treated as a calling
2920 // convention attribute. This is the simplest place to infer
2921 // "spir_kernel" for OpenCL kernels on SPIR.
2922 if (CC == CC_SpirFunction) {
2923 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2924 Attr; Attr = Attr->getNext()) {
2925 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2936 /// A simple notion of pointer kinds, which matches up with the various
2937 /// pointer declarators.
2938 enum class SimplePointerKind {
2945 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
2946 switch (nullability) {
2947 case NullabilityKind::NonNull:
2948 if (!Ident__Nonnull)
2949 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
2950 return Ident__Nonnull;
2952 case NullabilityKind::Nullable:
2953 if (!Ident__Nullable)
2954 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
2955 return Ident__Nullable;
2957 case NullabilityKind::Unspecified:
2958 if (!Ident__Null_unspecified)
2959 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
2960 return Ident__Null_unspecified;
2962 llvm_unreachable("Unknown nullability kind.");
2965 /// Retrieve the identifier "NSError".
2966 IdentifierInfo *Sema::getNSErrorIdent() {
2968 Ident_NSError = PP.getIdentifierInfo("NSError");
2970 return Ident_NSError;
2973 /// Check whether there is a nullability attribute of any kind in the given
2975 static bool hasNullabilityAttr(const AttributeList *attrs) {
2976 for (const AttributeList *attr = attrs; attr;
2977 attr = attr->getNext()) {
2978 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
2979 attr->getKind() == AttributeList::AT_TypeNullable ||
2980 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
2988 /// Describes the kind of a pointer a declarator describes.
2989 enum class PointerDeclaratorKind {
2992 // Single-level pointer.
2994 // Multi-level pointer (of any pointer kind).
2997 MaybePointerToCFRef,
3001 NSErrorPointerPointer,
3005 /// Classify the given declarator, whose type-specified is \c type, based on
3006 /// what kind of pointer it refers to.
3008 /// This is used to determine the default nullability.
3009 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
3011 Declarator &declarator) {
3012 unsigned numNormalPointers = 0;
3014 // For any dependent type, we consider it a non-pointer.
3015 if (type->isDependentType())
3016 return PointerDeclaratorKind::NonPointer;
3018 // Look through the declarator chunks to identify pointers.
3019 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3020 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3021 switch (chunk.Kind) {
3022 case DeclaratorChunk::Array:
3023 case DeclaratorChunk::Function:
3026 case DeclaratorChunk::BlockPointer:
3027 case DeclaratorChunk::MemberPointer:
3028 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3029 : PointerDeclaratorKind::SingleLevelPointer;
3031 case DeclaratorChunk::Paren:
3032 case DeclaratorChunk::Reference:
3035 case DeclaratorChunk::Pointer:
3036 ++numNormalPointers;
3037 if (numNormalPointers > 2)
3038 return PointerDeclaratorKind::MultiLevelPointer;
3043 // Then, dig into the type specifier itself.
3044 unsigned numTypeSpecifierPointers = 0;
3046 // Decompose normal pointers.
3047 if (auto ptrType = type->getAs<PointerType>()) {
3048 ++numNormalPointers;
3050 if (numNormalPointers > 2)
3051 return PointerDeclaratorKind::MultiLevelPointer;
3053 type = ptrType->getPointeeType();
3054 ++numTypeSpecifierPointers;
3058 // Decompose block pointers.
3059 if (type->getAs<BlockPointerType>()) {
3060 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3061 : PointerDeclaratorKind::SingleLevelPointer;
3064 // Decompose member pointers.
3065 if (type->getAs<MemberPointerType>()) {
3066 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3067 : PointerDeclaratorKind::SingleLevelPointer;
3070 // Look at Objective-C object pointers.
3071 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3072 ++numNormalPointers;
3073 ++numTypeSpecifierPointers;
3075 // If this is NSError**, report that.
3076 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3077 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3078 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3079 return PointerDeclaratorKind::NSErrorPointerPointer;
3086 // Look at Objective-C class types.
3087 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3088 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3089 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3090 return PointerDeclaratorKind::NSErrorPointerPointer;;
3096 // If at this point we haven't seen a pointer, we won't see one.
3097 if (numNormalPointers == 0)
3098 return PointerDeclaratorKind::NonPointer;
3100 if (auto recordType = type->getAs<RecordType>()) {
3101 RecordDecl *recordDecl = recordType->getDecl();
3103 bool isCFError = false;
3105 // If we already know about CFError, test it directly.
3106 isCFError = (S.CFError == recordDecl);
3108 // Check whether this is CFError, which we identify based on its bridge
3110 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3111 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3112 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3113 S.CFError = recordDecl;
3120 // If this is CFErrorRef*, report it as such.
3121 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3122 return PointerDeclaratorKind::CFErrorRefPointer;
3131 switch (numNormalPointers) {
3133 return PointerDeclaratorKind::NonPointer;
3136 return PointerDeclaratorKind::SingleLevelPointer;
3139 return PointerDeclaratorKind::MaybePointerToCFRef;
3142 return PointerDeclaratorKind::MultiLevelPointer;
3146 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3147 SourceLocation loc) {
3148 // If we're anywhere in a function, method, or closure context, don't perform
3149 // completeness checks.
3150 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3151 if (ctx->isFunctionOrMethod())
3154 if (ctx->isFileContext())
3158 // We only care about the expansion location.
3159 loc = S.SourceMgr.getExpansionLoc(loc);
3160 FileID file = S.SourceMgr.getFileID(loc);
3161 if (file.isInvalid())
3164 // Retrieve file information.
3165 bool invalid = false;
3166 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3167 if (invalid || !sloc.isFile())
3170 // We don't want to perform completeness checks on the main file or in
3172 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3173 if (fileInfo.getIncludeLoc().isInvalid())
3175 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3176 S.Diags.getSuppressSystemWarnings()) {
3183 /// Check for consistent use of nullability.
3184 static void checkNullabilityConsistency(TypeProcessingState &state,
3185 SimplePointerKind pointerKind,
3186 SourceLocation pointerLoc) {
3187 Sema &S = state.getSema();
3189 // Determine which file we're performing consistency checking for.
3190 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3191 if (file.isInvalid())
3194 // If we haven't seen any type nullability in this file, we won't warn now
3196 FileNullability &fileNullability = S.NullabilityMap[file];
3197 if (!fileNullability.SawTypeNullability) {
3198 // If this is the first pointer declarator in the file, record it.
3199 if (fileNullability.PointerLoc.isInvalid() &&
3200 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
3202 fileNullability.PointerLoc = pointerLoc;
3203 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3209 // Complain about missing nullability.
3210 S.Diag(pointerLoc, diag::warn_nullability_missing)
3211 << static_cast<unsigned>(pointerKind);
3214 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3215 QualType declSpecType,
3216 TypeSourceInfo *TInfo) {
3217 // The TypeSourceInfo that this function returns will not be a null type.
3218 // If there is an error, this function will fill in a dummy type as fallback.
3219 QualType T = declSpecType;
3220 Declarator &D = state.getDeclarator();
3221 Sema &S = state.getSema();
3222 ASTContext &Context = S.Context;
3223 const LangOptions &LangOpts = S.getLangOpts();
3225 // The name we're declaring, if any.
3226 DeclarationName Name;
3227 if (D.getIdentifier())
3228 Name = D.getIdentifier();
3230 // Does this declaration declare a typedef-name?
3231 bool IsTypedefName =
3232 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3233 D.getContext() == Declarator::AliasDeclContext ||
3234 D.getContext() == Declarator::AliasTemplateContext;
3236 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3237 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3238 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3239 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3241 // If T is 'decltype(auto)', the only declarators we can have are parens
3242 // and at most one function declarator if this is a function declaration.
3243 if (const AutoType *AT = T->getAs<AutoType>()) {
3244 if (AT->isDecltypeAuto()) {
3245 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3246 unsigned Index = E - I - 1;
3247 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3248 unsigned DiagId = diag::err_decltype_auto_compound_type;
3249 unsigned DiagKind = 0;
3250 switch (DeclChunk.Kind) {
3251 case DeclaratorChunk::Paren:
3253 case DeclaratorChunk::Function: {
3255 if (D.isFunctionDeclarationContext() &&
3256 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3258 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3261 case DeclaratorChunk::Pointer:
3262 case DeclaratorChunk::BlockPointer:
3263 case DeclaratorChunk::MemberPointer:
3266 case DeclaratorChunk::Reference:
3269 case DeclaratorChunk::Array:
3274 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3275 D.setInvalidType(true);
3281 // Determine whether we should infer _Nonnull on pointer types.
3282 Optional<NullabilityKind> inferNullability;
3283 bool inferNullabilityCS = false;
3284 bool inferNullabilityInnerOnly = false;
3285 bool inferNullabilityInnerOnlyComplete = false;
3287 // Are we in an assume-nonnull region?
3288 bool inAssumeNonNullRegion = false;
3289 if (S.PP.getPragmaAssumeNonNullLoc().isValid() &&
3290 !state.getDeclarator().isObjCWeakProperty() &&
3291 !S.deduceWeakPropertyFromType(T)) {
3292 inAssumeNonNullRegion = true;
3293 // Determine which file we saw the assume-nonnull region in.
3294 FileID file = getNullabilityCompletenessCheckFileID(
3295 S, S.PP.getPragmaAssumeNonNullLoc());
3296 if (!file.isInvalid()) {
3297 FileNullability &fileNullability = S.NullabilityMap[file];
3299 // If we haven't seen any type nullability before, now we have.
3300 if (!fileNullability.SawTypeNullability) {
3301 if (fileNullability.PointerLoc.isValid()) {
3302 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
3303 << static_cast<unsigned>(fileNullability.PointerKind);
3306 fileNullability.SawTypeNullability = true;
3311 // Whether to complain about missing nullability specifiers or not.
3315 /// Complain on the inner pointers (but not the outermost
3318 /// Complain about any pointers that don't have nullability
3319 /// specified or inferred.
3321 } complainAboutMissingNullability = CAMN_No;
3322 unsigned NumPointersRemaining = 0;
3324 if (IsTypedefName) {
3325 // For typedefs, we do not infer any nullability (the default),
3326 // and we only complain about missing nullability specifiers on
3328 complainAboutMissingNullability = CAMN_InnerPointers;
3330 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3331 ++NumPointersRemaining;
3334 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3335 DeclaratorChunk &chunk = D.getTypeObject(i);
3336 switch (chunk.Kind) {
3337 case DeclaratorChunk::Array:
3338 case DeclaratorChunk::Function:
3341 case DeclaratorChunk::BlockPointer:
3342 case DeclaratorChunk::MemberPointer:
3343 ++NumPointersRemaining;
3346 case DeclaratorChunk::Paren:
3347 case DeclaratorChunk::Reference:
3350 case DeclaratorChunk::Pointer:
3351 ++NumPointersRemaining;
3356 bool isFunctionOrMethod = false;
3357 switch (auto context = state.getDeclarator().getContext()) {
3358 case Declarator::ObjCParameterContext:
3359 case Declarator::ObjCResultContext:
3360 case Declarator::PrototypeContext:
3361 case Declarator::TrailingReturnContext:
3362 isFunctionOrMethod = true;
3365 case Declarator::MemberContext:
3366 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3367 complainAboutMissingNullability = CAMN_No;
3372 case Declarator::FileContext:
3373 case Declarator::KNRTypeListContext:
3374 complainAboutMissingNullability = CAMN_Yes;
3376 // Nullability inference depends on the type and declarator.
3377 switch (classifyPointerDeclarator(S, T, D)) {
3378 case PointerDeclaratorKind::NonPointer:
3379 case PointerDeclaratorKind::MultiLevelPointer:
3380 // Cannot infer nullability.
3383 case PointerDeclaratorKind::SingleLevelPointer:
3384 // Infer _Nonnull if we are in an assumes-nonnull region.
3385 if (inAssumeNonNullRegion) {
3386 inferNullability = NullabilityKind::NonNull;
3387 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3388 context == Declarator::ObjCResultContext);
3392 case PointerDeclaratorKind::CFErrorRefPointer:
3393 case PointerDeclaratorKind::NSErrorPointerPointer:
3394 // Within a function or method signature, infer _Nullable at both
3396 if (isFunctionOrMethod && inAssumeNonNullRegion)
3397 inferNullability = NullabilityKind::Nullable;
3400 case PointerDeclaratorKind::MaybePointerToCFRef:
3401 if (isFunctionOrMethod) {
3402 // On pointer-to-pointer parameters marked cf_returns_retained or
3403 // cf_returns_not_retained, if the outer pointer is explicit then
3404 // infer the inner pointer as _Nullable.
3405 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3407 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3408 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3410 NextAttr = NextAttr->getNext();
3414 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3415 if (hasCFReturnsAttr(D.getAttributes()) ||
3416 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3417 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3418 inferNullability = NullabilityKind::Nullable;
3419 inferNullabilityInnerOnly = true;
3427 case Declarator::ConversionIdContext:
3428 complainAboutMissingNullability = CAMN_Yes;
3431 case Declarator::AliasDeclContext:
3432 case Declarator::AliasTemplateContext:
3433 case Declarator::BlockContext:
3434 case Declarator::BlockLiteralContext:
3435 case Declarator::ConditionContext:
3436 case Declarator::CXXCatchContext:
3437 case Declarator::CXXNewContext:
3438 case Declarator::ForContext:
3439 case Declarator::LambdaExprContext:
3440 case Declarator::LambdaExprParameterContext:
3441 case Declarator::ObjCCatchContext:
3442 case Declarator::TemplateParamContext:
3443 case Declarator::TemplateTypeArgContext:
3444 case Declarator::TypeNameContext:
3445 // Don't infer in these contexts.
3450 // Local function that checks the nullability for a given pointer declarator.
3451 // Returns true if _Nonnull was inferred.
3452 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3453 SourceLocation pointerLoc,
3454 AttributeList *&attrs) -> AttributeList * {
3455 // We've seen a pointer.
3456 if (NumPointersRemaining > 0)
3457 --NumPointersRemaining;
3459 // If a nullability attribute is present, there's nothing to do.
3460 if (hasNullabilityAttr(attrs))
3463 // If we're supposed to infer nullability, do so now.
3464 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3465 AttributeList::Syntax syntax
3466 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3467 : AttributeList::AS_Keyword;
3468 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3470 S.getNullabilityKeyword(
3472 SourceRange(pointerLoc),
3473 nullptr, SourceLocation(),
3474 nullptr, 0, syntax);
3476 spliceAttrIntoList(*nullabilityAttr, attrs);
3478 if (inferNullabilityCS) {
3479 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3480 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3483 if (inferNullabilityInnerOnly)
3484 inferNullabilityInnerOnlyComplete = true;
3485 return nullabilityAttr;
3488 // If we're supposed to complain about missing nullability, do so
3489 // now if it's truly missing.
3490 switch (complainAboutMissingNullability) {
3494 case CAMN_InnerPointers:
3495 if (NumPointersRemaining == 0)
3500 checkNullabilityConsistency(state, pointerKind, pointerLoc);
3505 // If the type itself could have nullability but does not, infer pointer
3506 // nullability and perform consistency checking.
3507 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3508 !T->getNullability(S.Context)) {
3509 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3510 if (T->isBlockPointerType())
3511 pointerKind = SimplePointerKind::BlockPointer;
3512 else if (T->isMemberPointerType())
3513 pointerKind = SimplePointerKind::MemberPointer;
3515 if (auto *attr = inferPointerNullability(
3516 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3517 D.getMutableDeclSpec().getAttributes().getListRef())) {
3518 T = Context.getAttributedType(
3519 AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3520 attr->setUsedAsTypeAttr();
3524 // Walk the DeclTypeInfo, building the recursive type as we go.
3525 // DeclTypeInfos are ordered from the identifier out, which is
3526 // opposite of what we want :).
3527 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3528 unsigned chunkIndex = e - i - 1;
3529 state.setCurrentChunkIndex(chunkIndex);
3530 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3531 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3532 switch (DeclType.Kind) {
3533 case DeclaratorChunk::Paren:
3534 T = S.BuildParenType(T);
3536 case DeclaratorChunk::BlockPointer:
3537 // If blocks are disabled, emit an error.
3538 if (!LangOpts.Blocks)
3539 S.Diag(DeclType.Loc, diag::err_blocks_disable);
3541 // Handle pointer nullability.
3542 inferPointerNullability(SimplePointerKind::BlockPointer,
3543 DeclType.Loc, DeclType.getAttrListRef());
3545 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3546 if (DeclType.Cls.TypeQuals)
3547 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3549 case DeclaratorChunk::Pointer:
3550 // Verify that we're not building a pointer to pointer to function with
3551 // exception specification.
3552 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3553 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3554 D.setInvalidType(true);
3555 // Build the type anyway.
3558 // Handle pointer nullability
3559 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3560 DeclType.getAttrListRef());
3562 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3563 T = Context.getObjCObjectPointerType(T);
3564 if (DeclType.Ptr.TypeQuals)
3565 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3568 T = S.BuildPointerType(T, DeclType.Loc, Name);
3569 if (DeclType.Ptr.TypeQuals)
3570 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3573 case DeclaratorChunk::Reference: {
3574 // Verify that we're not building a reference to pointer to function with
3575 // exception specification.
3576 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3577 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3578 D.setInvalidType(true);
3579 // Build the type anyway.
3581 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3583 if (DeclType.Ref.HasRestrict)
3584 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3587 case DeclaratorChunk::Array: {
3588 // Verify that we're not building an array of pointers to function with
3589 // exception specification.
3590 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3591 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3592 D.setInvalidType(true);
3593 // Build the type anyway.
3595 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3596 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3597 ArrayType::ArraySizeModifier ASM;
3599 ASM = ArrayType::Star;
3600 else if (ATI.hasStatic)
3601 ASM = ArrayType::Static;
3603 ASM = ArrayType::Normal;
3604 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3605 // FIXME: This check isn't quite right: it allows star in prototypes
3606 // for function definitions, and disallows some edge cases detailed
3607 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3608 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3609 ASM = ArrayType::Normal;
3610 D.setInvalidType(true);
3613 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3614 // shall appear only in a declaration of a function parameter with an
3616 if (ASM == ArrayType::Static || ATI.TypeQuals) {
3617 if (!(D.isPrototypeContext() ||
3618 D.getContext() == Declarator::KNRTypeListContext)) {
3619 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3620 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3621 // Remove the 'static' and the type qualifiers.
3622 if (ASM == ArrayType::Static)
3623 ASM = ArrayType::Normal;
3625 D.setInvalidType(true);
3628 // C99 6.7.5.2p1: ... and then only in the outermost array type
3630 unsigned x = chunkIndex;
3632 // Walk outwards along the declarator chunks.
3634 const DeclaratorChunk &DC = D.getTypeObject(x);
3636 case DeclaratorChunk::Paren:
3638 case DeclaratorChunk::Array:
3639 case DeclaratorChunk::Pointer:
3640 case DeclaratorChunk::Reference:
3641 case DeclaratorChunk::MemberPointer:
3642 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3643 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3644 if (ASM == ArrayType::Static)
3645 ASM = ArrayType::Normal;
3647 D.setInvalidType(true);
3649 case DeclaratorChunk::Function:
3650 case DeclaratorChunk::BlockPointer:
3651 // These are invalid anyway, so just ignore.
3656 const AutoType *AT = T->getContainedAutoType();
3657 // Allow arrays of auto if we are a generic lambda parameter.
3658 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3659 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3660 // We've already diagnosed this for decltype(auto).
3661 if (!AT->isDecltypeAuto())
3662 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3663 << getPrintableNameForEntity(Name) << T;
3668 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3669 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3672 case DeclaratorChunk::Function: {
3673 // If the function declarator has a prototype (i.e. it is not () and
3674 // does not have a K&R-style identifier list), then the arguments are part
3675 // of the type, otherwise the argument list is ().
3676 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3677 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3679 // Check for auto functions and trailing return type and adjust the
3680 // return type accordingly.
3681 if (!D.isInvalidType()) {
3682 // trailing-return-type is only required if we're declaring a function,
3683 // and not, for instance, a pointer to a function.
3684 if (D.getDeclSpec().containsPlaceholderType() &&
3685 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3686 !S.getLangOpts().CPlusPlus14) {
3687 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3688 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3689 ? diag::err_auto_missing_trailing_return
3690 : diag::err_deduced_return_type);
3692 D.setInvalidType(true);
3693 } else if (FTI.hasTrailingReturnType()) {
3694 // T must be exactly 'auto' at this point. See CWG issue 681.
3695 if (isa<ParenType>(T)) {
3696 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3697 diag::err_trailing_return_in_parens)
3698 << T << D.getDeclSpec().getSourceRange();
3699 D.setInvalidType(true);
3700 } else if (D.getContext() != Declarator::LambdaExprContext &&
3701 (T.hasQualifiers() || !isa<AutoType>(T) ||
3702 cast<AutoType>(T)->isDecltypeAuto())) {
3703 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3704 diag::err_trailing_return_without_auto)
3705 << T << D.getDeclSpec().getSourceRange();
3706 D.setInvalidType(true);
3708 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3710 // An error occurred parsing the trailing return type.
3712 D.setInvalidType(true);
3717 // C99 6.7.5.3p1: The return type may not be a function or array type.
3718 // For conversion functions, we'll diagnose this particular error later.
3719 if ((T->isArrayType() || T->isFunctionType()) &&
3720 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3721 unsigned diagID = diag::err_func_returning_array_function;
3722 // Last processing chunk in block context means this function chunk
3723 // represents the block.
3724 if (chunkIndex == 0 &&
3725 D.getContext() == Declarator::BlockLiteralContext)
3726 diagID = diag::err_block_returning_array_function;
3727 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3729 D.setInvalidType(true);
3732 // Do not allow returning half FP value.
3733 // FIXME: This really should be in BuildFunctionType.
3734 if (T->isHalfType()) {
3735 if (S.getLangOpts().OpenCL) {
3736 if (!S.getOpenCLOptions().cl_khr_fp16) {
3737 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3738 D.setInvalidType(true);
3740 } else if (!S.getLangOpts().HalfArgsAndReturns) {
3741 S.Diag(D.getIdentifierLoc(),
3742 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3743 D.setInvalidType(true);
3747 // Methods cannot return interface types. All ObjC objects are
3748 // passed by reference.
3749 if (T->isObjCObjectType()) {
3750 SourceLocation DiagLoc, FixitLoc;
3752 DiagLoc = TInfo->getTypeLoc().getLocStart();
3753 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3755 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3756 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3758 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3760 << FixItHint::CreateInsertion(FixitLoc, "*");
3762 T = Context.getObjCObjectPointerType(T);
3765 TLB.pushFullCopy(TInfo->getTypeLoc());
3766 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3767 TLoc.setStarLoc(FixitLoc);
3768 TInfo = TLB.getTypeSourceInfo(Context, T);
3771 D.setInvalidType(true);
3774 // cv-qualifiers on return types are pointless except when the type is a
3775 // class type in C++.
3776 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3777 !(S.getLangOpts().CPlusPlus &&
3778 (T->isDependentType() || T->isRecordType()))) {
3779 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3780 D.getFunctionDefinitionKind() == FDK_Definition) {
3781 // [6.9.1/3] qualified void return is invalid on a C
3782 // function definition. Apparently ok on declarations and
3783 // in C++ though (!)
3784 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3786 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3789 // Objective-C ARC ownership qualifiers are ignored on the function
3790 // return type (by type canonicalization). Complain if this attribute
3791 // was written here.
3792 if (T.getQualifiers().hasObjCLifetime()) {
3793 SourceLocation AttrLoc;
3794 if (chunkIndex + 1 < D.getNumTypeObjects()) {
3795 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3796 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3797 Attr; Attr = Attr->getNext()) {
3798 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3799 AttrLoc = Attr->getLoc();
3804 if (AttrLoc.isInvalid()) {
3805 for (const AttributeList *Attr
3806 = D.getDeclSpec().getAttributes().getList();
3807 Attr; Attr = Attr->getNext()) {
3808 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3809 AttrLoc = Attr->getLoc();
3815 if (AttrLoc.isValid()) {
3816 // The ownership attributes are almost always written via
3818 // __strong/__weak/__autoreleasing/__unsafe_unretained.
3819 if (AttrLoc.isMacroID())
3820 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3822 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3823 << T.getQualifiers().getObjCLifetime();
3827 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3829 // Types shall not be defined in return or parameter types.
3830 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3831 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3832 << Context.getTypeDeclType(Tag);
3835 // Exception specs are not allowed in typedefs. Complain, but add it
3837 if (IsTypedefName && FTI.getExceptionSpecType())
3838 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
3839 << (D.getContext() == Declarator::AliasDeclContext ||
3840 D.getContext() == Declarator::AliasTemplateContext);
3842 // If we see "T var();" or "T var(T());" at block scope, it is probably
3843 // an attempt to initialize a variable, not a function declaration.
3844 if (FTI.isAmbiguous)
3845 warnAboutAmbiguousFunction(S, D, DeclType, T);
3847 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3849 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3850 // Simple void foo(), where the incoming T is the result type.
3851 T = Context.getFunctionNoProtoType(T, EI);
3853 // We allow a zero-parameter variadic function in C if the
3854 // function is marked with the "overloadable" attribute. Scan
3855 // for this attribute now.
3856 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3857 bool Overloadable = false;
3858 for (const AttributeList *Attrs = D.getAttributes();
3859 Attrs; Attrs = Attrs->getNext()) {
3860 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3861 Overloadable = true;
3867 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3870 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3871 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3873 S.Diag(FTI.Params[0].IdentLoc,
3874 diag::err_ident_list_in_fn_declaration);
3875 D.setInvalidType(true);
3876 // Recover by creating a K&R-style function type.
3877 T = Context.getFunctionNoProtoType(T, EI);
3881 FunctionProtoType::ExtProtoInfo EPI;
3883 EPI.Variadic = FTI.isVariadic;
3884 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3885 EPI.TypeQuals = FTI.TypeQuals;
3886 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3887 : FTI.RefQualifierIsLValueRef? RQ_LValue
3890 // Otherwise, we have a function with a parameter list that is
3891 // potentially variadic.
3892 SmallVector<QualType, 16> ParamTys;
3893 ParamTys.reserve(FTI.NumParams);
3895 SmallVector<bool, 16> ConsumedParameters;
3896 ConsumedParameters.reserve(FTI.NumParams);
3897 bool HasAnyConsumedParameters = false;
3899 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3900 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3901 QualType ParamTy = Param->getType();
3902 assert(!ParamTy.isNull() && "Couldn't parse type?");
3904 // Look for 'void'. void is allowed only as a single parameter to a
3905 // function with no other parameters (C99 6.7.5.3p10). We record
3906 // int(void) as a FunctionProtoType with an empty parameter list.
3907 if (ParamTy->isVoidType()) {
3908 // If this is something like 'float(int, void)', reject it. 'void'
3909 // is an incomplete type (C99 6.2.5p19) and function decls cannot
3910 // have parameters of incomplete type.
3911 if (FTI.NumParams != 1 || FTI.isVariadic) {
3912 S.Diag(DeclType.Loc, diag::err_void_only_param);
3913 ParamTy = Context.IntTy;
3914 Param->setType(ParamTy);
3915 } else if (FTI.Params[i].Ident) {
3916 // Reject, but continue to parse 'int(void abc)'.
3917 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3918 ParamTy = Context.IntTy;
3919 Param->setType(ParamTy);
3921 // Reject, but continue to parse 'float(const void)'.
3922 if (ParamTy.hasQualifiers())
3923 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3925 // Do not add 'void' to the list.
3928 } else if (ParamTy->isHalfType()) {
3929 // Disallow half FP parameters.
3930 // FIXME: This really should be in BuildFunctionType.
3931 if (S.getLangOpts().OpenCL) {
3932 if (!S.getOpenCLOptions().cl_khr_fp16) {
3933 S.Diag(Param->getLocation(),
3934 diag::err_opencl_half_param) << ParamTy;
3936 Param->setInvalidDecl();
3938 } else if (!S.getLangOpts().HalfArgsAndReturns) {
3939 S.Diag(Param->getLocation(),
3940 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
3943 } else if (!FTI.hasPrototype) {
3944 if (ParamTy->isPromotableIntegerType()) {
3945 ParamTy = Context.getPromotedIntegerType(ParamTy);
3946 Param->setKNRPromoted(true);
3947 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
3948 if (BTy->getKind() == BuiltinType::Float) {
3949 ParamTy = Context.DoubleTy;
3950 Param->setKNRPromoted(true);
3955 if (LangOpts.ObjCAutoRefCount) {
3956 bool Consumed = Param->hasAttr<NSConsumedAttr>();
3957 ConsumedParameters.push_back(Consumed);
3958 HasAnyConsumedParameters |= Consumed;
3961 ParamTys.push_back(ParamTy);
3964 if (HasAnyConsumedParameters)
3965 EPI.ConsumedParameters = ConsumedParameters.data();
3967 SmallVector<QualType, 4> Exceptions;
3968 SmallVector<ParsedType, 2> DynamicExceptions;
3969 SmallVector<SourceRange, 2> DynamicExceptionRanges;
3970 Expr *NoexceptExpr = nullptr;
3972 if (FTI.getExceptionSpecType() == EST_Dynamic) {
3973 // FIXME: It's rather inefficient to have to split into two vectors
3975 unsigned N = FTI.NumExceptions;
3976 DynamicExceptions.reserve(N);
3977 DynamicExceptionRanges.reserve(N);
3978 for (unsigned I = 0; I != N; ++I) {
3979 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3980 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3982 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3983 NoexceptExpr = FTI.NoexceptExpr;
3986 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
3987 FTI.getExceptionSpecType(),
3989 DynamicExceptionRanges,
3994 T = Context.getFunctionType(T, ParamTys, EPI);
3999 case DeclaratorChunk::MemberPointer:
4000 // The scope spec must refer to a class, or be dependent.
4001 CXXScopeSpec &SS = DeclType.Mem.Scope();
4004 // Handle pointer nullability.
4005 inferPointerNullability(SimplePointerKind::MemberPointer,
4006 DeclType.Loc, DeclType.getAttrListRef());
4008 if (SS.isInvalid()) {
4009 // Avoid emitting extra errors if we already errored on the scope.
4010 D.setInvalidType(true);
4011 } else if (S.isDependentScopeSpecifier(SS) ||
4012 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4013 NestedNameSpecifier *NNS = SS.getScopeRep();
4014 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4015 switch (NNS->getKind()) {
4016 case NestedNameSpecifier::Identifier:
4017 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4018 NNS->getAsIdentifier());
4021 case NestedNameSpecifier::Namespace:
4022 case NestedNameSpecifier::NamespaceAlias:
4023 case NestedNameSpecifier::Global:
4024 case NestedNameSpecifier::Super:
4025 llvm_unreachable("Nested-name-specifier must name a type");
4027 case NestedNameSpecifier::TypeSpec:
4028 case NestedNameSpecifier::TypeSpecWithTemplate:
4029 ClsType = QualType(NNS->getAsType(), 0);
4030 // Note: if the NNS has a prefix and ClsType is a nondependent
4031 // TemplateSpecializationType, then the NNS prefix is NOT included
4032 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4033 // NOTE: in particular, no wrap occurs if ClsType already is an
4034 // Elaborated, DependentName, or DependentTemplateSpecialization.
4035 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4036 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4040 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4041 diag::err_illegal_decl_mempointer_in_nonclass)
4042 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4043 << DeclType.Mem.Scope().getRange();
4044 D.setInvalidType(true);
4047 if (!ClsType.isNull())
4048 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4052 D.setInvalidType(true);
4053 } else if (DeclType.Mem.TypeQuals) {
4054 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4060 D.setInvalidType(true);
4064 // See if there are any attributes on this declarator chunk.
4065 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
4066 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
4069 assert(!T.isNull() && "T must not be null after this point");
4071 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4072 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4073 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4076 // A cv-qualifier-seq shall only be part of the function type
4077 // for a nonstatic member function, the function type to which a pointer
4078 // to member refers, or the top-level function type of a function typedef
4081 // Core issue 547 also allows cv-qualifiers on function types that are
4082 // top-level template type arguments.
4084 if (!D.getCXXScopeSpec().isSet()) {
4085 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4086 D.getContext() != Declarator::LambdaExprContext) ||
4087 D.getDeclSpec().isFriendSpecified());
4089 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4090 FreeFunction = (DC && !DC->isRecord());
4093 // C++11 [dcl.fct]p6 (w/DR1417):
4094 // An attempt to specify a function type with a cv-qualifier-seq or a
4095 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4096 // - the function type for a non-static member function,
4097 // - the function type to which a pointer to member refers,
4098 // - the top-level function type of a function typedef declaration or
4099 // alias-declaration,
4100 // - the type-id in the default argument of a type-parameter, or
4101 // - the type-id of a template-argument for a type-parameter
4103 // FIXME: Checking this here is insufficient. We accept-invalid on:
4105 // template<typename T> struct S { void f(T); };
4106 // S<int() const> s;
4108 // ... for instance.
4109 if (IsQualifiedFunction &&
4111 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4113 D.getContext() != Declarator::TemplateTypeArgContext) {
4114 SourceLocation Loc = D.getLocStart();
4115 SourceRange RemovalRange;
4117 if (D.isFunctionDeclarator(I)) {
4118 SmallVector<SourceLocation, 4> RemovalLocs;
4119 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4120 assert(Chunk.Kind == DeclaratorChunk::Function);
4121 if (Chunk.Fun.hasRefQualifier())
4122 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4123 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4124 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4125 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4126 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4127 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4128 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4129 if (!RemovalLocs.empty()) {
4130 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4131 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4132 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4133 Loc = RemovalLocs.front();
4137 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4138 << FreeFunction << D.isFunctionDeclarator() << T
4139 << getFunctionQualifiersAsString(FnTy)
4140 << FixItHint::CreateRemoval(RemovalRange);
4142 // Strip the cv-qualifiers and ref-qualifiers from the type.
4143 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4145 EPI.RefQualifier = RQ_None;
4147 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4149 // Rebuild any parens around the identifier in the function type.
4150 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4151 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4153 T = S.BuildParenType(T);
4158 // Apply any undistributed attributes from the declarator.
4159 if (AttributeList *attrs = D.getAttributes())
4160 processTypeAttrs(state, T, TAL_DeclName, attrs);
4162 // Diagnose any ignored type attributes.
4163 state.diagnoseIgnoredTypeAttrs(T);
4165 // C++0x [dcl.constexpr]p9:
4166 // A constexpr specifier used in an object declaration declares the object
4168 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4172 // If there was an ellipsis in the declarator, the declaration declares a
4173 // parameter pack whose type may be a pack expansion type.
4174 if (D.hasEllipsis()) {
4175 // C++0x [dcl.fct]p13:
4176 // A declarator-id or abstract-declarator containing an ellipsis shall
4177 // only be used in a parameter-declaration. Such a parameter-declaration
4178 // is a parameter pack (14.5.3). [...]
4179 switch (D.getContext()) {
4180 case Declarator::PrototypeContext:
4181 case Declarator::LambdaExprParameterContext:
4182 // C++0x [dcl.fct]p13:
4183 // [...] When it is part of a parameter-declaration-clause, the
4184 // parameter pack is a function parameter pack (14.5.3). The type T
4185 // of the declarator-id of the function parameter pack shall contain
4186 // a template parameter pack; each template parameter pack in T is
4187 // expanded by the function parameter pack.
4189 // We represent function parameter packs as function parameters whose
4190 // type is a pack expansion.
4191 if (!T->containsUnexpandedParameterPack()) {
4192 S.Diag(D.getEllipsisLoc(),
4193 diag::err_function_parameter_pack_without_parameter_packs)
4194 << T << D.getSourceRange();
4195 D.setEllipsisLoc(SourceLocation());
4197 T = Context.getPackExpansionType(T, None);
4200 case Declarator::TemplateParamContext:
4201 // C++0x [temp.param]p15:
4202 // If a template-parameter is a [...] is a parameter-declaration that
4203 // declares a parameter pack (8.3.5), then the template-parameter is a
4204 // template parameter pack (14.5.3).
4206 // Note: core issue 778 clarifies that, if there are any unexpanded
4207 // parameter packs in the type of the non-type template parameter, then
4208 // it expands those parameter packs.
4209 if (T->containsUnexpandedParameterPack())
4210 T = Context.getPackExpansionType(T, None);
4212 S.Diag(D.getEllipsisLoc(),
4213 LangOpts.CPlusPlus11
4214 ? diag::warn_cxx98_compat_variadic_templates
4215 : diag::ext_variadic_templates);
4218 case Declarator::FileContext:
4219 case Declarator::KNRTypeListContext:
4220 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4221 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4222 case Declarator::TypeNameContext:
4223 case Declarator::CXXNewContext:
4224 case Declarator::AliasDeclContext:
4225 case Declarator::AliasTemplateContext:
4226 case Declarator::MemberContext:
4227 case Declarator::BlockContext:
4228 case Declarator::ForContext:
4229 case Declarator::ConditionContext:
4230 case Declarator::CXXCatchContext:
4231 case Declarator::ObjCCatchContext:
4232 case Declarator::BlockLiteralContext:
4233 case Declarator::LambdaExprContext:
4234 case Declarator::ConversionIdContext:
4235 case Declarator::TrailingReturnContext:
4236 case Declarator::TemplateTypeArgContext:
4237 // FIXME: We may want to allow parameter packs in block-literal contexts
4239 S.Diag(D.getEllipsisLoc(),
4240 diag::err_ellipsis_in_declarator_not_parameter);
4241 D.setEllipsisLoc(SourceLocation());
4246 assert(!T.isNull() && "T must not be null at the end of this function");
4247 if (D.isInvalidType())
4248 return Context.getTrivialTypeSourceInfo(T);
4250 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4253 /// GetTypeForDeclarator - Convert the type for the specified
4254 /// declarator to Type instances.
4256 /// The result of this call will never be null, but the associated
4257 /// type may be a null type if there's an unrecoverable error.
4258 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4259 // Determine the type of the declarator. Not all forms of declarator
4262 TypeProcessingState state(*this, D);
4264 TypeSourceInfo *ReturnTypeInfo = nullptr;
4265 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4267 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4268 inferARCWriteback(state, T);
4270 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4273 static void transferARCOwnershipToDeclSpec(Sema &S,
4274 QualType &declSpecTy,
4275 Qualifiers::ObjCLifetime ownership) {
4276 if (declSpecTy->isObjCRetainableType() &&
4277 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4279 qs.addObjCLifetime(ownership);
4280 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4284 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4285 Qualifiers::ObjCLifetime ownership,
4286 unsigned chunkIndex) {
4287 Sema &S = state.getSema();
4288 Declarator &D = state.getDeclarator();
4290 // Look for an explicit lifetime attribute.
4291 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4292 for (const AttributeList *attr = chunk.getAttrs(); attr;
4293 attr = attr->getNext())
4294 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4297 const char *attrStr = nullptr;
4298 switch (ownership) {
4299 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4300 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4301 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4302 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4303 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4306 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4307 Arg->Ident = &S.Context.Idents.get(attrStr);
4308 Arg->Loc = SourceLocation();
4310 ArgsUnion Args(Arg);
4312 // If there wasn't one, add one (with an invalid source location
4313 // so that we don't make an AttributedType for it).
4314 AttributeList *attr = D.getAttributePool()
4315 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4316 /*scope*/ nullptr, SourceLocation(),
4317 /*args*/ &Args, 1, AttributeList::AS_GNU);
4318 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4320 // TODO: mark whether we did this inference?
4323 /// \brief Used for transferring ownership in casts resulting in l-values.
4324 static void transferARCOwnership(TypeProcessingState &state,
4325 QualType &declSpecTy,
4326 Qualifiers::ObjCLifetime ownership) {
4327 Sema &S = state.getSema();
4328 Declarator &D = state.getDeclarator();
4331 bool hasIndirection = false;
4332 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4333 DeclaratorChunk &chunk = D.getTypeObject(i);
4334 switch (chunk.Kind) {
4335 case DeclaratorChunk::Paren:
4339 case DeclaratorChunk::Array:
4340 case DeclaratorChunk::Reference:
4341 case DeclaratorChunk::Pointer:
4343 hasIndirection = true;
4347 case DeclaratorChunk::BlockPointer:
4349 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4352 case DeclaratorChunk::Function:
4353 case DeclaratorChunk::MemberPointer:
4361 DeclaratorChunk &chunk = D.getTypeObject(inner);
4362 if (chunk.Kind == DeclaratorChunk::Pointer) {
4363 if (declSpecTy->isObjCRetainableType())
4364 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4365 if (declSpecTy->isObjCObjectType() && hasIndirection)
4366 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4368 assert(chunk.Kind == DeclaratorChunk::Array ||
4369 chunk.Kind == DeclaratorChunk::Reference);
4370 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4374 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4375 TypeProcessingState state(*this, D);
4377 TypeSourceInfo *ReturnTypeInfo = nullptr;
4378 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4380 if (getLangOpts().ObjCAutoRefCount) {
4381 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4382 if (ownership != Qualifiers::OCL_None)
4383 transferARCOwnership(state, declSpecTy, ownership);
4386 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4389 /// Map an AttributedType::Kind to an AttributeList::Kind.
4390 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4392 case AttributedType::attr_address_space:
4393 return AttributeList::AT_AddressSpace;
4394 case AttributedType::attr_regparm:
4395 return AttributeList::AT_Regparm;
4396 case AttributedType::attr_vector_size:
4397 return AttributeList::AT_VectorSize;
4398 case AttributedType::attr_neon_vector_type:
4399 return AttributeList::AT_NeonVectorType;
4400 case AttributedType::attr_neon_polyvector_type:
4401 return AttributeList::AT_NeonPolyVectorType;
4402 case AttributedType::attr_objc_gc:
4403 return AttributeList::AT_ObjCGC;
4404 case AttributedType::attr_objc_ownership:
4405 return AttributeList::AT_ObjCOwnership;
4406 case AttributedType::attr_noreturn:
4407 return AttributeList::AT_NoReturn;
4408 case AttributedType::attr_cdecl:
4409 return AttributeList::AT_CDecl;
4410 case AttributedType::attr_fastcall:
4411 return AttributeList::AT_FastCall;
4412 case AttributedType::attr_stdcall:
4413 return AttributeList::AT_StdCall;
4414 case AttributedType::attr_thiscall:
4415 return AttributeList::AT_ThisCall;
4416 case AttributedType::attr_pascal:
4417 return AttributeList::AT_Pascal;
4418 case AttributedType::attr_vectorcall:
4419 return AttributeList::AT_VectorCall;
4420 case AttributedType::attr_pcs:
4421 case AttributedType::attr_pcs_vfp:
4422 return AttributeList::AT_Pcs;
4423 case AttributedType::attr_inteloclbicc:
4424 return AttributeList::AT_IntelOclBicc;
4425 case AttributedType::attr_ms_abi:
4426 return AttributeList::AT_MSABI;
4427 case AttributedType::attr_sysv_abi:
4428 return AttributeList::AT_SysVABI;
4429 case AttributedType::attr_ptr32:
4430 return AttributeList::AT_Ptr32;
4431 case AttributedType::attr_ptr64:
4432 return AttributeList::AT_Ptr64;
4433 case AttributedType::attr_sptr:
4434 return AttributeList::AT_SPtr;
4435 case AttributedType::attr_uptr:
4436 return AttributeList::AT_UPtr;
4437 case AttributedType::attr_nonnull:
4438 return AttributeList::AT_TypeNonNull;
4439 case AttributedType::attr_nullable:
4440 return AttributeList::AT_TypeNullable;
4441 case AttributedType::attr_null_unspecified:
4442 return AttributeList::AT_TypeNullUnspecified;
4443 case AttributedType::attr_objc_kindof:
4444 return AttributeList::AT_ObjCKindOf;
4446 llvm_unreachable("unexpected attribute kind!");
4449 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4450 const AttributeList *attrs,
4451 const AttributeList *DeclAttrs = nullptr) {
4452 // DeclAttrs and attrs cannot be both empty.
4453 assert((attrs || DeclAttrs) &&
4454 "no type attributes in the expected location!");
4456 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4457 // Try to search for an attribute of matching kind in attrs list.
4458 while (attrs && attrs->getKind() != parsedKind)
4459 attrs = attrs->getNext();
4461 // No matching type attribute in attrs list found.
4462 // Try searching through C++11 attributes in the declarator attribute list.
4463 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4464 DeclAttrs->getKind() != parsedKind))
4465 DeclAttrs = DeclAttrs->getNext();
4469 assert(attrs && "no matching type attribute in expected location!");
4471 TL.setAttrNameLoc(attrs->getLoc());
4472 if (TL.hasAttrExprOperand()) {
4473 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4474 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4475 } else if (TL.hasAttrEnumOperand()) {
4476 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4477 "unexpected attribute operand kind");
4478 if (attrs->isArgIdent(0))
4479 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4481 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4484 // FIXME: preserve this information to here.
4485 if (TL.hasAttrOperand())
4486 TL.setAttrOperandParensRange(SourceRange());
4490 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4491 ASTContext &Context;
4495 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4496 : Context(Context), DS(DS) {}
4498 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4499 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4500 Visit(TL.getModifiedLoc());
4502 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4503 Visit(TL.getUnqualifiedLoc());
4505 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4506 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4508 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4509 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4510 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4511 // addition field. What we have is good enough for dispay of location
4512 // of 'fixit' on interface name.
4513 TL.setNameEndLoc(DS.getLocEnd());
4515 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4516 TypeSourceInfo *RepTInfo = nullptr;
4517 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4518 TL.copy(RepTInfo->getTypeLoc());
4520 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4521 TypeSourceInfo *RepTInfo = nullptr;
4522 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
4523 TL.copy(RepTInfo->getTypeLoc());
4525 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4526 TypeSourceInfo *TInfo = nullptr;
4527 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4529 // If we got no declarator info from previous Sema routines,
4530 // just fill with the typespec loc.
4532 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4536 TypeLoc OldTL = TInfo->getTypeLoc();
4537 if (TInfo->getType()->getAs<ElaboratedType>()) {
4538 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4539 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4540 .castAs<TemplateSpecializationTypeLoc>();
4543 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4544 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4548 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4549 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4550 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4551 TL.setParensRange(DS.getTypeofParensRange());
4553 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4554 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4555 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4556 TL.setParensRange(DS.getTypeofParensRange());
4557 assert(DS.getRepAsType());
4558 TypeSourceInfo *TInfo = nullptr;
4559 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4560 TL.setUnderlyingTInfo(TInfo);
4562 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4563 // FIXME: This holds only because we only have one unary transform.
4564 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4565 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4566 TL.setParensRange(DS.getTypeofParensRange());
4567 assert(DS.getRepAsType());
4568 TypeSourceInfo *TInfo = nullptr;
4569 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4570 TL.setUnderlyingTInfo(TInfo);
4572 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4573 // By default, use the source location of the type specifier.
4574 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4575 if (TL.needsExtraLocalData()) {
4576 // Set info for the written builtin specifiers.
4577 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4578 // Try to have a meaningful source location.
4579 if (TL.getWrittenSignSpec() != TSS_unspecified)
4580 // Sign spec loc overrides the others (e.g., 'unsigned long').
4581 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4582 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4583 // Width spec loc overrides type spec loc (e.g., 'short int').
4584 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4587 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4588 ElaboratedTypeKeyword Keyword
4589 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4590 if (DS.getTypeSpecType() == TST_typename) {
4591 TypeSourceInfo *TInfo = nullptr;
4592 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4594 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4598 TL.setElaboratedKeywordLoc(Keyword != ETK_None
4599 ? DS.getTypeSpecTypeLoc()
4600 : SourceLocation());
4601 const CXXScopeSpec& SS = DS.getTypeSpecScope();
4602 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4603 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4605 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4606 assert(DS.getTypeSpecType() == TST_typename);
4607 TypeSourceInfo *TInfo = nullptr;
4608 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4610 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4612 void VisitDependentTemplateSpecializationTypeLoc(
4613 DependentTemplateSpecializationTypeLoc TL) {
4614 assert(DS.getTypeSpecType() == TST_typename);
4615 TypeSourceInfo *TInfo = nullptr;
4616 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4619 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4621 void VisitTagTypeLoc(TagTypeLoc TL) {
4622 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4624 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4625 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4626 // or an _Atomic qualifier.
4627 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4628 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4629 TL.setParensRange(DS.getTypeofParensRange());
4631 TypeSourceInfo *TInfo = nullptr;
4632 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4634 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4636 TL.setKWLoc(DS.getAtomicSpecLoc());
4637 // No parens, to indicate this was spelled as an _Atomic qualifier.
4638 TL.setParensRange(SourceRange());
4639 Visit(TL.getValueLoc());
4643 void VisitTypeLoc(TypeLoc TL) {
4644 // FIXME: add other typespec types and change this to an assert.
4645 TL.initialize(Context, DS.getTypeSpecTypeLoc());
4649 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4650 ASTContext &Context;
4651 const DeclaratorChunk &Chunk;
4654 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4655 : Context(Context), Chunk(Chunk) {}
4657 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4658 llvm_unreachable("qualified type locs not expected here!");
4660 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4661 llvm_unreachable("decayed type locs not expected here!");
4664 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4665 fillAttributedTypeLoc(TL, Chunk.getAttrs());
4667 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4670 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4671 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4672 TL.setCaretLoc(Chunk.Loc);
4674 void VisitPointerTypeLoc(PointerTypeLoc TL) {
4675 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4676 TL.setStarLoc(Chunk.Loc);
4678 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4679 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4680 TL.setStarLoc(Chunk.Loc);
4682 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4683 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4684 const CXXScopeSpec& SS = Chunk.Mem.Scope();
4685 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4687 const Type* ClsTy = TL.getClass();
4688 QualType ClsQT = QualType(ClsTy, 0);
4689 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4690 // Now copy source location info into the type loc component.
4691 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4692 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4693 case NestedNameSpecifier::Identifier:
4694 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4696 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4697 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4698 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4699 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4703 case NestedNameSpecifier::TypeSpec:
4704 case NestedNameSpecifier::TypeSpecWithTemplate:
4705 if (isa<ElaboratedType>(ClsTy)) {
4706 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4707 ETLoc.setElaboratedKeywordLoc(SourceLocation());
4708 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4709 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4710 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4712 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4716 case NestedNameSpecifier::Namespace:
4717 case NestedNameSpecifier::NamespaceAlias:
4718 case NestedNameSpecifier::Global:
4719 case NestedNameSpecifier::Super:
4720 llvm_unreachable("Nested-name-specifier must name a type");
4723 // Finally fill in MemberPointerLocInfo fields.
4724 TL.setStarLoc(Chunk.Loc);
4725 TL.setClassTInfo(ClsTInfo);
4727 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4728 assert(Chunk.Kind == DeclaratorChunk::Reference);
4729 // 'Amp' is misleading: this might have been originally
4730 /// spelled with AmpAmp.
4731 TL.setAmpLoc(Chunk.Loc);
4733 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4734 assert(Chunk.Kind == DeclaratorChunk::Reference);
4735 assert(!Chunk.Ref.LValueRef);
4736 TL.setAmpAmpLoc(Chunk.Loc);
4738 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4739 assert(Chunk.Kind == DeclaratorChunk::Array);
4740 TL.setLBracketLoc(Chunk.Loc);
4741 TL.setRBracketLoc(Chunk.EndLoc);
4742 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4744 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4745 assert(Chunk.Kind == DeclaratorChunk::Function);
4746 TL.setLocalRangeBegin(Chunk.Loc);
4747 TL.setLocalRangeEnd(Chunk.EndLoc);
4749 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4750 TL.setLParenLoc(FTI.getLParenLoc());
4751 TL.setRParenLoc(FTI.getRParenLoc());
4752 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4753 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4754 TL.setParam(tpi++, Param);
4756 // FIXME: exception specs
4758 void VisitParenTypeLoc(ParenTypeLoc TL) {
4759 assert(Chunk.Kind == DeclaratorChunk::Paren);
4760 TL.setLParenLoc(Chunk.Loc);
4761 TL.setRParenLoc(Chunk.EndLoc);
4764 void VisitTypeLoc(TypeLoc TL) {
4765 llvm_unreachable("unsupported TypeLoc kind in declarator!");
4770 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4772 switch (Chunk.Kind) {
4773 case DeclaratorChunk::Function:
4774 case DeclaratorChunk::Array:
4775 case DeclaratorChunk::Paren:
4776 llvm_unreachable("cannot be _Atomic qualified");
4778 case DeclaratorChunk::Pointer:
4779 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4782 case DeclaratorChunk::BlockPointer:
4783 case DeclaratorChunk::Reference:
4784 case DeclaratorChunk::MemberPointer:
4785 // FIXME: Provide a source location for the _Atomic keyword.
4790 ATL.setParensRange(SourceRange());
4793 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4795 /// \param T QualType referring to the type as written in source code.
4797 /// \param ReturnTypeInfo For declarators whose return type does not show
4798 /// up in the normal place in the declaration specifiers (such as a C++
4799 /// conversion function), this pointer will refer to a type source information
4800 /// for that return type.
4802 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4803 TypeSourceInfo *ReturnTypeInfo) {
4804 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4805 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4806 const AttributeList *DeclAttrs = D.getAttributes();
4808 // Handle parameter packs whose type is a pack expansion.
4809 if (isa<PackExpansionType>(T)) {
4810 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4811 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4814 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4815 // An AtomicTypeLoc might be produced by an atomic qualifier in this
4816 // declarator chunk.
4817 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4818 fillAtomicQualLoc(ATL, D.getTypeObject(i));
4819 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4822 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4823 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4824 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4827 // FIXME: Ordering here?
4828 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4829 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4831 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4832 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4835 // If we have different source information for the return type, use
4836 // that. This really only applies to C++ conversion functions.
4837 if (ReturnTypeInfo) {
4838 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4839 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4840 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4842 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4848 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4849 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
4850 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4851 // and Sema during declaration parsing. Try deallocating/caching them when
4852 // it's appropriate, instead of allocating them and keeping them around.
4853 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4855 new (LocT) LocInfoType(T, TInfo);
4856 assert(LocT->getTypeClass() != T->getTypeClass() &&
4857 "LocInfoType's TypeClass conflicts with an existing Type class");
4858 return ParsedType::make(QualType(LocT, 0));
4861 void LocInfoType::getAsStringInternal(std::string &Str,
4862 const PrintingPolicy &Policy) const {
4863 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4864 " was used directly instead of getting the QualType through"
4865 " GetTypeFromParser");
4868 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4869 // C99 6.7.6: Type names have no identifier. This is already validated by
4871 assert(D.getIdentifier() == nullptr &&
4872 "Type name should have no identifier!");
4874 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4875 QualType T = TInfo->getType();
4876 if (D.isInvalidType())
4879 // Make sure there are no unused decl attributes on the declarator.
4880 // We don't want to do this for ObjC parameters because we're going
4881 // to apply them to the actual parameter declaration.
4882 // Likewise, we don't want to do this for alias declarations, because
4883 // we are actually going to build a declaration from this eventually.
4884 if (D.getContext() != Declarator::ObjCParameterContext &&
4885 D.getContext() != Declarator::AliasDeclContext &&
4886 D.getContext() != Declarator::AliasTemplateContext)
4887 checkUnusedDeclAttributes(D);
4889 if (getLangOpts().CPlusPlus) {
4890 // Check that there are no default arguments (C++ only).
4891 CheckExtraCXXDefaultArguments(D);
4894 return CreateParsedType(T, TInfo);
4897 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4898 QualType T = Context.getObjCInstanceType();
4899 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4900 return CreateParsedType(T, TInfo);
4904 //===----------------------------------------------------------------------===//
4905 // Type Attribute Processing
4906 //===----------------------------------------------------------------------===//
4908 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
4909 /// specified type. The attribute contains 1 argument, the id of the address
4910 /// space for the type.
4911 static void HandleAddressSpaceTypeAttribute(QualType &Type,
4912 const AttributeList &Attr, Sema &S){
4914 // If this type is already address space qualified, reject it.
4915 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
4916 // qualifiers for two or more different address spaces."
4917 if (Type.getAddressSpace()) {
4918 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
4923 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
4924 // qualified by an address-space qualifier."
4925 if (Type->isFunctionType()) {
4926 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
4932 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
4933 // Check the attribute arguments.
4934 if (Attr.getNumArgs() != 1) {
4935 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4936 << Attr.getName() << 1;
4940 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4941 llvm::APSInt addrSpace(32);
4942 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
4943 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
4944 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4945 << Attr.getName() << AANT_ArgumentIntegerConstant
4946 << ASArgExpr->getSourceRange();
4952 if (addrSpace.isSigned()) {
4953 if (addrSpace.isNegative()) {
4954 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
4955 << ASArgExpr->getSourceRange();
4959 addrSpace.setIsSigned(false);
4961 llvm::APSInt max(addrSpace.getBitWidth());
4962 max = Qualifiers::MaxAddressSpace;
4963 if (addrSpace > max) {
4964 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
4965 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
4969 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
4971 // The keyword-based type attributes imply which address space to use.
4972 switch (Attr.getKind()) {
4973 case AttributeList::AT_OpenCLGlobalAddressSpace:
4974 ASIdx = LangAS::opencl_global; break;
4975 case AttributeList::AT_OpenCLLocalAddressSpace:
4976 ASIdx = LangAS::opencl_local; break;
4977 case AttributeList::AT_OpenCLConstantAddressSpace:
4978 ASIdx = LangAS::opencl_constant; break;
4979 case AttributeList::AT_OpenCLGenericAddressSpace:
4980 ASIdx = LangAS::opencl_generic; break;
4982 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
4987 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
4990 /// Does this type have a "direct" ownership qualifier? That is,
4991 /// is it written like "__strong id", as opposed to something like
4992 /// "typeof(foo)", where that happens to be strong?
4993 static bool hasDirectOwnershipQualifier(QualType type) {
4994 // Fast path: no qualifier at all.
4995 assert(type.getQualifiers().hasObjCLifetime());
4999 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5000 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5003 type = attr->getModifiedType();
5005 // X *__strong (...)
5006 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5007 type = paren->getInnerType();
5009 // That's it for things we want to complain about. In particular,
5010 // we do not want to look through typedefs, typeof(expr),
5011 // typeof(type), or any other way that the type is somehow
5020 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5021 /// attribute on the specified type.
5023 /// Returns 'true' if the attribute was handled.
5024 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5025 AttributeList &attr,
5027 bool NonObjCPointer = false;
5029 if (!type->isDependentType() && !type->isUndeducedType()) {
5030 if (const PointerType *ptr = type->getAs<PointerType>()) {
5031 QualType pointee = ptr->getPointeeType();
5032 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5034 // It is important not to lose the source info that there was an attribute
5035 // applied to non-objc pointer. We will create an attributed type but
5036 // its type will be the same as the original type.
5037 NonObjCPointer = true;
5038 } else if (!type->isObjCRetainableType()) {
5042 // Don't accept an ownership attribute in the declspec if it would
5043 // just be the return type of a block pointer.
5044 if (state.isProcessingDeclSpec()) {
5045 Declarator &D = state.getDeclarator();
5046 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5047 /*onlyBlockPointers=*/true))
5052 Sema &S = state.getSema();
5053 SourceLocation AttrLoc = attr.getLoc();
5054 if (AttrLoc.isMacroID())
5055 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5057 if (!attr.isArgIdent(0)) {
5058 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5059 << attr.getName() << AANT_ArgumentString;
5064 // Consume lifetime attributes without further comment outside of
5066 if (!S.getLangOpts().ObjCAutoRefCount)
5069 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5070 Qualifiers::ObjCLifetime lifetime;
5071 if (II->isStr("none"))
5072 lifetime = Qualifiers::OCL_ExplicitNone;
5073 else if (II->isStr("strong"))
5074 lifetime = Qualifiers::OCL_Strong;
5075 else if (II->isStr("weak"))
5076 lifetime = Qualifiers::OCL_Weak;
5077 else if (II->isStr("autoreleasing"))
5078 lifetime = Qualifiers::OCL_Autoreleasing;
5080 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5081 << attr.getName() << II;
5086 SplitQualType underlyingType = type.split();
5088 // Check for redundant/conflicting ownership qualifiers.
5089 if (Qualifiers::ObjCLifetime previousLifetime
5090 = type.getQualifiers().getObjCLifetime()) {
5091 // If it's written directly, that's an error.
5092 if (hasDirectOwnershipQualifier(type)) {
5093 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5098 // Otherwise, if the qualifiers actually conflict, pull sugar off
5099 // until we reach a type that is directly qualified.
5100 if (previousLifetime != lifetime) {
5101 // This should always terminate: the canonical type is
5102 // qualified, so some bit of sugar must be hiding it.
5103 while (!underlyingType.Quals.hasObjCLifetime()) {
5104 underlyingType = underlyingType.getSingleStepDesugaredType();
5106 underlyingType.Quals.removeObjCLifetime();
5110 underlyingType.Quals.addObjCLifetime(lifetime);
5112 if (NonObjCPointer) {
5113 StringRef name = attr.getName()->getName();
5115 case Qualifiers::OCL_None:
5116 case Qualifiers::OCL_ExplicitNone:
5118 case Qualifiers::OCL_Strong: name = "__strong"; break;
5119 case Qualifiers::OCL_Weak: name = "__weak"; break;
5120 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5122 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5123 << TDS_ObjCObjOrBlock << type;
5126 QualType origType = type;
5127 if (!NonObjCPointer)
5128 type = S.Context.getQualifiedType(underlyingType);
5130 // If we have a valid source location for the attribute, use an
5131 // AttributedType instead.
5132 if (AttrLoc.isValid())
5133 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5136 // Forbid __weak if the runtime doesn't support it.
5137 if (lifetime == Qualifiers::OCL_Weak &&
5138 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
5140 // Actually, delay this until we know what we're parsing.
5141 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5142 S.DelayedDiagnostics.add(
5143 sema::DelayedDiagnostic::makeForbiddenType(
5144 S.getSourceManager().getExpansionLoc(AttrLoc),
5145 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
5147 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
5154 // Forbid __weak for class objects marked as
5155 // objc_arc_weak_reference_unavailable
5156 if (lifetime == Qualifiers::OCL_Weak) {
5157 if (const ObjCObjectPointerType *ObjT =
5158 type->getAs<ObjCObjectPointerType>()) {
5159 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5160 if (Class->isArcWeakrefUnavailable()) {
5161 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5162 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5163 diag::note_class_declared);
5172 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5173 /// attribute on the specified type. Returns true to indicate that
5174 /// the attribute was handled, false to indicate that the type does
5175 /// not permit the attribute.
5176 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5177 AttributeList &attr,
5179 Sema &S = state.getSema();
5181 // Delay if this isn't some kind of pointer.
5182 if (!type->isPointerType() &&
5183 !type->isObjCObjectPointerType() &&
5184 !type->isBlockPointerType())
5187 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5188 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5193 // Check the attribute arguments.
5194 if (!attr.isArgIdent(0)) {
5195 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5196 << attr.getName() << AANT_ArgumentString;
5200 Qualifiers::GC GCAttr;
5201 if (attr.getNumArgs() > 1) {
5202 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5203 << attr.getName() << 1;
5208 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5209 if (II->isStr("weak"))
5210 GCAttr = Qualifiers::Weak;
5211 else if (II->isStr("strong"))
5212 GCAttr = Qualifiers::Strong;
5214 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5215 << attr.getName() << II;
5220 QualType origType = type;
5221 type = S.Context.getObjCGCQualType(origType, GCAttr);
5223 // Make an attributed type to preserve the source information.
5224 if (attr.getLoc().isValid())
5225 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5232 /// A helper class to unwrap a type down to a function for the
5233 /// purposes of applying attributes there.
5236 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5237 /// if (unwrapped.isFunctionType()) {
5238 /// const FunctionType *fn = unwrapped.get();
5239 /// // change fn somehow
5240 /// T = unwrapped.wrap(fn);
5242 struct FunctionTypeUnwrapper {
5253 const FunctionType *Fn;
5254 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5256 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5258 const Type *Ty = T.getTypePtr();
5259 if (isa<FunctionType>(Ty)) {
5260 Fn = cast<FunctionType>(Ty);
5262 } else if (isa<ParenType>(Ty)) {
5263 T = cast<ParenType>(Ty)->getInnerType();
5264 Stack.push_back(Parens);
5265 } else if (isa<PointerType>(Ty)) {
5266 T = cast<PointerType>(Ty)->getPointeeType();
5267 Stack.push_back(Pointer);
5268 } else if (isa<BlockPointerType>(Ty)) {
5269 T = cast<BlockPointerType>(Ty)->getPointeeType();
5270 Stack.push_back(BlockPointer);
5271 } else if (isa<MemberPointerType>(Ty)) {
5272 T = cast<MemberPointerType>(Ty)->getPointeeType();
5273 Stack.push_back(MemberPointer);
5274 } else if (isa<ReferenceType>(Ty)) {
5275 T = cast<ReferenceType>(Ty)->getPointeeType();
5276 Stack.push_back(Reference);
5278 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5284 T = QualType(DTy, 0);
5285 Stack.push_back(Desugar);
5290 bool isFunctionType() const { return (Fn != nullptr); }
5291 const FunctionType *get() const { return Fn; }
5293 QualType wrap(Sema &S, const FunctionType *New) {
5294 // If T wasn't modified from the unwrapped type, do nothing.
5295 if (New == get()) return Original;
5298 return wrap(S.Context, Original, 0);
5302 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5303 if (I == Stack.size())
5304 return C.getQualifiedType(Fn, Old.getQualifiers());
5306 // Build up the inner type, applying the qualifiers from the old
5307 // type to the new type.
5308 SplitQualType SplitOld = Old.split();
5310 // As a special case, tail-recurse if there are no qualifiers.
5311 if (SplitOld.Quals.empty())
5312 return wrap(C, SplitOld.Ty, I);
5313 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5316 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5317 if (I == Stack.size()) return QualType(Fn, 0);
5319 switch (static_cast<WrapKind>(Stack[I++])) {
5321 // This is the point at which we potentially lose source
5323 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5326 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5327 return C.getParenType(New);
5331 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5332 return C.getPointerType(New);
5335 case BlockPointer: {
5336 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5337 return C.getBlockPointerType(New);
5340 case MemberPointer: {
5341 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5342 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5343 return C.getMemberPointerType(New, OldMPT->getClass());
5347 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5348 QualType New = wrap(C, OldRef->getPointeeType(), I);
5349 if (isa<LValueReferenceType>(OldRef))
5350 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5352 return C.getRValueReferenceType(New);
5356 llvm_unreachable("unknown wrapping kind");
5361 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5362 AttributeList &Attr,
5364 Sema &S = State.getSema();
5366 AttributeList::Kind Kind = Attr.getKind();
5367 QualType Desugared = Type;
5368 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5370 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5372 // You cannot specify duplicate type attributes, so if the attribute has
5373 // already been applied, flag it.
5374 if (getAttrListKind(CurAttrKind) == Kind) {
5375 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5380 // You cannot have both __sptr and __uptr on the same type, nor can you
5381 // have __ptr32 and __ptr64.
5382 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5383 Kind == AttributeList::AT_Ptr64) ||
5384 (CurAttrKind == AttributedType::attr_ptr64 &&
5385 Kind == AttributeList::AT_Ptr32)) {
5386 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5387 << "'__ptr32'" << "'__ptr64'";
5389 } else if ((CurAttrKind == AttributedType::attr_sptr &&
5390 Kind == AttributeList::AT_UPtr) ||
5391 (CurAttrKind == AttributedType::attr_uptr &&
5392 Kind == AttributeList::AT_SPtr)) {
5393 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5394 << "'__sptr'" << "'__uptr'";
5398 Desugared = AT->getEquivalentType();
5399 AT = dyn_cast<AttributedType>(Desugared);
5402 // Pointer type qualifiers can only operate on pointer types, but not
5403 // pointer-to-member types.
5404 if (!isa<PointerType>(Desugared)) {
5405 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
5406 diag::err_attribute_no_member_pointers :
5407 diag::err_attribute_pointers_only) << Attr.getName();
5411 AttributedType::Kind TAK;
5413 default: llvm_unreachable("Unknown attribute kind");
5414 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5415 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5416 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5417 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5420 Type = S.Context.getAttributedType(TAK, Type, Type);
5424 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5425 NullabilityKind nullability,
5426 SourceLocation nullabilityLoc,
5427 bool isContextSensitive) {
5428 // We saw a nullability type specifier. If this is the first one for
5429 // this file, note that.
5430 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5431 if (!file.isInvalid()) {
5432 FileNullability &fileNullability = NullabilityMap[file];
5433 if (!fileNullability.SawTypeNullability) {
5434 // If we have already seen a pointer declarator without a nullability
5435 // annotation, complain about it.
5436 if (fileNullability.PointerLoc.isValid()) {
5437 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5438 << static_cast<unsigned>(fileNullability.PointerKind);
5441 fileNullability.SawTypeNullability = true;
5445 // Check for existing nullability attributes on the type.
5446 QualType desugared = type;
5447 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5448 // Check whether there is already a null
5449 if (auto existingNullability = attributed->getImmediateNullability()) {
5450 // Duplicated nullability.
5451 if (nullability == *existingNullability) {
5452 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5453 << DiagNullabilityKind(nullability, isContextSensitive)
5454 << FixItHint::CreateRemoval(nullabilityLoc);
5459 // Conflicting nullability.
5460 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5461 << DiagNullabilityKind(nullability, isContextSensitive)
5462 << DiagNullabilityKind(*existingNullability, false);
5466 desugared = attributed->getModifiedType();
5469 // If there is already a different nullability specifier, complain.
5470 // This (unlike the code above) looks through typedefs that might
5471 // have nullability specifiers on them, which means we cannot
5472 // provide a useful Fix-It.
5473 if (auto existingNullability = desugared->getNullability(Context)) {
5474 if (nullability != *existingNullability) {
5475 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5476 << DiagNullabilityKind(nullability, isContextSensitive)
5477 << DiagNullabilityKind(*existingNullability, false);
5479 // Try to find the typedef with the existing nullability specifier.
5480 if (auto typedefType = desugared->getAs<TypedefType>()) {
5481 TypedefNameDecl *typedefDecl = typedefType->getDecl();
5482 QualType underlyingType = typedefDecl->getUnderlyingType();
5483 if (auto typedefNullability
5484 = AttributedType::stripOuterNullability(underlyingType)) {
5485 if (*typedefNullability == *existingNullability) {
5486 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5487 << DiagNullabilityKind(*existingNullability, false);
5496 // If this definitely isn't a pointer type, reject the specifier.
5497 if (!desugared->canHaveNullability()) {
5498 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5499 << DiagNullabilityKind(nullability, isContextSensitive) << type;
5503 // For the context-sensitive keywords/Objective-C property
5504 // attributes, require that the type be a single-level pointer.
5505 if (isContextSensitive) {
5506 // Make sure that the pointee isn't itself a pointer type.
5507 QualType pointeeType = desugared->getPointeeType();
5508 if (pointeeType->isAnyPointerType() ||
5509 pointeeType->isObjCObjectPointerType() ||
5510 pointeeType->isMemberPointerType()) {
5511 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5512 << DiagNullabilityKind(nullability, true)
5514 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5515 << DiagNullabilityKind(nullability, false)
5517 << FixItHint::CreateReplacement(nullabilityLoc,
5518 getNullabilitySpelling(nullability));
5523 // Form the attributed type.
5524 type = Context.getAttributedType(
5525 AttributedType::getNullabilityAttrKind(nullability), type, type);
5529 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
5530 // Find out if it's an Objective-C object or object pointer type;
5531 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
5532 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
5533 : type->getAs<ObjCObjectType>();
5535 // If not, we can't apply __kindof.
5537 // FIXME: Handle dependent types that aren't yet object types.
5538 Diag(loc, diag::err_objc_kindof_nonobject)
5543 // Rebuild the "equivalent" type, which pushes __kindof down into
5545 QualType equivType = Context.getObjCObjectType(objType->getBaseType(),
5546 objType->getTypeArgsAsWritten(),
5547 objType->getProtocols(),
5550 // If we started with an object pointer type, rebuild it.
5552 equivType = Context.getObjCObjectPointerType(equivType);
5553 if (auto nullability = type->getNullability(Context)) {
5554 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
5555 equivType = Context.getAttributedType(attrKind, equivType, equivType);
5559 // Build the attributed type to record where __kindof occurred.
5560 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
5567 /// Map a nullability attribute kind to a nullability kind.
5568 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5570 case AttributeList::AT_TypeNonNull:
5571 return NullabilityKind::NonNull;
5573 case AttributeList::AT_TypeNullable:
5574 return NullabilityKind::Nullable;
5576 case AttributeList::AT_TypeNullUnspecified:
5577 return NullabilityKind::Unspecified;
5580 llvm_unreachable("not a nullability attribute kind");
5584 /// Distribute a nullability type attribute that cannot be applied to
5585 /// the type specifier to a pointer, block pointer, or member pointer
5586 /// declarator, complaining if necessary.
5588 /// \returns true if the nullability annotation was distributed, false
5590 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5592 AttributeList &attr) {
5593 Declarator &declarator = state.getDeclarator();
5595 /// Attempt to move the attribute to the specified chunk.
5596 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5597 // If there is already a nullability attribute there, don't add
5599 if (hasNullabilityAttr(chunk.getAttrListRef()))
5602 // Complain about the nullability qualifier being in the wrong
5609 PK_MemberFunctionPointer,
5611 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5613 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5614 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5616 auto diag = state.getSema().Diag(attr.getLoc(),
5617 diag::warn_nullability_declspec)
5618 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5619 attr.isContextSensitiveKeywordAttribute())
5621 << static_cast<unsigned>(pointerKind);
5623 // FIXME: MemberPointer chunks don't carry the location of the *.
5624 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5625 diag << FixItHint::CreateRemoval(attr.getLoc())
5626 << FixItHint::CreateInsertion(
5627 state.getSema().getPreprocessor()
5628 .getLocForEndOfToken(chunk.Loc),
5629 " " + attr.getName()->getName().str() + " ");
5632 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5633 chunk.getAttrListRef());
5637 // Move it to the outermost pointer, member pointer, or block
5638 // pointer declarator.
5639 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5640 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5641 switch (chunk.Kind) {
5642 case DeclaratorChunk::Pointer:
5643 case DeclaratorChunk::BlockPointer:
5644 case DeclaratorChunk::MemberPointer:
5645 return moveToChunk(chunk, false);
5647 case DeclaratorChunk::Paren:
5648 case DeclaratorChunk::Array:
5651 case DeclaratorChunk::Function:
5652 // Try to move past the return type to a function/block/member
5653 // function pointer.
5654 if (DeclaratorChunk *dest = maybeMovePastReturnType(
5656 /*onlyBlockPointers=*/false)) {
5657 return moveToChunk(*dest, true);
5662 // Don't walk through these.
5663 case DeclaratorChunk::Reference:
5671 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5672 assert(!Attr.isInvalid());
5673 switch (Attr.getKind()) {
5675 llvm_unreachable("not a calling convention attribute");
5676 case AttributeList::AT_CDecl:
5677 return AttributedType::attr_cdecl;
5678 case AttributeList::AT_FastCall:
5679 return AttributedType::attr_fastcall;
5680 case AttributeList::AT_StdCall:
5681 return AttributedType::attr_stdcall;
5682 case AttributeList::AT_ThisCall:
5683 return AttributedType::attr_thiscall;
5684 case AttributeList::AT_Pascal:
5685 return AttributedType::attr_pascal;
5686 case AttributeList::AT_VectorCall:
5687 return AttributedType::attr_vectorcall;
5688 case AttributeList::AT_Pcs: {
5689 // The attribute may have had a fixit applied where we treated an
5690 // identifier as a string literal. The contents of the string are valid,
5691 // but the form may not be.
5693 if (Attr.isArgExpr(0))
5694 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5696 Str = Attr.getArgAsIdent(0)->Ident->getName();
5697 return llvm::StringSwitch<AttributedType::Kind>(Str)
5698 .Case("aapcs", AttributedType::attr_pcs)
5699 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5701 case AttributeList::AT_IntelOclBicc:
5702 return AttributedType::attr_inteloclbicc;
5703 case AttributeList::AT_MSABI:
5704 return AttributedType::attr_ms_abi;
5705 case AttributeList::AT_SysVABI:
5706 return AttributedType::attr_sysv_abi;
5708 llvm_unreachable("unexpected attribute kind!");
5711 /// Process an individual function attribute. Returns true to
5712 /// indicate that the attribute was handled, false if it wasn't.
5713 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5714 AttributeList &attr,
5716 Sema &S = state.getSema();
5718 FunctionTypeUnwrapper unwrapped(S, type);
5720 if (attr.getKind() == AttributeList::AT_NoReturn) {
5721 if (S.CheckNoReturnAttr(attr))
5724 // Delay if this is not a function type.
5725 if (!unwrapped.isFunctionType())
5728 // Otherwise we can process right away.
5729 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5730 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5734 // ns_returns_retained is not always a type attribute, but if we got
5735 // here, we're treating it as one right now.
5736 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5737 assert(S.getLangOpts().ObjCAutoRefCount &&
5738 "ns_returns_retained treated as type attribute in non-ARC");
5739 if (attr.getNumArgs()) return true;
5741 // Delay if this is not a function type.
5742 if (!unwrapped.isFunctionType())
5745 FunctionType::ExtInfo EI
5746 = unwrapped.get()->getExtInfo().withProducesResult(true);
5747 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5751 if (attr.getKind() == AttributeList::AT_Regparm) {
5753 if (S.CheckRegparmAttr(attr, value))
5756 // Delay if this is not a function type.
5757 if (!unwrapped.isFunctionType())
5760 // Diagnose regparm with fastcall.
5761 const FunctionType *fn = unwrapped.get();
5762 CallingConv CC = fn->getCallConv();
5763 if (CC == CC_X86FastCall) {
5764 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5765 << FunctionType::getNameForCallConv(CC)
5771 FunctionType::ExtInfo EI =
5772 unwrapped.get()->getExtInfo().withRegParm(value);
5773 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5777 // Delay if the type didn't work out to a function.
5778 if (!unwrapped.isFunctionType()) return false;
5780 // Otherwise, a calling convention.
5782 if (S.CheckCallingConvAttr(attr, CC))
5785 const FunctionType *fn = unwrapped.get();
5786 CallingConv CCOld = fn->getCallConv();
5787 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5790 // Error out on when there's already an attribute on the type
5791 // and the CCs don't match.
5792 const AttributedType *AT = S.getCallingConvAttributedType(type);
5793 if (AT && AT->getAttrKind() != CCAttrKind) {
5794 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5795 << FunctionType::getNameForCallConv(CC)
5796 << FunctionType::getNameForCallConv(CCOld);
5802 // Diagnose use of callee-cleanup calling convention on variadic functions.
5803 if (!supportsVariadicCall(CC)) {
5804 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5805 if (FnP && FnP->isVariadic()) {
5806 unsigned DiagID = diag::err_cconv_varargs;
5807 // stdcall and fastcall are ignored with a warning for GCC and MS
5809 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5810 DiagID = diag::warn_cconv_varargs;
5812 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5818 // Also diagnose fastcall with regparm.
5819 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5820 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5821 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5826 // Modify the CC from the wrapped function type, wrap it all back, and then
5827 // wrap the whole thing in an AttributedType as written. The modified type
5828 // might have a different CC if we ignored the attribute.
5829 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5830 QualType Equivalent =
5831 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5832 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5836 bool Sema::hasExplicitCallingConv(QualType &T) {
5837 QualType R = T.IgnoreParens();
5838 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5839 if (AT->isCallingConv())
5841 R = AT->getModifiedType().IgnoreParens();
5846 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
5847 FunctionTypeUnwrapper Unwrapped(*this, T);
5848 const FunctionType *FT = Unwrapped.get();
5849 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5850 cast<FunctionProtoType>(FT)->isVariadic());
5852 // Only adjust types with the default convention. For example, on Windows we
5853 // should adjust a __cdecl type to __thiscall for instance methods, and a
5854 // __thiscall type to __cdecl for static methods.
5855 CallingConv CurCC = FT->getCallConv();
5856 CallingConv FromCC =
5857 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5858 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5859 if (CurCC != FromCC || FromCC == ToCC)
5862 if (hasExplicitCallingConv(T))
5865 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
5866 QualType Wrapped = Unwrapped.wrap(*this, FT);
5867 T = Context.getAdjustedType(T, Wrapped);
5870 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
5871 /// and float scalars, although arrays, pointers, and function return values are
5872 /// allowed in conjunction with this construct. Aggregates with this attribute
5873 /// are invalid, even if they are of the same size as a corresponding scalar.
5874 /// The raw attribute should contain precisely 1 argument, the vector size for
5875 /// the variable, measured in bytes. If curType and rawAttr are well formed,
5876 /// this routine will return a new vector type.
5877 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
5879 // Check the attribute arguments.
5880 if (Attr.getNumArgs() != 1) {
5881 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5882 << Attr.getName() << 1;
5886 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5887 llvm::APSInt vecSize(32);
5888 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
5889 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
5890 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5891 << Attr.getName() << AANT_ArgumentIntegerConstant
5892 << sizeExpr->getSourceRange();
5896 // The base type must be integer (not Boolean or enumeration) or float, and
5897 // can't already be a vector.
5898 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
5899 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
5900 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5904 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5905 // vecSize is specified in bytes - convert to bits.
5906 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
5908 // the vector size needs to be an integral multiple of the type size.
5909 if (vectorSize % typeSize) {
5910 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
5911 << sizeExpr->getSourceRange();
5915 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
5916 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
5917 << sizeExpr->getSourceRange();
5921 if (vectorSize == 0) {
5922 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
5923 << sizeExpr->getSourceRange();
5928 // Success! Instantiate the vector type, the number of elements is > 0, and
5929 // not required to be a power of 2, unlike GCC.
5930 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
5931 VectorType::GenericVector);
5934 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
5936 static void HandleExtVectorTypeAttr(QualType &CurType,
5937 const AttributeList &Attr,
5939 // check the attribute arguments.
5940 if (Attr.getNumArgs() != 1) {
5941 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5942 << Attr.getName() << 1;
5948 // Special case where the argument is a template id.
5949 if (Attr.isArgIdent(0)) {
5951 SourceLocation TemplateKWLoc;
5953 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5955 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
5957 if (Size.isInvalid())
5960 sizeExpr = Size.get();
5962 sizeExpr = Attr.getArgAsExpr(0);
5965 // Create the vector type.
5966 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
5971 static bool isPermittedNeonBaseType(QualType &Ty,
5972 VectorType::VectorKind VecKind, Sema &S) {
5973 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
5977 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
5979 // Signed poly is mathematically wrong, but has been baked into some ABIs by
5981 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
5982 Triple.getArch() == llvm::Triple::aarch64_be;
5983 if (VecKind == VectorType::NeonPolyVector) {
5984 if (IsPolyUnsigned) {
5985 // AArch64 polynomial vectors are unsigned and support poly64.
5986 return BTy->getKind() == BuiltinType::UChar ||
5987 BTy->getKind() == BuiltinType::UShort ||
5988 BTy->getKind() == BuiltinType::ULong ||
5989 BTy->getKind() == BuiltinType::ULongLong;
5991 // AArch32 polynomial vector are signed.
5992 return BTy->getKind() == BuiltinType::SChar ||
5993 BTy->getKind() == BuiltinType::Short;
5997 // Non-polynomial vector types: the usual suspects are allowed, as well as
5998 // float64_t on AArch64.
5999 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6000 Triple.getArch() == llvm::Triple::aarch64_be;
6002 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6005 return BTy->getKind() == BuiltinType::SChar ||
6006 BTy->getKind() == BuiltinType::UChar ||
6007 BTy->getKind() == BuiltinType::Short ||
6008 BTy->getKind() == BuiltinType::UShort ||
6009 BTy->getKind() == BuiltinType::Int ||
6010 BTy->getKind() == BuiltinType::UInt ||
6011 BTy->getKind() == BuiltinType::Long ||
6012 BTy->getKind() == BuiltinType::ULong ||
6013 BTy->getKind() == BuiltinType::LongLong ||
6014 BTy->getKind() == BuiltinType::ULongLong ||
6015 BTy->getKind() == BuiltinType::Float ||
6016 BTy->getKind() == BuiltinType::Half;
6019 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6020 /// "neon_polyvector_type" attributes are used to create vector types that
6021 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6022 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6023 /// the argument to these Neon attributes is the number of vector elements,
6024 /// not the vector size in bytes. The vector width and element type must
6025 /// match one of the standard Neon vector types.
6026 static void HandleNeonVectorTypeAttr(QualType& CurType,
6027 const AttributeList &Attr, Sema &S,
6028 VectorType::VectorKind VecKind) {
6029 // Target must have NEON
6030 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6031 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6035 // Check the attribute arguments.
6036 if (Attr.getNumArgs() != 1) {
6037 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6038 << Attr.getName() << 1;
6042 // The number of elements must be an ICE.
6043 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6044 llvm::APSInt numEltsInt(32);
6045 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6046 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6047 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6048 << Attr.getName() << AANT_ArgumentIntegerConstant
6049 << numEltsExpr->getSourceRange();
6053 // Only certain element types are supported for Neon vectors.
6054 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6055 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6060 // The total size of the vector must be 64 or 128 bits.
6061 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6062 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6063 unsigned vecSize = typeSize * numElts;
6064 if (vecSize != 64 && vecSize != 128) {
6065 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6070 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6073 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6074 TypeAttrLocation TAL, AttributeList *attrs) {
6075 // Scan through and apply attributes to this type where it makes sense. Some
6076 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6077 // type, but others can be present in the type specifiers even though they
6078 // apply to the decl. Here we apply type attributes and ignore the rest.
6080 AttributeList *next;
6082 AttributeList &attr = *attrs;
6083 next = attr.getNext();
6085 // Skip attributes that were marked to be invalid.
6086 if (attr.isInvalid())
6089 if (attr.isCXX11Attribute()) {
6090 // [[gnu::...]] attributes are treated as declaration attributes, so may
6091 // not appertain to a DeclaratorChunk, even if we handle them as type
6093 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6094 if (TAL == TAL_DeclChunk) {
6095 state.getSema().Diag(attr.getLoc(),
6096 diag::warn_cxx11_gnu_attribute_on_type)
6100 } else if (TAL != TAL_DeclChunk) {
6101 // Otherwise, only consider type processing for a C++11 attribute if
6102 // it's actually been applied to a type.
6107 // If this is an attribute we can handle, do so now,
6108 // otherwise, add it to the FnAttrs list for rechaining.
6109 switch (attr.getKind()) {
6111 // A C++11 attribute on a declarator chunk must appertain to a type.
6112 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6113 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6115 attr.setUsedAsTypeAttr();
6119 case AttributeList::UnknownAttribute:
6120 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6121 state.getSema().Diag(attr.getLoc(),
6122 diag::warn_unknown_attribute_ignored)
6126 case AttributeList::IgnoredAttribute:
6129 case AttributeList::AT_MayAlias:
6130 // FIXME: This attribute needs to actually be handled, but if we ignore
6131 // it it breaks large amounts of Linux software.
6132 attr.setUsedAsTypeAttr();
6134 case AttributeList::AT_OpenCLPrivateAddressSpace:
6135 case AttributeList::AT_OpenCLGlobalAddressSpace:
6136 case AttributeList::AT_OpenCLLocalAddressSpace:
6137 case AttributeList::AT_OpenCLConstantAddressSpace:
6138 case AttributeList::AT_OpenCLGenericAddressSpace:
6139 case AttributeList::AT_AddressSpace:
6140 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6141 attr.setUsedAsTypeAttr();
6143 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6144 if (!handleObjCPointerTypeAttr(state, attr, type))
6145 distributeObjCPointerTypeAttr(state, attr, type);
6146 attr.setUsedAsTypeAttr();
6148 case AttributeList::AT_VectorSize:
6149 HandleVectorSizeAttr(type, attr, state.getSema());
6150 attr.setUsedAsTypeAttr();
6152 case AttributeList::AT_ExtVectorType:
6153 HandleExtVectorTypeAttr(type, attr, state.getSema());
6154 attr.setUsedAsTypeAttr();
6156 case AttributeList::AT_NeonVectorType:
6157 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6158 VectorType::NeonVector);
6159 attr.setUsedAsTypeAttr();
6161 case AttributeList::AT_NeonPolyVectorType:
6162 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6163 VectorType::NeonPolyVector);
6164 attr.setUsedAsTypeAttr();
6166 case AttributeList::AT_OpenCLImageAccess:
6167 // FIXME: there should be some type checking happening here, I would
6168 // imagine, but the original handler's checking was entirely superfluous.
6169 attr.setUsedAsTypeAttr();
6172 MS_TYPE_ATTRS_CASELIST:
6173 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6174 attr.setUsedAsTypeAttr();
6178 NULLABILITY_TYPE_ATTRS_CASELIST:
6179 // Either add nullability here or try to distribute it. We
6180 // don't want to distribute the nullability specifier past any
6181 // dependent type, because that complicates the user model.
6182 if (type->canHaveNullability() || type->isDependentType() ||
6183 !distributeNullabilityTypeAttr(state, type, attr)) {
6184 if (state.getSema().checkNullabilityTypeSpecifier(
6186 mapNullabilityAttrKind(attr.getKind()),
6188 attr.isContextSensitiveKeywordAttribute())) {
6192 attr.setUsedAsTypeAttr();
6196 case AttributeList::AT_ObjCKindOf:
6197 // '__kindof' must be part of the decl-specifiers.
6204 state.getSema().Diag(attr.getLoc(),
6205 diag::err_objc_kindof_wrong_position)
6206 << FixItHint::CreateRemoval(attr.getLoc())
6207 << FixItHint::CreateInsertion(
6208 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6212 // Apply it regardless.
6213 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6215 attr.setUsedAsTypeAttr();
6218 case AttributeList::AT_NSReturnsRetained:
6219 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6221 // fallthrough into the function attrs
6223 FUNCTION_TYPE_ATTRS_CASELIST:
6224 attr.setUsedAsTypeAttr();
6226 // Never process function type attributes as part of the
6227 // declaration-specifiers.
6228 if (TAL == TAL_DeclSpec)
6229 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6231 // Otherwise, handle the possible delays.
6232 else if (!handleFunctionTypeAttr(state, attr, type))
6233 distributeFunctionTypeAttr(state, attr, type);
6236 } while ((attrs = next));
6239 /// \brief Ensure that the type of the given expression is complete.
6241 /// This routine checks whether the expression \p E has a complete type. If the
6242 /// expression refers to an instantiable construct, that instantiation is
6243 /// performed as needed to complete its type. Furthermore
6244 /// Sema::RequireCompleteType is called for the expression's type (or in the
6245 /// case of a reference type, the referred-to type).
6247 /// \param E The expression whose type is required to be complete.
6248 /// \param Diagnoser The object that will emit a diagnostic if the type is
6251 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6253 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
6254 QualType T = E->getType();
6256 // Fast path the case where the type is already complete.
6257 if (!T->isIncompleteType())
6258 // FIXME: The definition might not be visible.
6261 // Incomplete array types may be completed by the initializer attached to
6262 // their definitions. For static data members of class templates and for
6263 // variable templates, we need to instantiate the definition to get this
6264 // initializer and complete the type.
6265 if (T->isIncompleteArrayType()) {
6266 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6267 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6268 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6269 SourceLocation PointOfInstantiation = E->getExprLoc();
6271 if (MemberSpecializationInfo *MSInfo =
6272 Var->getMemberSpecializationInfo()) {
6273 // If we don't already have a point of instantiation, this is it.
6274 if (MSInfo->getPointOfInstantiation().isInvalid()) {
6275 MSInfo->setPointOfInstantiation(PointOfInstantiation);
6277 // This is a modification of an existing AST node. Notify
6279 if (ASTMutationListener *L = getASTMutationListener())
6280 L->StaticDataMemberInstantiated(Var);
6283 VarTemplateSpecializationDecl *VarSpec =
6284 cast<VarTemplateSpecializationDecl>(Var);
6285 if (VarSpec->getPointOfInstantiation().isInvalid())
6286 VarSpec->setPointOfInstantiation(PointOfInstantiation);
6289 InstantiateVariableDefinition(PointOfInstantiation, Var);
6291 // Update the type to the newly instantiated definition's type both
6292 // here and within the expression.
6293 if (VarDecl *Def = Var->getDefinition()) {
6300 // We still go on to try to complete the type independently, as it
6301 // may also require instantiations or diagnostics if it remains
6308 // FIXME: Are there other cases which require instantiating something other
6309 // than the type to complete the type of an expression?
6311 // Look through reference types and complete the referred type.
6312 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
6313 T = Ref->getPointeeType();
6315 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6319 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
6322 TypeDiagnoserDiag(unsigned DiagID)
6323 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
6325 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
6326 if (Suppressed) return;
6327 S.Diag(Loc, DiagID) << T;
6332 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6333 TypeDiagnoserDiag Diagnoser(DiagID);
6334 return RequireCompleteExprType(E, Diagnoser);
6337 /// @brief Ensure that the type T is a complete type.
6339 /// This routine checks whether the type @p T is complete in any
6340 /// context where a complete type is required. If @p T is a complete
6341 /// type, returns false. If @p T is a class template specialization,
6342 /// this routine then attempts to perform class template
6343 /// instantiation. If instantiation fails, or if @p T is incomplete
6344 /// and cannot be completed, issues the diagnostic @p diag (giving it
6345 /// the type @p T) and returns true.
6347 /// @param Loc The location in the source that the incomplete type
6348 /// diagnostic should refer to.
6350 /// @param T The type that this routine is examining for completeness.
6352 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
6353 /// @c false otherwise.
6354 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6355 TypeDiagnoser &Diagnoser) {
6356 if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
6358 if (const TagType *Tag = T->getAs<TagType>()) {
6359 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
6360 Tag->getDecl()->setCompleteDefinitionRequired();
6361 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
6367 /// \brief Determine whether there is any declaration of \p D that was ever a
6368 /// definition (perhaps before module merging) and is currently visible.
6369 /// \param D The definition of the entity.
6370 /// \param Suggested Filled in with the declaration that should be made visible
6371 /// in order to provide a definition of this entity.
6372 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
6373 /// not defined. This only matters for enums with a fixed underlying
6374 /// type, since in all other cases, a type is complete if and only if it
6376 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
6377 bool OnlyNeedComplete) {
6378 // Easy case: if we don't have modules, all declarations are visible.
6379 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
6382 // If this definition was instantiated from a template, map back to the
6383 // pattern from which it was instantiated.
6384 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
6385 // We're in the middle of defining it; this definition should be treated
6388 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
6389 if (auto *Pattern = RD->getTemplateInstantiationPattern())
6391 D = RD->getDefinition();
6392 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
6393 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
6395 if (OnlyNeedComplete && ED->isFixed()) {
6396 // If the enum has a fixed underlying type, and we're only looking for a
6397 // complete type (not a definition), any visible declaration of it will
6399 *Suggested = nullptr;
6400 for (auto *Redecl : ED->redecls()) {
6401 if (isVisible(Redecl))
6403 if (Redecl->isThisDeclarationADefinition() ||
6404 (Redecl->isCanonicalDecl() && !*Suggested))
6405 *Suggested = Redecl;
6409 D = ED->getDefinition();
6411 assert(D && "missing definition for pattern of instantiated definition");
6417 // The external source may have additional definitions of this type that are
6418 // visible, so complete the redeclaration chain now and ask again.
6419 if (auto *Source = Context.getExternalSource()) {
6420 Source->CompleteRedeclChain(D);
6421 return isVisible(D);
6427 /// Locks in the inheritance model for the given class and all of its bases.
6428 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
6429 RD = RD->getMostRecentDecl();
6430 if (!RD->hasAttr<MSInheritanceAttr>()) {
6431 MSInheritanceAttr::Spelling IM;
6433 switch (S.MSPointerToMemberRepresentationMethod) {
6434 case LangOptions::PPTMK_BestCase:
6435 IM = RD->calculateInheritanceModel();
6437 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6438 IM = MSInheritanceAttr::Keyword_single_inheritance;
6440 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6441 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6443 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6444 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6448 RD->addAttr(MSInheritanceAttr::CreateImplicit(
6449 S.getASTContext(), IM,
6450 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6451 LangOptions::PPTMK_BestCase,
6452 S.ImplicitMSInheritanceAttrLoc.isValid()
6453 ? S.ImplicitMSInheritanceAttrLoc
6454 : RD->getSourceRange()));
6458 /// \brief The implementation of RequireCompleteType
6459 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6460 TypeDiagnoser &Diagnoser) {
6461 // FIXME: Add this assertion to make sure we always get instantiation points.
6462 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6463 // FIXME: Add this assertion to help us flush out problems with
6464 // checking for dependent types and type-dependent expressions.
6466 // assert(!T->isDependentType() &&
6467 // "Can't ask whether a dependent type is complete");
6469 // If we have a complete type, we're done.
6470 NamedDecl *Def = nullptr;
6471 if (!T->isIncompleteType(&Def)) {
6472 // If we know about the definition but it is not visible, complain.
6473 NamedDecl *SuggestedDef = nullptr;
6474 if (!Diagnoser.Suppressed && Def &&
6475 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true))
6476 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true);
6478 // We lock in the inheritance model once somebody has asked us to ensure
6479 // that a pointer-to-member type is complete.
6480 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6481 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6482 if (!MPTy->getClass()->isDependentType()) {
6483 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
6484 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6492 const TagType *Tag = T->getAs<TagType>();
6493 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6495 // If there's an unimported definition of this type in a module (for
6496 // instance, because we forward declared it, then imported the definition),
6497 // import that definition now.
6499 // FIXME: What about other cases where an import extends a redeclaration
6500 // chain for a declaration that can be accessed through a mechanism other
6501 // than name lookup (eg, referenced in a template, or a variable whose type
6502 // could be completed by the module)?
6505 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6507 // Avoid diagnosing invalid decls as incomplete.
6508 if (D->isInvalidDecl())
6511 // Give the external AST source a chance to complete the type.
6512 if (auto *Source = Context.getExternalSource()) {
6514 Source->CompleteType(Tag->getDecl());
6516 Source->CompleteType(IFace->getDecl());
6518 // If the external source completed the type, go through the motions
6519 // again to ensure we're allowed to use the completed type.
6520 if (!T->isIncompleteType())
6521 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6525 // If we have a class template specialization or a class member of a
6526 // class template specialization, or an array with known size of such,
6527 // try to instantiate it.
6528 QualType MaybeTemplate = T;
6529 while (const ConstantArrayType *Array
6530 = Context.getAsConstantArrayType(MaybeTemplate))
6531 MaybeTemplate = Array->getElementType();
6532 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6533 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6534 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6535 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
6536 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
6537 TSK_ImplicitInstantiation,
6538 /*Complain=*/!Diagnoser.Suppressed);
6539 } else if (CXXRecordDecl *Rec
6540 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6541 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6542 if (!Rec->isBeingDefined() && Pattern) {
6543 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6544 assert(MSI && "Missing member specialization information?");
6545 // This record was instantiated from a class within a template.
6546 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6547 return InstantiateClass(Loc, Rec, Pattern,
6548 getTemplateInstantiationArgs(Rec),
6549 TSK_ImplicitInstantiation,
6550 /*Complain=*/!Diagnoser.Suppressed);
6555 if (Diagnoser.Suppressed)
6558 // We have an incomplete type. Produce a diagnostic.
6559 if (Ident___float128 &&
6560 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6561 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6565 Diagnoser.diagnose(*this, Loc, T);
6567 // If the type was a forward declaration of a class/struct/union
6568 // type, produce a note.
6569 if (Tag && !Tag->getDecl()->isInvalidDecl())
6570 Diag(Tag->getDecl()->getLocation(),
6571 Tag->isBeingDefined() ? diag::note_type_being_defined
6572 : diag::note_forward_declaration)
6573 << QualType(Tag, 0);
6575 // If the Objective-C class was a forward declaration, produce a note.
6576 if (IFace && !IFace->getDecl()->isInvalidDecl())
6577 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6579 // If we have external information that we can use to suggest a fix,
6582 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6587 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6589 TypeDiagnoserDiag Diagnoser(DiagID);
6590 return RequireCompleteType(Loc, T, Diagnoser);
6593 /// \brief Get diagnostic %select index for tag kind for
6594 /// literal type diagnostic message.
6595 /// WARNING: Indexes apply to particular diagnostics only!
6597 /// \returns diagnostic %select index.
6598 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6600 case TTK_Struct: return 0;
6601 case TTK_Interface: return 1;
6602 case TTK_Class: return 2;
6603 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6607 /// @brief Ensure that the type T is a literal type.
6609 /// This routine checks whether the type @p T is a literal type. If @p T is an
6610 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6611 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6612 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6613 /// it the type @p T), along with notes explaining why the type is not a
6614 /// literal type, and returns true.
6616 /// @param Loc The location in the source that the non-literal type
6617 /// diagnostic should refer to.
6619 /// @param T The type that this routine is examining for literalness.
6621 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6623 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6624 /// @c false otherwise.
6625 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6626 TypeDiagnoser &Diagnoser) {
6627 assert(!T->isDependentType() && "type should not be dependent");
6629 QualType ElemType = Context.getBaseElementType(T);
6630 RequireCompleteType(Loc, ElemType, 0);
6632 if (T->isLiteralType(Context))
6635 if (Diagnoser.Suppressed)
6638 Diagnoser.diagnose(*this, Loc, T);
6640 if (T->isVariableArrayType())
6643 const RecordType *RT = ElemType->getAs<RecordType>();
6647 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6649 // A partially-defined class type can't be a literal type, because a literal
6650 // class type must have a trivial destructor (which can't be checked until
6651 // the class definition is complete).
6652 if (!RD->isCompleteDefinition()) {
6653 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
6657 // If the class has virtual base classes, then it's not an aggregate, and
6658 // cannot have any constexpr constructors or a trivial default constructor,
6659 // so is non-literal. This is better to diagnose than the resulting absence
6660 // of constexpr constructors.
6661 if (RD->getNumVBases()) {
6662 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6663 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6664 for (const auto &I : RD->vbases())
6665 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6666 << I.getSourceRange();
6667 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6668 !RD->hasTrivialDefaultConstructor()) {
6669 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6670 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6671 for (const auto &I : RD->bases()) {
6672 if (!I.getType()->isLiteralType(Context)) {
6673 Diag(I.getLocStart(),
6674 diag::note_non_literal_base_class)
6675 << RD << I.getType() << I.getSourceRange();
6679 for (const auto *I : RD->fields()) {
6680 if (!I->getType()->isLiteralType(Context) ||
6681 I->getType().isVolatileQualified()) {
6682 Diag(I->getLocation(), diag::note_non_literal_field)
6683 << RD << I << I->getType()
6684 << I->getType().isVolatileQualified();
6688 } else if (!RD->hasTrivialDestructor()) {
6689 // All fields and bases are of literal types, so have trivial destructors.
6690 // If this class's destructor is non-trivial it must be user-declared.
6691 CXXDestructorDecl *Dtor = RD->getDestructor();
6692 assert(Dtor && "class has literal fields and bases but no dtor?");
6696 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6697 diag::note_non_literal_user_provided_dtor :
6698 diag::note_non_literal_nontrivial_dtor) << RD;
6699 if (!Dtor->isUserProvided())
6700 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6706 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6707 TypeDiagnoserDiag Diagnoser(DiagID);
6708 return RequireLiteralType(Loc, T, Diagnoser);
6711 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6712 /// and qualified by the nested-name-specifier contained in SS.
6713 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6714 const CXXScopeSpec &SS, QualType T) {
6717 NestedNameSpecifier *NNS;
6719 NNS = SS.getScopeRep();
6721 if (Keyword == ETK_None)
6725 return Context.getElaboratedType(Keyword, NNS, T);
6728 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6729 ExprResult ER = CheckPlaceholderExpr(E);
6730 if (ER.isInvalid()) return QualType();
6733 if (!E->isTypeDependent()) {
6734 QualType T = E->getType();
6735 if (const TagType *TT = T->getAs<TagType>())
6736 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6738 return Context.getTypeOfExprType(E);
6741 /// getDecltypeForExpr - Given an expr, will return the decltype for
6742 /// that expression, according to the rules in C++11
6743 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6744 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6745 if (E->isTypeDependent())
6746 return S.Context.DependentTy;
6748 // C++11 [dcl.type.simple]p4:
6749 // The type denoted by decltype(e) is defined as follows:
6751 // - if e is an unparenthesized id-expression or an unparenthesized class
6752 // member access (5.2.5), decltype(e) is the type of the entity named
6753 // by e. If there is no such entity, or if e names a set of overloaded
6754 // functions, the program is ill-formed;
6756 // We apply the same rules for Objective-C ivar and property references.
6757 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6758 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6759 return VD->getType();
6760 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6761 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6762 return FD->getType();
6763 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6764 return IR->getDecl()->getType();
6765 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6766 if (PR->isExplicitProperty())
6767 return PR->getExplicitProperty()->getType();
6768 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6769 return PE->getType();
6772 // C++11 [expr.lambda.prim]p18:
6773 // Every occurrence of decltype((x)) where x is a possibly
6774 // parenthesized id-expression that names an entity of automatic
6775 // storage duration is treated as if x were transformed into an
6776 // access to a corresponding data member of the closure type that
6777 // would have been declared if x were an odr-use of the denoted
6779 using namespace sema;
6780 if (S.getCurLambda()) {
6781 if (isa<ParenExpr>(E)) {
6782 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6783 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6784 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6786 return S.Context.getLValueReferenceType(T);
6793 // C++11 [dcl.type.simple]p4:
6795 QualType T = E->getType();
6796 switch (E->getValueKind()) {
6797 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6799 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6800 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6802 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6803 // - otherwise, decltype(e) is the type of e.
6804 case VK_RValue: break;
6810 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6811 bool AsUnevaluated) {
6812 ExprResult ER = CheckPlaceholderExpr(E);
6813 if (ER.isInvalid()) return QualType();
6816 if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
6817 E->HasSideEffects(Context, false)) {
6818 // The expression operand for decltype is in an unevaluated expression
6819 // context, so side effects could result in unintended consequences.
6820 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6823 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
6826 QualType Sema::BuildUnaryTransformType(QualType BaseType,
6827 UnaryTransformType::UTTKind UKind,
6828 SourceLocation Loc) {
6830 case UnaryTransformType::EnumUnderlyingType:
6831 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
6832 Diag(Loc, diag::err_only_enums_have_underlying_types);
6835 QualType Underlying = BaseType;
6836 if (!BaseType->isDependentType()) {
6837 // The enum could be incomplete if we're parsing its definition or
6838 // recovering from an error.
6839 NamedDecl *FwdDecl = nullptr;
6840 if (BaseType->isIncompleteType(&FwdDecl)) {
6841 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
6842 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
6846 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
6847 assert(ED && "EnumType has no EnumDecl");
6849 DiagnoseUseOfDecl(ED, Loc);
6851 Underlying = ED->getIntegerType();
6852 assert(!Underlying.isNull());
6854 return Context.getUnaryTransformType(BaseType, Underlying,
6855 UnaryTransformType::EnumUnderlyingType);
6858 llvm_unreachable("unknown unary transform type");
6861 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
6862 if (!T->isDependentType()) {
6863 // FIXME: It isn't entirely clear whether incomplete atomic types
6864 // are allowed or not; for simplicity, ban them for the moment.
6865 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
6868 int DisallowedKind = -1;
6869 if (T->isArrayType())
6871 else if (T->isFunctionType())
6873 else if (T->isReferenceType())
6875 else if (T->isAtomicType())
6877 else if (T.hasQualifiers())
6879 else if (!T.isTriviallyCopyableType(Context))
6880 // Some other non-trivially-copyable type (probably a C++ class)
6883 if (DisallowedKind != -1) {
6884 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
6888 // FIXME: Do we need any handling for ARC here?
6891 // Build the pointer type.
6892 return Context.getAtomicType(T);