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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Sema/DeclSpec.h"
28 #include "clang/Sema/DelayedDiagnostic.h"
29 #include "clang/Sema/Lookup.h"
30 #include "clang/Sema/ScopeInfo.h"
31 #include "clang/Sema/SemaInternal.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/ErrorHandling.h"
38 using namespace clang;
40 enum TypeDiagSelector {
46 /// isOmittedBlockReturnType - Return true if this declarator is missing a
47 /// return type because this is a omitted return type on a block literal.
48 static bool isOmittedBlockReturnType(const Declarator &D) {
49 if (D.getContext() != Declarator::BlockLiteralContext ||
50 D.getDeclSpec().hasTypeSpecifier())
53 if (D.getNumTypeObjects() == 0)
54 return true; // ^{ ... }
56 if (D.getNumTypeObjects() == 1 &&
57 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
58 return true; // ^(int X, float Y) { ... }
63 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
64 /// doesn't apply to the given type.
65 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
67 TypeDiagSelector WhichType;
68 bool useExpansionLoc = true;
69 switch (attr.getKind()) {
70 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
71 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
73 // Assume everything else was a function attribute.
74 WhichType = TDS_Function;
75 useExpansionLoc = false;
79 SourceLocation loc = attr.getLoc();
80 StringRef name = attr.getName()->getName();
82 // The GC attributes are usually written with macros; special-case them.
83 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
85 if (useExpansionLoc && loc.isMacroID() && II) {
86 if (II->isStr("strong")) {
87 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88 } else if (II->isStr("weak")) {
89 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100 case AttributeList::AT_ObjCGC: \
101 case AttributeList::AT_ObjCOwnership
103 // Calling convention attributes.
104 #define CALLING_CONV_ATTRS_CASELIST \
105 case AttributeList::AT_CDecl: \
106 case AttributeList::AT_FastCall: \
107 case AttributeList::AT_StdCall: \
108 case AttributeList::AT_ThisCall: \
109 case AttributeList::AT_RegCall: \
110 case AttributeList::AT_Pascal: \
111 case AttributeList::AT_SwiftCall: \
112 case AttributeList::AT_VectorCall: \
113 case AttributeList::AT_MSABI: \
114 case AttributeList::AT_SysVABI: \
115 case AttributeList::AT_Pcs: \
116 case AttributeList::AT_IntelOclBicc: \
117 case AttributeList::AT_PreserveMost: \
118 case AttributeList::AT_PreserveAll
120 // Function type attributes.
121 #define FUNCTION_TYPE_ATTRS_CASELIST \
122 case AttributeList::AT_NoReturn: \
123 case AttributeList::AT_Regparm: \
124 CALLING_CONV_ATTRS_CASELIST
126 // Microsoft-specific type qualifiers.
127 #define MS_TYPE_ATTRS_CASELIST \
128 case AttributeList::AT_Ptr32: \
129 case AttributeList::AT_Ptr64: \
130 case AttributeList::AT_SPtr: \
131 case AttributeList::AT_UPtr
133 // Nullability qualifiers.
134 #define NULLABILITY_TYPE_ATTRS_CASELIST \
135 case AttributeList::AT_TypeNonNull: \
136 case AttributeList::AT_TypeNullable: \
137 case AttributeList::AT_TypeNullUnspecified
140 /// An object which stores processing state for the entire
141 /// GetTypeForDeclarator process.
142 class TypeProcessingState {
145 /// The declarator being processed.
146 Declarator &declarator;
148 /// The index of the declarator chunk we're currently processing.
149 /// May be the total number of valid chunks, indicating the
153 /// Whether there are non-trivial modifications to the decl spec.
156 /// Whether we saved the attributes in the decl spec.
159 /// The original set of attributes on the DeclSpec.
160 SmallVector<AttributeList*, 2> savedAttrs;
162 /// A list of attributes to diagnose the uselessness of when the
163 /// processing is complete.
164 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
167 TypeProcessingState(Sema &sema, Declarator &declarator)
168 : sema(sema), declarator(declarator),
169 chunkIndex(declarator.getNumTypeObjects()),
170 trivial(true), hasSavedAttrs(false) {}
172 Sema &getSema() const {
176 Declarator &getDeclarator() const {
180 bool isProcessingDeclSpec() const {
181 return chunkIndex == declarator.getNumTypeObjects();
184 unsigned getCurrentChunkIndex() const {
188 void setCurrentChunkIndex(unsigned idx) {
189 assert(idx <= declarator.getNumTypeObjects());
193 AttributeList *&getCurrentAttrListRef() const {
194 if (isProcessingDeclSpec())
195 return getMutableDeclSpec().getAttributes().getListRef();
196 return declarator.getTypeObject(chunkIndex).getAttrListRef();
199 /// Save the current set of attributes on the DeclSpec.
200 void saveDeclSpecAttrs() {
201 // Don't try to save them multiple times.
202 if (hasSavedAttrs) return;
204 DeclSpec &spec = getMutableDeclSpec();
205 for (AttributeList *attr = spec.getAttributes().getList(); attr;
206 attr = attr->getNext())
207 savedAttrs.push_back(attr);
208 trivial &= savedAttrs.empty();
209 hasSavedAttrs = true;
212 /// Record that we had nowhere to put the given type attribute.
213 /// We will diagnose such attributes later.
214 void addIgnoredTypeAttr(AttributeList &attr) {
215 ignoredTypeAttrs.push_back(&attr);
218 /// Diagnose all the ignored type attributes, given that the
219 /// declarator worked out to the given type.
220 void diagnoseIgnoredTypeAttrs(QualType type) const {
221 for (auto *Attr : ignoredTypeAttrs)
222 diagnoseBadTypeAttribute(getSema(), *Attr, type);
225 ~TypeProcessingState() {
228 restoreDeclSpecAttrs();
232 DeclSpec &getMutableDeclSpec() const {
233 return const_cast<DeclSpec&>(declarator.getDeclSpec());
236 void restoreDeclSpecAttrs() {
237 assert(hasSavedAttrs);
239 if (savedAttrs.empty()) {
240 getMutableDeclSpec().getAttributes().set(nullptr);
244 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
245 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
246 savedAttrs[i]->setNext(savedAttrs[i+1]);
247 savedAttrs.back()->setNext(nullptr);
250 } // end anonymous namespace
252 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
257 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
259 head = attr.getNext();
263 AttributeList *cur = head;
265 assert(cur && cur->getNext() && "ran out of attrs?");
266 if (cur->getNext() == &attr) {
267 cur->setNext(attr.getNext());
270 cur = cur->getNext();
274 static void moveAttrFromListToList(AttributeList &attr,
275 AttributeList *&fromList,
276 AttributeList *&toList) {
277 spliceAttrOutOfList(attr, fromList);
278 spliceAttrIntoList(attr, toList);
281 /// The location of a type attribute.
282 enum TypeAttrLocation {
283 /// The attribute is in the decl-specifier-seq.
285 /// The attribute is part of a DeclaratorChunk.
287 /// The attribute is immediately after the declaration's name.
291 static void processTypeAttrs(TypeProcessingState &state,
292 QualType &type, TypeAttrLocation TAL,
293 AttributeList *attrs);
295 static bool handleFunctionTypeAttr(TypeProcessingState &state,
299 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
303 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
304 AttributeList &attr, QualType &type);
306 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
307 AttributeList &attr, QualType &type);
309 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
310 AttributeList &attr, QualType &type) {
311 if (attr.getKind() == AttributeList::AT_ObjCGC)
312 return handleObjCGCTypeAttr(state, attr, type);
313 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
314 return handleObjCOwnershipTypeAttr(state, attr, type);
317 /// Given the index of a declarator chunk, check whether that chunk
318 /// directly specifies the return type of a function and, if so, find
319 /// an appropriate place for it.
321 /// \param i - a notional index which the search will start
322 /// immediately inside
324 /// \param onlyBlockPointers Whether we should only look into block
325 /// pointer types (vs. all pointer types).
326 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
328 bool onlyBlockPointers) {
329 assert(i <= declarator.getNumTypeObjects());
331 DeclaratorChunk *result = nullptr;
333 // First, look inwards past parens for a function declarator.
334 for (; i != 0; --i) {
335 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
336 switch (fnChunk.Kind) {
337 case DeclaratorChunk::Paren:
340 // If we find anything except a function, bail out.
341 case DeclaratorChunk::Pointer:
342 case DeclaratorChunk::BlockPointer:
343 case DeclaratorChunk::Array:
344 case DeclaratorChunk::Reference:
345 case DeclaratorChunk::MemberPointer:
346 case DeclaratorChunk::Pipe:
349 // If we do find a function declarator, scan inwards from that,
350 // looking for a (block-)pointer declarator.
351 case DeclaratorChunk::Function:
352 for (--i; i != 0; --i) {
353 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
354 switch (ptrChunk.Kind) {
355 case DeclaratorChunk::Paren:
356 case DeclaratorChunk::Array:
357 case DeclaratorChunk::Function:
358 case DeclaratorChunk::Reference:
359 case DeclaratorChunk::Pipe:
362 case DeclaratorChunk::MemberPointer:
363 case DeclaratorChunk::Pointer:
364 if (onlyBlockPointers)
369 case DeclaratorChunk::BlockPointer:
373 llvm_unreachable("bad declarator chunk kind");
376 // If we run out of declarators doing that, we're done.
379 llvm_unreachable("bad declarator chunk kind");
381 // Okay, reconsider from our new point.
385 // Ran out of chunks, bail out.
389 /// Given that an objc_gc attribute was written somewhere on a
390 /// declaration *other* than on the declarator itself (for which, use
391 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
392 /// didn't apply in whatever position it was written in, try to move
393 /// it to a more appropriate position.
394 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
397 Declarator &declarator = state.getDeclarator();
399 // Move it to the outermost normal or block pointer declarator.
400 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
401 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
402 switch (chunk.Kind) {
403 case DeclaratorChunk::Pointer:
404 case DeclaratorChunk::BlockPointer: {
405 // But don't move an ARC ownership attribute to the return type
407 DeclaratorChunk *destChunk = nullptr;
408 if (state.isProcessingDeclSpec() &&
409 attr.getKind() == AttributeList::AT_ObjCOwnership)
410 destChunk = maybeMovePastReturnType(declarator, i - 1,
411 /*onlyBlockPointers=*/true);
412 if (!destChunk) destChunk = &chunk;
414 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
415 destChunk->getAttrListRef());
419 case DeclaratorChunk::Paren:
420 case DeclaratorChunk::Array:
423 // We may be starting at the return type of a block.
424 case DeclaratorChunk::Function:
425 if (state.isProcessingDeclSpec() &&
426 attr.getKind() == AttributeList::AT_ObjCOwnership) {
427 if (DeclaratorChunk *dest = maybeMovePastReturnType(
429 /*onlyBlockPointers=*/true)) {
430 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
431 dest->getAttrListRef());
437 // Don't walk through these.
438 case DeclaratorChunk::Reference:
439 case DeclaratorChunk::MemberPointer:
440 case DeclaratorChunk::Pipe:
446 diagnoseBadTypeAttribute(state.getSema(), attr, type);
449 /// Distribute an objc_gc type attribute that was written on the
452 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
454 QualType &declSpecType) {
455 Declarator &declarator = state.getDeclarator();
457 // objc_gc goes on the innermost pointer to something that's not a
459 unsigned innermost = -1U;
460 bool considerDeclSpec = true;
461 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
462 DeclaratorChunk &chunk = declarator.getTypeObject(i);
463 switch (chunk.Kind) {
464 case DeclaratorChunk::Pointer:
465 case DeclaratorChunk::BlockPointer:
469 case DeclaratorChunk::Reference:
470 case DeclaratorChunk::MemberPointer:
471 case DeclaratorChunk::Paren:
472 case DeclaratorChunk::Array:
473 case DeclaratorChunk::Pipe:
476 case DeclaratorChunk::Function:
477 considerDeclSpec = false;
483 // That might actually be the decl spec if we weren't blocked by
484 // anything in the declarator.
485 if (considerDeclSpec) {
486 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
487 // Splice the attribute into the decl spec. Prevents the
488 // attribute from being applied multiple times and gives
489 // the source-location-filler something to work with.
490 state.saveDeclSpecAttrs();
491 moveAttrFromListToList(attr, declarator.getAttrListRef(),
492 declarator.getMutableDeclSpec().getAttributes().getListRef());
497 // Otherwise, if we found an appropriate chunk, splice the attribute
499 if (innermost != -1U) {
500 moveAttrFromListToList(attr, declarator.getAttrListRef(),
501 declarator.getTypeObject(innermost).getAttrListRef());
505 // Otherwise, diagnose when we're done building the type.
506 spliceAttrOutOfList(attr, declarator.getAttrListRef());
507 state.addIgnoredTypeAttr(attr);
510 /// A function type attribute was written somewhere in a declaration
511 /// *other* than on the declarator itself or in the decl spec. Given
512 /// that it didn't apply in whatever position it was written in, try
513 /// to move it to a more appropriate position.
514 static void distributeFunctionTypeAttr(TypeProcessingState &state,
517 Declarator &declarator = state.getDeclarator();
519 // Try to push the attribute from the return type of a function to
520 // the function itself.
521 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
522 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
523 switch (chunk.Kind) {
524 case DeclaratorChunk::Function:
525 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
526 chunk.getAttrListRef());
529 case DeclaratorChunk::Paren:
530 case DeclaratorChunk::Pointer:
531 case DeclaratorChunk::BlockPointer:
532 case DeclaratorChunk::Array:
533 case DeclaratorChunk::Reference:
534 case DeclaratorChunk::MemberPointer:
535 case DeclaratorChunk::Pipe:
540 diagnoseBadTypeAttribute(state.getSema(), attr, type);
543 /// Try to distribute a function type attribute to the innermost
544 /// function chunk or type. Returns true if the attribute was
545 /// distributed, false if no location was found.
547 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
549 AttributeList *&attrList,
550 QualType &declSpecType) {
551 Declarator &declarator = state.getDeclarator();
553 // Put it on the innermost function chunk, if there is one.
554 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
555 DeclaratorChunk &chunk = declarator.getTypeObject(i);
556 if (chunk.Kind != DeclaratorChunk::Function) continue;
558 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
562 return handleFunctionTypeAttr(state, attr, declSpecType);
565 /// A function type attribute was written in the decl spec. Try to
566 /// apply it somewhere.
568 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
570 QualType &declSpecType) {
571 state.saveDeclSpecAttrs();
573 // C++11 attributes before the decl specifiers actually appertain to
574 // the declarators. Move them straight there. We don't support the
575 // 'put them wherever you like' semantics we allow for GNU attributes.
576 if (attr.isCXX11Attribute()) {
577 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
578 state.getDeclarator().getAttrListRef());
582 // Try to distribute to the innermost.
583 if (distributeFunctionTypeAttrToInnermost(state, attr,
584 state.getCurrentAttrListRef(),
588 // If that failed, diagnose the bad attribute when the declarator is
590 state.addIgnoredTypeAttr(attr);
593 /// A function type attribute was written on the declarator. Try to
594 /// apply it somewhere.
596 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
598 QualType &declSpecType) {
599 Declarator &declarator = state.getDeclarator();
601 // Try to distribute to the innermost.
602 if (distributeFunctionTypeAttrToInnermost(state, attr,
603 declarator.getAttrListRef(),
607 // If that failed, diagnose the bad attribute when the declarator is
609 spliceAttrOutOfList(attr, declarator.getAttrListRef());
610 state.addIgnoredTypeAttr(attr);
613 /// \brief Given that there are attributes written on the declarator
614 /// itself, try to distribute any type attributes to the appropriate
615 /// declarator chunk.
617 /// These are attributes like the following:
620 /// but not necessarily this:
622 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
623 QualType &declSpecType) {
624 // Collect all the type attributes from the declarator itself.
625 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
626 AttributeList *attr = state.getDeclarator().getAttributes();
629 next = attr->getNext();
631 // Do not distribute C++11 attributes. They have strict rules for what
632 // they appertain to.
633 if (attr->isCXX11Attribute())
636 switch (attr->getKind()) {
637 OBJC_POINTER_TYPE_ATTRS_CASELIST:
638 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
641 case AttributeList::AT_NSReturnsRetained:
642 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
646 FUNCTION_TYPE_ATTRS_CASELIST:
647 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
650 MS_TYPE_ATTRS_CASELIST:
651 // Microsoft type attributes cannot go after the declarator-id.
654 NULLABILITY_TYPE_ATTRS_CASELIST:
655 // Nullability specifiers cannot go after the declarator-id.
657 // Objective-C __kindof does not get distributed.
658 case AttributeList::AT_ObjCKindOf:
664 } while ((attr = next));
667 /// Add a synthetic '()' to a block-literal declarator if it is
668 /// required, given the return type.
669 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
670 QualType declSpecType) {
671 Declarator &declarator = state.getDeclarator();
673 // First, check whether the declarator would produce a function,
674 // i.e. whether the innermost semantic chunk is a function.
675 if (declarator.isFunctionDeclarator()) {
676 // If so, make that declarator a prototyped declarator.
677 declarator.getFunctionTypeInfo().hasPrototype = true;
681 // If there are any type objects, the type as written won't name a
682 // function, regardless of the decl spec type. This is because a
683 // block signature declarator is always an abstract-declarator, and
684 // abstract-declarators can't just be parentheses chunks. Therefore
685 // we need to build a function chunk unless there are no type
686 // objects and the decl spec type is a function.
687 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
690 // Note that there *are* cases with invalid declarators where
691 // declarators consist solely of parentheses. In general, these
692 // occur only in failed efforts to make function declarators, so
693 // faking up the function chunk is still the right thing to do.
695 // Otherwise, we need to fake up a function declarator.
696 SourceLocation loc = declarator.getLocStart();
698 // ...and *prepend* it to the declarator.
699 SourceLocation NoLoc;
700 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
702 /*IsAmbiguous=*/false,
706 /*EllipsisLoc=*/NoLoc,
709 /*RefQualifierIsLvalueRef=*/true,
710 /*RefQualifierLoc=*/NoLoc,
711 /*ConstQualifierLoc=*/NoLoc,
712 /*VolatileQualifierLoc=*/NoLoc,
713 /*RestrictQualifierLoc=*/NoLoc,
714 /*MutableLoc=*/NoLoc, EST_None,
715 /*ESpecRange=*/SourceRange(),
716 /*Exceptions=*/nullptr,
717 /*ExceptionRanges=*/nullptr,
719 /*NoexceptExpr=*/nullptr,
720 /*ExceptionSpecTokens=*/nullptr,
721 /*DeclsInPrototype=*/None,
722 loc, loc, declarator));
724 // For consistency, make sure the state still has us as processing
726 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
727 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
730 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
735 // If this occurs outside a template instantiation, warn the user about
736 // it; they probably didn't mean to specify a redundant qualifier.
737 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
738 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
739 QualLoc(DeclSpec::TQ_restrict, DS.getRestrictSpecLoc()),
740 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
741 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
742 if (!(RemoveTQs & Qual.first))
745 if (!S.inTemplateInstantiation()) {
746 if (TypeQuals & Qual.first)
747 S.Diag(Qual.second, DiagID)
748 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
749 << FixItHint::CreateRemoval(Qual.second);
752 TypeQuals &= ~Qual.first;
756 /// Return true if this is omitted block return type. Also check type
757 /// attributes and type qualifiers when returning true.
758 static bool checkOmittedBlockReturnType(Sema &S, Declarator &declarator,
760 if (!isOmittedBlockReturnType(declarator))
763 // Warn if we see type attributes for omitted return type on a block literal.
764 AttributeList *&attrs =
765 declarator.getMutableDeclSpec().getAttributes().getListRef();
766 AttributeList *prev = nullptr;
767 for (AttributeList *cur = attrs; cur; cur = cur->getNext()) {
768 AttributeList &attr = *cur;
769 // Skip attributes that were marked to be invalid or non-type
771 if (attr.isInvalid() || !attr.isTypeAttr()) {
775 S.Diag(attr.getLoc(),
776 diag::warn_block_literal_attributes_on_omitted_return_type)
778 // Remove cur from the list.
780 prev->setNext(cur->getNext());
783 attrs = cur->getNext();
787 // Warn if we see type qualifiers for omitted return type on a block literal.
788 const DeclSpec &DS = declarator.getDeclSpec();
789 unsigned TypeQuals = DS.getTypeQualifiers();
790 diagnoseAndRemoveTypeQualifiers(S, DS, TypeQuals, Result, (unsigned)-1,
791 diag::warn_block_literal_qualifiers_on_omitted_return_type);
792 declarator.getMutableDeclSpec().ClearTypeQualifiers();
797 /// Apply Objective-C type arguments to the given type.
798 static QualType applyObjCTypeArgs(Sema &S, SourceLocation loc, QualType type,
799 ArrayRef<TypeSourceInfo *> typeArgs,
800 SourceRange typeArgsRange,
801 bool failOnError = false) {
802 // We can only apply type arguments to an Objective-C class type.
803 const auto *objcObjectType = type->getAs<ObjCObjectType>();
804 if (!objcObjectType || !objcObjectType->getInterface()) {
805 S.Diag(loc, diag::err_objc_type_args_non_class)
814 // The class type must be parameterized.
815 ObjCInterfaceDecl *objcClass = objcObjectType->getInterface();
816 ObjCTypeParamList *typeParams = objcClass->getTypeParamList();
818 S.Diag(loc, diag::err_objc_type_args_non_parameterized_class)
819 << objcClass->getDeclName()
820 << FixItHint::CreateRemoval(typeArgsRange);
828 // The type must not already be specialized.
829 if (objcObjectType->isSpecialized()) {
830 S.Diag(loc, diag::err_objc_type_args_specialized_class)
832 << FixItHint::CreateRemoval(typeArgsRange);
840 // Check the type arguments.
841 SmallVector<QualType, 4> finalTypeArgs;
842 unsigned numTypeParams = typeParams->size();
843 bool anyPackExpansions = false;
844 for (unsigned i = 0, n = typeArgs.size(); i != n; ++i) {
845 TypeSourceInfo *typeArgInfo = typeArgs[i];
846 QualType typeArg = typeArgInfo->getType();
848 // Type arguments cannot have explicit qualifiers or nullability.
849 // We ignore indirect sources of these, e.g. behind typedefs or
850 // template arguments.
851 if (TypeLoc qual = typeArgInfo->getTypeLoc().findExplicitQualifierLoc()) {
852 bool diagnosed = false;
853 SourceRange rangeToRemove;
854 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
855 rangeToRemove = attr.getLocalSourceRange();
856 if (attr.getTypePtr()->getImmediateNullability()) {
857 typeArg = attr.getTypePtr()->getModifiedType();
858 S.Diag(attr.getLocStart(),
859 diag::err_objc_type_arg_explicit_nullability)
860 << typeArg << FixItHint::CreateRemoval(rangeToRemove);
866 S.Diag(qual.getLocStart(), diag::err_objc_type_arg_qualified)
867 << typeArg << typeArg.getQualifiers().getAsString()
868 << FixItHint::CreateRemoval(rangeToRemove);
872 // Remove qualifiers even if they're non-local.
873 typeArg = typeArg.getUnqualifiedType();
875 finalTypeArgs.push_back(typeArg);
877 if (typeArg->getAs<PackExpansionType>())
878 anyPackExpansions = true;
880 // Find the corresponding type parameter, if there is one.
881 ObjCTypeParamDecl *typeParam = nullptr;
882 if (!anyPackExpansions) {
883 if (i < numTypeParams) {
884 typeParam = typeParams->begin()[i];
886 // Too many arguments.
887 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
889 << objcClass->getDeclName()
890 << (unsigned)typeArgs.size()
892 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
902 // Objective-C object pointer types must be substitutable for the bounds.
903 if (const auto *typeArgObjC = typeArg->getAs<ObjCObjectPointerType>()) {
904 // If we don't have a type parameter to match against, assume
905 // everything is fine. There was a prior pack expansion that
906 // means we won't be able to match anything.
908 assert(anyPackExpansions && "Too many arguments?");
912 // Retrieve the bound.
913 QualType bound = typeParam->getUnderlyingType();
914 const auto *boundObjC = bound->getAs<ObjCObjectPointerType>();
916 // Determine whether the type argument is substitutable for the bound.
917 if (typeArgObjC->isObjCIdType()) {
918 // When the type argument is 'id', the only acceptable type
919 // parameter bound is 'id'.
920 if (boundObjC->isObjCIdType())
922 } else if (S.Context.canAssignObjCInterfaces(boundObjC, typeArgObjC)) {
923 // Otherwise, we follow the assignability rules.
927 // Diagnose the mismatch.
928 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
929 diag::err_objc_type_arg_does_not_match_bound)
930 << typeArg << bound << typeParam->getDeclName();
931 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
932 << typeParam->getDeclName();
940 // Block pointer types are permitted for unqualified 'id' bounds.
941 if (typeArg->isBlockPointerType()) {
942 // If we don't have a type parameter to match against, assume
943 // everything is fine. There was a prior pack expansion that
944 // means we won't be able to match anything.
946 assert(anyPackExpansions && "Too many arguments?");
950 // Retrieve the bound.
951 QualType bound = typeParam->getUnderlyingType();
952 if (bound->isBlockCompatibleObjCPointerType(S.Context))
955 // Diagnose the mismatch.
956 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
957 diag::err_objc_type_arg_does_not_match_bound)
958 << typeArg << bound << typeParam->getDeclName();
959 S.Diag(typeParam->getLocation(), diag::note_objc_type_param_here)
960 << typeParam->getDeclName();
968 // Dependent types will be checked at instantiation time.
969 if (typeArg->isDependentType()) {
973 // Diagnose non-id-compatible type arguments.
974 S.Diag(typeArgInfo->getTypeLoc().getLocStart(),
975 diag::err_objc_type_arg_not_id_compatible)
977 << typeArgInfo->getTypeLoc().getSourceRange();
985 // Make sure we didn't have the wrong number of arguments.
986 if (!anyPackExpansions && finalTypeArgs.size() != numTypeParams) {
987 S.Diag(loc, diag::err_objc_type_args_wrong_arity)
988 << (typeArgs.size() < typeParams->size())
989 << objcClass->getDeclName()
990 << (unsigned)finalTypeArgs.size()
991 << (unsigned)numTypeParams;
992 S.Diag(objcClass->getLocation(), diag::note_previous_decl)
1001 // Success. Form the specialized type.
1002 return S.Context.getObjCObjectType(type, finalTypeArgs, { }, false);
1005 QualType Sema::BuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
1006 SourceLocation ProtocolLAngleLoc,
1007 ArrayRef<ObjCProtocolDecl *> Protocols,
1008 ArrayRef<SourceLocation> ProtocolLocs,
1009 SourceLocation ProtocolRAngleLoc,
1011 QualType Result = QualType(Decl->getTypeForDecl(), 0);
1012 if (!Protocols.empty()) {
1014 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1017 Diag(SourceLocation(), diag::err_invalid_protocol_qualifiers)
1018 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1019 if (FailOnError) Result = QualType();
1021 if (FailOnError && Result.isNull())
1028 QualType Sema::BuildObjCObjectType(QualType BaseType,
1030 SourceLocation TypeArgsLAngleLoc,
1031 ArrayRef<TypeSourceInfo *> TypeArgs,
1032 SourceLocation TypeArgsRAngleLoc,
1033 SourceLocation ProtocolLAngleLoc,
1034 ArrayRef<ObjCProtocolDecl *> Protocols,
1035 ArrayRef<SourceLocation> ProtocolLocs,
1036 SourceLocation ProtocolRAngleLoc,
1038 QualType Result = BaseType;
1039 if (!TypeArgs.empty()) {
1040 Result = applyObjCTypeArgs(*this, Loc, Result, TypeArgs,
1041 SourceRange(TypeArgsLAngleLoc,
1044 if (FailOnError && Result.isNull())
1048 if (!Protocols.empty()) {
1050 Result = Context.applyObjCProtocolQualifiers(Result, Protocols,
1053 Diag(Loc, diag::err_invalid_protocol_qualifiers)
1054 << SourceRange(ProtocolLAngleLoc, ProtocolRAngleLoc);
1055 if (FailOnError) Result = QualType();
1057 if (FailOnError && Result.isNull())
1064 TypeResult Sema::actOnObjCProtocolQualifierType(
1065 SourceLocation lAngleLoc,
1066 ArrayRef<Decl *> protocols,
1067 ArrayRef<SourceLocation> protocolLocs,
1068 SourceLocation rAngleLoc) {
1069 // Form id<protocol-list>.
1070 QualType Result = Context.getObjCObjectType(
1071 Context.ObjCBuiltinIdTy, { },
1073 (ObjCProtocolDecl * const *)protocols.data(),
1076 Result = Context.getObjCObjectPointerType(Result);
1078 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1079 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1081 auto ObjCObjectPointerTL = ResultTL.castAs<ObjCObjectPointerTypeLoc>();
1082 ObjCObjectPointerTL.setStarLoc(SourceLocation()); // implicit
1084 auto ObjCObjectTL = ObjCObjectPointerTL.getPointeeLoc()
1085 .castAs<ObjCObjectTypeLoc>();
1086 ObjCObjectTL.setHasBaseTypeAsWritten(false);
1087 ObjCObjectTL.getBaseLoc().initialize(Context, SourceLocation());
1089 // No type arguments.
1090 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1091 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1093 // Fill in protocol qualifiers.
1094 ObjCObjectTL.setProtocolLAngleLoc(lAngleLoc);
1095 ObjCObjectTL.setProtocolRAngleLoc(rAngleLoc);
1096 for (unsigned i = 0, n = protocols.size(); i != n; ++i)
1097 ObjCObjectTL.setProtocolLoc(i, protocolLocs[i]);
1099 // We're done. Return the completed type to the parser.
1100 return CreateParsedType(Result, ResultTInfo);
1103 TypeResult Sema::actOnObjCTypeArgsAndProtocolQualifiers(
1106 ParsedType BaseType,
1107 SourceLocation TypeArgsLAngleLoc,
1108 ArrayRef<ParsedType> TypeArgs,
1109 SourceLocation TypeArgsRAngleLoc,
1110 SourceLocation ProtocolLAngleLoc,
1111 ArrayRef<Decl *> Protocols,
1112 ArrayRef<SourceLocation> ProtocolLocs,
1113 SourceLocation ProtocolRAngleLoc) {
1114 TypeSourceInfo *BaseTypeInfo = nullptr;
1115 QualType T = GetTypeFromParser(BaseType, &BaseTypeInfo);
1119 // Handle missing type-source info.
1121 BaseTypeInfo = Context.getTrivialTypeSourceInfo(T, Loc);
1123 // Extract type arguments.
1124 SmallVector<TypeSourceInfo *, 4> ActualTypeArgInfos;
1125 for (unsigned i = 0, n = TypeArgs.size(); i != n; ++i) {
1126 TypeSourceInfo *TypeArgInfo = nullptr;
1127 QualType TypeArg = GetTypeFromParser(TypeArgs[i], &TypeArgInfo);
1128 if (TypeArg.isNull()) {
1129 ActualTypeArgInfos.clear();
1133 assert(TypeArgInfo && "No type source info?");
1134 ActualTypeArgInfos.push_back(TypeArgInfo);
1137 // Build the object type.
1138 QualType Result = BuildObjCObjectType(
1139 T, BaseTypeInfo->getTypeLoc().getSourceRange().getBegin(),
1140 TypeArgsLAngleLoc, ActualTypeArgInfos, TypeArgsRAngleLoc,
1142 llvm::makeArrayRef((ObjCProtocolDecl * const *)Protocols.data(),
1144 ProtocolLocs, ProtocolRAngleLoc,
1145 /*FailOnError=*/false);
1150 // Create source information for this type.
1151 TypeSourceInfo *ResultTInfo = Context.CreateTypeSourceInfo(Result);
1152 TypeLoc ResultTL = ResultTInfo->getTypeLoc();
1154 // For id<Proto1, Proto2> or Class<Proto1, Proto2>, we'll have an
1155 // object pointer type. Fill in source information for it.
1156 if (auto ObjCObjectPointerTL = ResultTL.getAs<ObjCObjectPointerTypeLoc>()) {
1157 // The '*' is implicit.
1158 ObjCObjectPointerTL.setStarLoc(SourceLocation());
1159 ResultTL = ObjCObjectPointerTL.getPointeeLoc();
1162 if (auto OTPTL = ResultTL.getAs<ObjCTypeParamTypeLoc>()) {
1163 // Protocol qualifier information.
1164 if (OTPTL.getNumProtocols() > 0) {
1165 assert(OTPTL.getNumProtocols() == Protocols.size());
1166 OTPTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1167 OTPTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1168 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1169 OTPTL.setProtocolLoc(i, ProtocolLocs[i]);
1172 // We're done. Return the completed type to the parser.
1173 return CreateParsedType(Result, ResultTInfo);
1176 auto ObjCObjectTL = ResultTL.castAs<ObjCObjectTypeLoc>();
1178 // Type argument information.
1179 if (ObjCObjectTL.getNumTypeArgs() > 0) {
1180 assert(ObjCObjectTL.getNumTypeArgs() == ActualTypeArgInfos.size());
1181 ObjCObjectTL.setTypeArgsLAngleLoc(TypeArgsLAngleLoc);
1182 ObjCObjectTL.setTypeArgsRAngleLoc(TypeArgsRAngleLoc);
1183 for (unsigned i = 0, n = ActualTypeArgInfos.size(); i != n; ++i)
1184 ObjCObjectTL.setTypeArgTInfo(i, ActualTypeArgInfos[i]);
1186 ObjCObjectTL.setTypeArgsLAngleLoc(SourceLocation());
1187 ObjCObjectTL.setTypeArgsRAngleLoc(SourceLocation());
1190 // Protocol qualifier information.
1191 if (ObjCObjectTL.getNumProtocols() > 0) {
1192 assert(ObjCObjectTL.getNumProtocols() == Protocols.size());
1193 ObjCObjectTL.setProtocolLAngleLoc(ProtocolLAngleLoc);
1194 ObjCObjectTL.setProtocolRAngleLoc(ProtocolRAngleLoc);
1195 for (unsigned i = 0, n = Protocols.size(); i != n; ++i)
1196 ObjCObjectTL.setProtocolLoc(i, ProtocolLocs[i]);
1198 ObjCObjectTL.setProtocolLAngleLoc(SourceLocation());
1199 ObjCObjectTL.setProtocolRAngleLoc(SourceLocation());
1203 ObjCObjectTL.setHasBaseTypeAsWritten(true);
1204 if (ObjCObjectTL.getType() == T)
1205 ObjCObjectTL.getBaseLoc().initializeFullCopy(BaseTypeInfo->getTypeLoc());
1207 ObjCObjectTL.getBaseLoc().initialize(Context, Loc);
1209 // We're done. Return the completed type to the parser.
1210 return CreateParsedType(Result, ResultTInfo);
1213 static OpenCLAccessAttr::Spelling getImageAccess(const AttributeList *Attrs) {
1215 const AttributeList *Next = Attrs;
1217 const AttributeList &Attr = *Next;
1218 Next = Attr.getNext();
1219 if (Attr.getKind() == AttributeList::AT_OpenCLAccess) {
1220 return static_cast<OpenCLAccessAttr::Spelling>(
1221 Attr.getSemanticSpelling());
1225 return OpenCLAccessAttr::Keyword_read_only;
1228 /// \brief Convert the specified declspec to the appropriate type
1230 /// \param state Specifies the declarator containing the declaration specifier
1231 /// to be converted, along with other associated processing state.
1232 /// \returns The type described by the declaration specifiers. This function
1233 /// never returns null.
1234 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
1235 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
1238 Sema &S = state.getSema();
1239 Declarator &declarator = state.getDeclarator();
1240 const DeclSpec &DS = declarator.getDeclSpec();
1241 SourceLocation DeclLoc = declarator.getIdentifierLoc();
1242 if (DeclLoc.isInvalid())
1243 DeclLoc = DS.getLocStart();
1245 ASTContext &Context = S.Context;
1248 switch (DS.getTypeSpecType()) {
1249 case DeclSpec::TST_void:
1250 Result = Context.VoidTy;
1252 case DeclSpec::TST_char:
1253 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1254 Result = Context.CharTy;
1255 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
1256 Result = Context.SignedCharTy;
1258 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1259 "Unknown TSS value");
1260 Result = Context.UnsignedCharTy;
1263 case DeclSpec::TST_wchar:
1264 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
1265 Result = Context.WCharTy;
1266 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
1267 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1268 << DS.getSpecifierName(DS.getTypeSpecType(),
1269 Context.getPrintingPolicy());
1270 Result = Context.getSignedWCharType();
1272 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
1273 "Unknown TSS value");
1274 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
1275 << DS.getSpecifierName(DS.getTypeSpecType(),
1276 Context.getPrintingPolicy());
1277 Result = Context.getUnsignedWCharType();
1280 case DeclSpec::TST_char16:
1281 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1282 "Unknown TSS value");
1283 Result = Context.Char16Ty;
1285 case DeclSpec::TST_char32:
1286 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
1287 "Unknown TSS value");
1288 Result = Context.Char32Ty;
1290 case DeclSpec::TST_unspecified:
1291 // If this is a missing declspec in a block literal return context, then it
1292 // is inferred from the return statements inside the block.
1293 // The declspec is always missing in a lambda expr context; it is either
1294 // specified with a trailing return type or inferred.
1295 if (S.getLangOpts().CPlusPlus14 &&
1296 declarator.getContext() == Declarator::LambdaExprContext) {
1297 // In C++1y, a lambda's implicit return type is 'auto'.
1298 Result = Context.getAutoDeductType();
1300 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
1301 checkOmittedBlockReturnType(S, declarator,
1302 Context.DependentTy)) {
1303 Result = Context.DependentTy;
1307 // Unspecified typespec defaults to int in C90. However, the C90 grammar
1308 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
1309 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
1310 // Note that the one exception to this is function definitions, which are
1311 // allowed to be completely missing a declspec. This is handled in the
1312 // parser already though by it pretending to have seen an 'int' in this
1314 if (S.getLangOpts().ImplicitInt) {
1315 // In C89 mode, we only warn if there is a completely missing declspec
1316 // when one is not allowed.
1318 S.Diag(DeclLoc, diag::ext_missing_declspec)
1319 << DS.getSourceRange()
1320 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
1322 } else if (!DS.hasTypeSpecifier()) {
1323 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
1324 // "At least one type specifier shall be given in the declaration
1325 // specifiers in each declaration, and in the specifier-qualifier list in
1326 // each struct declaration and type name."
1327 if (S.getLangOpts().CPlusPlus) {
1328 S.Diag(DeclLoc, diag::err_missing_type_specifier)
1329 << DS.getSourceRange();
1331 // When this occurs in C++ code, often something is very broken with the
1332 // value being declared, poison it as invalid so we don't get chains of
1334 declarator.setInvalidType(true);
1335 } else if (S.getLangOpts().OpenCLVersion >= 200 && DS.isTypeSpecPipe()){
1336 S.Diag(DeclLoc, diag::err_missing_actual_pipe_type)
1337 << DS.getSourceRange();
1338 declarator.setInvalidType(true);
1340 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
1341 << DS.getSourceRange();
1346 case DeclSpec::TST_int: {
1347 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
1348 switch (DS.getTypeSpecWidth()) {
1349 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
1350 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
1351 case DeclSpec::TSW_long: Result = Context.LongTy; break;
1352 case DeclSpec::TSW_longlong:
1353 Result = Context.LongLongTy;
1355 // 'long long' is a C99 or C++11 feature.
1356 if (!S.getLangOpts().C99) {
1357 if (S.getLangOpts().CPlusPlus)
1358 S.Diag(DS.getTypeSpecWidthLoc(),
1359 S.getLangOpts().CPlusPlus11 ?
1360 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1362 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1367 switch (DS.getTypeSpecWidth()) {
1368 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
1369 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
1370 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
1371 case DeclSpec::TSW_longlong:
1372 Result = Context.UnsignedLongLongTy;
1374 // 'long long' is a C99 or C++11 feature.
1375 if (!S.getLangOpts().C99) {
1376 if (S.getLangOpts().CPlusPlus)
1377 S.Diag(DS.getTypeSpecWidthLoc(),
1378 S.getLangOpts().CPlusPlus11 ?
1379 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
1381 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
1388 case DeclSpec::TST_int128:
1389 if (!S.Context.getTargetInfo().hasInt128Type())
1390 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1392 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
1393 Result = Context.UnsignedInt128Ty;
1395 Result = Context.Int128Ty;
1397 case DeclSpec::TST_half: Result = Context.HalfTy; break;
1398 case DeclSpec::TST_float: Result = Context.FloatTy; break;
1399 case DeclSpec::TST_double:
1400 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
1401 Result = Context.LongDoubleTy;
1403 Result = Context.DoubleTy;
1405 case DeclSpec::TST_float128:
1406 if (!S.Context.getTargetInfo().hasFloat128Type())
1407 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_unsupported)
1409 Result = Context.Float128Ty;
1411 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
1413 case DeclSpec::TST_decimal32: // _Decimal32
1414 case DeclSpec::TST_decimal64: // _Decimal64
1415 case DeclSpec::TST_decimal128: // _Decimal128
1416 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
1417 Result = Context.IntTy;
1418 declarator.setInvalidType(true);
1420 case DeclSpec::TST_class:
1421 case DeclSpec::TST_enum:
1422 case DeclSpec::TST_union:
1423 case DeclSpec::TST_struct:
1424 case DeclSpec::TST_interface: {
1425 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
1427 // This can happen in C++ with ambiguous lookups.
1428 Result = Context.IntTy;
1429 declarator.setInvalidType(true);
1433 // If the type is deprecated or unavailable, diagnose it.
1434 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
1436 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1437 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
1439 // TypeQuals handled by caller.
1440 Result = Context.getTypeDeclType(D);
1442 // In both C and C++, make an ElaboratedType.
1443 ElaboratedTypeKeyword Keyword
1444 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
1445 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
1448 case DeclSpec::TST_typename: {
1449 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
1450 DS.getTypeSpecSign() == 0 &&
1451 "Can't handle qualifiers on typedef names yet!");
1452 Result = S.GetTypeFromParser(DS.getRepAsType());
1453 if (Result.isNull()) {
1454 declarator.setInvalidType(true);
1457 // TypeQuals handled by caller.
1460 case DeclSpec::TST_typeofType:
1461 // FIXME: Preserve type source info.
1462 Result = S.GetTypeFromParser(DS.getRepAsType());
1463 assert(!Result.isNull() && "Didn't get a type for typeof?");
1464 if (!Result->isDependentType())
1465 if (const TagType *TT = Result->getAs<TagType>())
1466 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1467 // TypeQuals handled by caller.
1468 Result = Context.getTypeOfType(Result);
1470 case DeclSpec::TST_typeofExpr: {
1471 Expr *E = DS.getRepAsExpr();
1472 assert(E && "Didn't get an expression for typeof?");
1473 // TypeQuals handled by caller.
1474 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1475 if (Result.isNull()) {
1476 Result = Context.IntTy;
1477 declarator.setInvalidType(true);
1481 case DeclSpec::TST_decltype: {
1482 Expr *E = DS.getRepAsExpr();
1483 assert(E && "Didn't get an expression for decltype?");
1484 // TypeQuals handled by caller.
1485 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1486 if (Result.isNull()) {
1487 Result = Context.IntTy;
1488 declarator.setInvalidType(true);
1492 case DeclSpec::TST_underlyingType:
1493 Result = S.GetTypeFromParser(DS.getRepAsType());
1494 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1495 Result = S.BuildUnaryTransformType(Result,
1496 UnaryTransformType::EnumUnderlyingType,
1497 DS.getTypeSpecTypeLoc());
1498 if (Result.isNull()) {
1499 Result = Context.IntTy;
1500 declarator.setInvalidType(true);
1504 case DeclSpec::TST_auto:
1505 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1508 case DeclSpec::TST_auto_type:
1509 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1512 case DeclSpec::TST_decltype_auto:
1513 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1514 /*IsDependent*/ false);
1517 case DeclSpec::TST_unknown_anytype:
1518 Result = Context.UnknownAnyTy;
1521 case DeclSpec::TST_atomic:
1522 Result = S.GetTypeFromParser(DS.getRepAsType());
1523 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1524 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1525 if (Result.isNull()) {
1526 Result = Context.IntTy;
1527 declarator.setInvalidType(true);
1531 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1532 case DeclSpec::TST_##ImgType##_t: \
1533 switch (getImageAccess(DS.getAttributes().getList())) { \
1534 case OpenCLAccessAttr::Keyword_write_only: \
1535 Result = Context.Id##WOTy; break; \
1536 case OpenCLAccessAttr::Keyword_read_write: \
1537 Result = Context.Id##RWTy; break; \
1538 case OpenCLAccessAttr::Keyword_read_only: \
1539 Result = Context.Id##ROTy; break; \
1542 #include "clang/Basic/OpenCLImageTypes.def"
1544 case DeclSpec::TST_error:
1545 Result = Context.IntTy;
1546 declarator.setInvalidType(true);
1550 if (S.getLangOpts().OpenCL &&
1551 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1552 declarator.setInvalidType(true);
1554 // Handle complex types.
1555 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1556 if (S.getLangOpts().Freestanding)
1557 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1558 Result = Context.getComplexType(Result);
1559 } else if (DS.isTypeAltiVecVector()) {
1560 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1561 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1562 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1563 if (DS.isTypeAltiVecPixel())
1564 VecKind = VectorType::AltiVecPixel;
1565 else if (DS.isTypeAltiVecBool())
1566 VecKind = VectorType::AltiVecBool;
1567 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1570 // FIXME: Imaginary.
1571 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1572 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1574 // Before we process any type attributes, synthesize a block literal
1575 // function declarator if necessary.
1576 if (declarator.getContext() == Declarator::BlockLiteralContext)
1577 maybeSynthesizeBlockSignature(state, Result);
1579 // Apply any type attributes from the decl spec. This may cause the
1580 // list of type attributes to be temporarily saved while the type
1581 // attributes are pushed around.
1582 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1583 if (!DS.isTypeSpecPipe())
1584 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1586 // Apply const/volatile/restrict qualifiers to T.
1587 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1588 // Warn about CV qualifiers on function types.
1590 // If the specification of a function type includes any type qualifiers,
1591 // the behavior is undefined.
1592 // C++11 [dcl.fct]p7:
1593 // The effect of a cv-qualifier-seq in a function declarator is not the
1594 // same as adding cv-qualification on top of the function type. In the
1595 // latter case, the cv-qualifiers are ignored.
1596 if (TypeQuals && Result->isFunctionType()) {
1597 diagnoseAndRemoveTypeQualifiers(
1598 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1599 S.getLangOpts().CPlusPlus
1600 ? diag::warn_typecheck_function_qualifiers_ignored
1601 : diag::warn_typecheck_function_qualifiers_unspecified);
1602 // No diagnostic for 'restrict' or '_Atomic' applied to a
1603 // function type; we'll diagnose those later, in BuildQualifiedType.
1606 // C++11 [dcl.ref]p1:
1607 // Cv-qualified references are ill-formed except when the
1608 // cv-qualifiers are introduced through the use of a typedef-name
1609 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1611 // There don't appear to be any other contexts in which a cv-qualified
1612 // reference type could be formed, so the 'ill-formed' clause here appears
1614 if (TypeQuals && Result->isReferenceType()) {
1615 diagnoseAndRemoveTypeQualifiers(
1616 S, DS, TypeQuals, Result,
1617 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1618 diag::warn_typecheck_reference_qualifiers);
1621 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1622 // than once in the same specifier-list or qualifier-list, either directly
1623 // or via one or more typedefs."
1624 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1625 && TypeQuals & Result.getCVRQualifiers()) {
1626 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1627 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1631 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1632 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1636 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1637 // produce a warning in this case.
1640 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1642 // If adding qualifiers fails, just use the unqualified type.
1643 if (Qualified.isNull())
1644 declarator.setInvalidType(true);
1649 assert(!Result.isNull() && "This function should not return a null type");
1653 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1655 return Entity.getAsString();
1660 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1661 Qualifiers Qs, const DeclSpec *DS) {
1665 // Ignore any attempt to form a cv-qualified reference.
1666 if (T->isReferenceType()) {
1668 Qs.removeVolatile();
1671 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1672 // object or incomplete types shall not be restrict-qualified."
1673 if (Qs.hasRestrict()) {
1674 unsigned DiagID = 0;
1677 if (T->isAnyPointerType() || T->isReferenceType() ||
1678 T->isMemberPointerType()) {
1680 if (T->isObjCObjectPointerType())
1682 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1683 EltTy = PTy->getPointeeType();
1685 EltTy = T->getPointeeType();
1687 // If we have a pointer or reference, the pointee must have an object
1689 if (!EltTy->isIncompleteOrObjectType()) {
1690 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1693 } else if (!T->isDependentType()) {
1694 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1699 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1700 Qs.removeRestrict();
1704 return Context.getQualifiedType(T, Qs);
1707 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1708 unsigned CVRAU, const DeclSpec *DS) {
1712 // Ignore any attempt to form a cv-qualified reference.
1713 if (T->isReferenceType())
1715 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1717 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1719 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1722 // If the same qualifier appears more than once in the same
1723 // specifier-qualifier-list, either directly or via one or more typedefs,
1724 // the behavior is the same as if it appeared only once.
1726 // It's not specified what happens when the _Atomic qualifier is applied to
1727 // a type specified with the _Atomic specifier, but we assume that this
1728 // should be treated as if the _Atomic qualifier appeared multiple times.
1729 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1731 // If other qualifiers appear along with the _Atomic qualifier in a
1732 // specifier-qualifier-list, the resulting type is the so-qualified
1735 // Don't need to worry about array types here, since _Atomic can't be
1736 // applied to such types.
1737 SplitQualType Split = T.getSplitUnqualifiedType();
1738 T = BuildAtomicType(QualType(Split.Ty, 0),
1739 DS ? DS->getAtomicSpecLoc() : Loc);
1742 Split.Quals.addCVRQualifiers(CVR);
1743 return BuildQualifiedType(T, Loc, Split.Quals);
1746 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1747 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1748 return BuildQualifiedType(T, Loc, Q, DS);
1751 /// \brief Build a paren type including \p T.
1752 QualType Sema::BuildParenType(QualType T) {
1753 return Context.getParenType(T);
1756 /// Given that we're building a pointer or reference to the given
1757 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1760 // Bail out if retention is unrequired or already specified.
1761 if (!type->isObjCLifetimeType() ||
1762 type.getObjCLifetime() != Qualifiers::OCL_None)
1765 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1767 // If the object type is const-qualified, we can safely use
1768 // __unsafe_unretained. This is safe (because there are no read
1769 // barriers), and it'll be safe to coerce anything but __weak* to
1770 // the resulting type.
1771 if (type.isConstQualified()) {
1772 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1774 // Otherwise, check whether the static type does not require
1775 // retaining. This currently only triggers for Class (possibly
1776 // protocol-qualifed, and arrays thereof).
1777 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1778 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1780 // If we are in an unevaluated context, like sizeof, skip adding a
1782 } else if (S.isUnevaluatedContext()) {
1785 // If that failed, give an error and recover using __strong. __strong
1786 // is the option most likely to prevent spurious second-order diagnostics,
1787 // like when binding a reference to a field.
1789 // These types can show up in private ivars in system headers, so
1790 // we need this to not be an error in those cases. Instead we
1792 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1793 S.DelayedDiagnostics.add(
1794 sema::DelayedDiagnostic::makeForbiddenType(loc,
1795 diag::err_arc_indirect_no_ownership, type, isReference));
1797 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1799 implicitLifetime = Qualifiers::OCL_Strong;
1801 assert(implicitLifetime && "didn't infer any lifetime!");
1804 qs.addObjCLifetime(implicitLifetime);
1805 return S.Context.getQualifiedType(type, qs);
1808 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1810 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1812 switch (FnTy->getRefQualifier()) {
1833 /// Kinds of declarator that cannot contain a qualified function type.
1835 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1836 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1837 /// at the topmost level of a type.
1839 /// Parens and member pointers are permitted. We don't diagnose array and
1840 /// function declarators, because they don't allow function types at all.
1842 /// The values of this enum are used in diagnostics.
1843 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1844 } // end anonymous namespace
1846 /// Check whether the type T is a qualified function type, and if it is,
1847 /// diagnose that it cannot be contained within the given kind of declarator.
1848 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1849 QualifiedFunctionKind QFK) {
1850 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1851 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1852 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1855 S.Diag(Loc, diag::err_compound_qualified_function_type)
1856 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1857 << getFunctionQualifiersAsString(FPT);
1861 /// \brief Build a pointer type.
1863 /// \param T The type to which we'll be building a pointer.
1865 /// \param Loc The location of the entity whose type involves this
1866 /// pointer type or, if there is no such entity, the location of the
1867 /// type that will have pointer type.
1869 /// \param Entity The name of the entity that involves the pointer
1872 /// \returns A suitable pointer type, if there are no
1873 /// errors. Otherwise, returns a NULL type.
1874 QualType Sema::BuildPointerType(QualType T,
1875 SourceLocation Loc, DeclarationName Entity) {
1876 if (T->isReferenceType()) {
1877 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1878 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1879 << getPrintableNameForEntity(Entity) << T;
1883 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1886 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1888 // In ARC, it is forbidden to build pointers to unqualified pointers.
1889 if (getLangOpts().ObjCAutoRefCount)
1890 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1892 // Build the pointer type.
1893 return Context.getPointerType(T);
1896 /// \brief Build a reference type.
1898 /// \param T The type to which we'll be building a reference.
1900 /// \param Loc The location of the entity whose type involves this
1901 /// reference type or, if there is no such entity, the location of the
1902 /// type that will have reference type.
1904 /// \param Entity The name of the entity that involves the reference
1907 /// \returns A suitable reference type, if there are no
1908 /// errors. Otherwise, returns a NULL type.
1909 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1911 DeclarationName Entity) {
1912 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1913 "Unresolved overloaded function type");
1915 // C++0x [dcl.ref]p6:
1916 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1917 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1918 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1919 // the type "lvalue reference to T", while an attempt to create the type
1920 // "rvalue reference to cv TR" creates the type TR.
1921 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1923 // C++ [dcl.ref]p4: There shall be no references to references.
1925 // According to C++ DR 106, references to references are only
1926 // diagnosed when they are written directly (e.g., "int & &"),
1927 // but not when they happen via a typedef:
1929 // typedef int& intref;
1930 // typedef intref& intref2;
1932 // Parser::ParseDeclaratorInternal diagnoses the case where
1933 // references are written directly; here, we handle the
1934 // collapsing of references-to-references as described in C++0x.
1935 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1938 // A declarator that specifies the type "reference to cv void"
1940 if (T->isVoidType()) {
1941 Diag(Loc, diag::err_reference_to_void);
1945 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1948 // In ARC, it is forbidden to build references to unqualified pointers.
1949 if (getLangOpts().ObjCAutoRefCount)
1950 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1952 // Handle restrict on references.
1954 return Context.getLValueReferenceType(T, SpelledAsLValue);
1955 return Context.getRValueReferenceType(T);
1958 /// \brief Build a Read-only Pipe type.
1960 /// \param T The type to which we'll be building a Pipe.
1962 /// \param Loc We do not use it for now.
1964 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1966 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
1967 return Context.getReadPipeType(T);
1970 /// \brief Build a Write-only Pipe type.
1972 /// \param T The type to which we'll be building a Pipe.
1974 /// \param Loc We do not use it for now.
1976 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1978 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
1979 return Context.getWritePipeType(T);
1982 /// Check whether the specified array size makes the array type a VLA. If so,
1983 /// return true, if not, return the size of the array in SizeVal.
1984 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1985 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1986 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1987 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1989 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1991 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1994 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1995 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1999 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2000 S.LangOpts.GNUMode ||
2001 S.LangOpts.OpenCL).isInvalid();
2004 /// \brief Build an array type.
2006 /// \param T The type of each element in the array.
2008 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2010 /// \param ArraySize Expression describing the size of the array.
2012 /// \param Brackets The range from the opening '[' to the closing ']'.
2014 /// \param Entity The name of the entity that involves the array
2017 /// \returns A suitable array type, if there are no errors. Otherwise,
2018 /// returns a NULL type.
2019 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2020 Expr *ArraySize, unsigned Quals,
2021 SourceRange Brackets, DeclarationName Entity) {
2023 SourceLocation Loc = Brackets.getBegin();
2024 if (getLangOpts().CPlusPlus) {
2025 // C++ [dcl.array]p1:
2026 // T is called the array element type; this type shall not be a reference
2027 // type, the (possibly cv-qualified) type void, a function type or an
2028 // abstract class type.
2030 // C++ [dcl.array]p3:
2031 // When several "array of" specifications are adjacent, [...] only the
2032 // first of the constant expressions that specify the bounds of the arrays
2035 // Note: function types are handled in the common path with C.
2036 if (T->isReferenceType()) {
2037 Diag(Loc, diag::err_illegal_decl_array_of_references)
2038 << getPrintableNameForEntity(Entity) << T;
2042 if (T->isVoidType() || T->isIncompleteArrayType()) {
2043 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2047 if (RequireNonAbstractType(Brackets.getBegin(), T,
2048 diag::err_array_of_abstract_type))
2051 // Mentioning a member pointer type for an array type causes us to lock in
2052 // an inheritance model, even if it's inside an unused typedef.
2053 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2054 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2055 if (!MPTy->getClass()->isDependentType())
2056 (void)isCompleteType(Loc, T);
2059 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2060 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2061 if (RequireCompleteType(Loc, T,
2062 diag::err_illegal_decl_array_incomplete_type))
2066 if (T->isFunctionType()) {
2067 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2068 << getPrintableNameForEntity(Entity) << T;
2072 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2073 // If the element type is a struct or union that contains a variadic
2074 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2075 if (EltTy->getDecl()->hasFlexibleArrayMember())
2076 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2077 } else if (T->isObjCObjectType()) {
2078 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2082 // Do placeholder conversions on the array size expression.
2083 if (ArraySize && ArraySize->hasPlaceholderType()) {
2084 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2085 if (Result.isInvalid()) return QualType();
2086 ArraySize = Result.get();
2089 // Do lvalue-to-rvalue conversions on the array size expression.
2090 if (ArraySize && !ArraySize->isRValue()) {
2091 ExprResult Result = DefaultLvalueConversion(ArraySize);
2092 if (Result.isInvalid())
2095 ArraySize = Result.get();
2098 // C99 6.7.5.2p1: The size expression shall have integer type.
2099 // C++11 allows contextual conversions to such types.
2100 if (!getLangOpts().CPlusPlus11 &&
2101 ArraySize && !ArraySize->isTypeDependent() &&
2102 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2103 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2104 << ArraySize->getType() << ArraySize->getSourceRange();
2108 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2110 if (ASM == ArrayType::Star)
2111 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2113 T = Context.getIncompleteArrayType(T, ASM, Quals);
2114 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2115 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2116 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2117 !T->isConstantSizeType()) ||
2118 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2119 // Even in C++11, don't allow contextual conversions in the array bound
2121 if (getLangOpts().CPlusPlus11 &&
2122 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2123 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2124 << ArraySize->getType() << ArraySize->getSourceRange();
2128 // C99: an array with an element type that has a non-constant-size is a VLA.
2129 // C99: an array with a non-ICE size is a VLA. We accept any expression
2130 // that we can fold to a non-zero positive value as an extension.
2131 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2133 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2134 // have a value greater than zero.
2135 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2137 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2138 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2140 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2141 << ArraySize->getSourceRange();
2144 if (ConstVal == 0) {
2145 // GCC accepts zero sized static arrays. We allow them when
2146 // we're not in a SFINAE context.
2147 Diag(ArraySize->getLocStart(),
2148 isSFINAEContext()? diag::err_typecheck_zero_array_size
2149 : diag::ext_typecheck_zero_array_size)
2150 << ArraySize->getSourceRange();
2152 if (ASM == ArrayType::Static) {
2153 Diag(ArraySize->getLocStart(),
2154 diag::warn_typecheck_zero_static_array_size)
2155 << ArraySize->getSourceRange();
2156 ASM = ArrayType::Normal;
2158 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2159 !T->isIncompleteType() && !T->isUndeducedType()) {
2160 // Is the array too large?
2161 unsigned ActiveSizeBits
2162 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2163 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2164 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2165 << ConstVal.toString(10)
2166 << ArraySize->getSourceRange();
2171 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2174 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2175 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2176 Diag(Loc, diag::err_opencl_vla);
2179 // CUDA device code doesn't support VLAs.
2180 if (getLangOpts().CUDA && T->isVariableArrayType())
2181 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2183 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2184 if (!getLangOpts().C99) {
2185 if (T->isVariableArrayType()) {
2186 // Prohibit the use of VLAs during template argument deduction.
2187 if (isSFINAEContext()) {
2188 Diag(Loc, diag::err_vla_in_sfinae);
2191 // Just extwarn about VLAs.
2193 Diag(Loc, diag::ext_vla);
2194 } else if (ASM != ArrayType::Normal || Quals != 0)
2196 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2197 : diag::ext_c99_array_usage) << ASM;
2200 if (T->isVariableArrayType()) {
2201 // Warn about VLAs for -Wvla.
2202 Diag(Loc, diag::warn_vla_used);
2205 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2206 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2207 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2208 if (getLangOpts().OpenCL) {
2209 const QualType ArrType = Context.getBaseElementType(T);
2210 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2211 ArrType->isSamplerT() || ArrType->isImageType()) {
2212 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2220 /// \brief Build an ext-vector type.
2222 /// Run the required checks for the extended vector type.
2223 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2224 SourceLocation AttrLoc) {
2225 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2226 // in conjunction with complex types (pointers, arrays, functions, etc.).
2228 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2229 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2230 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2231 // of bool aren't allowed.
2232 if ((!T->isDependentType() && !T->isIntegerType() &&
2233 !T->isRealFloatingType()) ||
2234 T->isBooleanType()) {
2235 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2239 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2240 llvm::APSInt vecSize(32);
2241 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2242 Diag(AttrLoc, diag::err_attribute_argument_type)
2243 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2244 << ArraySize->getSourceRange();
2248 // Unlike gcc's vector_size attribute, the size is specified as the
2249 // number of elements, not the number of bytes.
2250 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2252 if (vectorSize == 0) {
2253 Diag(AttrLoc, diag::err_attribute_zero_size)
2254 << ArraySize->getSourceRange();
2258 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2259 Diag(AttrLoc, diag::err_attribute_size_too_large)
2260 << ArraySize->getSourceRange();
2264 return Context.getExtVectorType(T, vectorSize);
2267 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2270 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2271 if (T->isArrayType() || T->isFunctionType()) {
2272 Diag(Loc, diag::err_func_returning_array_function)
2273 << T->isFunctionType() << T;
2277 // Functions cannot return half FP.
2278 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2279 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2280 FixItHint::CreateInsertion(Loc, "*");
2284 // Methods cannot return interface types. All ObjC objects are
2285 // passed by reference.
2286 if (T->isObjCObjectType()) {
2287 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2294 /// Check the extended parameter information. Most of the necessary
2295 /// checking should occur when applying the parameter attribute; the
2296 /// only other checks required are positional restrictions.
2297 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2298 const FunctionProtoType::ExtProtoInfo &EPI,
2299 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2300 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2302 bool hasCheckedSwiftCall = false;
2303 auto checkForSwiftCC = [&](unsigned paramIndex) {
2304 // Only do this once.
2305 if (hasCheckedSwiftCall) return;
2306 hasCheckedSwiftCall = true;
2307 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2308 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2309 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2312 for (size_t paramIndex = 0, numParams = paramTypes.size();
2313 paramIndex != numParams; ++paramIndex) {
2314 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2315 // Nothing interesting to check for orindary-ABI parameters.
2316 case ParameterABI::Ordinary:
2319 // swift_indirect_result parameters must be a prefix of the function
2321 case ParameterABI::SwiftIndirectResult:
2322 checkForSwiftCC(paramIndex);
2323 if (paramIndex != 0 &&
2324 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2325 != ParameterABI::SwiftIndirectResult) {
2326 S.Diag(getParamLoc(paramIndex),
2327 diag::err_swift_indirect_result_not_first);
2331 case ParameterABI::SwiftContext:
2332 checkForSwiftCC(paramIndex);
2335 // swift_error parameters must be preceded by a swift_context parameter.
2336 case ParameterABI::SwiftErrorResult:
2337 checkForSwiftCC(paramIndex);
2338 if (paramIndex == 0 ||
2339 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2340 ParameterABI::SwiftContext) {
2341 S.Diag(getParamLoc(paramIndex),
2342 diag::err_swift_error_result_not_after_swift_context);
2346 llvm_unreachable("bad ABI kind");
2350 QualType Sema::BuildFunctionType(QualType T,
2351 MutableArrayRef<QualType> ParamTypes,
2352 SourceLocation Loc, DeclarationName Entity,
2353 const FunctionProtoType::ExtProtoInfo &EPI) {
2354 bool Invalid = false;
2356 Invalid |= CheckFunctionReturnType(T, Loc);
2358 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2359 // FIXME: Loc is too inprecise here, should use proper locations for args.
2360 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2361 if (ParamType->isVoidType()) {
2362 Diag(Loc, diag::err_param_with_void_type);
2364 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2365 // Disallow half FP arguments.
2366 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2367 FixItHint::CreateInsertion(Loc, "*");
2371 ParamTypes[Idx] = ParamType;
2374 if (EPI.ExtParameterInfos) {
2375 checkExtParameterInfos(*this, ParamTypes, EPI,
2376 [=](unsigned i) { return Loc; });
2382 return Context.getFunctionType(T, ParamTypes, EPI);
2385 /// \brief Build a member pointer type \c T Class::*.
2387 /// \param T the type to which the member pointer refers.
2388 /// \param Class the class type into which the member pointer points.
2389 /// \param Loc the location where this type begins
2390 /// \param Entity the name of the entity that will have this member pointer type
2392 /// \returns a member pointer type, if successful, or a NULL type if there was
2394 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2396 DeclarationName Entity) {
2397 // Verify that we're not building a pointer to pointer to function with
2398 // exception specification.
2399 if (CheckDistantExceptionSpec(T)) {
2400 Diag(Loc, diag::err_distant_exception_spec);
2404 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2405 // with reference type, or "cv void."
2406 if (T->isReferenceType()) {
2407 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2408 << getPrintableNameForEntity(Entity) << T;
2412 if (T->isVoidType()) {
2413 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2414 << getPrintableNameForEntity(Entity);
2418 if (!Class->isDependentType() && !Class->isRecordType()) {
2419 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2423 // Adjust the default free function calling convention to the default method
2424 // calling convention.
2426 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2427 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2428 if (T->isFunctionType())
2429 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2431 return Context.getMemberPointerType(T, Class.getTypePtr());
2434 /// \brief Build a block pointer type.
2436 /// \param T The type to which we'll be building a block pointer.
2438 /// \param Loc The source location, used for diagnostics.
2440 /// \param Entity The name of the entity that involves the block pointer
2443 /// \returns A suitable block pointer type, if there are no
2444 /// errors. Otherwise, returns a NULL type.
2445 QualType Sema::BuildBlockPointerType(QualType T,
2447 DeclarationName Entity) {
2448 if (!T->isFunctionType()) {
2449 Diag(Loc, diag::err_nonfunction_block_type);
2453 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2456 return Context.getBlockPointerType(T);
2459 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2460 QualType QT = Ty.get();
2462 if (TInfo) *TInfo = nullptr;
2466 TypeSourceInfo *DI = nullptr;
2467 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2468 QT = LIT->getType();
2469 DI = LIT->getTypeSourceInfo();
2472 if (TInfo) *TInfo = DI;
2476 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2477 Qualifiers::ObjCLifetime ownership,
2478 unsigned chunkIndex);
2480 /// Given that this is the declaration of a parameter under ARC,
2481 /// attempt to infer attributes and such for pointer-to-whatever
2483 static void inferARCWriteback(TypeProcessingState &state,
2484 QualType &declSpecType) {
2485 Sema &S = state.getSema();
2486 Declarator &declarator = state.getDeclarator();
2488 // TODO: should we care about decl qualifiers?
2490 // Check whether the declarator has the expected form. We walk
2491 // from the inside out in order to make the block logic work.
2492 unsigned outermostPointerIndex = 0;
2493 bool isBlockPointer = false;
2494 unsigned numPointers = 0;
2495 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2496 unsigned chunkIndex = i;
2497 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2498 switch (chunk.Kind) {
2499 case DeclaratorChunk::Paren:
2503 case DeclaratorChunk::Reference:
2504 case DeclaratorChunk::Pointer:
2505 // Count the number of pointers. Treat references
2506 // interchangeably as pointers; if they're mis-ordered, normal
2507 // type building will discover that.
2508 outermostPointerIndex = chunkIndex;
2512 case DeclaratorChunk::BlockPointer:
2513 // If we have a pointer to block pointer, that's an acceptable
2514 // indirect reference; anything else is not an application of
2516 if (numPointers != 1) return;
2518 outermostPointerIndex = chunkIndex;
2519 isBlockPointer = true;
2521 // We don't care about pointer structure in return values here.
2524 case DeclaratorChunk::Array: // suppress if written (id[])?
2525 case DeclaratorChunk::Function:
2526 case DeclaratorChunk::MemberPointer:
2527 case DeclaratorChunk::Pipe:
2533 // If we have *one* pointer, then we want to throw the qualifier on
2534 // the declaration-specifiers, which means that it needs to be a
2535 // retainable object type.
2536 if (numPointers == 1) {
2537 // If it's not a retainable object type, the rule doesn't apply.
2538 if (!declSpecType->isObjCRetainableType()) return;
2540 // If it already has lifetime, don't do anything.
2541 if (declSpecType.getObjCLifetime()) return;
2543 // Otherwise, modify the type in-place.
2546 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2547 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2549 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2550 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2552 // If we have *two* pointers, then we want to throw the qualifier on
2553 // the outermost pointer.
2554 } else if (numPointers == 2) {
2555 // If we don't have a block pointer, we need to check whether the
2556 // declaration-specifiers gave us something that will turn into a
2557 // retainable object pointer after we slap the first pointer on it.
2558 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2561 // Look for an explicit lifetime attribute there.
2562 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2563 if (chunk.Kind != DeclaratorChunk::Pointer &&
2564 chunk.Kind != DeclaratorChunk::BlockPointer)
2566 for (const AttributeList *attr = chunk.getAttrs(); attr;
2567 attr = attr->getNext())
2568 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2571 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2572 outermostPointerIndex);
2574 // Any other number of pointers/references does not trigger the rule.
2577 // TODO: mark whether we did this inference?
2580 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2581 SourceLocation FallbackLoc,
2582 SourceLocation ConstQualLoc,
2583 SourceLocation VolatileQualLoc,
2584 SourceLocation RestrictQualLoc,
2585 SourceLocation AtomicQualLoc,
2586 SourceLocation UnalignedQualLoc) {
2594 } const QualKinds[5] = {
2595 { "const", DeclSpec::TQ_const, ConstQualLoc },
2596 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2597 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2598 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2599 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2602 SmallString<32> QualStr;
2603 unsigned NumQuals = 0;
2605 FixItHint FixIts[5];
2607 // Build a string naming the redundant qualifiers.
2608 for (auto &E : QualKinds) {
2609 if (Quals & E.Mask) {
2610 if (!QualStr.empty()) QualStr += ' ';
2613 // If we have a location for the qualifier, offer a fixit.
2614 SourceLocation QualLoc = E.Loc;
2615 if (QualLoc.isValid()) {
2616 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2617 if (Loc.isInvalid() ||
2618 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2626 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2627 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2630 // Diagnose pointless type qualifiers on the return type of a function.
2631 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2633 unsigned FunctionChunkIndex) {
2634 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2635 // FIXME: TypeSourceInfo doesn't preserve location information for
2637 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2638 RetTy.getLocalCVRQualifiers(),
2639 D.getIdentifierLoc());
2643 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2644 End = D.getNumTypeObjects();
2645 OuterChunkIndex != End; ++OuterChunkIndex) {
2646 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2647 switch (OuterChunk.Kind) {
2648 case DeclaratorChunk::Paren:
2651 case DeclaratorChunk::Pointer: {
2652 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2653 S.diagnoseIgnoredQualifiers(
2654 diag::warn_qual_return_type,
2657 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2658 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2659 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2660 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2661 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2665 case DeclaratorChunk::Function:
2666 case DeclaratorChunk::BlockPointer:
2667 case DeclaratorChunk::Reference:
2668 case DeclaratorChunk::Array:
2669 case DeclaratorChunk::MemberPointer:
2670 case DeclaratorChunk::Pipe:
2671 // FIXME: We can't currently provide an accurate source location and a
2672 // fix-it hint for these.
2673 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2674 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2675 RetTy.getCVRQualifiers() | AtomicQual,
2676 D.getIdentifierLoc());
2680 llvm_unreachable("unknown declarator chunk kind");
2683 // If the qualifiers come from a conversion function type, don't diagnose
2684 // them -- they're not necessarily redundant, since such a conversion
2685 // operator can be explicitly called as "x.operator const int()".
2686 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2689 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2690 // which are present there.
2691 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2692 D.getDeclSpec().getTypeQualifiers(),
2693 D.getIdentifierLoc(),
2694 D.getDeclSpec().getConstSpecLoc(),
2695 D.getDeclSpec().getVolatileSpecLoc(),
2696 D.getDeclSpec().getRestrictSpecLoc(),
2697 D.getDeclSpec().getAtomicSpecLoc(),
2698 D.getDeclSpec().getUnalignedSpecLoc());
2701 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2702 TypeSourceInfo *&ReturnTypeInfo) {
2703 Sema &SemaRef = state.getSema();
2704 Declarator &D = state.getDeclarator();
2706 ReturnTypeInfo = nullptr;
2708 // The TagDecl owned by the DeclSpec.
2709 TagDecl *OwnedTagDecl = nullptr;
2711 switch (D.getName().getKind()) {
2712 case UnqualifiedId::IK_ImplicitSelfParam:
2713 case UnqualifiedId::IK_OperatorFunctionId:
2714 case UnqualifiedId::IK_Identifier:
2715 case UnqualifiedId::IK_LiteralOperatorId:
2716 case UnqualifiedId::IK_TemplateId:
2717 T = ConvertDeclSpecToType(state);
2719 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2720 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2721 // Owned declaration is embedded in declarator.
2722 OwnedTagDecl->setEmbeddedInDeclarator(true);
2726 case UnqualifiedId::IK_ConstructorName:
2727 case UnqualifiedId::IK_ConstructorTemplateId:
2728 case UnqualifiedId::IK_DestructorName:
2729 // Constructors and destructors don't have return types. Use
2731 T = SemaRef.Context.VoidTy;
2732 processTypeAttrs(state, T, TAL_DeclSpec,
2733 D.getDeclSpec().getAttributes().getList());
2736 case UnqualifiedId::IK_DeductionGuideName:
2737 // Deduction guides have a trailing return type and no type in their
2738 // decl-specifier sequence. Use a placeholder return type for now.
2739 T = SemaRef.Context.DependentTy;
2742 case UnqualifiedId::IK_ConversionFunctionId:
2743 // The result type of a conversion function is the type that it
2745 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2750 if (D.getAttributes())
2751 distributeTypeAttrsFromDeclarator(state, T);
2753 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2754 if (DeducedType *Deduced = T->getContainedDeducedType()) {
2755 AutoType *Auto = dyn_cast<AutoType>(Deduced);
2758 // Is this a 'auto' or 'decltype(auto)' type (as opposed to __auto_type or
2759 // class template argument deduction)?
2760 bool IsCXXAutoType =
2761 (Auto && Auto->getKeyword() != AutoTypeKeyword::GNUAutoType);
2763 switch (D.getContext()) {
2764 case Declarator::LambdaExprContext:
2765 // Declared return type of a lambda-declarator is implicit and is always
2768 case Declarator::ObjCParameterContext:
2769 case Declarator::ObjCResultContext:
2770 case Declarator::PrototypeContext:
2773 case Declarator::LambdaExprParameterContext:
2774 // In C++14, generic lambdas allow 'auto' in their parameters.
2775 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2776 !Auto || Auto->getKeyword() != AutoTypeKeyword::Auto)
2779 // If auto is mentioned in a lambda parameter context, convert it to a
2780 // template parameter type.
2781 sema::LambdaScopeInfo *LSI = SemaRef.getCurLambda();
2782 assert(LSI && "No LambdaScopeInfo on the stack!");
2783 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
2784 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
2785 const bool IsParameterPack = D.hasEllipsis();
2787 // Create the TemplateTypeParmDecl here to retrieve the corresponding
2788 // template parameter type. Template parameters are temporarily added
2789 // to the TU until the associated TemplateDecl is created.
2790 TemplateTypeParmDecl *CorrespondingTemplateParam =
2791 TemplateTypeParmDecl::Create(
2792 SemaRef.Context, SemaRef.Context.getTranslationUnitDecl(),
2793 /*KeyLoc*/SourceLocation(), /*NameLoc*/D.getLocStart(),
2794 TemplateParameterDepth, AutoParameterPosition,
2795 /*Identifier*/nullptr, false, IsParameterPack);
2796 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
2797 // Replace the 'auto' in the function parameter with this invented
2798 // template type parameter.
2799 // FIXME: Retain some type sugar to indicate that this was written
2801 T = SemaRef.ReplaceAutoType(
2802 T, QualType(CorrespondingTemplateParam->getTypeForDecl(), 0));
2805 case Declarator::MemberContext: {
2806 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2807 D.isFunctionDeclarator())
2809 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2810 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2811 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2812 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2813 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2814 case TTK_Class: Error = 5; /* Class member */ break;
2815 case TTK_Interface: Error = 6; /* Interface member */ break;
2817 if (D.getDeclSpec().isFriendSpecified())
2818 Error = 20; // Friend type
2821 case Declarator::CXXCatchContext:
2822 case Declarator::ObjCCatchContext:
2823 Error = 7; // Exception declaration
2825 case Declarator::TemplateParamContext:
2826 if (isa<DeducedTemplateSpecializationType>(Deduced))
2827 Error = 19; // Template parameter
2828 else if (!SemaRef.getLangOpts().CPlusPlus1z)
2829 Error = 8; // Template parameter (until C++1z)
2831 case Declarator::BlockLiteralContext:
2832 Error = 9; // Block literal
2834 case Declarator::TemplateTypeArgContext:
2835 Error = 10; // Template type argument
2837 case Declarator::AliasDeclContext:
2838 case Declarator::AliasTemplateContext:
2839 Error = 12; // Type alias
2841 case Declarator::TrailingReturnContext:
2842 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2843 Error = 13; // Function return type
2845 case Declarator::ConversionIdContext:
2846 if (!SemaRef.getLangOpts().CPlusPlus14 || !IsCXXAutoType)
2847 Error = 14; // conversion-type-id
2849 case Declarator::FunctionalCastContext:
2850 if (isa<DeducedTemplateSpecializationType>(Deduced))
2853 case Declarator::TypeNameContext:
2854 Error = 15; // Generic
2856 case Declarator::FileContext:
2857 case Declarator::BlockContext:
2858 case Declarator::ForContext:
2859 case Declarator::InitStmtContext:
2860 case Declarator::ConditionContext:
2861 // FIXME: P0091R3 (erroneously) does not permit class template argument
2862 // deduction in conditions, for-init-statements, and other declarations
2863 // that are not simple-declarations.
2865 case Declarator::CXXNewContext:
2866 // FIXME: P0091R3 does not permit class template argument deduction here,
2867 // but we follow GCC and allow it anyway.
2868 if (!IsCXXAutoType && !isa<DeducedTemplateSpecializationType>(Deduced))
2869 Error = 17; // 'new' type
2871 case Declarator::KNRTypeListContext:
2872 Error = 18; // K&R function parameter
2876 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2879 // In Objective-C it is an error to use 'auto' on a function declarator
2880 // (and everywhere for '__auto_type').
2881 if (D.isFunctionDeclarator() &&
2882 (!SemaRef.getLangOpts().CPlusPlus11 || !IsCXXAutoType))
2885 bool HaveTrailing = false;
2887 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2888 // contains a trailing return type. That is only legal at the outermost
2889 // level. Check all declarator chunks (outermost first) anyway, to give
2890 // better diagnostics.
2891 // We don't support '__auto_type' with trailing return types.
2892 // FIXME: Should we only do this for 'auto' and not 'decltype(auto)'?
2893 if (SemaRef.getLangOpts().CPlusPlus11 && IsCXXAutoType &&
2894 D.hasTrailingReturnType()) {
2895 HaveTrailing = true;
2899 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2900 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2901 AutoRange = D.getName().getSourceRange();
2906 switch (Auto->getKeyword()) {
2907 case AutoTypeKeyword::Auto: Kind = 0; break;
2908 case AutoTypeKeyword::DecltypeAuto: Kind = 1; break;
2909 case AutoTypeKeyword::GNUAutoType: Kind = 2; break;
2912 assert(isa<DeducedTemplateSpecializationType>(Deduced) &&
2913 "unknown auto type");
2917 auto *DTST = dyn_cast<DeducedTemplateSpecializationType>(Deduced);
2918 TemplateName TN = DTST ? DTST->getTemplateName() : TemplateName();
2920 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2921 << Kind << Error << (int)SemaRef.getTemplateNameKindForDiagnostics(TN)
2922 << QualType(Deduced, 0) << AutoRange;
2923 if (auto *TD = TN.getAsTemplateDecl())
2924 SemaRef.Diag(TD->getLocation(), diag::note_template_decl_here);
2926 T = SemaRef.Context.IntTy;
2927 D.setInvalidType(true);
2928 } else if (!HaveTrailing) {
2929 // If there was a trailing return type, we already got
2930 // warn_cxx98_compat_trailing_return_type in the parser.
2931 SemaRef.Diag(AutoRange.getBegin(),
2932 diag::warn_cxx98_compat_auto_type_specifier)
2937 if (SemaRef.getLangOpts().CPlusPlus &&
2938 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2939 // Check the contexts where C++ forbids the declaration of a new class
2940 // or enumeration in a type-specifier-seq.
2941 unsigned DiagID = 0;
2942 switch (D.getContext()) {
2943 case Declarator::TrailingReturnContext:
2944 // Class and enumeration definitions are syntactically not allowed in
2945 // trailing return types.
2946 llvm_unreachable("parser should not have allowed this");
2948 case Declarator::FileContext:
2949 case Declarator::MemberContext:
2950 case Declarator::BlockContext:
2951 case Declarator::ForContext:
2952 case Declarator::InitStmtContext:
2953 case Declarator::BlockLiteralContext:
2954 case Declarator::LambdaExprContext:
2955 // C++11 [dcl.type]p3:
2956 // A type-specifier-seq shall not define a class or enumeration unless
2957 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2958 // the declaration of a template-declaration.
2959 case Declarator::AliasDeclContext:
2961 case Declarator::AliasTemplateContext:
2962 DiagID = diag::err_type_defined_in_alias_template;
2964 case Declarator::TypeNameContext:
2965 case Declarator::FunctionalCastContext:
2966 case Declarator::ConversionIdContext:
2967 case Declarator::TemplateParamContext:
2968 case Declarator::CXXNewContext:
2969 case Declarator::CXXCatchContext:
2970 case Declarator::ObjCCatchContext:
2971 case Declarator::TemplateTypeArgContext:
2972 DiagID = diag::err_type_defined_in_type_specifier;
2974 case Declarator::PrototypeContext:
2975 case Declarator::LambdaExprParameterContext:
2976 case Declarator::ObjCParameterContext:
2977 case Declarator::ObjCResultContext:
2978 case Declarator::KNRTypeListContext:
2980 // Types shall not be defined in return or parameter types.
2981 DiagID = diag::err_type_defined_in_param_type;
2983 case Declarator::ConditionContext:
2985 // The type-specifier-seq shall not contain typedef and shall not declare
2986 // a new class or enumeration.
2987 DiagID = diag::err_type_defined_in_condition;
2992 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2993 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2994 D.setInvalidType(true);
2998 assert(!T.isNull() && "This function should not return a null type");
3002 /// Produce an appropriate diagnostic for an ambiguity between a function
3003 /// declarator and a C++ direct-initializer.
3004 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
3005 DeclaratorChunk &DeclType, QualType RT) {
3006 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3007 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
3009 // If the return type is void there is no ambiguity.
3010 if (RT->isVoidType())
3013 // An initializer for a non-class type can have at most one argument.
3014 if (!RT->isRecordType() && FTI.NumParams > 1)
3017 // An initializer for a reference must have exactly one argument.
3018 if (RT->isReferenceType() && FTI.NumParams != 1)
3021 // Only warn if this declarator is declaring a function at block scope, and
3022 // doesn't have a storage class (such as 'extern') specified.
3023 if (!D.isFunctionDeclarator() ||
3024 D.getFunctionDefinitionKind() != FDK_Declaration ||
3025 !S.CurContext->isFunctionOrMethod() ||
3026 D.getDeclSpec().getStorageClassSpec()
3027 != DeclSpec::SCS_unspecified)
3030 // Inside a condition, a direct initializer is not permitted. We allow one to
3031 // be parsed in order to give better diagnostics in condition parsing.
3032 if (D.getContext() == Declarator::ConditionContext)
3035 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3037 S.Diag(DeclType.Loc,
3038 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3039 : diag::warn_empty_parens_are_function_decl)
3042 // If the declaration looks like:
3045 // and name lookup finds a function named 'f', then the ',' was
3046 // probably intended to be a ';'.
3047 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3048 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3049 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3050 if (Comma.getFileID() != Name.getFileID() ||
3051 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3052 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3053 Sema::LookupOrdinaryName);
3054 if (S.LookupName(Result, S.getCurScope()))
3055 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3056 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3057 << D.getIdentifier();
3061 if (FTI.NumParams > 0) {
3062 // For a declaration with parameters, eg. "T var(T());", suggest adding
3063 // parens around the first parameter to turn the declaration into a
3064 // variable declaration.
3065 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3066 SourceLocation B = Range.getBegin();
3067 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3068 // FIXME: Maybe we should suggest adding braces instead of parens
3069 // in C++11 for classes that don't have an initializer_list constructor.
3070 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3071 << FixItHint::CreateInsertion(B, "(")
3072 << FixItHint::CreateInsertion(E, ")");
3074 // For a declaration without parameters, eg. "T var();", suggest replacing
3075 // the parens with an initializer to turn the declaration into a variable
3077 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3079 // Empty parens mean value-initialization, and no parens mean
3080 // default initialization. These are equivalent if the default
3081 // constructor is user-provided or if zero-initialization is a
3083 if (RD && RD->hasDefinition() &&
3084 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3085 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3086 << FixItHint::CreateRemoval(ParenRange);
3089 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3090 if (Init.empty() && S.LangOpts.CPlusPlus11)
3093 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3094 << FixItHint::CreateReplacement(ParenRange, Init);
3099 /// Helper for figuring out the default CC for a function declarator type. If
3100 /// this is the outermost chunk, then we can determine the CC from the
3101 /// declarator context. If not, then this could be either a member function
3102 /// type or normal function type.
3104 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3105 const DeclaratorChunk::FunctionTypeInfo &FTI,
3106 unsigned ChunkIndex) {
3107 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3109 // Check for an explicit CC attribute.
3110 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3111 switch (Attr->getKind()) {
3112 CALLING_CONV_ATTRS_CASELIST: {
3113 // Ignore attributes that don't validate or can't apply to the
3114 // function type. We'll diagnose the failure to apply them in
3115 // handleFunctionTypeAttr.
3117 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3118 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3129 bool IsCXXInstanceMethod = false;
3131 if (S.getLangOpts().CPlusPlus) {
3132 // Look inwards through parentheses to see if this chunk will form a
3133 // member pointer type or if we're the declarator. Any type attributes
3134 // between here and there will override the CC we choose here.
3135 unsigned I = ChunkIndex;
3136 bool FoundNonParen = false;
3137 while (I && !FoundNonParen) {
3139 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3140 FoundNonParen = true;
3143 if (FoundNonParen) {
3144 // If we're not the declarator, we're a regular function type unless we're
3145 // in a member pointer.
3146 IsCXXInstanceMethod =
3147 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3148 } else if (D.getContext() == Declarator::LambdaExprContext) {
3149 // This can only be a call operator for a lambda, which is an instance
3151 IsCXXInstanceMethod = true;
3153 // We're the innermost decl chunk, so must be a function declarator.
3154 assert(D.isFunctionDeclarator());
3156 // If we're inside a record, we're declaring a method, but it could be
3157 // explicitly or implicitly static.
3158 IsCXXInstanceMethod =
3159 D.isFirstDeclarationOfMember() &&
3160 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3161 !D.isStaticMember();
3165 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3166 IsCXXInstanceMethod);
3168 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3169 // and AMDGPU targets, hence it cannot be treated as a calling
3170 // convention attribute. This is the simplest place to infer
3171 // calling convention for OpenCL kernels.
3172 if (S.getLangOpts().OpenCL) {
3173 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3174 Attr; Attr = Attr->getNext()) {
3175 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3176 llvm::Triple::ArchType arch = S.Context.getTargetInfo().getTriple().getArch();
3177 if (arch == llvm::Triple::spir || arch == llvm::Triple::spir64 ||
3178 arch == llvm::Triple::amdgcn || arch == llvm::Triple::r600) {
3179 CC = CC_OpenCLKernel;
3190 /// A simple notion of pointer kinds, which matches up with the various
3191 /// pointer declarators.
3192 enum class SimplePointerKind {
3198 } // end anonymous namespace
3200 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3201 switch (nullability) {
3202 case NullabilityKind::NonNull:
3203 if (!Ident__Nonnull)
3204 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3205 return Ident__Nonnull;
3207 case NullabilityKind::Nullable:
3208 if (!Ident__Nullable)
3209 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3210 return Ident__Nullable;
3212 case NullabilityKind::Unspecified:
3213 if (!Ident__Null_unspecified)
3214 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3215 return Ident__Null_unspecified;
3217 llvm_unreachable("Unknown nullability kind.");
3220 /// Retrieve the identifier "NSError".
3221 IdentifierInfo *Sema::getNSErrorIdent() {
3223 Ident_NSError = PP.getIdentifierInfo("NSError");
3225 return Ident_NSError;
3228 /// Check whether there is a nullability attribute of any kind in the given
3230 static bool hasNullabilityAttr(const AttributeList *attrs) {
3231 for (const AttributeList *attr = attrs; attr;
3232 attr = attr->getNext()) {
3233 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3234 attr->getKind() == AttributeList::AT_TypeNullable ||
3235 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3243 /// Describes the kind of a pointer a declarator describes.
3244 enum class PointerDeclaratorKind {
3247 // Single-level pointer.
3249 // Multi-level pointer (of any pointer kind).
3252 MaybePointerToCFRef,
3256 NSErrorPointerPointer,
3259 /// Describes a declarator chunk wrapping a pointer that marks inference as
3261 // These values must be kept in sync with diagnostics.
3262 enum class PointerWrappingDeclaratorKind {
3263 /// Pointer is top-level.
3265 /// Pointer is an array element.
3267 /// Pointer is the referent type of a C++ reference.
3270 } // end anonymous namespace
3272 /// Classify the given declarator, whose type-specified is \c type, based on
3273 /// what kind of pointer it refers to.
3275 /// This is used to determine the default nullability.
3276 static PointerDeclaratorKind
3277 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3278 PointerWrappingDeclaratorKind &wrappingKind) {
3279 unsigned numNormalPointers = 0;
3281 // For any dependent type, we consider it a non-pointer.
3282 if (type->isDependentType())
3283 return PointerDeclaratorKind::NonPointer;
3285 // Look through the declarator chunks to identify pointers.
3286 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3287 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3288 switch (chunk.Kind) {
3289 case DeclaratorChunk::Array:
3290 if (numNormalPointers == 0)
3291 wrappingKind = PointerWrappingDeclaratorKind::Array;
3294 case DeclaratorChunk::Function:
3295 case DeclaratorChunk::Pipe:
3298 case DeclaratorChunk::BlockPointer:
3299 case DeclaratorChunk::MemberPointer:
3300 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3301 : PointerDeclaratorKind::SingleLevelPointer;
3303 case DeclaratorChunk::Paren:
3306 case DeclaratorChunk::Reference:
3307 if (numNormalPointers == 0)
3308 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3311 case DeclaratorChunk::Pointer:
3312 ++numNormalPointers;
3313 if (numNormalPointers > 2)
3314 return PointerDeclaratorKind::MultiLevelPointer;
3319 // Then, dig into the type specifier itself.
3320 unsigned numTypeSpecifierPointers = 0;
3322 // Decompose normal pointers.
3323 if (auto ptrType = type->getAs<PointerType>()) {
3324 ++numNormalPointers;
3326 if (numNormalPointers > 2)
3327 return PointerDeclaratorKind::MultiLevelPointer;
3329 type = ptrType->getPointeeType();
3330 ++numTypeSpecifierPointers;
3334 // Decompose block pointers.
3335 if (type->getAs<BlockPointerType>()) {
3336 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3337 : PointerDeclaratorKind::SingleLevelPointer;
3340 // Decompose member pointers.
3341 if (type->getAs<MemberPointerType>()) {
3342 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3343 : PointerDeclaratorKind::SingleLevelPointer;
3346 // Look at Objective-C object pointers.
3347 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3348 ++numNormalPointers;
3349 ++numTypeSpecifierPointers;
3351 // If this is NSError**, report that.
3352 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3353 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3354 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3355 return PointerDeclaratorKind::NSErrorPointerPointer;
3362 // Look at Objective-C class types.
3363 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3364 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3365 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3366 return PointerDeclaratorKind::NSErrorPointerPointer;;
3372 // If at this point we haven't seen a pointer, we won't see one.
3373 if (numNormalPointers == 0)
3374 return PointerDeclaratorKind::NonPointer;
3376 if (auto recordType = type->getAs<RecordType>()) {
3377 RecordDecl *recordDecl = recordType->getDecl();
3379 bool isCFError = false;
3381 // If we already know about CFError, test it directly.
3382 isCFError = (S.CFError == recordDecl);
3384 // Check whether this is CFError, which we identify based on its bridge
3386 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3387 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3388 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3389 S.CFError = recordDecl;
3396 // If this is CFErrorRef*, report it as such.
3397 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3398 return PointerDeclaratorKind::CFErrorRefPointer;
3406 switch (numNormalPointers) {
3408 return PointerDeclaratorKind::NonPointer;
3411 return PointerDeclaratorKind::SingleLevelPointer;
3414 return PointerDeclaratorKind::MaybePointerToCFRef;
3417 return PointerDeclaratorKind::MultiLevelPointer;
3421 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3422 SourceLocation loc) {
3423 // If we're anywhere in a function, method, or closure context, don't perform
3424 // completeness checks.
3425 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3426 if (ctx->isFunctionOrMethod())
3429 if (ctx->isFileContext())
3433 // We only care about the expansion location.
3434 loc = S.SourceMgr.getExpansionLoc(loc);
3435 FileID file = S.SourceMgr.getFileID(loc);
3436 if (file.isInvalid())
3439 // Retrieve file information.
3440 bool invalid = false;
3441 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3442 if (invalid || !sloc.isFile())
3445 // We don't want to perform completeness checks on the main file or in
3447 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3448 if (fileInfo.getIncludeLoc().isInvalid())
3450 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3451 S.Diags.getSuppressSystemWarnings()) {
3458 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3459 /// taking into account whitespace before and after.
3460 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3461 SourceLocation PointerLoc,
3462 NullabilityKind Nullability) {
3463 assert(PointerLoc.isValid());
3464 if (PointerLoc.isMacroID())
3467 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3468 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3471 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3475 SmallString<32> InsertionTextBuf{" "};
3476 InsertionTextBuf += getNullabilitySpelling(Nullability);
3477 InsertionTextBuf += " ";
3478 StringRef InsertionText = InsertionTextBuf.str();
3480 if (isWhitespace(*NextChar)) {
3481 InsertionText = InsertionText.drop_back();
3482 } else if (NextChar[-1] == '[') {
3483 if (NextChar[0] == ']')
3484 InsertionText = InsertionText.drop_back().drop_front();
3486 InsertionText = InsertionText.drop_front();
3487 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3488 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3489 InsertionText = InsertionText.drop_back().drop_front();
3492 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3495 static void emitNullabilityConsistencyWarning(Sema &S,
3496 SimplePointerKind PointerKind,
3497 SourceLocation PointerLoc) {
3498 assert(PointerLoc.isValid());
3500 if (PointerKind == SimplePointerKind::Array) {
3501 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3503 S.Diag(PointerLoc, diag::warn_nullability_missing)
3504 << static_cast<unsigned>(PointerKind);
3507 if (PointerLoc.isMacroID())
3510 auto addFixIt = [&](NullabilityKind Nullability) {
3511 auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it);
3512 Diag << static_cast<unsigned>(Nullability);
3513 Diag << static_cast<unsigned>(PointerKind);
3514 fixItNullability(S, Diag, PointerLoc, Nullability);
3516 addFixIt(NullabilityKind::Nullable);
3517 addFixIt(NullabilityKind::NonNull);
3520 /// Complains about missing nullability if the file containing \p pointerLoc
3521 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3524 /// If the file has \e not seen other uses of nullability, this particular
3525 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3526 static void checkNullabilityConsistency(Sema &S,
3527 SimplePointerKind pointerKind,
3528 SourceLocation pointerLoc) {
3529 // Determine which file we're performing consistency checking for.
3530 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3531 if (file.isInvalid())
3534 // If we haven't seen any type nullability in this file, we won't warn now
3536 FileNullability &fileNullability = S.NullabilityMap[file];
3537 if (!fileNullability.SawTypeNullability) {
3538 // If this is the first pointer declarator in the file, and the appropriate
3539 // warning is on, record it in case we need to diagnose it retroactively.
3540 diag::kind diagKind;
3541 if (pointerKind == SimplePointerKind::Array)
3542 diagKind = diag::warn_nullability_missing_array;
3544 diagKind = diag::warn_nullability_missing;
3546 if (fileNullability.PointerLoc.isInvalid() &&
3547 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3548 fileNullability.PointerLoc = pointerLoc;
3549 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3555 // Complain about missing nullability.
3556 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc);
3559 /// Marks that a nullability feature has been used in the file containing
3562 /// If this file already had pointer types in it that were missing nullability,
3563 /// the first such instance is retroactively diagnosed.
3565 /// \sa checkNullabilityConsistency
3566 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3567 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3568 if (file.isInvalid())
3571 FileNullability &fileNullability = S.NullabilityMap[file];
3572 if (fileNullability.SawTypeNullability)
3574 fileNullability.SawTypeNullability = true;
3576 // If we haven't seen any type nullability before, now we have. Retroactively
3577 // diagnose the first unannotated pointer, if there was one.
3578 if (fileNullability.PointerLoc.isInvalid())
3581 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3582 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc);
3585 /// Returns true if any of the declarator chunks before \p endIndex include a
3586 /// level of indirection: array, pointer, reference, or pointer-to-member.
3588 /// Because declarator chunks are stored in outer-to-inner order, testing
3589 /// every chunk before \p endIndex is testing all chunks that embed the current
3590 /// chunk as part of their type.
3592 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3593 /// end index, in which case all chunks are tested.
3594 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3595 unsigned i = endIndex;
3597 // Walk outwards along the declarator chunks.
3599 const DeclaratorChunk &DC = D.getTypeObject(i);
3601 case DeclaratorChunk::Paren:
3603 case DeclaratorChunk::Array:
3604 case DeclaratorChunk::Pointer:
3605 case DeclaratorChunk::Reference:
3606 case DeclaratorChunk::MemberPointer:
3608 case DeclaratorChunk::Function:
3609 case DeclaratorChunk::BlockPointer:
3610 case DeclaratorChunk::Pipe:
3611 // These are invalid anyway, so just ignore.
3618 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3619 QualType declSpecType,
3620 TypeSourceInfo *TInfo) {
3621 // The TypeSourceInfo that this function returns will not be a null type.
3622 // If there is an error, this function will fill in a dummy type as fallback.
3623 QualType T = declSpecType;
3624 Declarator &D = state.getDeclarator();
3625 Sema &S = state.getSema();
3626 ASTContext &Context = S.Context;
3627 const LangOptions &LangOpts = S.getLangOpts();
3629 // The name we're declaring, if any.
3630 DeclarationName Name;
3631 if (D.getIdentifier())
3632 Name = D.getIdentifier();
3634 // Does this declaration declare a typedef-name?
3635 bool IsTypedefName =
3636 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3637 D.getContext() == Declarator::AliasDeclContext ||
3638 D.getContext() == Declarator::AliasTemplateContext;
3640 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3641 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3642 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3643 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3645 // If T is 'decltype(auto)', the only declarators we can have are parens
3646 // and at most one function declarator if this is a function declaration.
3647 // If T is a deduced class template specialization type, we can have no
3648 // declarator chunks at all.
3649 if (auto *DT = T->getAs<DeducedType>()) {
3650 const AutoType *AT = T->getAs<AutoType>();
3651 bool IsClassTemplateDeduction = isa<DeducedTemplateSpecializationType>(DT);
3652 if ((AT && AT->isDecltypeAuto()) || IsClassTemplateDeduction) {
3653 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3654 unsigned Index = E - I - 1;
3655 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3656 unsigned DiagId = IsClassTemplateDeduction
3657 ? diag::err_deduced_class_template_compound_type
3658 : diag::err_decltype_auto_compound_type;
3659 unsigned DiagKind = 0;
3660 switch (DeclChunk.Kind) {
3661 case DeclaratorChunk::Paren:
3662 // FIXME: Rejecting this is a little silly.
3663 if (IsClassTemplateDeduction) {
3668 case DeclaratorChunk::Function: {
3669 if (IsClassTemplateDeduction) {
3674 if (D.isFunctionDeclarationContext() &&
3675 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3677 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3680 case DeclaratorChunk::Pointer:
3681 case DeclaratorChunk::BlockPointer:
3682 case DeclaratorChunk::MemberPointer:
3685 case DeclaratorChunk::Reference:
3688 case DeclaratorChunk::Array:
3691 case DeclaratorChunk::Pipe:
3695 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3696 D.setInvalidType(true);
3702 // Determine whether we should infer _Nonnull on pointer types.
3703 Optional<NullabilityKind> inferNullability;
3704 bool inferNullabilityCS = false;
3705 bool inferNullabilityInnerOnly = false;
3706 bool inferNullabilityInnerOnlyComplete = false;
3708 // Are we in an assume-nonnull region?
3709 bool inAssumeNonNullRegion = false;
3710 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3711 if (assumeNonNullLoc.isValid()) {
3712 inAssumeNonNullRegion = true;
3713 recordNullabilitySeen(S, assumeNonNullLoc);
3716 // Whether to complain about missing nullability specifiers or not.
3720 /// Complain on the inner pointers (but not the outermost
3723 /// Complain about any pointers that don't have nullability
3724 /// specified or inferred.
3726 } complainAboutMissingNullability = CAMN_No;
3727 unsigned NumPointersRemaining = 0;
3728 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3730 if (IsTypedefName) {
3731 // For typedefs, we do not infer any nullability (the default),
3732 // and we only complain about missing nullability specifiers on
3734 complainAboutMissingNullability = CAMN_InnerPointers;
3736 auto isDependentNonPointerType = [](QualType T) -> bool {
3737 // Note: This is intended to be the same check as Type::canHaveNullability
3738 // except with all of the ambiguous cases being treated as 'false' rather
3740 return T->isDependentType() && !T->isAnyPointerType() &&
3741 !T->isBlockPointerType() && !T->isMemberPointerType();
3744 if (T->canHaveNullability() && !T->getNullability(S.Context) &&
3745 !isDependentNonPointerType(T)) {
3746 // Note that we allow but don't require nullability on dependent types.
3747 ++NumPointersRemaining;
3750 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3751 DeclaratorChunk &chunk = D.getTypeObject(i);
3752 switch (chunk.Kind) {
3753 case DeclaratorChunk::Array:
3754 case DeclaratorChunk::Function:
3755 case DeclaratorChunk::Pipe:
3758 case DeclaratorChunk::BlockPointer:
3759 case DeclaratorChunk::MemberPointer:
3760 ++NumPointersRemaining;
3763 case DeclaratorChunk::Paren:
3764 case DeclaratorChunk::Reference:
3767 case DeclaratorChunk::Pointer:
3768 ++NumPointersRemaining;
3773 bool isFunctionOrMethod = false;
3774 switch (auto context = state.getDeclarator().getContext()) {
3775 case Declarator::ObjCParameterContext:
3776 case Declarator::ObjCResultContext:
3777 case Declarator::PrototypeContext:
3778 case Declarator::TrailingReturnContext:
3779 isFunctionOrMethod = true;
3782 case Declarator::MemberContext:
3783 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3784 complainAboutMissingNullability = CAMN_No;
3788 // Weak properties are inferred to be nullable.
3789 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3790 inferNullability = NullabilityKind::Nullable;
3796 case Declarator::FileContext:
3797 case Declarator::KNRTypeListContext: {
3798 complainAboutMissingNullability = CAMN_Yes;
3800 // Nullability inference depends on the type and declarator.
3801 auto wrappingKind = PointerWrappingDeclaratorKind::None;
3802 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3803 case PointerDeclaratorKind::NonPointer:
3804 case PointerDeclaratorKind::MultiLevelPointer:
3805 // Cannot infer nullability.
3808 case PointerDeclaratorKind::SingleLevelPointer:
3809 // Infer _Nonnull if we are in an assumes-nonnull region.
3810 if (inAssumeNonNullRegion) {
3811 complainAboutInferringWithinChunk = wrappingKind;
3812 inferNullability = NullabilityKind::NonNull;
3813 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3814 context == Declarator::ObjCResultContext);
3818 case PointerDeclaratorKind::CFErrorRefPointer:
3819 case PointerDeclaratorKind::NSErrorPointerPointer:
3820 // Within a function or method signature, infer _Nullable at both
3822 if (isFunctionOrMethod && inAssumeNonNullRegion)
3823 inferNullability = NullabilityKind::Nullable;
3826 case PointerDeclaratorKind::MaybePointerToCFRef:
3827 if (isFunctionOrMethod) {
3828 // On pointer-to-pointer parameters marked cf_returns_retained or
3829 // cf_returns_not_retained, if the outer pointer is explicit then
3830 // infer the inner pointer as _Nullable.
3831 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3833 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3834 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3836 NextAttr = NextAttr->getNext();
3840 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3841 if (hasCFReturnsAttr(D.getAttributes()) ||
3842 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3843 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3844 inferNullability = NullabilityKind::Nullable;
3845 inferNullabilityInnerOnly = true;
3854 case Declarator::ConversionIdContext:
3855 complainAboutMissingNullability = CAMN_Yes;
3858 case Declarator::AliasDeclContext:
3859 case Declarator::AliasTemplateContext:
3860 case Declarator::BlockContext:
3861 case Declarator::BlockLiteralContext:
3862 case Declarator::ConditionContext:
3863 case Declarator::CXXCatchContext:
3864 case Declarator::CXXNewContext:
3865 case Declarator::ForContext:
3866 case Declarator::InitStmtContext:
3867 case Declarator::LambdaExprContext:
3868 case Declarator::LambdaExprParameterContext:
3869 case Declarator::ObjCCatchContext:
3870 case Declarator::TemplateParamContext:
3871 case Declarator::TemplateTypeArgContext:
3872 case Declarator::TypeNameContext:
3873 case Declarator::FunctionalCastContext:
3874 // Don't infer in these contexts.
3879 // Local function that returns true if its argument looks like a va_list.
3880 auto isVaList = [&S](QualType T) -> bool {
3881 auto *typedefTy = T->getAs<TypedefType>();
3884 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3886 if (typedefTy->getDecl() == vaListTypedef)
3888 if (auto *name = typedefTy->getDecl()->getIdentifier())
3889 if (name->isStr("va_list"))
3891 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
3892 } while (typedefTy);
3896 // Local function that checks the nullability for a given pointer declarator.
3897 // Returns true if _Nonnull was inferred.
3898 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3899 SourceLocation pointerLoc,
3900 AttributeList *&attrs) -> AttributeList * {
3901 // We've seen a pointer.
3902 if (NumPointersRemaining > 0)
3903 --NumPointersRemaining;
3905 // If a nullability attribute is present, there's nothing to do.
3906 if (hasNullabilityAttr(attrs))
3909 // If we're supposed to infer nullability, do so now.
3910 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3911 AttributeList::Syntax syntax
3912 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3913 : AttributeList::AS_Keyword;
3914 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3916 S.getNullabilityKeyword(
3918 SourceRange(pointerLoc),
3919 nullptr, SourceLocation(),
3920 nullptr, 0, syntax);
3922 spliceAttrIntoList(*nullabilityAttr, attrs);
3924 if (inferNullabilityCS) {
3925 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3926 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3929 if (pointerLoc.isValid() &&
3930 complainAboutInferringWithinChunk !=
3931 PointerWrappingDeclaratorKind::None) {
3933 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
3934 Diag << static_cast<int>(complainAboutInferringWithinChunk);
3935 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
3938 if (inferNullabilityInnerOnly)
3939 inferNullabilityInnerOnlyComplete = true;
3940 return nullabilityAttr;
3943 // If we're supposed to complain about missing nullability, do so
3944 // now if it's truly missing.
3945 switch (complainAboutMissingNullability) {
3949 case CAMN_InnerPointers:
3950 if (NumPointersRemaining == 0)
3955 checkNullabilityConsistency(S, pointerKind, pointerLoc);
3960 // If the type itself could have nullability but does not, infer pointer
3961 // nullability and perform consistency checking.
3962 if (S.CodeSynthesisContexts.empty()) {
3963 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3965 // Record that we've seen a pointer, but do nothing else.
3966 if (NumPointersRemaining > 0)
3967 --NumPointersRemaining;
3969 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3970 if (T->isBlockPointerType())
3971 pointerKind = SimplePointerKind::BlockPointer;
3972 else if (T->isMemberPointerType())
3973 pointerKind = SimplePointerKind::MemberPointer;
3975 if (auto *attr = inferPointerNullability(
3976 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3977 D.getMutableDeclSpec().getAttributes().getListRef())) {
3978 T = Context.getAttributedType(
3979 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
3980 attr->setUsedAsTypeAttr();
3985 if (complainAboutMissingNullability == CAMN_Yes &&
3986 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
3987 D.isPrototypeContext() &&
3988 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
3989 checkNullabilityConsistency(S, SimplePointerKind::Array,
3990 D.getDeclSpec().getTypeSpecTypeLoc());
3994 // Walk the DeclTypeInfo, building the recursive type as we go.
3995 // DeclTypeInfos are ordered from the identifier out, which is
3996 // opposite of what we want :).
3997 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3998 unsigned chunkIndex = e - i - 1;
3999 state.setCurrentChunkIndex(chunkIndex);
4000 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
4001 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
4002 switch (DeclType.Kind) {
4003 case DeclaratorChunk::Paren:
4004 T = S.BuildParenType(T);
4006 case DeclaratorChunk::BlockPointer:
4007 // If blocks are disabled, emit an error.
4008 if (!LangOpts.Blocks)
4009 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
4011 // Handle pointer nullability.
4012 inferPointerNullability(SimplePointerKind::BlockPointer,
4013 DeclType.Loc, DeclType.getAttrListRef());
4015 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
4016 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
4017 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
4018 // qualified with const.
4019 if (LangOpts.OpenCL)
4020 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
4021 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
4024 case DeclaratorChunk::Pointer:
4025 // Verify that we're not building a pointer to pointer to function with
4026 // exception specification.
4027 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4028 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4029 D.setInvalidType(true);
4030 // Build the type anyway.
4033 // Handle pointer nullability
4034 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
4035 DeclType.getAttrListRef());
4037 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4038 T = Context.getObjCObjectPointerType(T);
4039 if (DeclType.Ptr.TypeQuals)
4040 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4044 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4045 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4046 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4047 if (LangOpts.OpenCL) {
4048 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4049 T->isBlockPointerType()) {
4050 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4051 D.setInvalidType(true);
4055 T = S.BuildPointerType(T, DeclType.Loc, Name);
4056 if (DeclType.Ptr.TypeQuals)
4057 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4059 case DeclaratorChunk::Reference: {
4060 // Verify that we're not building a reference to pointer to function with
4061 // exception specification.
4062 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4063 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4064 D.setInvalidType(true);
4065 // Build the type anyway.
4067 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4069 if (DeclType.Ref.HasRestrict)
4070 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4073 case DeclaratorChunk::Array: {
4074 // Verify that we're not building an array of pointers to function with
4075 // exception specification.
4076 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4077 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4078 D.setInvalidType(true);
4079 // Build the type anyway.
4081 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4082 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4083 ArrayType::ArraySizeModifier ASM;
4085 ASM = ArrayType::Star;
4086 else if (ATI.hasStatic)
4087 ASM = ArrayType::Static;
4089 ASM = ArrayType::Normal;
4090 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4091 // FIXME: This check isn't quite right: it allows star in prototypes
4092 // for function definitions, and disallows some edge cases detailed
4093 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4094 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4095 ASM = ArrayType::Normal;
4096 D.setInvalidType(true);
4099 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4100 // shall appear only in a declaration of a function parameter with an
4102 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4103 if (!(D.isPrototypeContext() ||
4104 D.getContext() == Declarator::KNRTypeListContext)) {
4105 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4106 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4107 // Remove the 'static' and the type qualifiers.
4108 if (ASM == ArrayType::Static)
4109 ASM = ArrayType::Normal;
4111 D.setInvalidType(true);
4114 // C99 6.7.5.2p1: ... and then only in the outermost array type
4116 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4117 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4118 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4119 if (ASM == ArrayType::Static)
4120 ASM = ArrayType::Normal;
4122 D.setInvalidType(true);
4125 const AutoType *AT = T->getContainedAutoType();
4126 // Allow arrays of auto if we are a generic lambda parameter.
4127 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4128 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4129 // We've already diagnosed this for decltype(auto).
4130 if (!AT->isDecltypeAuto())
4131 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4132 << getPrintableNameForEntity(Name) << T;
4137 // Array parameters can be marked nullable as well, although it's not
4138 // necessary if they're marked 'static'.
4139 if (complainAboutMissingNullability == CAMN_Yes &&
4140 !hasNullabilityAttr(DeclType.getAttrs()) &&
4141 ASM != ArrayType::Static &&
4142 D.isPrototypeContext() &&
4143 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4144 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4147 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4148 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4151 case DeclaratorChunk::Function: {
4152 // If the function declarator has a prototype (i.e. it is not () and
4153 // does not have a K&R-style identifier list), then the arguments are part
4154 // of the type, otherwise the argument list is ().
4155 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4156 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4158 // Check for auto functions and trailing return type and adjust the
4159 // return type accordingly.
4160 if (!D.isInvalidType()) {
4161 // trailing-return-type is only required if we're declaring a function,
4162 // and not, for instance, a pointer to a function.
4163 if (D.getDeclSpec().hasAutoTypeSpec() &&
4164 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4165 !S.getLangOpts().CPlusPlus14) {
4166 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4167 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4168 ? diag::err_auto_missing_trailing_return
4169 : diag::err_deduced_return_type);
4171 D.setInvalidType(true);
4172 } else if (FTI.hasTrailingReturnType()) {
4173 // T must be exactly 'auto' at this point. See CWG issue 681.
4174 if (isa<ParenType>(T)) {
4175 S.Diag(D.getLocStart(),
4176 diag::err_trailing_return_in_parens)
4177 << T << D.getSourceRange();
4178 D.setInvalidType(true);
4179 } else if (D.getName().getKind() ==
4180 UnqualifiedId::IK_DeductionGuideName) {
4181 if (T != Context.DependentTy) {
4182 S.Diag(D.getDeclSpec().getLocStart(),
4183 diag::err_deduction_guide_with_complex_decl)
4184 << D.getSourceRange();
4185 D.setInvalidType(true);
4187 } else if (D.getContext() != Declarator::LambdaExprContext &&
4188 (T.hasQualifiers() || !isa<AutoType>(T) ||
4189 cast<AutoType>(T)->getKeyword() !=
4190 AutoTypeKeyword::Auto)) {
4191 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4192 diag::err_trailing_return_without_auto)
4193 << T << D.getDeclSpec().getSourceRange();
4194 D.setInvalidType(true);
4196 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4198 // An error occurred parsing the trailing return type.
4200 D.setInvalidType(true);
4205 // C99 6.7.5.3p1: The return type may not be a function or array type.
4206 // For conversion functions, we'll diagnose this particular error later.
4207 if (!D.isInvalidType() && (T->isArrayType() || T->isFunctionType()) &&
4208 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4209 unsigned diagID = diag::err_func_returning_array_function;
4210 // Last processing chunk in block context means this function chunk
4211 // represents the block.
4212 if (chunkIndex == 0 &&
4213 D.getContext() == Declarator::BlockLiteralContext)
4214 diagID = diag::err_block_returning_array_function;
4215 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4217 D.setInvalidType(true);
4220 // Do not allow returning half FP value.
4221 // FIXME: This really should be in BuildFunctionType.
4222 if (T->isHalfType()) {
4223 if (S.getLangOpts().OpenCL) {
4224 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4225 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4226 << T << 0 /*pointer hint*/;
4227 D.setInvalidType(true);
4229 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4230 S.Diag(D.getIdentifierLoc(),
4231 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4232 D.setInvalidType(true);
4236 if (LangOpts.OpenCL) {
4237 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4239 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4241 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4242 << T << 1 /*hint off*/;
4243 D.setInvalidType(true);
4245 // OpenCL doesn't support variadic functions and blocks
4246 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4247 // We also allow here any toolchain reserved identifiers.
4248 if (FTI.isVariadic &&
4249 !(D.getIdentifier() &&
4250 ((D.getIdentifier()->getName() == "printf" &&
4251 LangOpts.OpenCLVersion >= 120) ||
4252 D.getIdentifier()->getName().startswith("__")))) {
4253 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4254 D.setInvalidType(true);
4258 // Methods cannot return interface types. All ObjC objects are
4259 // passed by reference.
4260 if (T->isObjCObjectType()) {
4261 SourceLocation DiagLoc, FixitLoc;
4263 DiagLoc = TInfo->getTypeLoc().getLocStart();
4264 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4266 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4267 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4269 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4271 << FixItHint::CreateInsertion(FixitLoc, "*");
4273 T = Context.getObjCObjectPointerType(T);
4276 TLB.pushFullCopy(TInfo->getTypeLoc());
4277 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4278 TLoc.setStarLoc(FixitLoc);
4279 TInfo = TLB.getTypeSourceInfo(Context, T);
4282 D.setInvalidType(true);
4285 // cv-qualifiers on return types are pointless except when the type is a
4286 // class type in C++.
4287 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4288 !(S.getLangOpts().CPlusPlus &&
4289 (T->isDependentType() || T->isRecordType()))) {
4290 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4291 D.getFunctionDefinitionKind() == FDK_Definition) {
4292 // [6.9.1/3] qualified void return is invalid on a C
4293 // function definition. Apparently ok on declarations and
4294 // in C++ though (!)
4295 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4297 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4300 // Objective-C ARC ownership qualifiers are ignored on the function
4301 // return type (by type canonicalization). Complain if this attribute
4302 // was written here.
4303 if (T.getQualifiers().hasObjCLifetime()) {
4304 SourceLocation AttrLoc;
4305 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4306 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4307 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4308 Attr; Attr = Attr->getNext()) {
4309 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4310 AttrLoc = Attr->getLoc();
4315 if (AttrLoc.isInvalid()) {
4316 for (const AttributeList *Attr
4317 = D.getDeclSpec().getAttributes().getList();
4318 Attr; Attr = Attr->getNext()) {
4319 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4320 AttrLoc = Attr->getLoc();
4326 if (AttrLoc.isValid()) {
4327 // The ownership attributes are almost always written via
4329 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4330 if (AttrLoc.isMacroID())
4331 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4333 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4334 << T.getQualifiers().getObjCLifetime();
4338 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4340 // Types shall not be defined in return or parameter types.
4341 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4342 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4343 << Context.getTypeDeclType(Tag);
4346 // Exception specs are not allowed in typedefs. Complain, but add it
4348 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4349 S.Diag(FTI.getExceptionSpecLocBeg(),
4350 diag::err_exception_spec_in_typedef)
4351 << (D.getContext() == Declarator::AliasDeclContext ||
4352 D.getContext() == Declarator::AliasTemplateContext);
4354 // If we see "T var();" or "T var(T());" at block scope, it is probably
4355 // an attempt to initialize a variable, not a function declaration.
4356 if (FTI.isAmbiguous)
4357 warnAboutAmbiguousFunction(S, D, DeclType, T);
4359 // GNU warning -Wstrict-prototypes
4360 // Warn if a function declaration is without a prototype.
4361 // This warning is issued for all kinds of unprototyped function
4362 // declarations (i.e. function type typedef, function pointer etc.)
4364 // The empty list in a function declarator that is not part of a
4365 // definition of that function specifies that no information
4366 // about the number or types of the parameters is supplied.
4367 if (D.getFunctionDefinitionKind() == FDK_Declaration &&
4368 FTI.NumParams == 0 && !LangOpts.CPlusPlus)
4369 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4370 << 0 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4372 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4374 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4375 // Simple void foo(), where the incoming T is the result type.
4376 T = Context.getFunctionNoProtoType(T, EI);
4378 // We allow a zero-parameter variadic function in C if the
4379 // function is marked with the "overloadable" attribute. Scan
4380 // for this attribute now.
4381 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4382 bool Overloadable = false;
4383 for (const AttributeList *Attrs = D.getAttributes();
4384 Attrs; Attrs = Attrs->getNext()) {
4385 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4386 Overloadable = true;
4392 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4395 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4396 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4398 S.Diag(FTI.Params[0].IdentLoc,
4399 diag::err_ident_list_in_fn_declaration);
4400 D.setInvalidType(true);
4401 // Recover by creating a K&R-style function type.
4402 T = Context.getFunctionNoProtoType(T, EI);
4406 FunctionProtoType::ExtProtoInfo EPI;
4408 EPI.Variadic = FTI.isVariadic;
4409 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4410 EPI.TypeQuals = FTI.TypeQuals;
4411 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4412 : FTI.RefQualifierIsLValueRef? RQ_LValue
4415 // Otherwise, we have a function with a parameter list that is
4416 // potentially variadic.
4417 SmallVector<QualType, 16> ParamTys;
4418 ParamTys.reserve(FTI.NumParams);
4420 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4421 ExtParameterInfos(FTI.NumParams);
4422 bool HasAnyInterestingExtParameterInfos = false;
4424 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4425 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4426 QualType ParamTy = Param->getType();
4427 assert(!ParamTy.isNull() && "Couldn't parse type?");
4429 // Look for 'void'. void is allowed only as a single parameter to a
4430 // function with no other parameters (C99 6.7.5.3p10). We record
4431 // int(void) as a FunctionProtoType with an empty parameter list.
4432 if (ParamTy->isVoidType()) {
4433 // If this is something like 'float(int, void)', reject it. 'void'
4434 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4435 // have parameters of incomplete type.
4436 if (FTI.NumParams != 1 || FTI.isVariadic) {
4437 S.Diag(DeclType.Loc, diag::err_void_only_param);
4438 ParamTy = Context.IntTy;
4439 Param->setType(ParamTy);
4440 } else if (FTI.Params[i].Ident) {
4441 // Reject, but continue to parse 'int(void abc)'.
4442 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4443 ParamTy = Context.IntTy;
4444 Param->setType(ParamTy);
4446 // Reject, but continue to parse 'float(const void)'.
4447 if (ParamTy.hasQualifiers())
4448 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4450 // Do not add 'void' to the list.
4453 } else if (ParamTy->isHalfType()) {
4454 // Disallow half FP parameters.
4455 // FIXME: This really should be in BuildFunctionType.
4456 if (S.getLangOpts().OpenCL) {
4457 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4458 S.Diag(Param->getLocation(),
4459 diag::err_opencl_half_param) << ParamTy;
4461 Param->setInvalidDecl();
4463 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4464 S.Diag(Param->getLocation(),
4465 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4468 } else if (!FTI.hasPrototype) {
4469 if (ParamTy->isPromotableIntegerType()) {
4470 ParamTy = Context.getPromotedIntegerType(ParamTy);
4471 Param->setKNRPromoted(true);
4472 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4473 if (BTy->getKind() == BuiltinType::Float) {
4474 ParamTy = Context.DoubleTy;
4475 Param->setKNRPromoted(true);
4480 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4481 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4482 HasAnyInterestingExtParameterInfos = true;
4485 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4486 ExtParameterInfos[i] =
4487 ExtParameterInfos[i].withABI(attr->getABI());
4488 HasAnyInterestingExtParameterInfos = true;
4491 if (Param->hasAttr<PassObjectSizeAttr>()) {
4492 ExtParameterInfos[i] = ExtParameterInfos[i].withHasPassObjectSize();
4493 HasAnyInterestingExtParameterInfos = true;
4496 ParamTys.push_back(ParamTy);
4499 if (HasAnyInterestingExtParameterInfos) {
4500 EPI.ExtParameterInfos = ExtParameterInfos.data();
4501 checkExtParameterInfos(S, ParamTys, EPI,
4502 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4505 SmallVector<QualType, 4> Exceptions;
4506 SmallVector<ParsedType, 2> DynamicExceptions;
4507 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4508 Expr *NoexceptExpr = nullptr;
4510 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4511 // FIXME: It's rather inefficient to have to split into two vectors
4513 unsigned N = FTI.getNumExceptions();
4514 DynamicExceptions.reserve(N);
4515 DynamicExceptionRanges.reserve(N);
4516 for (unsigned I = 0; I != N; ++I) {
4517 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4518 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4520 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4521 NoexceptExpr = FTI.NoexceptExpr;
4524 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4525 FTI.getExceptionSpecType(),
4527 DynamicExceptionRanges,
4532 T = Context.getFunctionType(T, ParamTys, EPI);
4536 case DeclaratorChunk::MemberPointer: {
4537 // The scope spec must refer to a class, or be dependent.
4538 CXXScopeSpec &SS = DeclType.Mem.Scope();
4541 // Handle pointer nullability.
4542 inferPointerNullability(SimplePointerKind::MemberPointer,
4543 DeclType.Loc, DeclType.getAttrListRef());
4545 if (SS.isInvalid()) {
4546 // Avoid emitting extra errors if we already errored on the scope.
4547 D.setInvalidType(true);
4548 } else if (S.isDependentScopeSpecifier(SS) ||
4549 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4550 NestedNameSpecifier *NNS = SS.getScopeRep();
4551 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4552 switch (NNS->getKind()) {
4553 case NestedNameSpecifier::Identifier:
4554 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4555 NNS->getAsIdentifier());
4558 case NestedNameSpecifier::Namespace:
4559 case NestedNameSpecifier::NamespaceAlias:
4560 case NestedNameSpecifier::Global:
4561 case NestedNameSpecifier::Super:
4562 llvm_unreachable("Nested-name-specifier must name a type");
4564 case NestedNameSpecifier::TypeSpec:
4565 case NestedNameSpecifier::TypeSpecWithTemplate:
4566 ClsType = QualType(NNS->getAsType(), 0);
4567 // Note: if the NNS has a prefix and ClsType is a nondependent
4568 // TemplateSpecializationType, then the NNS prefix is NOT included
4569 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4570 // NOTE: in particular, no wrap occurs if ClsType already is an
4571 // Elaborated, DependentName, or DependentTemplateSpecialization.
4572 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4573 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4577 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4578 diag::err_illegal_decl_mempointer_in_nonclass)
4579 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4580 << DeclType.Mem.Scope().getRange();
4581 D.setInvalidType(true);
4584 if (!ClsType.isNull())
4585 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4589 D.setInvalidType(true);
4590 } else if (DeclType.Mem.TypeQuals) {
4591 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4596 case DeclaratorChunk::Pipe: {
4597 T = S.BuildReadPipeType(T, DeclType.Loc);
4598 processTypeAttrs(state, T, TAL_DeclSpec,
4599 D.getDeclSpec().getAttributes().getList());
4605 D.setInvalidType(true);
4609 // See if there are any attributes on this declarator chunk.
4610 processTypeAttrs(state, T, TAL_DeclChunk,
4611 const_cast<AttributeList *>(DeclType.getAttrs()));
4614 assert(!T.isNull() && "T must not be null after this point");
4616 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4617 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4618 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4621 // A cv-qualifier-seq shall only be part of the function type
4622 // for a nonstatic member function, the function type to which a pointer
4623 // to member refers, or the top-level function type of a function typedef
4626 // Core issue 547 also allows cv-qualifiers on function types that are
4627 // top-level template type arguments.
4628 enum { NonMember, Member, DeductionGuide } Kind = NonMember;
4629 if (D.getName().getKind() == UnqualifiedId::IK_DeductionGuideName)
4630 Kind = DeductionGuide;
4631 else if (!D.getCXXScopeSpec().isSet()) {
4632 if ((D.getContext() == Declarator::MemberContext ||
4633 D.getContext() == Declarator::LambdaExprContext) &&
4634 !D.getDeclSpec().isFriendSpecified())
4637 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4638 if (!DC || DC->isRecord())
4642 // C++11 [dcl.fct]p6 (w/DR1417):
4643 // An attempt to specify a function type with a cv-qualifier-seq or a
4644 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4645 // - the function type for a non-static member function,
4646 // - the function type to which a pointer to member refers,
4647 // - the top-level function type of a function typedef declaration or
4648 // alias-declaration,
4649 // - the type-id in the default argument of a type-parameter, or
4650 // - the type-id of a template-argument for a type-parameter
4652 // FIXME: Checking this here is insufficient. We accept-invalid on:
4654 // template<typename T> struct S { void f(T); };
4655 // S<int() const> s;
4657 // ... for instance.
4658 if (IsQualifiedFunction &&
4660 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4662 D.getContext() != Declarator::TemplateTypeArgContext) {
4663 SourceLocation Loc = D.getLocStart();
4664 SourceRange RemovalRange;
4666 if (D.isFunctionDeclarator(I)) {
4667 SmallVector<SourceLocation, 4> RemovalLocs;
4668 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4669 assert(Chunk.Kind == DeclaratorChunk::Function);
4670 if (Chunk.Fun.hasRefQualifier())
4671 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4672 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4673 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4674 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4675 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4676 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4677 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4678 if (!RemovalLocs.empty()) {
4679 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4680 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4681 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4682 Loc = RemovalLocs.front();
4686 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4687 << Kind << D.isFunctionDeclarator() << T
4688 << getFunctionQualifiersAsString(FnTy)
4689 << FixItHint::CreateRemoval(RemovalRange);
4691 // Strip the cv-qualifiers and ref-qualifiers from the type.
4692 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4694 EPI.RefQualifier = RQ_None;
4696 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4698 // Rebuild any parens around the identifier in the function type.
4699 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4700 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4702 T = S.BuildParenType(T);
4707 // Apply any undistributed attributes from the declarator.
4708 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4710 // Diagnose any ignored type attributes.
4711 state.diagnoseIgnoredTypeAttrs(T);
4713 // C++0x [dcl.constexpr]p9:
4714 // A constexpr specifier used in an object declaration declares the object
4716 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4720 // If there was an ellipsis in the declarator, the declaration declares a
4721 // parameter pack whose type may be a pack expansion type.
4722 if (D.hasEllipsis()) {
4723 // C++0x [dcl.fct]p13:
4724 // A declarator-id or abstract-declarator containing an ellipsis shall
4725 // only be used in a parameter-declaration. Such a parameter-declaration
4726 // is a parameter pack (14.5.3). [...]
4727 switch (D.getContext()) {
4728 case Declarator::PrototypeContext:
4729 case Declarator::LambdaExprParameterContext:
4730 // C++0x [dcl.fct]p13:
4731 // [...] When it is part of a parameter-declaration-clause, the
4732 // parameter pack is a function parameter pack (14.5.3). The type T
4733 // of the declarator-id of the function parameter pack shall contain
4734 // a template parameter pack; each template parameter pack in T is
4735 // expanded by the function parameter pack.
4737 // We represent function parameter packs as function parameters whose
4738 // type is a pack expansion.
4739 if (!T->containsUnexpandedParameterPack()) {
4740 S.Diag(D.getEllipsisLoc(),
4741 diag::err_function_parameter_pack_without_parameter_packs)
4742 << T << D.getSourceRange();
4743 D.setEllipsisLoc(SourceLocation());
4745 T = Context.getPackExpansionType(T, None);
4748 case Declarator::TemplateParamContext:
4749 // C++0x [temp.param]p15:
4750 // If a template-parameter is a [...] is a parameter-declaration that
4751 // declares a parameter pack (8.3.5), then the template-parameter is a
4752 // template parameter pack (14.5.3).
4754 // Note: core issue 778 clarifies that, if there are any unexpanded
4755 // parameter packs in the type of the non-type template parameter, then
4756 // it expands those parameter packs.
4757 if (T->containsUnexpandedParameterPack())
4758 T = Context.getPackExpansionType(T, None);
4760 S.Diag(D.getEllipsisLoc(),
4761 LangOpts.CPlusPlus11
4762 ? diag::warn_cxx98_compat_variadic_templates
4763 : diag::ext_variadic_templates);
4766 case Declarator::FileContext:
4767 case Declarator::KNRTypeListContext:
4768 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4769 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4770 case Declarator::TypeNameContext:
4771 case Declarator::FunctionalCastContext:
4772 case Declarator::CXXNewContext:
4773 case Declarator::AliasDeclContext:
4774 case Declarator::AliasTemplateContext:
4775 case Declarator::MemberContext:
4776 case Declarator::BlockContext:
4777 case Declarator::ForContext:
4778 case Declarator::InitStmtContext:
4779 case Declarator::ConditionContext:
4780 case Declarator::CXXCatchContext:
4781 case Declarator::ObjCCatchContext:
4782 case Declarator::BlockLiteralContext:
4783 case Declarator::LambdaExprContext:
4784 case Declarator::ConversionIdContext:
4785 case Declarator::TrailingReturnContext:
4786 case Declarator::TemplateTypeArgContext:
4787 // FIXME: We may want to allow parameter packs in block-literal contexts
4789 S.Diag(D.getEllipsisLoc(),
4790 diag::err_ellipsis_in_declarator_not_parameter);
4791 D.setEllipsisLoc(SourceLocation());
4796 assert(!T.isNull() && "T must not be null at the end of this function");
4797 if (D.isInvalidType())
4798 return Context.getTrivialTypeSourceInfo(T);
4800 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4803 /// GetTypeForDeclarator - Convert the type for the specified
4804 /// declarator to Type instances.
4806 /// The result of this call will never be null, but the associated
4807 /// type may be a null type if there's an unrecoverable error.
4808 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4809 // Determine the type of the declarator. Not all forms of declarator
4812 TypeProcessingState state(*this, D);
4814 TypeSourceInfo *ReturnTypeInfo = nullptr;
4815 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4817 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4818 inferARCWriteback(state, T);
4820 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4823 static void transferARCOwnershipToDeclSpec(Sema &S,
4824 QualType &declSpecTy,
4825 Qualifiers::ObjCLifetime ownership) {
4826 if (declSpecTy->isObjCRetainableType() &&
4827 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4829 qs.addObjCLifetime(ownership);
4830 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4834 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4835 Qualifiers::ObjCLifetime ownership,
4836 unsigned chunkIndex) {
4837 Sema &S = state.getSema();
4838 Declarator &D = state.getDeclarator();
4840 // Look for an explicit lifetime attribute.
4841 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4842 for (const AttributeList *attr = chunk.getAttrs(); attr;
4843 attr = attr->getNext())
4844 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4847 const char *attrStr = nullptr;
4848 switch (ownership) {
4849 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4850 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4851 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4852 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4853 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4856 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4857 Arg->Ident = &S.Context.Idents.get(attrStr);
4858 Arg->Loc = SourceLocation();
4860 ArgsUnion Args(Arg);
4862 // If there wasn't one, add one (with an invalid source location
4863 // so that we don't make an AttributedType for it).
4864 AttributeList *attr = D.getAttributePool()
4865 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4866 /*scope*/ nullptr, SourceLocation(),
4867 /*args*/ &Args, 1, AttributeList::AS_GNU);
4868 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4870 // TODO: mark whether we did this inference?
4873 /// \brief Used for transferring ownership in casts resulting in l-values.
4874 static void transferARCOwnership(TypeProcessingState &state,
4875 QualType &declSpecTy,
4876 Qualifiers::ObjCLifetime ownership) {
4877 Sema &S = state.getSema();
4878 Declarator &D = state.getDeclarator();
4881 bool hasIndirection = false;
4882 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4883 DeclaratorChunk &chunk = D.getTypeObject(i);
4884 switch (chunk.Kind) {
4885 case DeclaratorChunk::Paren:
4889 case DeclaratorChunk::Array:
4890 case DeclaratorChunk::Reference:
4891 case DeclaratorChunk::Pointer:
4893 hasIndirection = true;
4897 case DeclaratorChunk::BlockPointer:
4899 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4902 case DeclaratorChunk::Function:
4903 case DeclaratorChunk::MemberPointer:
4904 case DeclaratorChunk::Pipe:
4912 DeclaratorChunk &chunk = D.getTypeObject(inner);
4913 if (chunk.Kind == DeclaratorChunk::Pointer) {
4914 if (declSpecTy->isObjCRetainableType())
4915 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4916 if (declSpecTy->isObjCObjectType() && hasIndirection)
4917 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4919 assert(chunk.Kind == DeclaratorChunk::Array ||
4920 chunk.Kind == DeclaratorChunk::Reference);
4921 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4925 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4926 TypeProcessingState state(*this, D);
4928 TypeSourceInfo *ReturnTypeInfo = nullptr;
4929 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4931 if (getLangOpts().ObjC1) {
4932 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4933 if (ownership != Qualifiers::OCL_None)
4934 transferARCOwnership(state, declSpecTy, ownership);
4937 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4940 /// Map an AttributedType::Kind to an AttributeList::Kind.
4941 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4943 case AttributedType::attr_address_space:
4944 return AttributeList::AT_AddressSpace;
4945 case AttributedType::attr_regparm:
4946 return AttributeList::AT_Regparm;
4947 case AttributedType::attr_vector_size:
4948 return AttributeList::AT_VectorSize;
4949 case AttributedType::attr_neon_vector_type:
4950 return AttributeList::AT_NeonVectorType;
4951 case AttributedType::attr_neon_polyvector_type:
4952 return AttributeList::AT_NeonPolyVectorType;
4953 case AttributedType::attr_objc_gc:
4954 return AttributeList::AT_ObjCGC;
4955 case AttributedType::attr_objc_ownership:
4956 case AttributedType::attr_objc_inert_unsafe_unretained:
4957 return AttributeList::AT_ObjCOwnership;
4958 case AttributedType::attr_noreturn:
4959 return AttributeList::AT_NoReturn;
4960 case AttributedType::attr_cdecl:
4961 return AttributeList::AT_CDecl;
4962 case AttributedType::attr_fastcall:
4963 return AttributeList::AT_FastCall;
4964 case AttributedType::attr_stdcall:
4965 return AttributeList::AT_StdCall;
4966 case AttributedType::attr_thiscall:
4967 return AttributeList::AT_ThisCall;
4968 case AttributedType::attr_regcall:
4969 return AttributeList::AT_RegCall;
4970 case AttributedType::attr_pascal:
4971 return AttributeList::AT_Pascal;
4972 case AttributedType::attr_swiftcall:
4973 return AttributeList::AT_SwiftCall;
4974 case AttributedType::attr_vectorcall:
4975 return AttributeList::AT_VectorCall;
4976 case AttributedType::attr_pcs:
4977 case AttributedType::attr_pcs_vfp:
4978 return AttributeList::AT_Pcs;
4979 case AttributedType::attr_inteloclbicc:
4980 return AttributeList::AT_IntelOclBicc;
4981 case AttributedType::attr_ms_abi:
4982 return AttributeList::AT_MSABI;
4983 case AttributedType::attr_sysv_abi:
4984 return AttributeList::AT_SysVABI;
4985 case AttributedType::attr_preserve_most:
4986 return AttributeList::AT_PreserveMost;
4987 case AttributedType::attr_preserve_all:
4988 return AttributeList::AT_PreserveAll;
4989 case AttributedType::attr_ptr32:
4990 return AttributeList::AT_Ptr32;
4991 case AttributedType::attr_ptr64:
4992 return AttributeList::AT_Ptr64;
4993 case AttributedType::attr_sptr:
4994 return AttributeList::AT_SPtr;
4995 case AttributedType::attr_uptr:
4996 return AttributeList::AT_UPtr;
4997 case AttributedType::attr_nonnull:
4998 return AttributeList::AT_TypeNonNull;
4999 case AttributedType::attr_nullable:
5000 return AttributeList::AT_TypeNullable;
5001 case AttributedType::attr_null_unspecified:
5002 return AttributeList::AT_TypeNullUnspecified;
5003 case AttributedType::attr_objc_kindof:
5004 return AttributeList::AT_ObjCKindOf;
5006 llvm_unreachable("unexpected attribute kind!");
5009 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
5010 const AttributeList *attrs,
5011 const AttributeList *DeclAttrs = nullptr) {
5012 // DeclAttrs and attrs cannot be both empty.
5013 assert((attrs || DeclAttrs) &&
5014 "no type attributes in the expected location!");
5016 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
5017 // Try to search for an attribute of matching kind in attrs list.
5018 while (attrs && attrs->getKind() != parsedKind)
5019 attrs = attrs->getNext();
5021 // No matching type attribute in attrs list found.
5022 // Try searching through C++11 attributes in the declarator attribute list.
5023 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
5024 DeclAttrs->getKind() != parsedKind))
5025 DeclAttrs = DeclAttrs->getNext();
5029 assert(attrs && "no matching type attribute in expected location!");
5031 TL.setAttrNameLoc(attrs->getLoc());
5032 if (TL.hasAttrExprOperand()) {
5033 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
5034 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
5035 } else if (TL.hasAttrEnumOperand()) {
5036 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
5037 "unexpected attribute operand kind");
5038 if (attrs->isArgIdent(0))
5039 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
5041 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
5044 // FIXME: preserve this information to here.
5045 if (TL.hasAttrOperand())
5046 TL.setAttrOperandParensRange(SourceRange());
5050 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
5051 ASTContext &Context;
5055 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5056 : Context(Context), DS(DS) {}
5058 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5059 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5060 Visit(TL.getModifiedLoc());
5062 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5063 Visit(TL.getUnqualifiedLoc());
5065 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5066 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5068 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5069 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5070 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5071 // addition field. What we have is good enough for dispay of location
5072 // of 'fixit' on interface name.
5073 TL.setNameEndLoc(DS.getLocEnd());
5075 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5076 TypeSourceInfo *RepTInfo = nullptr;
5077 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5078 TL.copy(RepTInfo->getTypeLoc());
5080 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5081 TypeSourceInfo *RepTInfo = nullptr;
5082 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5083 TL.copy(RepTInfo->getTypeLoc());
5085 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5086 TypeSourceInfo *TInfo = nullptr;
5087 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5089 // If we got no declarator info from previous Sema routines,
5090 // just fill with the typespec loc.
5092 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5096 TypeLoc OldTL = TInfo->getTypeLoc();
5097 if (TInfo->getType()->getAs<ElaboratedType>()) {
5098 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5099 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5100 .castAs<TemplateSpecializationTypeLoc>();
5103 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5104 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5108 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5109 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5110 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5111 TL.setParensRange(DS.getTypeofParensRange());
5113 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5114 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5115 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5116 TL.setParensRange(DS.getTypeofParensRange());
5117 assert(DS.getRepAsType());
5118 TypeSourceInfo *TInfo = nullptr;
5119 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5120 TL.setUnderlyingTInfo(TInfo);
5122 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5123 // FIXME: This holds only because we only have one unary transform.
5124 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5125 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5126 TL.setParensRange(DS.getTypeofParensRange());
5127 assert(DS.getRepAsType());
5128 TypeSourceInfo *TInfo = nullptr;
5129 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5130 TL.setUnderlyingTInfo(TInfo);
5132 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5133 // By default, use the source location of the type specifier.
5134 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5135 if (TL.needsExtraLocalData()) {
5136 // Set info for the written builtin specifiers.
5137 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5138 // Try to have a meaningful source location.
5139 if (TL.getWrittenSignSpec() != TSS_unspecified)
5140 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5141 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5142 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5145 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5146 ElaboratedTypeKeyword Keyword
5147 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5148 if (DS.getTypeSpecType() == TST_typename) {
5149 TypeSourceInfo *TInfo = nullptr;
5150 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5152 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5156 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5157 ? DS.getTypeSpecTypeLoc()
5158 : SourceLocation());
5159 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5160 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5161 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5163 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5164 assert(DS.getTypeSpecType() == TST_typename);
5165 TypeSourceInfo *TInfo = nullptr;
5166 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5168 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5170 void VisitDependentTemplateSpecializationTypeLoc(
5171 DependentTemplateSpecializationTypeLoc TL) {
5172 assert(DS.getTypeSpecType() == TST_typename);
5173 TypeSourceInfo *TInfo = nullptr;
5174 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5177 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5179 void VisitTagTypeLoc(TagTypeLoc TL) {
5180 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5182 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5183 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5184 // or an _Atomic qualifier.
5185 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5186 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5187 TL.setParensRange(DS.getTypeofParensRange());
5189 TypeSourceInfo *TInfo = nullptr;
5190 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5192 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5194 TL.setKWLoc(DS.getAtomicSpecLoc());
5195 // No parens, to indicate this was spelled as an _Atomic qualifier.
5196 TL.setParensRange(SourceRange());
5197 Visit(TL.getValueLoc());
5201 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5202 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5204 TypeSourceInfo *TInfo = nullptr;
5205 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5206 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5209 void VisitTypeLoc(TypeLoc TL) {
5210 // FIXME: add other typespec types and change this to an assert.
5211 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5215 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5216 ASTContext &Context;
5217 const DeclaratorChunk &Chunk;
5220 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5221 : Context(Context), Chunk(Chunk) {}
5223 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5224 llvm_unreachable("qualified type locs not expected here!");
5226 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5227 llvm_unreachable("decayed type locs not expected here!");
5230 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5231 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5233 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5236 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5237 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5238 TL.setCaretLoc(Chunk.Loc);
5240 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5241 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5242 TL.setStarLoc(Chunk.Loc);
5244 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5245 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5246 TL.setStarLoc(Chunk.Loc);
5248 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5249 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5250 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5251 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5253 const Type* ClsTy = TL.getClass();
5254 QualType ClsQT = QualType(ClsTy, 0);
5255 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5256 // Now copy source location info into the type loc component.
5257 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5258 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5259 case NestedNameSpecifier::Identifier:
5260 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5262 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5263 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5264 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5265 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5269 case NestedNameSpecifier::TypeSpec:
5270 case NestedNameSpecifier::TypeSpecWithTemplate:
5271 if (isa<ElaboratedType>(ClsTy)) {
5272 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5273 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5274 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5275 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5276 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5278 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5282 case NestedNameSpecifier::Namespace:
5283 case NestedNameSpecifier::NamespaceAlias:
5284 case NestedNameSpecifier::Global:
5285 case NestedNameSpecifier::Super:
5286 llvm_unreachable("Nested-name-specifier must name a type");
5289 // Finally fill in MemberPointerLocInfo fields.
5290 TL.setStarLoc(Chunk.Loc);
5291 TL.setClassTInfo(ClsTInfo);
5293 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5294 assert(Chunk.Kind == DeclaratorChunk::Reference);
5295 // 'Amp' is misleading: this might have been originally
5296 /// spelled with AmpAmp.
5297 TL.setAmpLoc(Chunk.Loc);
5299 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5300 assert(Chunk.Kind == DeclaratorChunk::Reference);
5301 assert(!Chunk.Ref.LValueRef);
5302 TL.setAmpAmpLoc(Chunk.Loc);
5304 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5305 assert(Chunk.Kind == DeclaratorChunk::Array);
5306 TL.setLBracketLoc(Chunk.Loc);
5307 TL.setRBracketLoc(Chunk.EndLoc);
5308 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5310 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5311 assert(Chunk.Kind == DeclaratorChunk::Function);
5312 TL.setLocalRangeBegin(Chunk.Loc);
5313 TL.setLocalRangeEnd(Chunk.EndLoc);
5315 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5316 TL.setLParenLoc(FTI.getLParenLoc());
5317 TL.setRParenLoc(FTI.getRParenLoc());
5318 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5319 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5320 TL.setParam(tpi++, Param);
5322 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5324 void VisitParenTypeLoc(ParenTypeLoc TL) {
5325 assert(Chunk.Kind == DeclaratorChunk::Paren);
5326 TL.setLParenLoc(Chunk.Loc);
5327 TL.setRParenLoc(Chunk.EndLoc);
5329 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5330 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5331 TL.setKWLoc(Chunk.Loc);
5334 void VisitTypeLoc(TypeLoc TL) {
5335 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5338 } // end anonymous namespace
5340 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5342 switch (Chunk.Kind) {
5343 case DeclaratorChunk::Function:
5344 case DeclaratorChunk::Array:
5345 case DeclaratorChunk::Paren:
5346 case DeclaratorChunk::Pipe:
5347 llvm_unreachable("cannot be _Atomic qualified");
5349 case DeclaratorChunk::Pointer:
5350 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5353 case DeclaratorChunk::BlockPointer:
5354 case DeclaratorChunk::Reference:
5355 case DeclaratorChunk::MemberPointer:
5356 // FIXME: Provide a source location for the _Atomic keyword.
5361 ATL.setParensRange(SourceRange());
5364 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5366 /// \param T QualType referring to the type as written in source code.
5368 /// \param ReturnTypeInfo For declarators whose return type does not show
5369 /// up in the normal place in the declaration specifiers (such as a C++
5370 /// conversion function), this pointer will refer to a type source information
5371 /// for that return type.
5373 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5374 TypeSourceInfo *ReturnTypeInfo) {
5375 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5376 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5377 const AttributeList *DeclAttrs = D.getAttributes();
5379 // Handle parameter packs whose type is a pack expansion.
5380 if (isa<PackExpansionType>(T)) {
5381 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5382 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5385 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5386 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5387 // declarator chunk.
5388 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5389 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5390 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5393 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5394 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5395 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5398 // FIXME: Ordering here?
5399 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5400 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5402 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5403 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5406 // If we have different source information for the return type, use
5407 // that. This really only applies to C++ conversion functions.
5408 if (ReturnTypeInfo) {
5409 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5410 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5411 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5413 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5419 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5420 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5421 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5422 // and Sema during declaration parsing. Try deallocating/caching them when
5423 // it's appropriate, instead of allocating them and keeping them around.
5424 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5426 new (LocT) LocInfoType(T, TInfo);
5427 assert(LocT->getTypeClass() != T->getTypeClass() &&
5428 "LocInfoType's TypeClass conflicts with an existing Type class");
5429 return ParsedType::make(QualType(LocT, 0));
5432 void LocInfoType::getAsStringInternal(std::string &Str,
5433 const PrintingPolicy &Policy) const {
5434 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5435 " was used directly instead of getting the QualType through"
5436 " GetTypeFromParser");
5439 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5440 // C99 6.7.6: Type names have no identifier. This is already validated by
5442 assert(D.getIdentifier() == nullptr &&
5443 "Type name should have no identifier!");
5445 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5446 QualType T = TInfo->getType();
5447 if (D.isInvalidType())
5450 // Make sure there are no unused decl attributes on the declarator.
5451 // We don't want to do this for ObjC parameters because we're going
5452 // to apply them to the actual parameter declaration.
5453 // Likewise, we don't want to do this for alias declarations, because
5454 // we are actually going to build a declaration from this eventually.
5455 if (D.getContext() != Declarator::ObjCParameterContext &&
5456 D.getContext() != Declarator::AliasDeclContext &&
5457 D.getContext() != Declarator::AliasTemplateContext)
5458 checkUnusedDeclAttributes(D);
5460 if (getLangOpts().CPlusPlus) {
5461 // Check that there are no default arguments (C++ only).
5462 CheckExtraCXXDefaultArguments(D);
5465 return CreateParsedType(T, TInfo);
5468 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5469 QualType T = Context.getObjCInstanceType();
5470 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5471 return CreateParsedType(T, TInfo);
5474 //===----------------------------------------------------------------------===//
5475 // Type Attribute Processing
5476 //===----------------------------------------------------------------------===//
5478 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5479 /// specified type. The attribute contains 1 argument, the id of the address
5480 /// space for the type.
5481 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5482 const AttributeList &Attr, Sema &S){
5484 // If this type is already address space qualified, reject it.
5485 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5486 // qualifiers for two or more different address spaces."
5487 if (Type.getAddressSpace()) {
5488 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5493 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5494 // qualified by an address-space qualifier."
5495 if (Type->isFunctionType()) {
5496 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5502 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5503 // Check the attribute arguments.
5504 if (Attr.getNumArgs() != 1) {
5505 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5506 << Attr.getName() << 1;
5510 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5511 llvm::APSInt addrSpace(32);
5512 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5513 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5514 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5515 << Attr.getName() << AANT_ArgumentIntegerConstant
5516 << ASArgExpr->getSourceRange();
5522 if (addrSpace.isSigned()) {
5523 if (addrSpace.isNegative()) {
5524 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5525 << ASArgExpr->getSourceRange();
5529 addrSpace.setIsSigned(false);
5531 llvm::APSInt max(addrSpace.getBitWidth());
5532 max = Qualifiers::MaxAddressSpace - LangAS::Count;
5533 if (addrSpace > max) {
5534 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5535 << (unsigned)max.getZExtValue() << ASArgExpr->getSourceRange();
5539 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()) + LangAS::Count;
5541 // The keyword-based type attributes imply which address space to use.
5542 switch (Attr.getKind()) {
5543 case AttributeList::AT_OpenCLGlobalAddressSpace:
5544 ASIdx = LangAS::opencl_global; break;
5545 case AttributeList::AT_OpenCLLocalAddressSpace:
5546 ASIdx = LangAS::opencl_local; break;
5547 case AttributeList::AT_OpenCLConstantAddressSpace:
5548 ASIdx = LangAS::opencl_constant; break;
5549 case AttributeList::AT_OpenCLGenericAddressSpace:
5550 ASIdx = LangAS::opencl_generic; break;
5552 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5557 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5560 /// Does this type have a "direct" ownership qualifier? That is,
5561 /// is it written like "__strong id", as opposed to something like
5562 /// "typeof(foo)", where that happens to be strong?
5563 static bool hasDirectOwnershipQualifier(QualType type) {
5564 // Fast path: no qualifier at all.
5565 assert(type.getQualifiers().hasObjCLifetime());
5569 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5570 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5573 type = attr->getModifiedType();
5575 // X *__strong (...)
5576 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5577 type = paren->getInnerType();
5579 // That's it for things we want to complain about. In particular,
5580 // we do not want to look through typedefs, typeof(expr),
5581 // typeof(type), or any other way that the type is somehow
5590 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5591 /// attribute on the specified type.
5593 /// Returns 'true' if the attribute was handled.
5594 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5595 AttributeList &attr,
5597 bool NonObjCPointer = false;
5599 if (!type->isDependentType() && !type->isUndeducedType()) {
5600 if (const PointerType *ptr = type->getAs<PointerType>()) {
5601 QualType pointee = ptr->getPointeeType();
5602 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5604 // It is important not to lose the source info that there was an attribute
5605 // applied to non-objc pointer. We will create an attributed type but
5606 // its type will be the same as the original type.
5607 NonObjCPointer = true;
5608 } else if (!type->isObjCRetainableType()) {
5612 // Don't accept an ownership attribute in the declspec if it would
5613 // just be the return type of a block pointer.
5614 if (state.isProcessingDeclSpec()) {
5615 Declarator &D = state.getDeclarator();
5616 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5617 /*onlyBlockPointers=*/true))
5622 Sema &S = state.getSema();
5623 SourceLocation AttrLoc = attr.getLoc();
5624 if (AttrLoc.isMacroID())
5625 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5627 if (!attr.isArgIdent(0)) {
5628 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5629 << attr.getName() << AANT_ArgumentString;
5634 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5635 Qualifiers::ObjCLifetime lifetime;
5636 if (II->isStr("none"))
5637 lifetime = Qualifiers::OCL_ExplicitNone;
5638 else if (II->isStr("strong"))
5639 lifetime = Qualifiers::OCL_Strong;
5640 else if (II->isStr("weak"))
5641 lifetime = Qualifiers::OCL_Weak;
5642 else if (II->isStr("autoreleasing"))
5643 lifetime = Qualifiers::OCL_Autoreleasing;
5645 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5646 << attr.getName() << II;
5651 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5652 // outside of ARC mode.
5653 if (!S.getLangOpts().ObjCAutoRefCount &&
5654 lifetime != Qualifiers::OCL_Weak &&
5655 lifetime != Qualifiers::OCL_ExplicitNone) {
5659 SplitQualType underlyingType = type.split();
5661 // Check for redundant/conflicting ownership qualifiers.
5662 if (Qualifiers::ObjCLifetime previousLifetime
5663 = type.getQualifiers().getObjCLifetime()) {
5664 // If it's written directly, that's an error.
5665 if (hasDirectOwnershipQualifier(type)) {
5666 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5671 // Otherwise, if the qualifiers actually conflict, pull sugar off
5672 // and remove the ObjCLifetime qualifiers.
5673 if (previousLifetime != lifetime) {
5674 // It's possible to have multiple local ObjCLifetime qualifiers. We
5675 // can't stop after we reach a type that is directly qualified.
5676 const Type *prevTy = nullptr;
5677 while (!prevTy || prevTy != underlyingType.Ty) {
5678 prevTy = underlyingType.Ty;
5679 underlyingType = underlyingType.getSingleStepDesugaredType();
5681 underlyingType.Quals.removeObjCLifetime();
5685 underlyingType.Quals.addObjCLifetime(lifetime);
5687 if (NonObjCPointer) {
5688 StringRef name = attr.getName()->getName();
5690 case Qualifiers::OCL_None:
5691 case Qualifiers::OCL_ExplicitNone:
5693 case Qualifiers::OCL_Strong: name = "__strong"; break;
5694 case Qualifiers::OCL_Weak: name = "__weak"; break;
5695 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5697 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5698 << TDS_ObjCObjOrBlock << type;
5701 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5702 // because having both 'T' and '__unsafe_unretained T' exist in the type
5703 // system causes unfortunate widespread consistency problems. (For example,
5704 // they're not considered compatible types, and we mangle them identicially
5705 // as template arguments.) These problems are all individually fixable,
5706 // but it's easier to just not add the qualifier and instead sniff it out
5707 // in specific places using isObjCInertUnsafeUnretainedType().
5709 // Doing this does means we miss some trivial consistency checks that
5710 // would've triggered in ARC, but that's better than trying to solve all
5711 // the coexistence problems with __unsafe_unretained.
5712 if (!S.getLangOpts().ObjCAutoRefCount &&
5713 lifetime == Qualifiers::OCL_ExplicitNone) {
5714 type = S.Context.getAttributedType(
5715 AttributedType::attr_objc_inert_unsafe_unretained,
5720 QualType origType = type;
5721 if (!NonObjCPointer)
5722 type = S.Context.getQualifiedType(underlyingType);
5724 // If we have a valid source location for the attribute, use an
5725 // AttributedType instead.
5726 if (AttrLoc.isValid())
5727 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5730 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5731 unsigned diagnostic, QualType type) {
5732 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5733 S.DelayedDiagnostics.add(
5734 sema::DelayedDiagnostic::makeForbiddenType(
5735 S.getSourceManager().getExpansionLoc(loc),
5736 diagnostic, type, /*ignored*/ 0));
5738 S.Diag(loc, diagnostic);
5742 // Sometimes, __weak isn't allowed.
5743 if (lifetime == Qualifiers::OCL_Weak &&
5744 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5746 // Use a specialized diagnostic if the runtime just doesn't support them.
5747 unsigned diagnostic =
5748 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5749 : diag::err_arc_weak_no_runtime);
5751 // In any case, delay the diagnostic until we know what we're parsing.
5752 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5758 // Forbid __weak for class objects marked as
5759 // objc_arc_weak_reference_unavailable
5760 if (lifetime == Qualifiers::OCL_Weak) {
5761 if (const ObjCObjectPointerType *ObjT =
5762 type->getAs<ObjCObjectPointerType>()) {
5763 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5764 if (Class->isArcWeakrefUnavailable()) {
5765 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5766 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5767 diag::note_class_declared);
5776 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5777 /// attribute on the specified type. Returns true to indicate that
5778 /// the attribute was handled, false to indicate that the type does
5779 /// not permit the attribute.
5780 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5781 AttributeList &attr,
5783 Sema &S = state.getSema();
5785 // Delay if this isn't some kind of pointer.
5786 if (!type->isPointerType() &&
5787 !type->isObjCObjectPointerType() &&
5788 !type->isBlockPointerType())
5791 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5792 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5797 // Check the attribute arguments.
5798 if (!attr.isArgIdent(0)) {
5799 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5800 << attr.getName() << AANT_ArgumentString;
5804 Qualifiers::GC GCAttr;
5805 if (attr.getNumArgs() > 1) {
5806 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5807 << attr.getName() << 1;
5812 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5813 if (II->isStr("weak"))
5814 GCAttr = Qualifiers::Weak;
5815 else if (II->isStr("strong"))
5816 GCAttr = Qualifiers::Strong;
5818 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5819 << attr.getName() << II;
5824 QualType origType = type;
5825 type = S.Context.getObjCGCQualType(origType, GCAttr);
5827 // Make an attributed type to preserve the source information.
5828 if (attr.getLoc().isValid())
5829 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5836 /// A helper class to unwrap a type down to a function for the
5837 /// purposes of applying attributes there.
5840 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5841 /// if (unwrapped.isFunctionType()) {
5842 /// const FunctionType *fn = unwrapped.get();
5843 /// // change fn somehow
5844 /// T = unwrapped.wrap(fn);
5846 struct FunctionTypeUnwrapper {
5858 const FunctionType *Fn;
5859 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5861 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5863 const Type *Ty = T.getTypePtr();
5864 if (isa<FunctionType>(Ty)) {
5865 Fn = cast<FunctionType>(Ty);
5867 } else if (isa<ParenType>(Ty)) {
5868 T = cast<ParenType>(Ty)->getInnerType();
5869 Stack.push_back(Parens);
5870 } else if (isa<PointerType>(Ty)) {
5871 T = cast<PointerType>(Ty)->getPointeeType();
5872 Stack.push_back(Pointer);
5873 } else if (isa<BlockPointerType>(Ty)) {
5874 T = cast<BlockPointerType>(Ty)->getPointeeType();
5875 Stack.push_back(BlockPointer);
5876 } else if (isa<MemberPointerType>(Ty)) {
5877 T = cast<MemberPointerType>(Ty)->getPointeeType();
5878 Stack.push_back(MemberPointer);
5879 } else if (isa<ReferenceType>(Ty)) {
5880 T = cast<ReferenceType>(Ty)->getPointeeType();
5881 Stack.push_back(Reference);
5882 } else if (isa<AttributedType>(Ty)) {
5883 T = cast<AttributedType>(Ty)->getEquivalentType();
5884 Stack.push_back(Attributed);
5886 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5892 T = QualType(DTy, 0);
5893 Stack.push_back(Desugar);
5898 bool isFunctionType() const { return (Fn != nullptr); }
5899 const FunctionType *get() const { return Fn; }
5901 QualType wrap(Sema &S, const FunctionType *New) {
5902 // If T wasn't modified from the unwrapped type, do nothing.
5903 if (New == get()) return Original;
5906 return wrap(S.Context, Original, 0);
5910 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5911 if (I == Stack.size())
5912 return C.getQualifiedType(Fn, Old.getQualifiers());
5914 // Build up the inner type, applying the qualifiers from the old
5915 // type to the new type.
5916 SplitQualType SplitOld = Old.split();
5918 // As a special case, tail-recurse if there are no qualifiers.
5919 if (SplitOld.Quals.empty())
5920 return wrap(C, SplitOld.Ty, I);
5921 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5924 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5925 if (I == Stack.size()) return QualType(Fn, 0);
5927 switch (static_cast<WrapKind>(Stack[I++])) {
5929 // This is the point at which we potentially lose source
5931 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5934 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5937 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5938 return C.getParenType(New);
5942 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5943 return C.getPointerType(New);
5946 case BlockPointer: {
5947 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5948 return C.getBlockPointerType(New);
5951 case MemberPointer: {
5952 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5953 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5954 return C.getMemberPointerType(New, OldMPT->getClass());
5958 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5959 QualType New = wrap(C, OldRef->getPointeeType(), I);
5960 if (isa<LValueReferenceType>(OldRef))
5961 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5963 return C.getRValueReferenceType(New);
5967 llvm_unreachable("unknown wrapping kind");
5970 } // end anonymous namespace
5972 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5973 AttributeList &Attr,
5975 Sema &S = State.getSema();
5977 AttributeList::Kind Kind = Attr.getKind();
5978 QualType Desugared = Type;
5979 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5981 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5983 // You cannot specify duplicate type attributes, so if the attribute has
5984 // already been applied, flag it.
5985 if (getAttrListKind(CurAttrKind) == Kind) {
5986 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5991 // You cannot have both __sptr and __uptr on the same type, nor can you
5992 // have __ptr32 and __ptr64.
5993 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5994 Kind == AttributeList::AT_Ptr64) ||
5995 (CurAttrKind == AttributedType::attr_ptr64 &&
5996 Kind == AttributeList::AT_Ptr32)) {
5997 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5998 << "'__ptr32'" << "'__ptr64'";
6000 } else if ((CurAttrKind == AttributedType::attr_sptr &&
6001 Kind == AttributeList::AT_UPtr) ||
6002 (CurAttrKind == AttributedType::attr_uptr &&
6003 Kind == AttributeList::AT_SPtr)) {
6004 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
6005 << "'__sptr'" << "'__uptr'";
6009 Desugared = AT->getEquivalentType();
6010 AT = dyn_cast<AttributedType>(Desugared);
6013 // Pointer type qualifiers can only operate on pointer types, but not
6014 // pointer-to-member types.
6015 if (!isa<PointerType>(Desugared)) {
6016 if (Type->isMemberPointerType())
6017 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
6020 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
6021 << Attr.getName() << 0;
6025 AttributedType::Kind TAK;
6027 default: llvm_unreachable("Unknown attribute kind");
6028 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
6029 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
6030 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
6031 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
6034 Type = S.Context.getAttributedType(TAK, Type, Type);
6038 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
6039 NullabilityKind nullability,
6040 SourceLocation nullabilityLoc,
6041 bool isContextSensitive,
6042 bool allowOnArrayType) {
6043 recordNullabilitySeen(*this, nullabilityLoc);
6045 // Check for existing nullability attributes on the type.
6046 QualType desugared = type;
6047 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
6048 // Check whether there is already a null
6049 if (auto existingNullability = attributed->getImmediateNullability()) {
6050 // Duplicated nullability.
6051 if (nullability == *existingNullability) {
6052 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
6053 << DiagNullabilityKind(nullability, isContextSensitive)
6054 << FixItHint::CreateRemoval(nullabilityLoc);
6059 // Conflicting nullability.
6060 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6061 << DiagNullabilityKind(nullability, isContextSensitive)
6062 << DiagNullabilityKind(*existingNullability, false);
6066 desugared = attributed->getModifiedType();
6069 // If there is already a different nullability specifier, complain.
6070 // This (unlike the code above) looks through typedefs that might
6071 // have nullability specifiers on them, which means we cannot
6072 // provide a useful Fix-It.
6073 if (auto existingNullability = desugared->getNullability(Context)) {
6074 if (nullability != *existingNullability) {
6075 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6076 << DiagNullabilityKind(nullability, isContextSensitive)
6077 << DiagNullabilityKind(*existingNullability, false);
6079 // Try to find the typedef with the existing nullability specifier.
6080 if (auto typedefType = desugared->getAs<TypedefType>()) {
6081 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6082 QualType underlyingType = typedefDecl->getUnderlyingType();
6083 if (auto typedefNullability
6084 = AttributedType::stripOuterNullability(underlyingType)) {
6085 if (*typedefNullability == *existingNullability) {
6086 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6087 << DiagNullabilityKind(*existingNullability, false);
6096 // If this definitely isn't a pointer type, reject the specifier.
6097 if (!desugared->canHaveNullability() &&
6098 !(allowOnArrayType && desugared->isArrayType())) {
6099 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6100 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6104 // For the context-sensitive keywords/Objective-C property
6105 // attributes, require that the type be a single-level pointer.
6106 if (isContextSensitive) {
6107 // Make sure that the pointee isn't itself a pointer type.
6108 const Type *pointeeType;
6109 if (desugared->isArrayType())
6110 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6112 pointeeType = desugared->getPointeeType().getTypePtr();
6114 if (pointeeType->isAnyPointerType() ||
6115 pointeeType->isObjCObjectPointerType() ||
6116 pointeeType->isMemberPointerType()) {
6117 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6118 << DiagNullabilityKind(nullability, true)
6120 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6121 << DiagNullabilityKind(nullability, false)
6123 << FixItHint::CreateReplacement(nullabilityLoc,
6124 getNullabilitySpelling(nullability));
6129 // Form the attributed type.
6130 type = Context.getAttributedType(
6131 AttributedType::getNullabilityAttrKind(nullability), type, type);
6135 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6136 if (isa<ObjCTypeParamType>(type)) {
6137 // Build the attributed type to record where __kindof occurred.
6138 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6143 // Find out if it's an Objective-C object or object pointer type;
6144 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6145 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6146 : type->getAs<ObjCObjectType>();
6148 // If not, we can't apply __kindof.
6150 // FIXME: Handle dependent types that aren't yet object types.
6151 Diag(loc, diag::err_objc_kindof_nonobject)
6156 // Rebuild the "equivalent" type, which pushes __kindof down into
6158 // There is no need to apply kindof on an unqualified id type.
6159 QualType equivType = Context.getObjCObjectType(
6160 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6161 objType->getProtocols(),
6162 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6164 // If we started with an object pointer type, rebuild it.
6166 equivType = Context.getObjCObjectPointerType(equivType);
6167 if (auto nullability = type->getNullability(Context)) {
6168 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6169 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6173 // Build the attributed type to record where __kindof occurred.
6174 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6181 /// Map a nullability attribute kind to a nullability kind.
6182 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6184 case AttributeList::AT_TypeNonNull:
6185 return NullabilityKind::NonNull;
6187 case AttributeList::AT_TypeNullable:
6188 return NullabilityKind::Nullable;
6190 case AttributeList::AT_TypeNullUnspecified:
6191 return NullabilityKind::Unspecified;
6194 llvm_unreachable("not a nullability attribute kind");
6198 /// Distribute a nullability type attribute that cannot be applied to
6199 /// the type specifier to a pointer, block pointer, or member pointer
6200 /// declarator, complaining if necessary.
6202 /// \returns true if the nullability annotation was distributed, false
6204 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6206 AttributeList &attr) {
6207 Declarator &declarator = state.getDeclarator();
6209 /// Attempt to move the attribute to the specified chunk.
6210 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6211 // If there is already a nullability attribute there, don't add
6213 if (hasNullabilityAttr(chunk.getAttrListRef()))
6216 // Complain about the nullability qualifier being in the wrong
6223 PK_MemberFunctionPointer,
6225 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6227 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6228 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6230 auto diag = state.getSema().Diag(attr.getLoc(),
6231 diag::warn_nullability_declspec)
6232 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6233 attr.isContextSensitiveKeywordAttribute())
6235 << static_cast<unsigned>(pointerKind);
6237 // FIXME: MemberPointer chunks don't carry the location of the *.
6238 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6239 diag << FixItHint::CreateRemoval(attr.getLoc())
6240 << FixItHint::CreateInsertion(
6241 state.getSema().getPreprocessor()
6242 .getLocForEndOfToken(chunk.Loc),
6243 " " + attr.getName()->getName().str() + " ");
6246 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6247 chunk.getAttrListRef());
6251 // Move it to the outermost pointer, member pointer, or block
6252 // pointer declarator.
6253 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6254 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6255 switch (chunk.Kind) {
6256 case DeclaratorChunk::Pointer:
6257 case DeclaratorChunk::BlockPointer:
6258 case DeclaratorChunk::MemberPointer:
6259 return moveToChunk(chunk, false);
6261 case DeclaratorChunk::Paren:
6262 case DeclaratorChunk::Array:
6265 case DeclaratorChunk::Function:
6266 // Try to move past the return type to a function/block/member
6267 // function pointer.
6268 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6270 /*onlyBlockPointers=*/false)) {
6271 return moveToChunk(*dest, true);
6276 // Don't walk through these.
6277 case DeclaratorChunk::Reference:
6278 case DeclaratorChunk::Pipe:
6286 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6287 assert(!Attr.isInvalid());
6288 switch (Attr.getKind()) {
6290 llvm_unreachable("not a calling convention attribute");
6291 case AttributeList::AT_CDecl:
6292 return AttributedType::attr_cdecl;
6293 case AttributeList::AT_FastCall:
6294 return AttributedType::attr_fastcall;
6295 case AttributeList::AT_StdCall:
6296 return AttributedType::attr_stdcall;
6297 case AttributeList::AT_ThisCall:
6298 return AttributedType::attr_thiscall;
6299 case AttributeList::AT_RegCall:
6300 return AttributedType::attr_regcall;
6301 case AttributeList::AT_Pascal:
6302 return AttributedType::attr_pascal;
6303 case AttributeList::AT_SwiftCall:
6304 return AttributedType::attr_swiftcall;
6305 case AttributeList::AT_VectorCall:
6306 return AttributedType::attr_vectorcall;
6307 case AttributeList::AT_Pcs: {
6308 // The attribute may have had a fixit applied where we treated an
6309 // identifier as a string literal. The contents of the string are valid,
6310 // but the form may not be.
6312 if (Attr.isArgExpr(0))
6313 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6315 Str = Attr.getArgAsIdent(0)->Ident->getName();
6316 return llvm::StringSwitch<AttributedType::Kind>(Str)
6317 .Case("aapcs", AttributedType::attr_pcs)
6318 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6320 case AttributeList::AT_IntelOclBicc:
6321 return AttributedType::attr_inteloclbicc;
6322 case AttributeList::AT_MSABI:
6323 return AttributedType::attr_ms_abi;
6324 case AttributeList::AT_SysVABI:
6325 return AttributedType::attr_sysv_abi;
6326 case AttributeList::AT_PreserveMost:
6327 return AttributedType::attr_preserve_most;
6328 case AttributeList::AT_PreserveAll:
6329 return AttributedType::attr_preserve_all;
6331 llvm_unreachable("unexpected attribute kind!");
6334 /// Process an individual function attribute. Returns true to
6335 /// indicate that the attribute was handled, false if it wasn't.
6336 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6337 AttributeList &attr,
6339 Sema &S = state.getSema();
6341 FunctionTypeUnwrapper unwrapped(S, type);
6343 if (attr.getKind() == AttributeList::AT_NoReturn) {
6344 if (S.CheckNoReturnAttr(attr))
6347 // Delay if this is not a function type.
6348 if (!unwrapped.isFunctionType())
6351 // Otherwise we can process right away.
6352 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6353 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6357 // ns_returns_retained is not always a type attribute, but if we got
6358 // here, we're treating it as one right now.
6359 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6360 assert(S.getLangOpts().ObjCAutoRefCount &&
6361 "ns_returns_retained treated as type attribute in non-ARC");
6362 if (attr.getNumArgs()) return true;
6364 // Delay if this is not a function type.
6365 if (!unwrapped.isFunctionType())
6368 FunctionType::ExtInfo EI
6369 = unwrapped.get()->getExtInfo().withProducesResult(true);
6370 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6374 if (attr.getKind() == AttributeList::AT_Regparm) {
6376 if (S.CheckRegparmAttr(attr, value))
6379 // Delay if this is not a function type.
6380 if (!unwrapped.isFunctionType())
6383 // Diagnose regparm with fastcall.
6384 const FunctionType *fn = unwrapped.get();
6385 CallingConv CC = fn->getCallConv();
6386 if (CC == CC_X86FastCall) {
6387 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6388 << FunctionType::getNameForCallConv(CC)
6394 FunctionType::ExtInfo EI =
6395 unwrapped.get()->getExtInfo().withRegParm(value);
6396 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6400 // Delay if the type didn't work out to a function.
6401 if (!unwrapped.isFunctionType()) return false;
6403 // Otherwise, a calling convention.
6405 if (S.CheckCallingConvAttr(attr, CC))
6408 const FunctionType *fn = unwrapped.get();
6409 CallingConv CCOld = fn->getCallConv();
6410 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6413 // Error out on when there's already an attribute on the type
6414 // and the CCs don't match.
6415 const AttributedType *AT = S.getCallingConvAttributedType(type);
6416 if (AT && AT->getAttrKind() != CCAttrKind) {
6417 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6418 << FunctionType::getNameForCallConv(CC)
6419 << FunctionType::getNameForCallConv(CCOld);
6425 // Diagnose use of variadic functions with calling conventions that
6426 // don't support them (e.g. because they're callee-cleanup).
6427 // We delay warning about this on unprototyped function declarations
6428 // until after redeclaration checking, just in case we pick up a
6429 // prototype that way. And apparently we also "delay" warning about
6430 // unprototyped function types in general, despite not necessarily having
6431 // much ability to diagnose it later.
6432 if (!supportsVariadicCall(CC)) {
6433 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6434 if (FnP && FnP->isVariadic()) {
6435 unsigned DiagID = diag::err_cconv_varargs;
6437 // stdcall and fastcall are ignored with a warning for GCC and MS
6439 bool IsInvalid = true;
6440 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6441 DiagID = diag::warn_cconv_varargs;
6445 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6446 if (IsInvalid) attr.setInvalid();
6451 // Also diagnose fastcall with regparm.
6452 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6453 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6454 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6459 // Modify the CC from the wrapped function type, wrap it all back, and then
6460 // wrap the whole thing in an AttributedType as written. The modified type
6461 // might have a different CC if we ignored the attribute.
6462 QualType Equivalent;
6466 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6468 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6470 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6474 bool Sema::hasExplicitCallingConv(QualType &T) {
6475 QualType R = T.IgnoreParens();
6476 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6477 if (AT->isCallingConv())
6479 R = AT->getModifiedType().IgnoreParens();
6484 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6485 SourceLocation Loc) {
6486 FunctionTypeUnwrapper Unwrapped(*this, T);
6487 const FunctionType *FT = Unwrapped.get();
6488 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6489 cast<FunctionProtoType>(FT)->isVariadic());
6490 CallingConv CurCC = FT->getCallConv();
6491 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6496 // MS compiler ignores explicit calling convention attributes on structors. We
6497 // should do the same.
6498 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6499 // Issue a warning on ignored calling convention -- except of __stdcall.
6500 // Again, this is what MS compiler does.
6501 if (CurCC != CC_X86StdCall)
6502 Diag(Loc, diag::warn_cconv_structors)
6503 << FunctionType::getNameForCallConv(CurCC);
6504 // Default adjustment.
6506 // Only adjust types with the default convention. For example, on Windows
6507 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6508 // __thiscall type to __cdecl for static methods.
6509 CallingConv DefaultCC =
6510 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6512 if (CurCC != DefaultCC || DefaultCC == ToCC)
6515 if (hasExplicitCallingConv(T))
6519 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6520 QualType Wrapped = Unwrapped.wrap(*this, FT);
6521 T = Context.getAdjustedType(T, Wrapped);
6524 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6525 /// and float scalars, although arrays, pointers, and function return values are
6526 /// allowed in conjunction with this construct. Aggregates with this attribute
6527 /// are invalid, even if they are of the same size as a corresponding scalar.
6528 /// The raw attribute should contain precisely 1 argument, the vector size for
6529 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6530 /// this routine will return a new vector type.
6531 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6533 // Check the attribute arguments.
6534 if (Attr.getNumArgs() != 1) {
6535 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6536 << Attr.getName() << 1;
6540 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6541 llvm::APSInt vecSize(32);
6542 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6543 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6544 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6545 << Attr.getName() << AANT_ArgumentIntegerConstant
6546 << sizeExpr->getSourceRange();
6550 // The base type must be integer (not Boolean or enumeration) or float, and
6551 // can't already be a vector.
6552 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6553 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6554 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6558 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6559 // vecSize is specified in bytes - convert to bits.
6560 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6562 // the vector size needs to be an integral multiple of the type size.
6563 if (vectorSize % typeSize) {
6564 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6565 << sizeExpr->getSourceRange();
6569 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6570 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6571 << sizeExpr->getSourceRange();
6575 if (vectorSize == 0) {
6576 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6577 << sizeExpr->getSourceRange();
6582 // Success! Instantiate the vector type, the number of elements is > 0, and
6583 // not required to be a power of 2, unlike GCC.
6584 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6585 VectorType::GenericVector);
6588 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6590 static void HandleExtVectorTypeAttr(QualType &CurType,
6591 const AttributeList &Attr,
6593 // check the attribute arguments.
6594 if (Attr.getNumArgs() != 1) {
6595 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6596 << Attr.getName() << 1;
6602 // Special case where the argument is a template id.
6603 if (Attr.isArgIdent(0)) {
6605 SourceLocation TemplateKWLoc;
6607 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6609 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6611 if (Size.isInvalid())
6614 sizeExpr = Size.get();
6616 sizeExpr = Attr.getArgAsExpr(0);
6619 // Create the vector type.
6620 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6625 static bool isPermittedNeonBaseType(QualType &Ty,
6626 VectorType::VectorKind VecKind, Sema &S) {
6627 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6631 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6633 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6635 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6636 Triple.getArch() == llvm::Triple::aarch64_be;
6637 if (VecKind == VectorType::NeonPolyVector) {
6638 if (IsPolyUnsigned) {
6639 // AArch64 polynomial vectors are unsigned and support poly64.
6640 return BTy->getKind() == BuiltinType::UChar ||
6641 BTy->getKind() == BuiltinType::UShort ||
6642 BTy->getKind() == BuiltinType::ULong ||
6643 BTy->getKind() == BuiltinType::ULongLong;
6645 // AArch32 polynomial vector are signed.
6646 return BTy->getKind() == BuiltinType::SChar ||
6647 BTy->getKind() == BuiltinType::Short;
6651 // Non-polynomial vector types: the usual suspects are allowed, as well as
6652 // float64_t on AArch64.
6653 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6654 Triple.getArch() == llvm::Triple::aarch64_be;
6656 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6659 return BTy->getKind() == BuiltinType::SChar ||
6660 BTy->getKind() == BuiltinType::UChar ||
6661 BTy->getKind() == BuiltinType::Short ||
6662 BTy->getKind() == BuiltinType::UShort ||
6663 BTy->getKind() == BuiltinType::Int ||
6664 BTy->getKind() == BuiltinType::UInt ||
6665 BTy->getKind() == BuiltinType::Long ||
6666 BTy->getKind() == BuiltinType::ULong ||
6667 BTy->getKind() == BuiltinType::LongLong ||
6668 BTy->getKind() == BuiltinType::ULongLong ||
6669 BTy->getKind() == BuiltinType::Float ||
6670 BTy->getKind() == BuiltinType::Half;
6673 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6674 /// "neon_polyvector_type" attributes are used to create vector types that
6675 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6676 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6677 /// the argument to these Neon attributes is the number of vector elements,
6678 /// not the vector size in bytes. The vector width and element type must
6679 /// match one of the standard Neon vector types.
6680 static void HandleNeonVectorTypeAttr(QualType& CurType,
6681 const AttributeList &Attr, Sema &S,
6682 VectorType::VectorKind VecKind) {
6683 // Target must have NEON
6684 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6685 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6689 // Check the attribute arguments.
6690 if (Attr.getNumArgs() != 1) {
6691 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6692 << Attr.getName() << 1;
6696 // The number of elements must be an ICE.
6697 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6698 llvm::APSInt numEltsInt(32);
6699 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6700 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6701 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6702 << Attr.getName() << AANT_ArgumentIntegerConstant
6703 << numEltsExpr->getSourceRange();
6707 // Only certain element types are supported for Neon vectors.
6708 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6709 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6714 // The total size of the vector must be 64 or 128 bits.
6715 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6716 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6717 unsigned vecSize = typeSize * numElts;
6718 if (vecSize != 64 && vecSize != 128) {
6719 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6724 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6727 /// Handle OpenCL Access Qualifier Attribute.
6728 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6730 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6731 if (!(CurType->isImageType() || CurType->isPipeType())) {
6732 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6737 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6738 QualType PointeeTy = TypedefTy->desugar();
6739 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6741 std::string PrevAccessQual;
6742 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6743 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6744 case BuiltinType::Id: \
6745 PrevAccessQual = #Access; \
6747 #include "clang/Basic/OpenCLImageTypes.def"
6749 assert(0 && "Unable to find corresponding image type.");
6752 S.Diag(TypedefTy->getDecl()->getLocStart(),
6753 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6754 } else if (CurType->isPipeType()) {
6755 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6756 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6757 CurType = S.Context.getWritePipeType(ElemType);
6762 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6763 TypeAttrLocation TAL, AttributeList *attrs) {
6764 // Scan through and apply attributes to this type where it makes sense. Some
6765 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6766 // type, but others can be present in the type specifiers even though they
6767 // apply to the decl. Here we apply type attributes and ignore the rest.
6769 bool hasOpenCLAddressSpace = false;
6771 AttributeList &attr = *attrs;
6772 attrs = attr.getNext(); // reset to the next here due to early loop continue
6775 // Skip attributes that were marked to be invalid.
6776 if (attr.isInvalid())
6779 if (attr.isCXX11Attribute()) {
6780 // [[gnu::...]] attributes are treated as declaration attributes, so may
6781 // not appertain to a DeclaratorChunk, even if we handle them as type
6783 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6784 if (TAL == TAL_DeclChunk) {
6785 state.getSema().Diag(attr.getLoc(),
6786 diag::warn_cxx11_gnu_attribute_on_type)
6790 } else if (TAL != TAL_DeclChunk) {
6791 // Otherwise, only consider type processing for a C++11 attribute if
6792 // it's actually been applied to a type.
6797 // If this is an attribute we can handle, do so now,
6798 // otherwise, add it to the FnAttrs list for rechaining.
6799 switch (attr.getKind()) {
6801 // A C++11 attribute on a declarator chunk must appertain to a type.
6802 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6803 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6805 attr.setUsedAsTypeAttr();
6809 case AttributeList::UnknownAttribute:
6810 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6811 state.getSema().Diag(attr.getLoc(),
6812 diag::warn_unknown_attribute_ignored)
6816 case AttributeList::IgnoredAttribute:
6819 case AttributeList::AT_MayAlias:
6820 // FIXME: This attribute needs to actually be handled, but if we ignore
6821 // it it breaks large amounts of Linux software.
6822 attr.setUsedAsTypeAttr();
6824 case AttributeList::AT_OpenCLPrivateAddressSpace:
6825 case AttributeList::AT_OpenCLGlobalAddressSpace:
6826 case AttributeList::AT_OpenCLLocalAddressSpace:
6827 case AttributeList::AT_OpenCLConstantAddressSpace:
6828 case AttributeList::AT_OpenCLGenericAddressSpace:
6829 case AttributeList::AT_AddressSpace:
6830 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6831 attr.setUsedAsTypeAttr();
6832 hasOpenCLAddressSpace = true;
6834 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6835 if (!handleObjCPointerTypeAttr(state, attr, type))
6836 distributeObjCPointerTypeAttr(state, attr, type);
6837 attr.setUsedAsTypeAttr();
6839 case AttributeList::AT_VectorSize:
6840 HandleVectorSizeAttr(type, attr, state.getSema());
6841 attr.setUsedAsTypeAttr();
6843 case AttributeList::AT_ExtVectorType:
6844 HandleExtVectorTypeAttr(type, attr, state.getSema());
6845 attr.setUsedAsTypeAttr();
6847 case AttributeList::AT_NeonVectorType:
6848 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6849 VectorType::NeonVector);
6850 attr.setUsedAsTypeAttr();
6852 case AttributeList::AT_NeonPolyVectorType:
6853 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6854 VectorType::NeonPolyVector);
6855 attr.setUsedAsTypeAttr();
6857 case AttributeList::AT_OpenCLAccess:
6858 HandleOpenCLAccessAttr(type, attr, state.getSema());
6859 attr.setUsedAsTypeAttr();
6862 MS_TYPE_ATTRS_CASELIST:
6863 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6864 attr.setUsedAsTypeAttr();
6868 NULLABILITY_TYPE_ATTRS_CASELIST:
6869 // Either add nullability here or try to distribute it. We
6870 // don't want to distribute the nullability specifier past any
6871 // dependent type, because that complicates the user model.
6872 if (type->canHaveNullability() || type->isDependentType() ||
6873 type->isArrayType() ||
6874 !distributeNullabilityTypeAttr(state, type, attr)) {
6876 if (TAL == TAL_DeclChunk)
6877 endIndex = state.getCurrentChunkIndex();
6879 endIndex = state.getDeclarator().getNumTypeObjects();
6880 bool allowOnArrayType =
6881 state.getDeclarator().isPrototypeContext() &&
6882 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
6883 if (state.getSema().checkNullabilityTypeSpecifier(
6885 mapNullabilityAttrKind(attr.getKind()),
6887 attr.isContextSensitiveKeywordAttribute(),
6888 allowOnArrayType)) {
6892 attr.setUsedAsTypeAttr();
6896 case AttributeList::AT_ObjCKindOf:
6897 // '__kindof' must be part of the decl-specifiers.
6904 state.getSema().Diag(attr.getLoc(),
6905 diag::err_objc_kindof_wrong_position)
6906 << FixItHint::CreateRemoval(attr.getLoc())
6907 << FixItHint::CreateInsertion(
6908 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6912 // Apply it regardless.
6913 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6915 attr.setUsedAsTypeAttr();
6918 case AttributeList::AT_NSReturnsRetained:
6919 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6921 // fallthrough into the function attrs
6923 FUNCTION_TYPE_ATTRS_CASELIST:
6924 attr.setUsedAsTypeAttr();
6926 // Never process function type attributes as part of the
6927 // declaration-specifiers.
6928 if (TAL == TAL_DeclSpec)
6929 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6931 // Otherwise, handle the possible delays.
6932 else if (!handleFunctionTypeAttr(state, attr, type))
6933 distributeFunctionTypeAttr(state, attr, type);
6938 // If address space is not set, OpenCL 2.0 defines non private default
6939 // address spaces for some cases:
6940 // OpenCL 2.0, section 6.5:
6941 // The address space for a variable at program scope or a static variable
6942 // inside a function can either be __global or __constant, but defaults to
6943 // __global if not specified.
6945 // Pointers that are declared without pointing to a named address space point
6946 // to the generic address space.
6947 if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6948 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6949 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6950 Declarator &D = state.getDeclarator();
6951 if (state.getCurrentChunkIndex() > 0 &&
6952 (D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6953 DeclaratorChunk::Pointer ||
6954 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6955 DeclaratorChunk::BlockPointer)) {
6956 type = state.getSema().Context.getAddrSpaceQualType(
6957 type, LangAS::opencl_generic);
6958 } else if (state.getCurrentChunkIndex() == 0 &&
6959 D.getContext() == Declarator::FileContext &&
6960 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6961 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6962 !type->isSamplerT())
6963 type = state.getSema().Context.getAddrSpaceQualType(
6964 type, LangAS::opencl_global);
6965 else if (state.getCurrentChunkIndex() == 0 &&
6966 D.getContext() == Declarator::BlockContext &&
6967 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6968 type = state.getSema().Context.getAddrSpaceQualType(
6969 type, LangAS::opencl_global);
6973 void Sema::completeExprArrayBound(Expr *E) {
6974 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6975 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6976 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6977 SourceLocation PointOfInstantiation = E->getExprLoc();
6979 if (MemberSpecializationInfo *MSInfo =
6980 Var->getMemberSpecializationInfo()) {
6981 // If we don't already have a point of instantiation, this is it.
6982 if (MSInfo->getPointOfInstantiation().isInvalid()) {
6983 MSInfo->setPointOfInstantiation(PointOfInstantiation);
6985 // This is a modification of an existing AST node. Notify
6987 if (ASTMutationListener *L = getASTMutationListener())
6988 L->StaticDataMemberInstantiated(Var);
6991 VarTemplateSpecializationDecl *VarSpec =
6992 cast<VarTemplateSpecializationDecl>(Var);
6993 if (VarSpec->getPointOfInstantiation().isInvalid())
6994 VarSpec->setPointOfInstantiation(PointOfInstantiation);
6997 InstantiateVariableDefinition(PointOfInstantiation, Var);
6999 // Update the type to the newly instantiated definition's type both
7000 // here and within the expression.
7001 if (VarDecl *Def = Var->getDefinition()) {
7003 QualType T = Def->getType();
7005 // FIXME: Update the type on all intervening expressions.
7009 // We still go on to try to complete the type independently, as it
7010 // may also require instantiations or diagnostics if it remains
7017 /// \brief Ensure that the type of the given expression is complete.
7019 /// This routine checks whether the expression \p E has a complete type. If the
7020 /// expression refers to an instantiable construct, that instantiation is
7021 /// performed as needed to complete its type. Furthermore
7022 /// Sema::RequireCompleteType is called for the expression's type (or in the
7023 /// case of a reference type, the referred-to type).
7025 /// \param E The expression whose type is required to be complete.
7026 /// \param Diagnoser The object that will emit a diagnostic if the type is
7029 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
7031 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
7032 QualType T = E->getType();
7034 // Incomplete array types may be completed by the initializer attached to
7035 // their definitions. For static data members of class templates and for
7036 // variable templates, we need to instantiate the definition to get this
7037 // initializer and complete the type.
7038 if (T->isIncompleteArrayType()) {
7039 completeExprArrayBound(E);
7043 // FIXME: Are there other cases which require instantiating something other
7044 // than the type to complete the type of an expression?
7046 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
7049 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
7050 BoundTypeDiagnoser<> Diagnoser(DiagID);
7051 return RequireCompleteExprType(E, Diagnoser);
7054 /// @brief Ensure that the type T is a complete type.
7056 /// This routine checks whether the type @p T is complete in any
7057 /// context where a complete type is required. If @p T is a complete
7058 /// type, returns false. If @p T is a class template specialization,
7059 /// this routine then attempts to perform class template
7060 /// instantiation. If instantiation fails, or if @p T is incomplete
7061 /// and cannot be completed, issues the diagnostic @p diag (giving it
7062 /// the type @p T) and returns true.
7064 /// @param Loc The location in the source that the incomplete type
7065 /// diagnostic should refer to.
7067 /// @param T The type that this routine is examining for completeness.
7069 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7070 /// @c false otherwise.
7071 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7072 TypeDiagnoser &Diagnoser) {
7073 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7075 if (const TagType *Tag = T->getAs<TagType>()) {
7076 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7077 Tag->getDecl()->setCompleteDefinitionRequired();
7078 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7084 /// \brief Determine whether there is any declaration of \p D that was ever a
7085 /// definition (perhaps before module merging) and is currently visible.
7086 /// \param D The definition of the entity.
7087 /// \param Suggested Filled in with the declaration that should be made visible
7088 /// in order to provide a definition of this entity.
7089 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7090 /// not defined. This only matters for enums with a fixed underlying
7091 /// type, since in all other cases, a type is complete if and only if it
7093 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7094 bool OnlyNeedComplete) {
7095 // Easy case: if we don't have modules, all declarations are visible.
7096 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7099 // If this definition was instantiated from a template, map back to the
7100 // pattern from which it was instantiated.
7101 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7102 // We're in the middle of defining it; this definition should be treated
7105 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7106 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7108 D = RD->getDefinition();
7109 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7110 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7112 if (OnlyNeedComplete && ED->isFixed()) {
7113 // If the enum has a fixed underlying type, and we're only looking for a
7114 // complete type (not a definition), any visible declaration of it will
7116 *Suggested = nullptr;
7117 for (auto *Redecl : ED->redecls()) {
7118 if (isVisible(Redecl))
7120 if (Redecl->isThisDeclarationADefinition() ||
7121 (Redecl->isCanonicalDecl() && !*Suggested))
7122 *Suggested = Redecl;
7126 D = ED->getDefinition();
7127 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7128 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7130 D = FD->getDefinition();
7131 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7132 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7134 D = VD->getDefinition();
7136 assert(D && "missing definition for pattern of instantiated definition");
7142 // The external source may have additional definitions of this entity that are
7143 // visible, so complete the redeclaration chain now and ask again.
7144 if (auto *Source = Context.getExternalSource()) {
7145 Source->CompleteRedeclChain(D);
7146 return isVisible(D);
7152 /// Locks in the inheritance model for the given class and all of its bases.
7153 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7154 RD = RD->getMostRecentDecl();
7155 if (!RD->hasAttr<MSInheritanceAttr>()) {
7156 MSInheritanceAttr::Spelling IM;
7158 switch (S.MSPointerToMemberRepresentationMethod) {
7159 case LangOptions::PPTMK_BestCase:
7160 IM = RD->calculateInheritanceModel();
7162 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7163 IM = MSInheritanceAttr::Keyword_single_inheritance;
7165 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7166 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7168 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7169 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7173 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7174 S.getASTContext(), IM,
7175 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7176 LangOptions::PPTMK_BestCase,
7177 S.ImplicitMSInheritanceAttrLoc.isValid()
7178 ? S.ImplicitMSInheritanceAttrLoc
7179 : RD->getSourceRange()));
7180 S.Consumer.AssignInheritanceModel(RD);
7184 /// \brief The implementation of RequireCompleteType
7185 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7186 TypeDiagnoser *Diagnoser) {
7187 // FIXME: Add this assertion to make sure we always get instantiation points.
7188 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7189 // FIXME: Add this assertion to help us flush out problems with
7190 // checking for dependent types and type-dependent expressions.
7192 // assert(!T->isDependentType() &&
7193 // "Can't ask whether a dependent type is complete");
7195 // We lock in the inheritance model once somebody has asked us to ensure
7196 // that a pointer-to-member type is complete.
7197 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7198 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7199 if (!MPTy->getClass()->isDependentType()) {
7200 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7201 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7206 NamedDecl *Def = nullptr;
7207 bool Incomplete = T->isIncompleteType(&Def);
7209 // Check that any necessary explicit specializations are visible. For an
7210 // enum, we just need the declaration, so don't check this.
7211 if (Def && !isa<EnumDecl>(Def))
7212 checkSpecializationVisibility(Loc, Def);
7214 // If we have a complete type, we're done.
7216 // If we know about the definition but it is not visible, complain.
7217 NamedDecl *SuggestedDef = nullptr;
7219 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7220 // If the user is going to see an error here, recover by making the
7221 // definition visible.
7222 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7224 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7225 /*Recover*/TreatAsComplete);
7226 return !TreatAsComplete;
7232 const TagType *Tag = T->getAs<TagType>();
7233 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7235 // If there's an unimported definition of this type in a module (for
7236 // instance, because we forward declared it, then imported the definition),
7237 // import that definition now.
7239 // FIXME: What about other cases where an import extends a redeclaration
7240 // chain for a declaration that can be accessed through a mechanism other
7241 // than name lookup (eg, referenced in a template, or a variable whose type
7242 // could be completed by the module)?
7244 // FIXME: Should we map through to the base array element type before
7245 // checking for a tag type?
7248 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7250 // Avoid diagnosing invalid decls as incomplete.
7251 if (D->isInvalidDecl())
7254 // Give the external AST source a chance to complete the type.
7255 if (auto *Source = Context.getExternalSource()) {
7257 Source->CompleteType(Tag->getDecl());
7259 Source->CompleteType(IFace->getDecl());
7261 // If the external source completed the type, go through the motions
7262 // again to ensure we're allowed to use the completed type.
7263 if (!T->isIncompleteType())
7264 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7268 // If we have a class template specialization or a class member of a
7269 // class template specialization, or an array with known size of such,
7270 // try to instantiate it.
7271 QualType MaybeTemplate = T;
7272 while (const ConstantArrayType *Array
7273 = Context.getAsConstantArrayType(MaybeTemplate))
7274 MaybeTemplate = Array->getElementType();
7275 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7276 bool Instantiated = false;
7277 bool Diagnosed = false;
7278 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7279 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7280 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7281 Diagnosed = InstantiateClassTemplateSpecialization(
7282 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7283 /*Complain=*/Diagnoser);
7284 Instantiated = true;
7286 } else if (CXXRecordDecl *Rec
7287 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7288 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7289 if (!Rec->isBeingDefined() && Pattern) {
7290 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7291 assert(MSI && "Missing member specialization information?");
7292 // This record was instantiated from a class within a template.
7293 if (MSI->getTemplateSpecializationKind() !=
7294 TSK_ExplicitSpecialization) {
7295 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7296 getTemplateInstantiationArgs(Rec),
7297 TSK_ImplicitInstantiation,
7298 /*Complain=*/Diagnoser);
7299 Instantiated = true;
7305 // Instantiate* might have already complained that the template is not
7306 // defined, if we asked it to.
7307 if (Diagnoser && Diagnosed)
7309 // If we instantiated a definition, check that it's usable, even if
7310 // instantiation produced an error, so that repeated calls to this
7311 // function give consistent answers.
7312 if (!T->isIncompleteType())
7313 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7317 // FIXME: If we didn't instantiate a definition because of an explicit
7318 // specialization declaration, check that it's visible.
7323 Diagnoser->diagnose(*this, Loc, T);
7325 // If the type was a forward declaration of a class/struct/union
7326 // type, produce a note.
7327 if (Tag && !Tag->getDecl()->isInvalidDecl())
7328 Diag(Tag->getDecl()->getLocation(),
7329 Tag->isBeingDefined() ? diag::note_type_being_defined
7330 : diag::note_forward_declaration)
7331 << QualType(Tag, 0);
7333 // If the Objective-C class was a forward declaration, produce a note.
7334 if (IFace && !IFace->getDecl()->isInvalidDecl())
7335 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7337 // If we have external information that we can use to suggest a fix,
7340 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7345 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7347 BoundTypeDiagnoser<> Diagnoser(DiagID);
7348 return RequireCompleteType(Loc, T, Diagnoser);
7351 /// \brief Get diagnostic %select index for tag kind for
7352 /// literal type diagnostic message.
7353 /// WARNING: Indexes apply to particular diagnostics only!
7355 /// \returns diagnostic %select index.
7356 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7358 case TTK_Struct: return 0;
7359 case TTK_Interface: return 1;
7360 case TTK_Class: return 2;
7361 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7365 /// @brief Ensure that the type T is a literal type.
7367 /// This routine checks whether the type @p T is a literal type. If @p T is an
7368 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7369 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7370 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7371 /// it the type @p T), along with notes explaining why the type is not a
7372 /// literal type, and returns true.
7374 /// @param Loc The location in the source that the non-literal type
7375 /// diagnostic should refer to.
7377 /// @param T The type that this routine is examining for literalness.
7379 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7381 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7382 /// @c false otherwise.
7383 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7384 TypeDiagnoser &Diagnoser) {
7385 assert(!T->isDependentType() && "type should not be dependent");
7387 QualType ElemType = Context.getBaseElementType(T);
7388 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7389 T->isLiteralType(Context))
7392 Diagnoser.diagnose(*this, Loc, T);
7394 if (T->isVariableArrayType())
7397 const RecordType *RT = ElemType->getAs<RecordType>();
7401 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7403 // A partially-defined class type can't be a literal type, because a literal
7404 // class type must have a trivial destructor (which can't be checked until
7405 // the class definition is complete).
7406 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7409 // If the class has virtual base classes, then it's not an aggregate, and
7410 // cannot have any constexpr constructors or a trivial default constructor,
7411 // so is non-literal. This is better to diagnose than the resulting absence
7412 // of constexpr constructors.
7413 if (RD->getNumVBases()) {
7414 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7415 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7416 for (const auto &I : RD->vbases())
7417 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7418 << I.getSourceRange();
7419 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7420 !RD->hasTrivialDefaultConstructor()) {
7421 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7422 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7423 for (const auto &I : RD->bases()) {
7424 if (!I.getType()->isLiteralType(Context)) {
7425 Diag(I.getLocStart(),
7426 diag::note_non_literal_base_class)
7427 << RD << I.getType() << I.getSourceRange();
7431 for (const auto *I : RD->fields()) {
7432 if (!I->getType()->isLiteralType(Context) ||
7433 I->getType().isVolatileQualified()) {
7434 Diag(I->getLocation(), diag::note_non_literal_field)
7435 << RD << I << I->getType()
7436 << I->getType().isVolatileQualified();
7440 } else if (!RD->hasTrivialDestructor()) {
7441 // All fields and bases are of literal types, so have trivial destructors.
7442 // If this class's destructor is non-trivial it must be user-declared.
7443 CXXDestructorDecl *Dtor = RD->getDestructor();
7444 assert(Dtor && "class has literal fields and bases but no dtor?");
7448 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7449 diag::note_non_literal_user_provided_dtor :
7450 diag::note_non_literal_nontrivial_dtor) << RD;
7451 if (!Dtor->isUserProvided())
7452 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7458 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7459 BoundTypeDiagnoser<> Diagnoser(DiagID);
7460 return RequireLiteralType(Loc, T, Diagnoser);
7463 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7464 /// and qualified by the nested-name-specifier contained in SS.
7465 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7466 const CXXScopeSpec &SS, QualType T) {
7469 NestedNameSpecifier *NNS;
7471 NNS = SS.getScopeRep();
7473 if (Keyword == ETK_None)
7477 return Context.getElaboratedType(Keyword, NNS, T);
7480 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7481 ExprResult ER = CheckPlaceholderExpr(E);
7482 if (ER.isInvalid()) return QualType();
7485 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7486 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7488 if (!E->isTypeDependent()) {
7489 QualType T = E->getType();
7490 if (const TagType *TT = T->getAs<TagType>())
7491 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7493 return Context.getTypeOfExprType(E);
7496 /// getDecltypeForExpr - Given an expr, will return the decltype for
7497 /// that expression, according to the rules in C++11
7498 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7499 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7500 if (E->isTypeDependent())
7501 return S.Context.DependentTy;
7503 // C++11 [dcl.type.simple]p4:
7504 // The type denoted by decltype(e) is defined as follows:
7506 // - if e is an unparenthesized id-expression or an unparenthesized class
7507 // member access (5.2.5), decltype(e) is the type of the entity named
7508 // by e. If there is no such entity, or if e names a set of overloaded
7509 // functions, the program is ill-formed;
7511 // We apply the same rules for Objective-C ivar and property references.
7512 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7513 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7514 return VD->getType();
7515 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7516 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7517 return FD->getType();
7518 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7519 return IR->getDecl()->getType();
7520 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7521 if (PR->isExplicitProperty())
7522 return PR->getExplicitProperty()->getType();
7523 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7524 return PE->getType();
7527 // C++11 [expr.lambda.prim]p18:
7528 // Every occurrence of decltype((x)) where x is a possibly
7529 // parenthesized id-expression that names an entity of automatic
7530 // storage duration is treated as if x were transformed into an
7531 // access to a corresponding data member of the closure type that
7532 // would have been declared if x were an odr-use of the denoted
7534 using namespace sema;
7535 if (S.getCurLambda()) {
7536 if (isa<ParenExpr>(E)) {
7537 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7538 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7539 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7541 return S.Context.getLValueReferenceType(T);
7548 // C++11 [dcl.type.simple]p4:
7550 QualType T = E->getType();
7551 switch (E->getValueKind()) {
7552 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7554 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7555 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7557 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7558 // - otherwise, decltype(e) is the type of e.
7559 case VK_RValue: break;
7565 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7566 bool AsUnevaluated) {
7567 ExprResult ER = CheckPlaceholderExpr(E);
7568 if (ER.isInvalid()) return QualType();
7571 if (AsUnevaluated && CodeSynthesisContexts.empty() &&
7572 E->HasSideEffects(Context, false)) {
7573 // The expression operand for decltype is in an unevaluated expression
7574 // context, so side effects could result in unintended consequences.
7575 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7578 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7581 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7582 UnaryTransformType::UTTKind UKind,
7583 SourceLocation Loc) {
7585 case UnaryTransformType::EnumUnderlyingType:
7586 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7587 Diag(Loc, diag::err_only_enums_have_underlying_types);
7590 QualType Underlying = BaseType;
7591 if (!BaseType->isDependentType()) {
7592 // The enum could be incomplete if we're parsing its definition or
7593 // recovering from an error.
7594 NamedDecl *FwdDecl = nullptr;
7595 if (BaseType->isIncompleteType(&FwdDecl)) {
7596 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7597 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7601 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7602 assert(ED && "EnumType has no EnumDecl");
7604 DiagnoseUseOfDecl(ED, Loc);
7606 Underlying = ED->getIntegerType();
7607 assert(!Underlying.isNull());
7609 return Context.getUnaryTransformType(BaseType, Underlying,
7610 UnaryTransformType::EnumUnderlyingType);
7613 llvm_unreachable("unknown unary transform type");
7616 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7617 if (!T->isDependentType()) {
7618 // FIXME: It isn't entirely clear whether incomplete atomic types
7619 // are allowed or not; for simplicity, ban them for the moment.
7620 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7623 int DisallowedKind = -1;
7624 if (T->isArrayType())
7626 else if (T->isFunctionType())
7628 else if (T->isReferenceType())
7630 else if (T->isAtomicType())
7632 else if (T.hasQualifiers())
7634 else if (!T.isTriviallyCopyableType(Context))
7635 // Some other non-trivially-copyable type (probably a C++ class)
7638 if (DisallowedKind != -1) {
7639 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7643 // FIXME: Do we need any handling for ARC here?
7646 // Build the pointer type.
7647 return Context.getAtomicType(T);