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.ActiveTemplateInstantiations.empty()) {
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 // TypeQuals handled by caller.
1506 // If auto is mentioned in a lambda parameter context, convert it to a
1507 // template parameter type immediately, with the appropriate depth and
1508 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1509 // being analyzed (which tracks the invented type template parameter).
1510 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1511 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1512 assert(LSI && "No LambdaScopeInfo on the stack!");
1513 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1514 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1515 const bool IsParameterPack = declarator.hasEllipsis();
1517 // Turns out we must create the TemplateTypeParmDecl here to
1518 // retrieve the corresponding template parameter type.
1519 TemplateTypeParmDecl *CorrespondingTemplateParam =
1520 TemplateTypeParmDecl::Create(Context,
1521 // Temporarily add to the TranslationUnit DeclContext. When the
1522 // associated TemplateParameterList is attached to a template
1523 // declaration (such as FunctionTemplateDecl), the DeclContext
1524 // for each template parameter gets updated appropriately via
1525 // a call to AdoptTemplateParameterList.
1526 Context.getTranslationUnitDecl(),
1527 /*KeyLoc*/ SourceLocation(),
1528 /*NameLoc*/ declarator.getLocStart(),
1529 TemplateParameterDepth,
1530 AutoParameterPosition, // our template param index
1531 /* Identifier*/ nullptr, false, IsParameterPack);
1532 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1533 // Replace the 'auto' in the function parameter with this invented
1534 // template type parameter.
1535 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1537 Result = Context.getAutoType(QualType(), AutoTypeKeyword::Auto, false);
1541 case DeclSpec::TST_auto_type:
1542 Result = Context.getAutoType(QualType(), AutoTypeKeyword::GNUAutoType, false);
1545 case DeclSpec::TST_decltype_auto:
1546 Result = Context.getAutoType(QualType(), AutoTypeKeyword::DecltypeAuto,
1547 /*IsDependent*/ false);
1550 case DeclSpec::TST_unknown_anytype:
1551 Result = Context.UnknownAnyTy;
1554 case DeclSpec::TST_atomic:
1555 Result = S.GetTypeFromParser(DS.getRepAsType());
1556 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1557 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1558 if (Result.isNull()) {
1559 Result = Context.IntTy;
1560 declarator.setInvalidType(true);
1564 #define GENERIC_IMAGE_TYPE(ImgType, Id) \
1565 case DeclSpec::TST_##ImgType##_t: \
1566 switch (getImageAccess(DS.getAttributes().getList())) { \
1567 case OpenCLAccessAttr::Keyword_write_only: \
1568 Result = Context.Id##WOTy; break; \
1569 case OpenCLAccessAttr::Keyword_read_write: \
1570 Result = Context.Id##RWTy; break; \
1571 case OpenCLAccessAttr::Keyword_read_only: \
1572 Result = Context.Id##ROTy; break; \
1575 #include "clang/Basic/OpenCLImageTypes.def"
1577 case DeclSpec::TST_error:
1578 Result = Context.IntTy;
1579 declarator.setInvalidType(true);
1583 if (S.getLangOpts().OpenCL &&
1584 S.checkOpenCLDisabledTypeDeclSpec(DS, Result))
1585 declarator.setInvalidType(true);
1587 // Handle complex types.
1588 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1589 if (S.getLangOpts().Freestanding)
1590 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1591 Result = Context.getComplexType(Result);
1592 } else if (DS.isTypeAltiVecVector()) {
1593 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1594 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1595 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1596 if (DS.isTypeAltiVecPixel())
1597 VecKind = VectorType::AltiVecPixel;
1598 else if (DS.isTypeAltiVecBool())
1599 VecKind = VectorType::AltiVecBool;
1600 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1603 // FIXME: Imaginary.
1604 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1605 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1607 // Before we process any type attributes, synthesize a block literal
1608 // function declarator if necessary.
1609 if (declarator.getContext() == Declarator::BlockLiteralContext)
1610 maybeSynthesizeBlockSignature(state, Result);
1612 // Apply any type attributes from the decl spec. This may cause the
1613 // list of type attributes to be temporarily saved while the type
1614 // attributes are pushed around.
1615 // pipe attributes will be handled later ( at GetFullTypeForDeclarator )
1616 if (!DS.isTypeSpecPipe())
1617 processTypeAttrs(state, Result, TAL_DeclSpec, DS.getAttributes().getList());
1619 // Apply const/volatile/restrict qualifiers to T.
1620 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1621 // Warn about CV qualifiers on function types.
1623 // If the specification of a function type includes any type qualifiers,
1624 // the behavior is undefined.
1625 // C++11 [dcl.fct]p7:
1626 // The effect of a cv-qualifier-seq in a function declarator is not the
1627 // same as adding cv-qualification on top of the function type. In the
1628 // latter case, the cv-qualifiers are ignored.
1629 if (TypeQuals && Result->isFunctionType()) {
1630 diagnoseAndRemoveTypeQualifiers(
1631 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1632 S.getLangOpts().CPlusPlus
1633 ? diag::warn_typecheck_function_qualifiers_ignored
1634 : diag::warn_typecheck_function_qualifiers_unspecified);
1635 // No diagnostic for 'restrict' or '_Atomic' applied to a
1636 // function type; we'll diagnose those later, in BuildQualifiedType.
1639 // C++11 [dcl.ref]p1:
1640 // Cv-qualified references are ill-formed except when the
1641 // cv-qualifiers are introduced through the use of a typedef-name
1642 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1644 // There don't appear to be any other contexts in which a cv-qualified
1645 // reference type could be formed, so the 'ill-formed' clause here appears
1647 if (TypeQuals && Result->isReferenceType()) {
1648 diagnoseAndRemoveTypeQualifiers(
1649 S, DS, TypeQuals, Result,
1650 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1651 diag::warn_typecheck_reference_qualifiers);
1654 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1655 // than once in the same specifier-list or qualifier-list, either directly
1656 // or via one or more typedefs."
1657 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1658 && TypeQuals & Result.getCVRQualifiers()) {
1659 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1660 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1664 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1665 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1669 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1670 // produce a warning in this case.
1673 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1675 // If adding qualifiers fails, just use the unqualified type.
1676 if (Qualified.isNull())
1677 declarator.setInvalidType(true);
1682 assert(!Result.isNull() && "This function should not return a null type");
1686 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1688 return Entity.getAsString();
1693 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1694 Qualifiers Qs, const DeclSpec *DS) {
1698 // Ignore any attempt to form a cv-qualified reference.
1699 if (T->isReferenceType()) {
1701 Qs.removeVolatile();
1704 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1705 // object or incomplete types shall not be restrict-qualified."
1706 if (Qs.hasRestrict()) {
1707 unsigned DiagID = 0;
1710 if (T->isAnyPointerType() || T->isReferenceType() ||
1711 T->isMemberPointerType()) {
1713 if (T->isObjCObjectPointerType())
1715 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1716 EltTy = PTy->getPointeeType();
1718 EltTy = T->getPointeeType();
1720 // If we have a pointer or reference, the pointee must have an object
1722 if (!EltTy->isIncompleteOrObjectType()) {
1723 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1726 } else if (!T->isDependentType()) {
1727 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1732 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1733 Qs.removeRestrict();
1737 return Context.getQualifiedType(T, Qs);
1740 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1741 unsigned CVRAU, const DeclSpec *DS) {
1745 // Ignore any attempt to form a cv-qualified reference.
1746 if (T->isReferenceType())
1748 ~(DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic);
1750 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic and
1752 unsigned CVR = CVRAU & ~(DeclSpec::TQ_atomic | DeclSpec::TQ_unaligned);
1755 // If the same qualifier appears more than once in the same
1756 // specifier-qualifier-list, either directly or via one or more typedefs,
1757 // the behavior is the same as if it appeared only once.
1759 // It's not specified what happens when the _Atomic qualifier is applied to
1760 // a type specified with the _Atomic specifier, but we assume that this
1761 // should be treated as if the _Atomic qualifier appeared multiple times.
1762 if (CVRAU & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1764 // If other qualifiers appear along with the _Atomic qualifier in a
1765 // specifier-qualifier-list, the resulting type is the so-qualified
1768 // Don't need to worry about array types here, since _Atomic can't be
1769 // applied to such types.
1770 SplitQualType Split = T.getSplitUnqualifiedType();
1771 T = BuildAtomicType(QualType(Split.Ty, 0),
1772 DS ? DS->getAtomicSpecLoc() : Loc);
1775 Split.Quals.addCVRQualifiers(CVR);
1776 return BuildQualifiedType(T, Loc, Split.Quals);
1779 Qualifiers Q = Qualifiers::fromCVRMask(CVR);
1780 Q.setUnaligned(CVRAU & DeclSpec::TQ_unaligned);
1781 return BuildQualifiedType(T, Loc, Q, DS);
1784 /// \brief Build a paren type including \p T.
1785 QualType Sema::BuildParenType(QualType T) {
1786 return Context.getParenType(T);
1789 /// Given that we're building a pointer or reference to the given
1790 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1793 // Bail out if retention is unrequired or already specified.
1794 if (!type->isObjCLifetimeType() ||
1795 type.getObjCLifetime() != Qualifiers::OCL_None)
1798 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1800 // If the object type is const-qualified, we can safely use
1801 // __unsafe_unretained. This is safe (because there are no read
1802 // barriers), and it'll be safe to coerce anything but __weak* to
1803 // the resulting type.
1804 if (type.isConstQualified()) {
1805 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1807 // Otherwise, check whether the static type does not require
1808 // retaining. This currently only triggers for Class (possibly
1809 // protocol-qualifed, and arrays thereof).
1810 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1811 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1813 // If we are in an unevaluated context, like sizeof, skip adding a
1815 } else if (S.isUnevaluatedContext()) {
1818 // If that failed, give an error and recover using __strong. __strong
1819 // is the option most likely to prevent spurious second-order diagnostics,
1820 // like when binding a reference to a field.
1822 // These types can show up in private ivars in system headers, so
1823 // we need this to not be an error in those cases. Instead we
1825 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1826 S.DelayedDiagnostics.add(
1827 sema::DelayedDiagnostic::makeForbiddenType(loc,
1828 diag::err_arc_indirect_no_ownership, type, isReference));
1830 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1832 implicitLifetime = Qualifiers::OCL_Strong;
1834 assert(implicitLifetime && "didn't infer any lifetime!");
1837 qs.addObjCLifetime(implicitLifetime);
1838 return S.Context.getQualifiedType(type, qs);
1841 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1843 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1845 switch (FnTy->getRefQualifier()) {
1866 /// Kinds of declarator that cannot contain a qualified function type.
1868 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1869 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1870 /// at the topmost level of a type.
1872 /// Parens and member pointers are permitted. We don't diagnose array and
1873 /// function declarators, because they don't allow function types at all.
1875 /// The values of this enum are used in diagnostics.
1876 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1877 } // end anonymous namespace
1879 /// Check whether the type T is a qualified function type, and if it is,
1880 /// diagnose that it cannot be contained within the given kind of declarator.
1881 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1882 QualifiedFunctionKind QFK) {
1883 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1884 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1885 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1888 S.Diag(Loc, diag::err_compound_qualified_function_type)
1889 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1890 << getFunctionQualifiersAsString(FPT);
1894 /// \brief Build a pointer type.
1896 /// \param T The type to which we'll be building a pointer.
1898 /// \param Loc The location of the entity whose type involves this
1899 /// pointer type or, if there is no such entity, the location of the
1900 /// type that will have pointer type.
1902 /// \param Entity The name of the entity that involves the pointer
1905 /// \returns A suitable pointer type, if there are no
1906 /// errors. Otherwise, returns a NULL type.
1907 QualType Sema::BuildPointerType(QualType T,
1908 SourceLocation Loc, DeclarationName Entity) {
1909 if (T->isReferenceType()) {
1910 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1911 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1912 << getPrintableNameForEntity(Entity) << T;
1916 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1919 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1921 // In ARC, it is forbidden to build pointers to unqualified pointers.
1922 if (getLangOpts().ObjCAutoRefCount)
1923 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1925 // Build the pointer type.
1926 return Context.getPointerType(T);
1929 /// \brief Build a reference type.
1931 /// \param T The type to which we'll be building a reference.
1933 /// \param Loc The location of the entity whose type involves this
1934 /// reference type or, if there is no such entity, the location of the
1935 /// type that will have reference type.
1937 /// \param Entity The name of the entity that involves the reference
1940 /// \returns A suitable reference type, if there are no
1941 /// errors. Otherwise, returns a NULL type.
1942 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1944 DeclarationName Entity) {
1945 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1946 "Unresolved overloaded function type");
1948 // C++0x [dcl.ref]p6:
1949 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1950 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1951 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1952 // the type "lvalue reference to T", while an attempt to create the type
1953 // "rvalue reference to cv TR" creates the type TR.
1954 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1956 // C++ [dcl.ref]p4: There shall be no references to references.
1958 // According to C++ DR 106, references to references are only
1959 // diagnosed when they are written directly (e.g., "int & &"),
1960 // but not when they happen via a typedef:
1962 // typedef int& intref;
1963 // typedef intref& intref2;
1965 // Parser::ParseDeclaratorInternal diagnoses the case where
1966 // references are written directly; here, we handle the
1967 // collapsing of references-to-references as described in C++0x.
1968 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1971 // A declarator that specifies the type "reference to cv void"
1973 if (T->isVoidType()) {
1974 Diag(Loc, diag::err_reference_to_void);
1978 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1981 // In ARC, it is forbidden to build references to unqualified pointers.
1982 if (getLangOpts().ObjCAutoRefCount)
1983 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1985 // Handle restrict on references.
1987 return Context.getLValueReferenceType(T, SpelledAsLValue);
1988 return Context.getRValueReferenceType(T);
1991 /// \brief Build a Read-only Pipe type.
1993 /// \param T The type to which we'll be building a Pipe.
1995 /// \param Loc We do not use it for now.
1997 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
1999 QualType Sema::BuildReadPipeType(QualType T, SourceLocation Loc) {
2000 return Context.getReadPipeType(T);
2003 /// \brief Build a Write-only Pipe type.
2005 /// \param T The type to which we'll be building a Pipe.
2007 /// \param Loc We do not use it for now.
2009 /// \returns A suitable pipe type, if there are no errors. Otherwise, returns a
2011 QualType Sema::BuildWritePipeType(QualType T, SourceLocation Loc) {
2012 return Context.getWritePipeType(T);
2015 /// Check whether the specified array size makes the array type a VLA. If so,
2016 /// return true, if not, return the size of the array in SizeVal.
2017 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
2018 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
2019 // (like gnu99, but not c99) accept any evaluatable value as an extension.
2020 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
2022 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
2024 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
2027 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
2028 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
2032 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
2033 S.LangOpts.GNUMode ||
2034 S.LangOpts.OpenCL).isInvalid();
2037 /// \brief Build an array type.
2039 /// \param T The type of each element in the array.
2041 /// \param ASM C99 array size modifier (e.g., '*', 'static').
2043 /// \param ArraySize Expression describing the size of the array.
2045 /// \param Brackets The range from the opening '[' to the closing ']'.
2047 /// \param Entity The name of the entity that involves the array
2050 /// \returns A suitable array type, if there are no errors. Otherwise,
2051 /// returns a NULL type.
2052 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
2053 Expr *ArraySize, unsigned Quals,
2054 SourceRange Brackets, DeclarationName Entity) {
2056 SourceLocation Loc = Brackets.getBegin();
2057 if (getLangOpts().CPlusPlus) {
2058 // C++ [dcl.array]p1:
2059 // T is called the array element type; this type shall not be a reference
2060 // type, the (possibly cv-qualified) type void, a function type or an
2061 // abstract class type.
2063 // C++ [dcl.array]p3:
2064 // When several "array of" specifications are adjacent, [...] only the
2065 // first of the constant expressions that specify the bounds of the arrays
2068 // Note: function types are handled in the common path with C.
2069 if (T->isReferenceType()) {
2070 Diag(Loc, diag::err_illegal_decl_array_of_references)
2071 << getPrintableNameForEntity(Entity) << T;
2075 if (T->isVoidType() || T->isIncompleteArrayType()) {
2076 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
2080 if (RequireNonAbstractType(Brackets.getBegin(), T,
2081 diag::err_array_of_abstract_type))
2084 // Mentioning a member pointer type for an array type causes us to lock in
2085 // an inheritance model, even if it's inside an unused typedef.
2086 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
2087 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
2088 if (!MPTy->getClass()->isDependentType())
2089 (void)isCompleteType(Loc, T);
2092 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
2093 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
2094 if (RequireCompleteType(Loc, T,
2095 diag::err_illegal_decl_array_incomplete_type))
2099 if (T->isFunctionType()) {
2100 Diag(Loc, diag::err_illegal_decl_array_of_functions)
2101 << getPrintableNameForEntity(Entity) << T;
2105 if (const RecordType *EltTy = T->getAs<RecordType>()) {
2106 // If the element type is a struct or union that contains a variadic
2107 // array, accept it as a GNU extension: C99 6.7.2.1p2.
2108 if (EltTy->getDecl()->hasFlexibleArrayMember())
2109 Diag(Loc, diag::ext_flexible_array_in_array) << T;
2110 } else if (T->isObjCObjectType()) {
2111 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
2115 // Do placeholder conversions on the array size expression.
2116 if (ArraySize && ArraySize->hasPlaceholderType()) {
2117 ExprResult Result = CheckPlaceholderExpr(ArraySize);
2118 if (Result.isInvalid()) return QualType();
2119 ArraySize = Result.get();
2122 // Do lvalue-to-rvalue conversions on the array size expression.
2123 if (ArraySize && !ArraySize->isRValue()) {
2124 ExprResult Result = DefaultLvalueConversion(ArraySize);
2125 if (Result.isInvalid())
2128 ArraySize = Result.get();
2131 // C99 6.7.5.2p1: The size expression shall have integer type.
2132 // C++11 allows contextual conversions to such types.
2133 if (!getLangOpts().CPlusPlus11 &&
2134 ArraySize && !ArraySize->isTypeDependent() &&
2135 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2136 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2137 << ArraySize->getType() << ArraySize->getSourceRange();
2141 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
2143 if (ASM == ArrayType::Star)
2144 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
2146 T = Context.getIncompleteArrayType(T, ASM, Quals);
2147 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
2148 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
2149 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
2150 !T->isConstantSizeType()) ||
2151 isArraySizeVLA(*this, ArraySize, ConstVal)) {
2152 // Even in C++11, don't allow contextual conversions in the array bound
2154 if (getLangOpts().CPlusPlus11 &&
2155 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
2156 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
2157 << ArraySize->getType() << ArraySize->getSourceRange();
2161 // C99: an array with an element type that has a non-constant-size is a VLA.
2162 // C99: an array with a non-ICE size is a VLA. We accept any expression
2163 // that we can fold to a non-zero positive value as an extension.
2164 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
2166 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
2167 // have a value greater than zero.
2168 if (ConstVal.isSigned() && ConstVal.isNegative()) {
2170 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
2171 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
2173 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
2174 << ArraySize->getSourceRange();
2177 if (ConstVal == 0) {
2178 // GCC accepts zero sized static arrays. We allow them when
2179 // we're not in a SFINAE context.
2180 Diag(ArraySize->getLocStart(),
2181 isSFINAEContext()? diag::err_typecheck_zero_array_size
2182 : diag::ext_typecheck_zero_array_size)
2183 << ArraySize->getSourceRange();
2185 if (ASM == ArrayType::Static) {
2186 Diag(ArraySize->getLocStart(),
2187 diag::warn_typecheck_zero_static_array_size)
2188 << ArraySize->getSourceRange();
2189 ASM = ArrayType::Normal;
2191 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
2192 !T->isIncompleteType() && !T->isUndeducedType()) {
2193 // Is the array too large?
2194 unsigned ActiveSizeBits
2195 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
2196 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
2197 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
2198 << ConstVal.toString(10)
2199 << ArraySize->getSourceRange();
2204 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
2207 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
2208 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
2209 Diag(Loc, diag::err_opencl_vla);
2212 // CUDA device code doesn't support VLAs.
2213 if (getLangOpts().CUDA && T->isVariableArrayType())
2214 CUDADiagIfDeviceCode(Loc, diag::err_cuda_vla) << CurrentCUDATarget();
2216 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
2217 if (!getLangOpts().C99) {
2218 if (T->isVariableArrayType()) {
2219 // Prohibit the use of VLAs during template argument deduction.
2220 if (isSFINAEContext()) {
2221 Diag(Loc, diag::err_vla_in_sfinae);
2224 // Just extwarn about VLAs.
2226 Diag(Loc, diag::ext_vla);
2227 } else if (ASM != ArrayType::Normal || Quals != 0)
2229 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
2230 : diag::ext_c99_array_usage) << ASM;
2233 if (T->isVariableArrayType()) {
2234 // Warn about VLAs for -Wvla.
2235 Diag(Loc, diag::warn_vla_used);
2238 // OpenCL v2.0 s6.12.5 - Arrays of blocks are not supported.
2239 // OpenCL v2.0 s6.16.13.1 - Arrays of pipe type are not supported.
2240 // OpenCL v2.0 s6.9.b - Arrays of image/sampler type are not supported.
2241 if (getLangOpts().OpenCL) {
2242 const QualType ArrType = Context.getBaseElementType(T);
2243 if (ArrType->isBlockPointerType() || ArrType->isPipeType() ||
2244 ArrType->isSamplerT() || ArrType->isImageType()) {
2245 Diag(Loc, diag::err_opencl_invalid_type_array) << ArrType;
2253 /// \brief Build an ext-vector type.
2255 /// Run the required checks for the extended vector type.
2256 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
2257 SourceLocation AttrLoc) {
2258 // Unlike gcc's vector_size attribute, we do not allow vectors to be defined
2259 // in conjunction with complex types (pointers, arrays, functions, etc.).
2261 // Additionally, OpenCL prohibits vectors of booleans (they're considered a
2262 // reserved data type under OpenCL v2.0 s6.1.4), we don't support selects
2263 // on bitvectors, and we have no well-defined ABI for bitvectors, so vectors
2264 // of bool aren't allowed.
2265 if ((!T->isDependentType() && !T->isIntegerType() &&
2266 !T->isRealFloatingType()) ||
2267 T->isBooleanType()) {
2268 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
2272 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
2273 llvm::APSInt vecSize(32);
2274 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
2275 Diag(AttrLoc, diag::err_attribute_argument_type)
2276 << "ext_vector_type" << AANT_ArgumentIntegerConstant
2277 << ArraySize->getSourceRange();
2281 // Unlike gcc's vector_size attribute, the size is specified as the
2282 // number of elements, not the number of bytes.
2283 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
2285 if (vectorSize == 0) {
2286 Diag(AttrLoc, diag::err_attribute_zero_size)
2287 << ArraySize->getSourceRange();
2291 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
2292 Diag(AttrLoc, diag::err_attribute_size_too_large)
2293 << ArraySize->getSourceRange();
2297 return Context.getExtVectorType(T, vectorSize);
2300 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
2303 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
2304 if (T->isArrayType() || T->isFunctionType()) {
2305 Diag(Loc, diag::err_func_returning_array_function)
2306 << T->isFunctionType() << T;
2310 // Functions cannot return half FP.
2311 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2312 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
2313 FixItHint::CreateInsertion(Loc, "*");
2317 // Methods cannot return interface types. All ObjC objects are
2318 // passed by reference.
2319 if (T->isObjCObjectType()) {
2320 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
2327 /// Check the extended parameter information. Most of the necessary
2328 /// checking should occur when applying the parameter attribute; the
2329 /// only other checks required are positional restrictions.
2330 static void checkExtParameterInfos(Sema &S, ArrayRef<QualType> paramTypes,
2331 const FunctionProtoType::ExtProtoInfo &EPI,
2332 llvm::function_ref<SourceLocation(unsigned)> getParamLoc) {
2333 assert(EPI.ExtParameterInfos && "shouldn't get here without param infos");
2335 bool hasCheckedSwiftCall = false;
2336 auto checkForSwiftCC = [&](unsigned paramIndex) {
2337 // Only do this once.
2338 if (hasCheckedSwiftCall) return;
2339 hasCheckedSwiftCall = true;
2340 if (EPI.ExtInfo.getCC() == CC_Swift) return;
2341 S.Diag(getParamLoc(paramIndex), diag::err_swift_param_attr_not_swiftcall)
2342 << getParameterABISpelling(EPI.ExtParameterInfos[paramIndex].getABI());
2345 for (size_t paramIndex = 0, numParams = paramTypes.size();
2346 paramIndex != numParams; ++paramIndex) {
2347 switch (EPI.ExtParameterInfos[paramIndex].getABI()) {
2348 // Nothing interesting to check for orindary-ABI parameters.
2349 case ParameterABI::Ordinary:
2352 // swift_indirect_result parameters must be a prefix of the function
2354 case ParameterABI::SwiftIndirectResult:
2355 checkForSwiftCC(paramIndex);
2356 if (paramIndex != 0 &&
2357 EPI.ExtParameterInfos[paramIndex - 1].getABI()
2358 != ParameterABI::SwiftIndirectResult) {
2359 S.Diag(getParamLoc(paramIndex),
2360 diag::err_swift_indirect_result_not_first);
2364 case ParameterABI::SwiftContext:
2365 checkForSwiftCC(paramIndex);
2368 // swift_error parameters must be preceded by a swift_context parameter.
2369 case ParameterABI::SwiftErrorResult:
2370 checkForSwiftCC(paramIndex);
2371 if (paramIndex == 0 ||
2372 EPI.ExtParameterInfos[paramIndex - 1].getABI() !=
2373 ParameterABI::SwiftContext) {
2374 S.Diag(getParamLoc(paramIndex),
2375 diag::err_swift_error_result_not_after_swift_context);
2379 llvm_unreachable("bad ABI kind");
2383 QualType Sema::BuildFunctionType(QualType T,
2384 MutableArrayRef<QualType> ParamTypes,
2385 SourceLocation Loc, DeclarationName Entity,
2386 const FunctionProtoType::ExtProtoInfo &EPI) {
2387 bool Invalid = false;
2389 Invalid |= CheckFunctionReturnType(T, Loc);
2391 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
2392 // FIXME: Loc is too inprecise here, should use proper locations for args.
2393 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
2394 if (ParamType->isVoidType()) {
2395 Diag(Loc, diag::err_param_with_void_type);
2397 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
2398 // Disallow half FP arguments.
2399 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
2400 FixItHint::CreateInsertion(Loc, "*");
2404 ParamTypes[Idx] = ParamType;
2407 if (EPI.ExtParameterInfos) {
2408 checkExtParameterInfos(*this, ParamTypes, EPI,
2409 [=](unsigned i) { return Loc; });
2415 return Context.getFunctionType(T, ParamTypes, EPI);
2418 /// \brief Build a member pointer type \c T Class::*.
2420 /// \param T the type to which the member pointer refers.
2421 /// \param Class the class type into which the member pointer points.
2422 /// \param Loc the location where this type begins
2423 /// \param Entity the name of the entity that will have this member pointer type
2425 /// \returns a member pointer type, if successful, or a NULL type if there was
2427 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
2429 DeclarationName Entity) {
2430 // Verify that we're not building a pointer to pointer to function with
2431 // exception specification.
2432 if (CheckDistantExceptionSpec(T)) {
2433 Diag(Loc, diag::err_distant_exception_spec);
2437 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
2438 // with reference type, or "cv void."
2439 if (T->isReferenceType()) {
2440 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
2441 << getPrintableNameForEntity(Entity) << T;
2445 if (T->isVoidType()) {
2446 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
2447 << getPrintableNameForEntity(Entity);
2451 if (!Class->isDependentType() && !Class->isRecordType()) {
2452 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
2456 // Adjust the default free function calling convention to the default method
2457 // calling convention.
2459 (Entity.getNameKind() == DeclarationName::CXXConstructorName) ||
2460 (Entity.getNameKind() == DeclarationName::CXXDestructorName);
2461 if (T->isFunctionType())
2462 adjustMemberFunctionCC(T, /*IsStatic=*/false, IsCtorOrDtor, Loc);
2464 return Context.getMemberPointerType(T, Class.getTypePtr());
2467 /// \brief Build a block pointer type.
2469 /// \param T The type to which we'll be building a block pointer.
2471 /// \param Loc The source location, used for diagnostics.
2473 /// \param Entity The name of the entity that involves the block pointer
2476 /// \returns A suitable block pointer type, if there are no
2477 /// errors. Otherwise, returns a NULL type.
2478 QualType Sema::BuildBlockPointerType(QualType T,
2480 DeclarationName Entity) {
2481 if (!T->isFunctionType()) {
2482 Diag(Loc, diag::err_nonfunction_block_type);
2486 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
2489 return Context.getBlockPointerType(T);
2492 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
2493 QualType QT = Ty.get();
2495 if (TInfo) *TInfo = nullptr;
2499 TypeSourceInfo *DI = nullptr;
2500 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
2501 QT = LIT->getType();
2502 DI = LIT->getTypeSourceInfo();
2505 if (TInfo) *TInfo = DI;
2509 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
2510 Qualifiers::ObjCLifetime ownership,
2511 unsigned chunkIndex);
2513 /// Given that this is the declaration of a parameter under ARC,
2514 /// attempt to infer attributes and such for pointer-to-whatever
2516 static void inferARCWriteback(TypeProcessingState &state,
2517 QualType &declSpecType) {
2518 Sema &S = state.getSema();
2519 Declarator &declarator = state.getDeclarator();
2521 // TODO: should we care about decl qualifiers?
2523 // Check whether the declarator has the expected form. We walk
2524 // from the inside out in order to make the block logic work.
2525 unsigned outermostPointerIndex = 0;
2526 bool isBlockPointer = false;
2527 unsigned numPointers = 0;
2528 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
2529 unsigned chunkIndex = i;
2530 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
2531 switch (chunk.Kind) {
2532 case DeclaratorChunk::Paren:
2536 case DeclaratorChunk::Reference:
2537 case DeclaratorChunk::Pointer:
2538 // Count the number of pointers. Treat references
2539 // interchangeably as pointers; if they're mis-ordered, normal
2540 // type building will discover that.
2541 outermostPointerIndex = chunkIndex;
2545 case DeclaratorChunk::BlockPointer:
2546 // If we have a pointer to block pointer, that's an acceptable
2547 // indirect reference; anything else is not an application of
2549 if (numPointers != 1) return;
2551 outermostPointerIndex = chunkIndex;
2552 isBlockPointer = true;
2554 // We don't care about pointer structure in return values here.
2557 case DeclaratorChunk::Array: // suppress if written (id[])?
2558 case DeclaratorChunk::Function:
2559 case DeclaratorChunk::MemberPointer:
2560 case DeclaratorChunk::Pipe:
2566 // If we have *one* pointer, then we want to throw the qualifier on
2567 // the declaration-specifiers, which means that it needs to be a
2568 // retainable object type.
2569 if (numPointers == 1) {
2570 // If it's not a retainable object type, the rule doesn't apply.
2571 if (!declSpecType->isObjCRetainableType()) return;
2573 // If it already has lifetime, don't do anything.
2574 if (declSpecType.getObjCLifetime()) return;
2576 // Otherwise, modify the type in-place.
2579 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2580 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2582 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2583 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2585 // If we have *two* pointers, then we want to throw the qualifier on
2586 // the outermost pointer.
2587 } else if (numPointers == 2) {
2588 // If we don't have a block pointer, we need to check whether the
2589 // declaration-specifiers gave us something that will turn into a
2590 // retainable object pointer after we slap the first pointer on it.
2591 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2594 // Look for an explicit lifetime attribute there.
2595 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2596 if (chunk.Kind != DeclaratorChunk::Pointer &&
2597 chunk.Kind != DeclaratorChunk::BlockPointer)
2599 for (const AttributeList *attr = chunk.getAttrs(); attr;
2600 attr = attr->getNext())
2601 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2604 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2605 outermostPointerIndex);
2607 // Any other number of pointers/references does not trigger the rule.
2610 // TODO: mark whether we did this inference?
2613 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2614 SourceLocation FallbackLoc,
2615 SourceLocation ConstQualLoc,
2616 SourceLocation VolatileQualLoc,
2617 SourceLocation RestrictQualLoc,
2618 SourceLocation AtomicQualLoc,
2619 SourceLocation UnalignedQualLoc) {
2627 } const QualKinds[5] = {
2628 { "const", DeclSpec::TQ_const, ConstQualLoc },
2629 { "volatile", DeclSpec::TQ_volatile, VolatileQualLoc },
2630 { "restrict", DeclSpec::TQ_restrict, RestrictQualLoc },
2631 { "__unaligned", DeclSpec::TQ_unaligned, UnalignedQualLoc },
2632 { "_Atomic", DeclSpec::TQ_atomic, AtomicQualLoc }
2635 SmallString<32> QualStr;
2636 unsigned NumQuals = 0;
2638 FixItHint FixIts[5];
2640 // Build a string naming the redundant qualifiers.
2641 for (auto &E : QualKinds) {
2642 if (Quals & E.Mask) {
2643 if (!QualStr.empty()) QualStr += ' ';
2646 // If we have a location for the qualifier, offer a fixit.
2647 SourceLocation QualLoc = E.Loc;
2648 if (QualLoc.isValid()) {
2649 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2650 if (Loc.isInvalid() ||
2651 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2659 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2660 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2663 // Diagnose pointless type qualifiers on the return type of a function.
2664 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2666 unsigned FunctionChunkIndex) {
2667 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2668 // FIXME: TypeSourceInfo doesn't preserve location information for
2670 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2671 RetTy.getLocalCVRQualifiers(),
2672 D.getIdentifierLoc());
2676 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2677 End = D.getNumTypeObjects();
2678 OuterChunkIndex != End; ++OuterChunkIndex) {
2679 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2680 switch (OuterChunk.Kind) {
2681 case DeclaratorChunk::Paren:
2684 case DeclaratorChunk::Pointer: {
2685 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2686 S.diagnoseIgnoredQualifiers(
2687 diag::warn_qual_return_type,
2690 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2691 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2692 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2693 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc),
2694 SourceLocation::getFromRawEncoding(PTI.UnalignedQualLoc));
2698 case DeclaratorChunk::Function:
2699 case DeclaratorChunk::BlockPointer:
2700 case DeclaratorChunk::Reference:
2701 case DeclaratorChunk::Array:
2702 case DeclaratorChunk::MemberPointer:
2703 case DeclaratorChunk::Pipe:
2704 // FIXME: We can't currently provide an accurate source location and a
2705 // fix-it hint for these.
2706 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2707 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2708 RetTy.getCVRQualifiers() | AtomicQual,
2709 D.getIdentifierLoc());
2713 llvm_unreachable("unknown declarator chunk kind");
2716 // If the qualifiers come from a conversion function type, don't diagnose
2717 // them -- they're not necessarily redundant, since such a conversion
2718 // operator can be explicitly called as "x.operator const int()".
2719 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2722 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2723 // which are present there.
2724 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2725 D.getDeclSpec().getTypeQualifiers(),
2726 D.getIdentifierLoc(),
2727 D.getDeclSpec().getConstSpecLoc(),
2728 D.getDeclSpec().getVolatileSpecLoc(),
2729 D.getDeclSpec().getRestrictSpecLoc(),
2730 D.getDeclSpec().getAtomicSpecLoc(),
2731 D.getDeclSpec().getUnalignedSpecLoc());
2734 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2735 TypeSourceInfo *&ReturnTypeInfo) {
2736 Sema &SemaRef = state.getSema();
2737 Declarator &D = state.getDeclarator();
2739 ReturnTypeInfo = nullptr;
2741 // The TagDecl owned by the DeclSpec.
2742 TagDecl *OwnedTagDecl = nullptr;
2744 switch (D.getName().getKind()) {
2745 case UnqualifiedId::IK_ImplicitSelfParam:
2746 case UnqualifiedId::IK_OperatorFunctionId:
2747 case UnqualifiedId::IK_Identifier:
2748 case UnqualifiedId::IK_LiteralOperatorId:
2749 case UnqualifiedId::IK_TemplateId:
2750 T = ConvertDeclSpecToType(state);
2752 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2753 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2754 // Owned declaration is embedded in declarator.
2755 OwnedTagDecl->setEmbeddedInDeclarator(true);
2759 case UnqualifiedId::IK_ConstructorName:
2760 case UnqualifiedId::IK_ConstructorTemplateId:
2761 case UnqualifiedId::IK_DestructorName:
2762 // Constructors and destructors don't have return types. Use
2764 T = SemaRef.Context.VoidTy;
2765 processTypeAttrs(state, T, TAL_DeclSpec,
2766 D.getDeclSpec().getAttributes().getList());
2769 case UnqualifiedId::IK_ConversionFunctionId:
2770 // The result type of a conversion function is the type that it
2772 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2777 if (D.getAttributes())
2778 distributeTypeAttrsFromDeclarator(state, T);
2780 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2781 if (D.getDeclSpec().containsPlaceholderType()) {
2784 switch (D.getContext()) {
2785 case Declarator::LambdaExprContext:
2786 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2787 case Declarator::ObjCParameterContext:
2788 case Declarator::ObjCResultContext:
2789 case Declarator::PrototypeContext:
2792 case Declarator::LambdaExprParameterContext:
2793 // In C++14, generic lambdas allow 'auto' in their parameters.
2794 if (!(SemaRef.getLangOpts().CPlusPlus14
2795 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2798 case Declarator::MemberContext: {
2799 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
2800 D.isFunctionDeclarator())
2802 bool Cxx = SemaRef.getLangOpts().CPlusPlus;
2803 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2804 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2805 case TTK_Struct: Error = Cxx ? 1 : 2; /* Struct member */ break;
2806 case TTK_Union: Error = Cxx ? 3 : 4; /* Union member */ break;
2807 case TTK_Class: Error = 5; /* Class member */ break;
2808 case TTK_Interface: Error = 6; /* Interface member */ break;
2812 case Declarator::CXXCatchContext:
2813 case Declarator::ObjCCatchContext:
2814 Error = 7; // Exception declaration
2816 case Declarator::TemplateParamContext:
2817 if (!SemaRef.getLangOpts().CPlusPlus1z)
2818 Error = 8; // Template parameter
2820 case Declarator::BlockLiteralContext:
2821 Error = 9; // Block literal
2823 case Declarator::TemplateTypeArgContext:
2824 Error = 10; // Template type argument
2826 case Declarator::AliasDeclContext:
2827 case Declarator::AliasTemplateContext:
2828 Error = 12; // Type alias
2830 case Declarator::TrailingReturnContext:
2831 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2832 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2833 Error = 13; // Function return type
2835 case Declarator::ConversionIdContext:
2836 if (!SemaRef.getLangOpts().CPlusPlus14 ||
2837 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2838 Error = 14; // conversion-type-id
2840 case Declarator::TypeNameContext:
2841 Error = 15; // Generic
2843 case Declarator::FileContext:
2844 case Declarator::BlockContext:
2845 case Declarator::ForContext:
2846 case Declarator::InitStmtContext:
2847 case Declarator::ConditionContext:
2849 case Declarator::CXXNewContext:
2850 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type)
2851 Error = 17; // 'new' type
2853 case Declarator::KNRTypeListContext:
2854 Error = 18; // K&R function parameter
2858 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2861 // In Objective-C it is an error to use 'auto' on a function declarator
2862 // (and everywhere for '__auto_type').
2863 if (D.isFunctionDeclarator() &&
2864 (!SemaRef.getLangOpts().CPlusPlus11 ||
2865 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto_type))
2868 bool HaveTrailing = false;
2870 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2871 // contains a trailing return type. That is only legal at the outermost
2872 // level. Check all declarator chunks (outermost first) anyway, to give
2873 // better diagnostics.
2874 // We don't support '__auto_type' with trailing return types.
2875 if (SemaRef.getLangOpts().CPlusPlus11 &&
2876 D.getDeclSpec().getTypeSpecType() != DeclSpec::TST_auto_type) {
2877 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2878 unsigned chunkIndex = e - i - 1;
2879 state.setCurrentChunkIndex(chunkIndex);
2880 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2881 if (DeclType.Kind == DeclaratorChunk::Function) {
2882 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2883 if (FTI.hasTrailingReturnType()) {
2884 HaveTrailing = true;
2892 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2893 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2894 AutoRange = D.getName().getSourceRange();
2898 switch (D.getDeclSpec().getTypeSpecType()) {
2899 case DeclSpec::TST_auto: Keyword = 0; break;
2900 case DeclSpec::TST_decltype_auto: Keyword = 1; break;
2901 case DeclSpec::TST_auto_type: Keyword = 2; break;
2902 default: llvm_unreachable("unknown auto TypeSpecType");
2904 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2905 << Keyword << Error << AutoRange;
2906 T = SemaRef.Context.IntTy;
2907 D.setInvalidType(true);
2908 } else if (!HaveTrailing) {
2909 // If there was a trailing return type, we already got
2910 // warn_cxx98_compat_trailing_return_type in the parser.
2911 SemaRef.Diag(AutoRange.getBegin(),
2912 diag::warn_cxx98_compat_auto_type_specifier)
2917 if (SemaRef.getLangOpts().CPlusPlus &&
2918 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2919 // Check the contexts where C++ forbids the declaration of a new class
2920 // or enumeration in a type-specifier-seq.
2921 unsigned DiagID = 0;
2922 switch (D.getContext()) {
2923 case Declarator::TrailingReturnContext:
2924 // Class and enumeration definitions are syntactically not allowed in
2925 // trailing return types.
2926 llvm_unreachable("parser should not have allowed this");
2928 case Declarator::FileContext:
2929 case Declarator::MemberContext:
2930 case Declarator::BlockContext:
2931 case Declarator::ForContext:
2932 case Declarator::InitStmtContext:
2933 case Declarator::BlockLiteralContext:
2934 case Declarator::LambdaExprContext:
2935 // C++11 [dcl.type]p3:
2936 // A type-specifier-seq shall not define a class or enumeration unless
2937 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2938 // the declaration of a template-declaration.
2939 case Declarator::AliasDeclContext:
2941 case Declarator::AliasTemplateContext:
2942 DiagID = diag::err_type_defined_in_alias_template;
2944 case Declarator::TypeNameContext:
2945 case Declarator::ConversionIdContext:
2946 case Declarator::TemplateParamContext:
2947 case Declarator::CXXNewContext:
2948 case Declarator::CXXCatchContext:
2949 case Declarator::ObjCCatchContext:
2950 case Declarator::TemplateTypeArgContext:
2951 DiagID = diag::err_type_defined_in_type_specifier;
2953 case Declarator::PrototypeContext:
2954 case Declarator::LambdaExprParameterContext:
2955 case Declarator::ObjCParameterContext:
2956 case Declarator::ObjCResultContext:
2957 case Declarator::KNRTypeListContext:
2959 // Types shall not be defined in return or parameter types.
2960 DiagID = diag::err_type_defined_in_param_type;
2962 case Declarator::ConditionContext:
2964 // The type-specifier-seq shall not contain typedef and shall not declare
2965 // a new class or enumeration.
2966 DiagID = diag::err_type_defined_in_condition;
2971 SemaRef.Diag(OwnedTagDecl->getLocation(), DiagID)
2972 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2973 D.setInvalidType(true);
2977 assert(!T.isNull() && "This function should not return a null type");
2981 /// Produce an appropriate diagnostic for an ambiguity between a function
2982 /// declarator and a C++ direct-initializer.
2983 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2984 DeclaratorChunk &DeclType, QualType RT) {
2985 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2986 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2988 // If the return type is void there is no ambiguity.
2989 if (RT->isVoidType())
2992 // An initializer for a non-class type can have at most one argument.
2993 if (!RT->isRecordType() && FTI.NumParams > 1)
2996 // An initializer for a reference must have exactly one argument.
2997 if (RT->isReferenceType() && FTI.NumParams != 1)
3000 // Only warn if this declarator is declaring a function at block scope, and
3001 // doesn't have a storage class (such as 'extern') specified.
3002 if (!D.isFunctionDeclarator() ||
3003 D.getFunctionDefinitionKind() != FDK_Declaration ||
3004 !S.CurContext->isFunctionOrMethod() ||
3005 D.getDeclSpec().getStorageClassSpec()
3006 != DeclSpec::SCS_unspecified)
3009 // Inside a condition, a direct initializer is not permitted. We allow one to
3010 // be parsed in order to give better diagnostics in condition parsing.
3011 if (D.getContext() == Declarator::ConditionContext)
3014 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
3016 S.Diag(DeclType.Loc,
3017 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
3018 : diag::warn_empty_parens_are_function_decl)
3021 // If the declaration looks like:
3024 // and name lookup finds a function named 'f', then the ',' was
3025 // probably intended to be a ';'.
3026 if (!D.isFirstDeclarator() && D.getIdentifier()) {
3027 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
3028 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
3029 if (Comma.getFileID() != Name.getFileID() ||
3030 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
3031 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
3032 Sema::LookupOrdinaryName);
3033 if (S.LookupName(Result, S.getCurScope()))
3034 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
3035 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
3036 << D.getIdentifier();
3040 if (FTI.NumParams > 0) {
3041 // For a declaration with parameters, eg. "T var(T());", suggest adding
3042 // parens around the first parameter to turn the declaration into a
3043 // variable declaration.
3044 SourceRange Range = FTI.Params[0].Param->getSourceRange();
3045 SourceLocation B = Range.getBegin();
3046 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
3047 // FIXME: Maybe we should suggest adding braces instead of parens
3048 // in C++11 for classes that don't have an initializer_list constructor.
3049 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
3050 << FixItHint::CreateInsertion(B, "(")
3051 << FixItHint::CreateInsertion(E, ")");
3053 // For a declaration without parameters, eg. "T var();", suggest replacing
3054 // the parens with an initializer to turn the declaration into a variable
3056 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
3058 // Empty parens mean value-initialization, and no parens mean
3059 // default initialization. These are equivalent if the default
3060 // constructor is user-provided or if zero-initialization is a
3062 if (RD && RD->hasDefinition() &&
3063 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
3064 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
3065 << FixItHint::CreateRemoval(ParenRange);
3068 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
3069 if (Init.empty() && S.LangOpts.CPlusPlus11)
3072 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
3073 << FixItHint::CreateReplacement(ParenRange, Init);
3078 /// Helper for figuring out the default CC for a function declarator type. If
3079 /// this is the outermost chunk, then we can determine the CC from the
3080 /// declarator context. If not, then this could be either a member function
3081 /// type or normal function type.
3083 getCCForDeclaratorChunk(Sema &S, Declarator &D,
3084 const DeclaratorChunk::FunctionTypeInfo &FTI,
3085 unsigned ChunkIndex) {
3086 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
3088 // Check for an explicit CC attribute.
3089 for (auto Attr = FTI.AttrList; Attr; Attr = Attr->getNext()) {
3090 switch (Attr->getKind()) {
3091 CALLING_CONV_ATTRS_CASELIST: {
3092 // Ignore attributes that don't validate or can't apply to the
3093 // function type. We'll diagnose the failure to apply them in
3094 // handleFunctionTypeAttr.
3096 if (!S.CheckCallingConvAttr(*Attr, CC) &&
3097 (!FTI.isVariadic || supportsVariadicCall(CC))) {
3108 bool IsCXXInstanceMethod = false;
3110 if (S.getLangOpts().CPlusPlus) {
3111 // Look inwards through parentheses to see if this chunk will form a
3112 // member pointer type or if we're the declarator. Any type attributes
3113 // between here and there will override the CC we choose here.
3114 unsigned I = ChunkIndex;
3115 bool FoundNonParen = false;
3116 while (I && !FoundNonParen) {
3118 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
3119 FoundNonParen = true;
3122 if (FoundNonParen) {
3123 // If we're not the declarator, we're a regular function type unless we're
3124 // in a member pointer.
3125 IsCXXInstanceMethod =
3126 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
3127 } else if (D.getContext() == Declarator::LambdaExprContext) {
3128 // This can only be a call operator for a lambda, which is an instance
3130 IsCXXInstanceMethod = true;
3132 // We're the innermost decl chunk, so must be a function declarator.
3133 assert(D.isFunctionDeclarator());
3135 // If we're inside a record, we're declaring a method, but it could be
3136 // explicitly or implicitly static.
3137 IsCXXInstanceMethod =
3138 D.isFirstDeclarationOfMember() &&
3139 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
3140 !D.isStaticMember();
3144 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
3145 IsCXXInstanceMethod);
3147 // Attribute AT_OpenCLKernel affects the calling convention for SPIR
3148 // and AMDGPU targets, hence it cannot be treated as a calling
3149 // convention attribute. This is the simplest place to infer
3150 // calling convention for OpenCL kernels.
3151 if (S.getLangOpts().OpenCL) {
3152 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
3153 Attr; Attr = Attr->getNext()) {
3154 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
3155 llvm::Triple::ArchType arch = S.Context.getTargetInfo().getTriple().getArch();
3156 if (arch == llvm::Triple::spir || arch == llvm::Triple::spir64 ||
3157 arch == llvm::Triple::amdgcn) {
3158 CC = CC_OpenCLKernel;
3169 /// A simple notion of pointer kinds, which matches up with the various
3170 /// pointer declarators.
3171 enum class SimplePointerKind {
3177 } // end anonymous namespace
3179 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
3180 switch (nullability) {
3181 case NullabilityKind::NonNull:
3182 if (!Ident__Nonnull)
3183 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
3184 return Ident__Nonnull;
3186 case NullabilityKind::Nullable:
3187 if (!Ident__Nullable)
3188 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
3189 return Ident__Nullable;
3191 case NullabilityKind::Unspecified:
3192 if (!Ident__Null_unspecified)
3193 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
3194 return Ident__Null_unspecified;
3196 llvm_unreachable("Unknown nullability kind.");
3199 /// Retrieve the identifier "NSError".
3200 IdentifierInfo *Sema::getNSErrorIdent() {
3202 Ident_NSError = PP.getIdentifierInfo("NSError");
3204 return Ident_NSError;
3207 /// Check whether there is a nullability attribute of any kind in the given
3209 static bool hasNullabilityAttr(const AttributeList *attrs) {
3210 for (const AttributeList *attr = attrs; attr;
3211 attr = attr->getNext()) {
3212 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
3213 attr->getKind() == AttributeList::AT_TypeNullable ||
3214 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
3222 /// Describes the kind of a pointer a declarator describes.
3223 enum class PointerDeclaratorKind {
3226 // Single-level pointer.
3228 // Multi-level pointer (of any pointer kind).
3231 MaybePointerToCFRef,
3235 NSErrorPointerPointer,
3238 /// Describes a declarator chunk wrapping a pointer that marks inference as
3240 // These values must be kept in sync with diagnostics.
3241 enum class PointerWrappingDeclaratorKind {
3242 /// Pointer is top-level.
3244 /// Pointer is an array element.
3246 /// Pointer is the referent type of a C++ reference.
3249 } // end anonymous namespace
3251 /// Classify the given declarator, whose type-specified is \c type, based on
3252 /// what kind of pointer it refers to.
3254 /// This is used to determine the default nullability.
3255 static PointerDeclaratorKind
3256 classifyPointerDeclarator(Sema &S, QualType type, Declarator &declarator,
3257 PointerWrappingDeclaratorKind &wrappingKind) {
3258 unsigned numNormalPointers = 0;
3260 // For any dependent type, we consider it a non-pointer.
3261 if (type->isDependentType())
3262 return PointerDeclaratorKind::NonPointer;
3264 // Look through the declarator chunks to identify pointers.
3265 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
3266 DeclaratorChunk &chunk = declarator.getTypeObject(i);
3267 switch (chunk.Kind) {
3268 case DeclaratorChunk::Array:
3269 if (numNormalPointers == 0)
3270 wrappingKind = PointerWrappingDeclaratorKind::Array;
3273 case DeclaratorChunk::Function:
3274 case DeclaratorChunk::Pipe:
3277 case DeclaratorChunk::BlockPointer:
3278 case DeclaratorChunk::MemberPointer:
3279 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3280 : PointerDeclaratorKind::SingleLevelPointer;
3282 case DeclaratorChunk::Paren:
3285 case DeclaratorChunk::Reference:
3286 if (numNormalPointers == 0)
3287 wrappingKind = PointerWrappingDeclaratorKind::Reference;
3290 case DeclaratorChunk::Pointer:
3291 ++numNormalPointers;
3292 if (numNormalPointers > 2)
3293 return PointerDeclaratorKind::MultiLevelPointer;
3298 // Then, dig into the type specifier itself.
3299 unsigned numTypeSpecifierPointers = 0;
3301 // Decompose normal pointers.
3302 if (auto ptrType = type->getAs<PointerType>()) {
3303 ++numNormalPointers;
3305 if (numNormalPointers > 2)
3306 return PointerDeclaratorKind::MultiLevelPointer;
3308 type = ptrType->getPointeeType();
3309 ++numTypeSpecifierPointers;
3313 // Decompose block pointers.
3314 if (type->getAs<BlockPointerType>()) {
3315 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3316 : PointerDeclaratorKind::SingleLevelPointer;
3319 // Decompose member pointers.
3320 if (type->getAs<MemberPointerType>()) {
3321 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
3322 : PointerDeclaratorKind::SingleLevelPointer;
3325 // Look at Objective-C object pointers.
3326 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
3327 ++numNormalPointers;
3328 ++numTypeSpecifierPointers;
3330 // If this is NSError**, report that.
3331 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
3332 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
3333 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3334 return PointerDeclaratorKind::NSErrorPointerPointer;
3341 // Look at Objective-C class types.
3342 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
3343 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
3344 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
3345 return PointerDeclaratorKind::NSErrorPointerPointer;;
3351 // If at this point we haven't seen a pointer, we won't see one.
3352 if (numNormalPointers == 0)
3353 return PointerDeclaratorKind::NonPointer;
3355 if (auto recordType = type->getAs<RecordType>()) {
3356 RecordDecl *recordDecl = recordType->getDecl();
3358 bool isCFError = false;
3360 // If we already know about CFError, test it directly.
3361 isCFError = (S.CFError == recordDecl);
3363 // Check whether this is CFError, which we identify based on its bridge
3365 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
3366 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
3367 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
3368 S.CFError = recordDecl;
3375 // If this is CFErrorRef*, report it as such.
3376 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
3377 return PointerDeclaratorKind::CFErrorRefPointer;
3385 switch (numNormalPointers) {
3387 return PointerDeclaratorKind::NonPointer;
3390 return PointerDeclaratorKind::SingleLevelPointer;
3393 return PointerDeclaratorKind::MaybePointerToCFRef;
3396 return PointerDeclaratorKind::MultiLevelPointer;
3400 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
3401 SourceLocation loc) {
3402 // If we're anywhere in a function, method, or closure context, don't perform
3403 // completeness checks.
3404 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
3405 if (ctx->isFunctionOrMethod())
3408 if (ctx->isFileContext())
3412 // We only care about the expansion location.
3413 loc = S.SourceMgr.getExpansionLoc(loc);
3414 FileID file = S.SourceMgr.getFileID(loc);
3415 if (file.isInvalid())
3418 // Retrieve file information.
3419 bool invalid = false;
3420 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
3421 if (invalid || !sloc.isFile())
3424 // We don't want to perform completeness checks on the main file or in
3426 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
3427 if (fileInfo.getIncludeLoc().isInvalid())
3429 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
3430 S.Diags.getSuppressSystemWarnings()) {
3437 /// Creates a fix-it to insert a C-style nullability keyword at \p pointerLoc,
3438 /// taking into account whitespace before and after.
3439 static void fixItNullability(Sema &S, DiagnosticBuilder &Diag,
3440 SourceLocation PointerLoc,
3441 NullabilityKind Nullability) {
3442 assert(PointerLoc.isValid());
3443 if (PointerLoc.isMacroID())
3446 SourceLocation FixItLoc = S.getLocForEndOfToken(PointerLoc);
3447 if (!FixItLoc.isValid() || FixItLoc == PointerLoc)
3450 const char *NextChar = S.SourceMgr.getCharacterData(FixItLoc);
3454 SmallString<32> InsertionTextBuf{" "};
3455 InsertionTextBuf += getNullabilitySpelling(Nullability);
3456 InsertionTextBuf += " ";
3457 StringRef InsertionText = InsertionTextBuf.str();
3459 if (isWhitespace(*NextChar)) {
3460 InsertionText = InsertionText.drop_back();
3461 } else if (NextChar[-1] == '[') {
3462 if (NextChar[0] == ']')
3463 InsertionText = InsertionText.drop_back().drop_front();
3465 InsertionText = InsertionText.drop_front();
3466 } else if (!isIdentifierBody(NextChar[0], /*allow dollar*/true) &&
3467 !isIdentifierBody(NextChar[-1], /*allow dollar*/true)) {
3468 InsertionText = InsertionText.drop_back().drop_front();
3471 Diag << FixItHint::CreateInsertion(FixItLoc, InsertionText);
3474 static void emitNullabilityConsistencyWarning(Sema &S,
3475 SimplePointerKind PointerKind,
3476 SourceLocation PointerLoc) {
3477 assert(PointerLoc.isValid());
3479 if (PointerKind == SimplePointerKind::Array) {
3480 S.Diag(PointerLoc, diag::warn_nullability_missing_array);
3482 S.Diag(PointerLoc, diag::warn_nullability_missing)
3483 << static_cast<unsigned>(PointerKind);
3486 if (PointerLoc.isMacroID())
3489 auto addFixIt = [&](NullabilityKind Nullability) {
3490 auto Diag = S.Diag(PointerLoc, diag::note_nullability_fix_it);
3491 Diag << static_cast<unsigned>(Nullability);
3492 Diag << static_cast<unsigned>(PointerKind);
3493 fixItNullability(S, Diag, PointerLoc, Nullability);
3495 addFixIt(NullabilityKind::Nullable);
3496 addFixIt(NullabilityKind::NonNull);
3499 /// Complains about missing nullability if the file containing \p pointerLoc
3500 /// has other uses of nullability (either the keywords or the \c assume_nonnull
3503 /// If the file has \e not seen other uses of nullability, this particular
3504 /// pointer is saved for possible later diagnosis. See recordNullabilitySeen().
3505 static void checkNullabilityConsistency(Sema &S,
3506 SimplePointerKind pointerKind,
3507 SourceLocation pointerLoc) {
3508 // Determine which file we're performing consistency checking for.
3509 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
3510 if (file.isInvalid())
3513 // If we haven't seen any type nullability in this file, we won't warn now
3515 FileNullability &fileNullability = S.NullabilityMap[file];
3516 if (!fileNullability.SawTypeNullability) {
3517 // If this is the first pointer declarator in the file, and the appropriate
3518 // warning is on, record it in case we need to diagnose it retroactively.
3519 diag::kind diagKind;
3520 if (pointerKind == SimplePointerKind::Array)
3521 diagKind = diag::warn_nullability_missing_array;
3523 diagKind = diag::warn_nullability_missing;
3525 if (fileNullability.PointerLoc.isInvalid() &&
3526 !S.Context.getDiagnostics().isIgnored(diagKind, pointerLoc)) {
3527 fileNullability.PointerLoc = pointerLoc;
3528 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
3534 // Complain about missing nullability.
3535 emitNullabilityConsistencyWarning(S, pointerKind, pointerLoc);
3538 /// Marks that a nullability feature has been used in the file containing
3541 /// If this file already had pointer types in it that were missing nullability,
3542 /// the first such instance is retroactively diagnosed.
3544 /// \sa checkNullabilityConsistency
3545 static void recordNullabilitySeen(Sema &S, SourceLocation loc) {
3546 FileID file = getNullabilityCompletenessCheckFileID(S, loc);
3547 if (file.isInvalid())
3550 FileNullability &fileNullability = S.NullabilityMap[file];
3551 if (fileNullability.SawTypeNullability)
3553 fileNullability.SawTypeNullability = true;
3555 // If we haven't seen any type nullability before, now we have. Retroactively
3556 // diagnose the first unannotated pointer, if there was one.
3557 if (fileNullability.PointerLoc.isInvalid())
3560 auto kind = static_cast<SimplePointerKind>(fileNullability.PointerKind);
3561 emitNullabilityConsistencyWarning(S, kind, fileNullability.PointerLoc);
3564 /// Returns true if any of the declarator chunks before \p endIndex include a
3565 /// level of indirection: array, pointer, reference, or pointer-to-member.
3567 /// Because declarator chunks are stored in outer-to-inner order, testing
3568 /// every chunk before \p endIndex is testing all chunks that embed the current
3569 /// chunk as part of their type.
3571 /// It is legal to pass the result of Declarator::getNumTypeObjects() as the
3572 /// end index, in which case all chunks are tested.
3573 static bool hasOuterPointerLikeChunk(const Declarator &D, unsigned endIndex) {
3574 unsigned i = endIndex;
3576 // Walk outwards along the declarator chunks.
3578 const DeclaratorChunk &DC = D.getTypeObject(i);
3580 case DeclaratorChunk::Paren:
3582 case DeclaratorChunk::Array:
3583 case DeclaratorChunk::Pointer:
3584 case DeclaratorChunk::Reference:
3585 case DeclaratorChunk::MemberPointer:
3587 case DeclaratorChunk::Function:
3588 case DeclaratorChunk::BlockPointer:
3589 case DeclaratorChunk::Pipe:
3590 // These are invalid anyway, so just ignore.
3597 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
3598 QualType declSpecType,
3599 TypeSourceInfo *TInfo) {
3600 // The TypeSourceInfo that this function returns will not be a null type.
3601 // If there is an error, this function will fill in a dummy type as fallback.
3602 QualType T = declSpecType;
3603 Declarator &D = state.getDeclarator();
3604 Sema &S = state.getSema();
3605 ASTContext &Context = S.Context;
3606 const LangOptions &LangOpts = S.getLangOpts();
3608 // The name we're declaring, if any.
3609 DeclarationName Name;
3610 if (D.getIdentifier())
3611 Name = D.getIdentifier();
3613 // Does this declaration declare a typedef-name?
3614 bool IsTypedefName =
3615 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
3616 D.getContext() == Declarator::AliasDeclContext ||
3617 D.getContext() == Declarator::AliasTemplateContext;
3619 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
3620 bool IsQualifiedFunction = T->isFunctionProtoType() &&
3621 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
3622 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
3624 // If T is 'decltype(auto)', the only declarators we can have are parens
3625 // and at most one function declarator if this is a function declaration.
3626 if (const AutoType *AT = T->getAs<AutoType>()) {
3627 if (AT->isDecltypeAuto()) {
3628 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
3629 unsigned Index = E - I - 1;
3630 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
3631 unsigned DiagId = diag::err_decltype_auto_compound_type;
3632 unsigned DiagKind = 0;
3633 switch (DeclChunk.Kind) {
3634 case DeclaratorChunk::Paren:
3636 case DeclaratorChunk::Function: {
3638 if (D.isFunctionDeclarationContext() &&
3639 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
3641 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
3644 case DeclaratorChunk::Pointer:
3645 case DeclaratorChunk::BlockPointer:
3646 case DeclaratorChunk::MemberPointer:
3649 case DeclaratorChunk::Reference:
3652 case DeclaratorChunk::Array:
3655 case DeclaratorChunk::Pipe:
3659 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
3660 D.setInvalidType(true);
3666 // Determine whether we should infer _Nonnull on pointer types.
3667 Optional<NullabilityKind> inferNullability;
3668 bool inferNullabilityCS = false;
3669 bool inferNullabilityInnerOnly = false;
3670 bool inferNullabilityInnerOnlyComplete = false;
3672 // Are we in an assume-nonnull region?
3673 bool inAssumeNonNullRegion = false;
3674 SourceLocation assumeNonNullLoc = S.PP.getPragmaAssumeNonNullLoc();
3675 if (assumeNonNullLoc.isValid()) {
3676 inAssumeNonNullRegion = true;
3677 recordNullabilitySeen(S, assumeNonNullLoc);
3680 // Whether to complain about missing nullability specifiers or not.
3684 /// Complain on the inner pointers (but not the outermost
3687 /// Complain about any pointers that don't have nullability
3688 /// specified or inferred.
3690 } complainAboutMissingNullability = CAMN_No;
3691 unsigned NumPointersRemaining = 0;
3692 auto complainAboutInferringWithinChunk = PointerWrappingDeclaratorKind::None;
3694 if (IsTypedefName) {
3695 // For typedefs, we do not infer any nullability (the default),
3696 // and we only complain about missing nullability specifiers on
3698 complainAboutMissingNullability = CAMN_InnerPointers;
3700 auto isDependentNonPointerType = [](QualType T) -> bool {
3701 // Note: This is intended to be the same check as Type::canHaveNullability
3702 // except with all of the ambiguous cases being treated as 'false' rather
3704 return T->isDependentType() && !T->isAnyPointerType() &&
3705 !T->isBlockPointerType() && !T->isMemberPointerType();
3708 if (T->canHaveNullability() && !T->getNullability(S.Context) &&
3709 !isDependentNonPointerType(T)) {
3710 // Note that we allow but don't require nullability on dependent types.
3711 ++NumPointersRemaining;
3714 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
3715 DeclaratorChunk &chunk = D.getTypeObject(i);
3716 switch (chunk.Kind) {
3717 case DeclaratorChunk::Array:
3718 case DeclaratorChunk::Function:
3719 case DeclaratorChunk::Pipe:
3722 case DeclaratorChunk::BlockPointer:
3723 case DeclaratorChunk::MemberPointer:
3724 ++NumPointersRemaining;
3727 case DeclaratorChunk::Paren:
3728 case DeclaratorChunk::Reference:
3731 case DeclaratorChunk::Pointer:
3732 ++NumPointersRemaining;
3737 bool isFunctionOrMethod = false;
3738 switch (auto context = state.getDeclarator().getContext()) {
3739 case Declarator::ObjCParameterContext:
3740 case Declarator::ObjCResultContext:
3741 case Declarator::PrototypeContext:
3742 case Declarator::TrailingReturnContext:
3743 isFunctionOrMethod = true;
3746 case Declarator::MemberContext:
3747 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
3748 complainAboutMissingNullability = CAMN_No;
3752 // Weak properties are inferred to be nullable.
3753 if (state.getDeclarator().isObjCWeakProperty() && inAssumeNonNullRegion) {
3754 inferNullability = NullabilityKind::Nullable;
3760 case Declarator::FileContext:
3761 case Declarator::KNRTypeListContext: {
3762 complainAboutMissingNullability = CAMN_Yes;
3764 // Nullability inference depends on the type and declarator.
3765 auto wrappingKind = PointerWrappingDeclaratorKind::None;
3766 switch (classifyPointerDeclarator(S, T, D, wrappingKind)) {
3767 case PointerDeclaratorKind::NonPointer:
3768 case PointerDeclaratorKind::MultiLevelPointer:
3769 // Cannot infer nullability.
3772 case PointerDeclaratorKind::SingleLevelPointer:
3773 // Infer _Nonnull if we are in an assumes-nonnull region.
3774 if (inAssumeNonNullRegion) {
3775 complainAboutInferringWithinChunk = wrappingKind;
3776 inferNullability = NullabilityKind::NonNull;
3777 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3778 context == Declarator::ObjCResultContext);
3782 case PointerDeclaratorKind::CFErrorRefPointer:
3783 case PointerDeclaratorKind::NSErrorPointerPointer:
3784 // Within a function or method signature, infer _Nullable at both
3786 if (isFunctionOrMethod && inAssumeNonNullRegion)
3787 inferNullability = NullabilityKind::Nullable;
3790 case PointerDeclaratorKind::MaybePointerToCFRef:
3791 if (isFunctionOrMethod) {
3792 // On pointer-to-pointer parameters marked cf_returns_retained or
3793 // cf_returns_not_retained, if the outer pointer is explicit then
3794 // infer the inner pointer as _Nullable.
3795 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3797 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3798 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3800 NextAttr = NextAttr->getNext();
3804 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3805 if (hasCFReturnsAttr(D.getAttributes()) ||
3806 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3807 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3808 inferNullability = NullabilityKind::Nullable;
3809 inferNullabilityInnerOnly = true;
3818 case Declarator::ConversionIdContext:
3819 complainAboutMissingNullability = CAMN_Yes;
3822 case Declarator::AliasDeclContext:
3823 case Declarator::AliasTemplateContext:
3824 case Declarator::BlockContext:
3825 case Declarator::BlockLiteralContext:
3826 case Declarator::ConditionContext:
3827 case Declarator::CXXCatchContext:
3828 case Declarator::CXXNewContext:
3829 case Declarator::ForContext:
3830 case Declarator::InitStmtContext:
3831 case Declarator::LambdaExprContext:
3832 case Declarator::LambdaExprParameterContext:
3833 case Declarator::ObjCCatchContext:
3834 case Declarator::TemplateParamContext:
3835 case Declarator::TemplateTypeArgContext:
3836 case Declarator::TypeNameContext:
3837 // Don't infer in these contexts.
3842 // Local function that returns true if its argument looks like a va_list.
3843 auto isVaList = [&S](QualType T) -> bool {
3844 auto *typedefTy = T->getAs<TypedefType>();
3847 TypedefDecl *vaListTypedef = S.Context.getBuiltinVaListDecl();
3849 if (typedefTy->getDecl() == vaListTypedef)
3851 if (auto *name = typedefTy->getDecl()->getIdentifier())
3852 if (name->isStr("va_list"))
3854 typedefTy = typedefTy->desugar()->getAs<TypedefType>();
3855 } while (typedefTy);
3859 // Local function that checks the nullability for a given pointer declarator.
3860 // Returns true if _Nonnull was inferred.
3861 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3862 SourceLocation pointerLoc,
3863 AttributeList *&attrs) -> AttributeList * {
3864 // We've seen a pointer.
3865 if (NumPointersRemaining > 0)
3866 --NumPointersRemaining;
3868 // If a nullability attribute is present, there's nothing to do.
3869 if (hasNullabilityAttr(attrs))
3872 // If we're supposed to infer nullability, do so now.
3873 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3874 AttributeList::Syntax syntax
3875 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3876 : AttributeList::AS_Keyword;
3877 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3879 S.getNullabilityKeyword(
3881 SourceRange(pointerLoc),
3882 nullptr, SourceLocation(),
3883 nullptr, 0, syntax);
3885 spliceAttrIntoList(*nullabilityAttr, attrs);
3887 if (inferNullabilityCS) {
3888 state.getDeclarator().getMutableDeclSpec().getObjCQualifiers()
3889 ->setObjCDeclQualifier(ObjCDeclSpec::DQ_CSNullability);
3892 if (pointerLoc.isValid() &&
3893 complainAboutInferringWithinChunk !=
3894 PointerWrappingDeclaratorKind::None) {
3896 S.Diag(pointerLoc, diag::warn_nullability_inferred_on_nested_type);
3897 Diag << static_cast<int>(complainAboutInferringWithinChunk);
3898 fixItNullability(S, Diag, pointerLoc, NullabilityKind::NonNull);
3901 if (inferNullabilityInnerOnly)
3902 inferNullabilityInnerOnlyComplete = true;
3903 return nullabilityAttr;
3906 // If we're supposed to complain about missing nullability, do so
3907 // now if it's truly missing.
3908 switch (complainAboutMissingNullability) {
3912 case CAMN_InnerPointers:
3913 if (NumPointersRemaining == 0)
3918 checkNullabilityConsistency(S, pointerKind, pointerLoc);
3923 // If the type itself could have nullability but does not, infer pointer
3924 // nullability and perform consistency checking.
3925 if (S.ActiveTemplateInstantiations.empty()) {
3926 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
3928 // Record that we've seen a pointer, but do nothing else.
3929 if (NumPointersRemaining > 0)
3930 --NumPointersRemaining;
3932 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3933 if (T->isBlockPointerType())
3934 pointerKind = SimplePointerKind::BlockPointer;
3935 else if (T->isMemberPointerType())
3936 pointerKind = SimplePointerKind::MemberPointer;
3938 if (auto *attr = inferPointerNullability(
3939 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3940 D.getMutableDeclSpec().getAttributes().getListRef())) {
3941 T = Context.getAttributedType(
3942 AttributedType::getNullabilityAttrKind(*inferNullability),T,T);
3943 attr->setUsedAsTypeAttr();
3948 if (complainAboutMissingNullability == CAMN_Yes &&
3949 T->isArrayType() && !T->getNullability(S.Context) && !isVaList(T) &&
3950 D.isPrototypeContext() &&
3951 !hasOuterPointerLikeChunk(D, D.getNumTypeObjects())) {
3952 checkNullabilityConsistency(S, SimplePointerKind::Array,
3953 D.getDeclSpec().getTypeSpecTypeLoc());
3957 // Walk the DeclTypeInfo, building the recursive type as we go.
3958 // DeclTypeInfos are ordered from the identifier out, which is
3959 // opposite of what we want :).
3960 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3961 unsigned chunkIndex = e - i - 1;
3962 state.setCurrentChunkIndex(chunkIndex);
3963 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3964 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3965 switch (DeclType.Kind) {
3966 case DeclaratorChunk::Paren:
3967 T = S.BuildParenType(T);
3969 case DeclaratorChunk::BlockPointer:
3970 // If blocks are disabled, emit an error.
3971 if (!LangOpts.Blocks)
3972 S.Diag(DeclType.Loc, diag::err_blocks_disable) << LangOpts.OpenCL;
3974 // Handle pointer nullability.
3975 inferPointerNullability(SimplePointerKind::BlockPointer,
3976 DeclType.Loc, DeclType.getAttrListRef());
3978 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3979 if (DeclType.Cls.TypeQuals || LangOpts.OpenCL) {
3980 // OpenCL v2.0, s6.12.5 - Block variable declarations are implicitly
3981 // qualified with const.
3982 if (LangOpts.OpenCL)
3983 DeclType.Cls.TypeQuals |= DeclSpec::TQ_const;
3984 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3987 case DeclaratorChunk::Pointer:
3988 // Verify that we're not building a pointer to pointer to function with
3989 // exception specification.
3990 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3991 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3992 D.setInvalidType(true);
3993 // Build the type anyway.
3996 // Handle pointer nullability
3997 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3998 DeclType.getAttrListRef());
4000 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
4001 T = Context.getObjCObjectPointerType(T);
4002 if (DeclType.Ptr.TypeQuals)
4003 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4007 // OpenCL v2.0 s6.9b - Pointer to image/sampler cannot be used.
4008 // OpenCL v2.0 s6.13.16.1 - Pointer to pipe cannot be used.
4009 // OpenCL v2.0 s6.12.5 - Pointers to Blocks are not allowed.
4010 if (LangOpts.OpenCL) {
4011 if (T->isImageType() || T->isSamplerT() || T->isPipeType() ||
4012 T->isBlockPointerType()) {
4013 S.Diag(D.getIdentifierLoc(), diag::err_opencl_pointer_to_type) << T;
4014 D.setInvalidType(true);
4018 T = S.BuildPointerType(T, DeclType.Loc, Name);
4019 if (DeclType.Ptr.TypeQuals)
4020 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
4022 case DeclaratorChunk::Reference: {
4023 // Verify that we're not building a reference to pointer to function with
4024 // exception specification.
4025 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4026 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4027 D.setInvalidType(true);
4028 // Build the type anyway.
4030 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
4032 if (DeclType.Ref.HasRestrict)
4033 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
4036 case DeclaratorChunk::Array: {
4037 // Verify that we're not building an array of pointers to function with
4038 // exception specification.
4039 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
4040 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
4041 D.setInvalidType(true);
4042 // Build the type anyway.
4044 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
4045 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
4046 ArrayType::ArraySizeModifier ASM;
4048 ASM = ArrayType::Star;
4049 else if (ATI.hasStatic)
4050 ASM = ArrayType::Static;
4052 ASM = ArrayType::Normal;
4053 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
4054 // FIXME: This check isn't quite right: it allows star in prototypes
4055 // for function definitions, and disallows some edge cases detailed
4056 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
4057 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
4058 ASM = ArrayType::Normal;
4059 D.setInvalidType(true);
4062 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
4063 // shall appear only in a declaration of a function parameter with an
4065 if (ASM == ArrayType::Static || ATI.TypeQuals) {
4066 if (!(D.isPrototypeContext() ||
4067 D.getContext() == Declarator::KNRTypeListContext)) {
4068 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
4069 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4070 // Remove the 'static' and the type qualifiers.
4071 if (ASM == ArrayType::Static)
4072 ASM = ArrayType::Normal;
4074 D.setInvalidType(true);
4077 // C99 6.7.5.2p1: ... and then only in the outermost array type
4079 if (hasOuterPointerLikeChunk(D, chunkIndex)) {
4080 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
4081 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
4082 if (ASM == ArrayType::Static)
4083 ASM = ArrayType::Normal;
4085 D.setInvalidType(true);
4088 const AutoType *AT = T->getContainedAutoType();
4089 // Allow arrays of auto if we are a generic lambda parameter.
4090 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
4091 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
4092 // We've already diagnosed this for decltype(auto).
4093 if (!AT->isDecltypeAuto())
4094 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
4095 << getPrintableNameForEntity(Name) << T;
4100 // Array parameters can be marked nullable as well, although it's not
4101 // necessary if they're marked 'static'.
4102 if (complainAboutMissingNullability == CAMN_Yes &&
4103 !hasNullabilityAttr(DeclType.getAttrs()) &&
4104 ASM != ArrayType::Static &&
4105 D.isPrototypeContext() &&
4106 !hasOuterPointerLikeChunk(D, chunkIndex)) {
4107 checkNullabilityConsistency(S, SimplePointerKind::Array, DeclType.Loc);
4110 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
4111 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
4114 case DeclaratorChunk::Function: {
4115 // If the function declarator has a prototype (i.e. it is not () and
4116 // does not have a K&R-style identifier list), then the arguments are part
4117 // of the type, otherwise the argument list is ().
4118 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
4119 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
4121 // Check for auto functions and trailing return type and adjust the
4122 // return type accordingly.
4123 if (!D.isInvalidType()) {
4124 // trailing-return-type is only required if we're declaring a function,
4125 // and not, for instance, a pointer to a function.
4126 if (D.getDeclSpec().containsPlaceholderType() &&
4127 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
4128 !S.getLangOpts().CPlusPlus14) {
4129 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4130 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
4131 ? diag::err_auto_missing_trailing_return
4132 : diag::err_deduced_return_type);
4134 D.setInvalidType(true);
4135 } else if (FTI.hasTrailingReturnType()) {
4136 // T must be exactly 'auto' at this point. See CWG issue 681.
4137 if (isa<ParenType>(T)) {
4138 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4139 diag::err_trailing_return_in_parens)
4140 << T << D.getDeclSpec().getSourceRange();
4141 D.setInvalidType(true);
4142 } else if (D.getContext() != Declarator::LambdaExprContext &&
4143 (T.hasQualifiers() || !isa<AutoType>(T) ||
4144 cast<AutoType>(T)->getKeyword() != AutoTypeKeyword::Auto)) {
4145 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
4146 diag::err_trailing_return_without_auto)
4147 << T << D.getDeclSpec().getSourceRange();
4148 D.setInvalidType(true);
4150 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
4152 // An error occurred parsing the trailing return type.
4154 D.setInvalidType(true);
4159 // C99 6.7.5.3p1: The return type may not be a function or array type.
4160 // For conversion functions, we'll diagnose this particular error later.
4161 if ((T->isArrayType() || T->isFunctionType()) &&
4162 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
4163 unsigned diagID = diag::err_func_returning_array_function;
4164 // Last processing chunk in block context means this function chunk
4165 // represents the block.
4166 if (chunkIndex == 0 &&
4167 D.getContext() == Declarator::BlockLiteralContext)
4168 diagID = diag::err_block_returning_array_function;
4169 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
4171 D.setInvalidType(true);
4174 // Do not allow returning half FP value.
4175 // FIXME: This really should be in BuildFunctionType.
4176 if (T->isHalfType()) {
4177 if (S.getLangOpts().OpenCL) {
4178 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4179 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4180 << T << 0 /*pointer hint*/;
4181 D.setInvalidType(true);
4183 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4184 S.Diag(D.getIdentifierLoc(),
4185 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
4186 D.setInvalidType(true);
4190 if (LangOpts.OpenCL) {
4191 // OpenCL v2.0 s6.12.5 - A block cannot be the return value of a
4193 if (T->isBlockPointerType() || T->isImageType() || T->isSamplerT() ||
4195 S.Diag(D.getIdentifierLoc(), diag::err_opencl_invalid_return)
4196 << T << 1 /*hint off*/;
4197 D.setInvalidType(true);
4199 // OpenCL doesn't support variadic functions and blocks
4200 // (s6.9.e and s6.12.5 OpenCL v2.0) except for printf.
4201 // We also allow here any toolchain reserved identifiers.
4202 if (FTI.isVariadic &&
4203 !(D.getIdentifier() &&
4204 ((D.getIdentifier()->getName() == "printf" &&
4205 LangOpts.OpenCLVersion >= 120) ||
4206 D.getIdentifier()->getName().startswith("__")))) {
4207 S.Diag(D.getIdentifierLoc(), diag::err_opencl_variadic_function);
4208 D.setInvalidType(true);
4212 // Methods cannot return interface types. All ObjC objects are
4213 // passed by reference.
4214 if (T->isObjCObjectType()) {
4215 SourceLocation DiagLoc, FixitLoc;
4217 DiagLoc = TInfo->getTypeLoc().getLocStart();
4218 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
4220 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
4221 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
4223 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
4225 << FixItHint::CreateInsertion(FixitLoc, "*");
4227 T = Context.getObjCObjectPointerType(T);
4230 TLB.pushFullCopy(TInfo->getTypeLoc());
4231 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
4232 TLoc.setStarLoc(FixitLoc);
4233 TInfo = TLB.getTypeSourceInfo(Context, T);
4236 D.setInvalidType(true);
4239 // cv-qualifiers on return types are pointless except when the type is a
4240 // class type in C++.
4241 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
4242 !(S.getLangOpts().CPlusPlus &&
4243 (T->isDependentType() || T->isRecordType()))) {
4244 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
4245 D.getFunctionDefinitionKind() == FDK_Definition) {
4246 // [6.9.1/3] qualified void return is invalid on a C
4247 // function definition. Apparently ok on declarations and
4248 // in C++ though (!)
4249 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
4251 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
4254 // Objective-C ARC ownership qualifiers are ignored on the function
4255 // return type (by type canonicalization). Complain if this attribute
4256 // was written here.
4257 if (T.getQualifiers().hasObjCLifetime()) {
4258 SourceLocation AttrLoc;
4259 if (chunkIndex + 1 < D.getNumTypeObjects()) {
4260 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
4261 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
4262 Attr; Attr = Attr->getNext()) {
4263 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4264 AttrLoc = Attr->getLoc();
4269 if (AttrLoc.isInvalid()) {
4270 for (const AttributeList *Attr
4271 = D.getDeclSpec().getAttributes().getList();
4272 Attr; Attr = Attr->getNext()) {
4273 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
4274 AttrLoc = Attr->getLoc();
4280 if (AttrLoc.isValid()) {
4281 // The ownership attributes are almost always written via
4283 // __strong/__weak/__autoreleasing/__unsafe_unretained.
4284 if (AttrLoc.isMacroID())
4285 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
4287 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
4288 << T.getQualifiers().getObjCLifetime();
4292 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
4294 // Types shall not be defined in return or parameter types.
4295 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
4296 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
4297 << Context.getTypeDeclType(Tag);
4300 // Exception specs are not allowed in typedefs. Complain, but add it
4302 if (IsTypedefName && FTI.getExceptionSpecType() && !LangOpts.CPlusPlus1z)
4303 S.Diag(FTI.getExceptionSpecLocBeg(),
4304 diag::err_exception_spec_in_typedef)
4305 << (D.getContext() == Declarator::AliasDeclContext ||
4306 D.getContext() == Declarator::AliasTemplateContext);
4308 // If we see "T var();" or "T var(T());" at block scope, it is probably
4309 // an attempt to initialize a variable, not a function declaration.
4310 if (FTI.isAmbiguous)
4311 warnAboutAmbiguousFunction(S, D, DeclType, T);
4313 // GNU warning -Wstrict-prototypes
4314 // Warn if a function declaration is without a prototype.
4315 // This warning is issued for all kinds of unprototyped function
4316 // declarations (i.e. function type typedef, function pointer etc.)
4318 // The empty list in a function declarator that is not part of a
4319 // definition of that function specifies that no information
4320 // about the number or types of the parameters is supplied.
4321 if (D.getFunctionDefinitionKind() == FDK_Declaration &&
4322 FTI.NumParams == 0 && !LangOpts.CPlusPlus)
4323 S.Diag(DeclType.Loc, diag::warn_strict_prototypes)
4324 << 0 << FixItHint::CreateInsertion(FTI.getRParenLoc(), "void");
4326 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
4328 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
4329 // Simple void foo(), where the incoming T is the result type.
4330 T = Context.getFunctionNoProtoType(T, EI);
4332 // We allow a zero-parameter variadic function in C if the
4333 // function is marked with the "overloadable" attribute. Scan
4334 // for this attribute now.
4335 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
4336 bool Overloadable = false;
4337 for (const AttributeList *Attrs = D.getAttributes();
4338 Attrs; Attrs = Attrs->getNext()) {
4339 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
4340 Overloadable = true;
4346 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
4349 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
4350 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
4352 S.Diag(FTI.Params[0].IdentLoc,
4353 diag::err_ident_list_in_fn_declaration);
4354 D.setInvalidType(true);
4355 // Recover by creating a K&R-style function type.
4356 T = Context.getFunctionNoProtoType(T, EI);
4360 FunctionProtoType::ExtProtoInfo EPI;
4362 EPI.Variadic = FTI.isVariadic;
4363 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
4364 EPI.TypeQuals = FTI.TypeQuals;
4365 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
4366 : FTI.RefQualifierIsLValueRef? RQ_LValue
4369 // Otherwise, we have a function with a parameter list that is
4370 // potentially variadic.
4371 SmallVector<QualType, 16> ParamTys;
4372 ParamTys.reserve(FTI.NumParams);
4374 SmallVector<FunctionProtoType::ExtParameterInfo, 16>
4375 ExtParameterInfos(FTI.NumParams);
4376 bool HasAnyInterestingExtParameterInfos = false;
4378 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
4379 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4380 QualType ParamTy = Param->getType();
4381 assert(!ParamTy.isNull() && "Couldn't parse type?");
4383 // Look for 'void'. void is allowed only as a single parameter to a
4384 // function with no other parameters (C99 6.7.5.3p10). We record
4385 // int(void) as a FunctionProtoType with an empty parameter list.
4386 if (ParamTy->isVoidType()) {
4387 // If this is something like 'float(int, void)', reject it. 'void'
4388 // is an incomplete type (C99 6.2.5p19) and function decls cannot
4389 // have parameters of incomplete type.
4390 if (FTI.NumParams != 1 || FTI.isVariadic) {
4391 S.Diag(DeclType.Loc, diag::err_void_only_param);
4392 ParamTy = Context.IntTy;
4393 Param->setType(ParamTy);
4394 } else if (FTI.Params[i].Ident) {
4395 // Reject, but continue to parse 'int(void abc)'.
4396 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
4397 ParamTy = Context.IntTy;
4398 Param->setType(ParamTy);
4400 // Reject, but continue to parse 'float(const void)'.
4401 if (ParamTy.hasQualifiers())
4402 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
4404 // Do not add 'void' to the list.
4407 } else if (ParamTy->isHalfType()) {
4408 // Disallow half FP parameters.
4409 // FIXME: This really should be in BuildFunctionType.
4410 if (S.getLangOpts().OpenCL) {
4411 if (!S.getOpenCLOptions().isEnabled("cl_khr_fp16")) {
4412 S.Diag(Param->getLocation(),
4413 diag::err_opencl_half_param) << ParamTy;
4415 Param->setInvalidDecl();
4417 } else if (!S.getLangOpts().HalfArgsAndReturns) {
4418 S.Diag(Param->getLocation(),
4419 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
4422 } else if (!FTI.hasPrototype) {
4423 if (ParamTy->isPromotableIntegerType()) {
4424 ParamTy = Context.getPromotedIntegerType(ParamTy);
4425 Param->setKNRPromoted(true);
4426 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
4427 if (BTy->getKind() == BuiltinType::Float) {
4428 ParamTy = Context.DoubleTy;
4429 Param->setKNRPromoted(true);
4434 if (LangOpts.ObjCAutoRefCount && Param->hasAttr<NSConsumedAttr>()) {
4435 ExtParameterInfos[i] = ExtParameterInfos[i].withIsConsumed(true);
4436 HasAnyInterestingExtParameterInfos = true;
4439 if (auto attr = Param->getAttr<ParameterABIAttr>()) {
4440 ExtParameterInfos[i] =
4441 ExtParameterInfos[i].withABI(attr->getABI());
4442 HasAnyInterestingExtParameterInfos = true;
4445 ParamTys.push_back(ParamTy);
4448 if (HasAnyInterestingExtParameterInfos) {
4449 EPI.ExtParameterInfos = ExtParameterInfos.data();
4450 checkExtParameterInfos(S, ParamTys, EPI,
4451 [&](unsigned i) { return FTI.Params[i].Param->getLocation(); });
4454 SmallVector<QualType, 4> Exceptions;
4455 SmallVector<ParsedType, 2> DynamicExceptions;
4456 SmallVector<SourceRange, 2> DynamicExceptionRanges;
4457 Expr *NoexceptExpr = nullptr;
4459 if (FTI.getExceptionSpecType() == EST_Dynamic) {
4460 // FIXME: It's rather inefficient to have to split into two vectors
4462 unsigned N = FTI.getNumExceptions();
4463 DynamicExceptions.reserve(N);
4464 DynamicExceptionRanges.reserve(N);
4465 for (unsigned I = 0; I != N; ++I) {
4466 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
4467 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
4469 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
4470 NoexceptExpr = FTI.NoexceptExpr;
4473 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
4474 FTI.getExceptionSpecType(),
4476 DynamicExceptionRanges,
4481 T = Context.getFunctionType(T, ParamTys, EPI);
4485 case DeclaratorChunk::MemberPointer: {
4486 // The scope spec must refer to a class, or be dependent.
4487 CXXScopeSpec &SS = DeclType.Mem.Scope();
4490 // Handle pointer nullability.
4491 inferPointerNullability(SimplePointerKind::MemberPointer,
4492 DeclType.Loc, DeclType.getAttrListRef());
4494 if (SS.isInvalid()) {
4495 // Avoid emitting extra errors if we already errored on the scope.
4496 D.setInvalidType(true);
4497 } else if (S.isDependentScopeSpecifier(SS) ||
4498 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
4499 NestedNameSpecifier *NNS = SS.getScopeRep();
4500 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
4501 switch (NNS->getKind()) {
4502 case NestedNameSpecifier::Identifier:
4503 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
4504 NNS->getAsIdentifier());
4507 case NestedNameSpecifier::Namespace:
4508 case NestedNameSpecifier::NamespaceAlias:
4509 case NestedNameSpecifier::Global:
4510 case NestedNameSpecifier::Super:
4511 llvm_unreachable("Nested-name-specifier must name a type");
4513 case NestedNameSpecifier::TypeSpec:
4514 case NestedNameSpecifier::TypeSpecWithTemplate:
4515 ClsType = QualType(NNS->getAsType(), 0);
4516 // Note: if the NNS has a prefix and ClsType is a nondependent
4517 // TemplateSpecializationType, then the NNS prefix is NOT included
4518 // in ClsType; hence we wrap ClsType into an ElaboratedType.
4519 // NOTE: in particular, no wrap occurs if ClsType already is an
4520 // Elaborated, DependentName, or DependentTemplateSpecialization.
4521 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
4522 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
4526 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
4527 diag::err_illegal_decl_mempointer_in_nonclass)
4528 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
4529 << DeclType.Mem.Scope().getRange();
4530 D.setInvalidType(true);
4533 if (!ClsType.isNull())
4534 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
4538 D.setInvalidType(true);
4539 } else if (DeclType.Mem.TypeQuals) {
4540 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
4545 case DeclaratorChunk::Pipe: {
4546 T = S.BuildReadPipeType(T, DeclType.Loc);
4547 processTypeAttrs(state, T, TAL_DeclSpec,
4548 D.getDeclSpec().getAttributes().getList());
4554 D.setInvalidType(true);
4558 // See if there are any attributes on this declarator chunk.
4559 processTypeAttrs(state, T, TAL_DeclChunk,
4560 const_cast<AttributeList *>(DeclType.getAttrs()));
4563 assert(!T.isNull() && "T must not be null after this point");
4565 if (LangOpts.CPlusPlus && T->isFunctionType()) {
4566 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
4567 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
4570 // A cv-qualifier-seq shall only be part of the function type
4571 // for a nonstatic member function, the function type to which a pointer
4572 // to member refers, or the top-level function type of a function typedef
4575 // Core issue 547 also allows cv-qualifiers on function types that are
4576 // top-level template type arguments.
4578 if (!D.getCXXScopeSpec().isSet()) {
4579 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
4580 D.getContext() != Declarator::LambdaExprContext) ||
4581 D.getDeclSpec().isFriendSpecified());
4583 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
4584 FreeFunction = (DC && !DC->isRecord());
4587 // C++11 [dcl.fct]p6 (w/DR1417):
4588 // An attempt to specify a function type with a cv-qualifier-seq or a
4589 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
4590 // - the function type for a non-static member function,
4591 // - the function type to which a pointer to member refers,
4592 // - the top-level function type of a function typedef declaration or
4593 // alias-declaration,
4594 // - the type-id in the default argument of a type-parameter, or
4595 // - the type-id of a template-argument for a type-parameter
4597 // FIXME: Checking this here is insufficient. We accept-invalid on:
4599 // template<typename T> struct S { void f(T); };
4600 // S<int() const> s;
4602 // ... for instance.
4603 if (IsQualifiedFunction &&
4605 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
4607 D.getContext() != Declarator::TemplateTypeArgContext) {
4608 SourceLocation Loc = D.getLocStart();
4609 SourceRange RemovalRange;
4611 if (D.isFunctionDeclarator(I)) {
4612 SmallVector<SourceLocation, 4> RemovalLocs;
4613 const DeclaratorChunk &Chunk = D.getTypeObject(I);
4614 assert(Chunk.Kind == DeclaratorChunk::Function);
4615 if (Chunk.Fun.hasRefQualifier())
4616 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
4617 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
4618 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
4619 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
4620 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
4621 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
4622 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
4623 if (!RemovalLocs.empty()) {
4624 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
4625 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
4626 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
4627 Loc = RemovalLocs.front();
4631 S.Diag(Loc, diag::err_invalid_qualified_function_type)
4632 << FreeFunction << D.isFunctionDeclarator() << T
4633 << getFunctionQualifiersAsString(FnTy)
4634 << FixItHint::CreateRemoval(RemovalRange);
4636 // Strip the cv-qualifiers and ref-qualifiers from the type.
4637 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
4639 EPI.RefQualifier = RQ_None;
4641 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
4643 // Rebuild any parens around the identifier in the function type.
4644 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4645 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
4647 T = S.BuildParenType(T);
4652 // Apply any undistributed attributes from the declarator.
4653 processTypeAttrs(state, T, TAL_DeclName, D.getAttributes());
4655 // Diagnose any ignored type attributes.
4656 state.diagnoseIgnoredTypeAttrs(T);
4658 // C++0x [dcl.constexpr]p9:
4659 // A constexpr specifier used in an object declaration declares the object
4661 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
4665 // If there was an ellipsis in the declarator, the declaration declares a
4666 // parameter pack whose type may be a pack expansion type.
4667 if (D.hasEllipsis()) {
4668 // C++0x [dcl.fct]p13:
4669 // A declarator-id or abstract-declarator containing an ellipsis shall
4670 // only be used in a parameter-declaration. Such a parameter-declaration
4671 // is a parameter pack (14.5.3). [...]
4672 switch (D.getContext()) {
4673 case Declarator::PrototypeContext:
4674 case Declarator::LambdaExprParameterContext:
4675 // C++0x [dcl.fct]p13:
4676 // [...] When it is part of a parameter-declaration-clause, the
4677 // parameter pack is a function parameter pack (14.5.3). The type T
4678 // of the declarator-id of the function parameter pack shall contain
4679 // a template parameter pack; each template parameter pack in T is
4680 // expanded by the function parameter pack.
4682 // We represent function parameter packs as function parameters whose
4683 // type is a pack expansion.
4684 if (!T->containsUnexpandedParameterPack()) {
4685 S.Diag(D.getEllipsisLoc(),
4686 diag::err_function_parameter_pack_without_parameter_packs)
4687 << T << D.getSourceRange();
4688 D.setEllipsisLoc(SourceLocation());
4690 T = Context.getPackExpansionType(T, None);
4693 case Declarator::TemplateParamContext:
4694 // C++0x [temp.param]p15:
4695 // If a template-parameter is a [...] is a parameter-declaration that
4696 // declares a parameter pack (8.3.5), then the template-parameter is a
4697 // template parameter pack (14.5.3).
4699 // Note: core issue 778 clarifies that, if there are any unexpanded
4700 // parameter packs in the type of the non-type template parameter, then
4701 // it expands those parameter packs.
4702 if (T->containsUnexpandedParameterPack())
4703 T = Context.getPackExpansionType(T, None);
4705 S.Diag(D.getEllipsisLoc(),
4706 LangOpts.CPlusPlus11
4707 ? diag::warn_cxx98_compat_variadic_templates
4708 : diag::ext_variadic_templates);
4711 case Declarator::FileContext:
4712 case Declarator::KNRTypeListContext:
4713 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
4714 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
4715 case Declarator::TypeNameContext:
4716 case Declarator::CXXNewContext:
4717 case Declarator::AliasDeclContext:
4718 case Declarator::AliasTemplateContext:
4719 case Declarator::MemberContext:
4720 case Declarator::BlockContext:
4721 case Declarator::ForContext:
4722 case Declarator::InitStmtContext:
4723 case Declarator::ConditionContext:
4724 case Declarator::CXXCatchContext:
4725 case Declarator::ObjCCatchContext:
4726 case Declarator::BlockLiteralContext:
4727 case Declarator::LambdaExprContext:
4728 case Declarator::ConversionIdContext:
4729 case Declarator::TrailingReturnContext:
4730 case Declarator::TemplateTypeArgContext:
4731 // FIXME: We may want to allow parameter packs in block-literal contexts
4733 S.Diag(D.getEllipsisLoc(),
4734 diag::err_ellipsis_in_declarator_not_parameter);
4735 D.setEllipsisLoc(SourceLocation());
4740 assert(!T.isNull() && "T must not be null at the end of this function");
4741 if (D.isInvalidType())
4742 return Context.getTrivialTypeSourceInfo(T);
4744 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
4747 /// GetTypeForDeclarator - Convert the type for the specified
4748 /// declarator to Type instances.
4750 /// The result of this call will never be null, but the associated
4751 /// type may be a null type if there's an unrecoverable error.
4752 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
4753 // Determine the type of the declarator. Not all forms of declarator
4756 TypeProcessingState state(*this, D);
4758 TypeSourceInfo *ReturnTypeInfo = nullptr;
4759 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4761 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
4762 inferARCWriteback(state, T);
4764 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
4767 static void transferARCOwnershipToDeclSpec(Sema &S,
4768 QualType &declSpecTy,
4769 Qualifiers::ObjCLifetime ownership) {
4770 if (declSpecTy->isObjCRetainableType() &&
4771 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
4773 qs.addObjCLifetime(ownership);
4774 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
4778 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
4779 Qualifiers::ObjCLifetime ownership,
4780 unsigned chunkIndex) {
4781 Sema &S = state.getSema();
4782 Declarator &D = state.getDeclarator();
4784 // Look for an explicit lifetime attribute.
4785 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
4786 for (const AttributeList *attr = chunk.getAttrs(); attr;
4787 attr = attr->getNext())
4788 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
4791 const char *attrStr = nullptr;
4792 switch (ownership) {
4793 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
4794 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
4795 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
4796 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
4797 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
4800 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
4801 Arg->Ident = &S.Context.Idents.get(attrStr);
4802 Arg->Loc = SourceLocation();
4804 ArgsUnion Args(Arg);
4806 // If there wasn't one, add one (with an invalid source location
4807 // so that we don't make an AttributedType for it).
4808 AttributeList *attr = D.getAttributePool()
4809 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
4810 /*scope*/ nullptr, SourceLocation(),
4811 /*args*/ &Args, 1, AttributeList::AS_GNU);
4812 spliceAttrIntoList(*attr, chunk.getAttrListRef());
4814 // TODO: mark whether we did this inference?
4817 /// \brief Used for transferring ownership in casts resulting in l-values.
4818 static void transferARCOwnership(TypeProcessingState &state,
4819 QualType &declSpecTy,
4820 Qualifiers::ObjCLifetime ownership) {
4821 Sema &S = state.getSema();
4822 Declarator &D = state.getDeclarator();
4825 bool hasIndirection = false;
4826 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4827 DeclaratorChunk &chunk = D.getTypeObject(i);
4828 switch (chunk.Kind) {
4829 case DeclaratorChunk::Paren:
4833 case DeclaratorChunk::Array:
4834 case DeclaratorChunk::Reference:
4835 case DeclaratorChunk::Pointer:
4837 hasIndirection = true;
4841 case DeclaratorChunk::BlockPointer:
4843 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
4846 case DeclaratorChunk::Function:
4847 case DeclaratorChunk::MemberPointer:
4848 case DeclaratorChunk::Pipe:
4856 DeclaratorChunk &chunk = D.getTypeObject(inner);
4857 if (chunk.Kind == DeclaratorChunk::Pointer) {
4858 if (declSpecTy->isObjCRetainableType())
4859 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4860 if (declSpecTy->isObjCObjectType() && hasIndirection)
4861 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
4863 assert(chunk.Kind == DeclaratorChunk::Array ||
4864 chunk.Kind == DeclaratorChunk::Reference);
4865 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
4869 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
4870 TypeProcessingState state(*this, D);
4872 TypeSourceInfo *ReturnTypeInfo = nullptr;
4873 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
4875 if (getLangOpts().ObjC1) {
4876 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4877 if (ownership != Qualifiers::OCL_None)
4878 transferARCOwnership(state, declSpecTy, ownership);
4881 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4884 /// Map an AttributedType::Kind to an AttributeList::Kind.
4885 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4887 case AttributedType::attr_address_space:
4888 return AttributeList::AT_AddressSpace;
4889 case AttributedType::attr_regparm:
4890 return AttributeList::AT_Regparm;
4891 case AttributedType::attr_vector_size:
4892 return AttributeList::AT_VectorSize;
4893 case AttributedType::attr_neon_vector_type:
4894 return AttributeList::AT_NeonVectorType;
4895 case AttributedType::attr_neon_polyvector_type:
4896 return AttributeList::AT_NeonPolyVectorType;
4897 case AttributedType::attr_objc_gc:
4898 return AttributeList::AT_ObjCGC;
4899 case AttributedType::attr_objc_ownership:
4900 case AttributedType::attr_objc_inert_unsafe_unretained:
4901 return AttributeList::AT_ObjCOwnership;
4902 case AttributedType::attr_noreturn:
4903 return AttributeList::AT_NoReturn;
4904 case AttributedType::attr_cdecl:
4905 return AttributeList::AT_CDecl;
4906 case AttributedType::attr_fastcall:
4907 return AttributeList::AT_FastCall;
4908 case AttributedType::attr_stdcall:
4909 return AttributeList::AT_StdCall;
4910 case AttributedType::attr_thiscall:
4911 return AttributeList::AT_ThisCall;
4912 case AttributedType::attr_regcall:
4913 return AttributeList::AT_RegCall;
4914 case AttributedType::attr_pascal:
4915 return AttributeList::AT_Pascal;
4916 case AttributedType::attr_swiftcall:
4917 return AttributeList::AT_SwiftCall;
4918 case AttributedType::attr_vectorcall:
4919 return AttributeList::AT_VectorCall;
4920 case AttributedType::attr_pcs:
4921 case AttributedType::attr_pcs_vfp:
4922 return AttributeList::AT_Pcs;
4923 case AttributedType::attr_inteloclbicc:
4924 return AttributeList::AT_IntelOclBicc;
4925 case AttributedType::attr_ms_abi:
4926 return AttributeList::AT_MSABI;
4927 case AttributedType::attr_sysv_abi:
4928 return AttributeList::AT_SysVABI;
4929 case AttributedType::attr_preserve_most:
4930 return AttributeList::AT_PreserveMost;
4931 case AttributedType::attr_preserve_all:
4932 return AttributeList::AT_PreserveAll;
4933 case AttributedType::attr_ptr32:
4934 return AttributeList::AT_Ptr32;
4935 case AttributedType::attr_ptr64:
4936 return AttributeList::AT_Ptr64;
4937 case AttributedType::attr_sptr:
4938 return AttributeList::AT_SPtr;
4939 case AttributedType::attr_uptr:
4940 return AttributeList::AT_UPtr;
4941 case AttributedType::attr_nonnull:
4942 return AttributeList::AT_TypeNonNull;
4943 case AttributedType::attr_nullable:
4944 return AttributeList::AT_TypeNullable;
4945 case AttributedType::attr_null_unspecified:
4946 return AttributeList::AT_TypeNullUnspecified;
4947 case AttributedType::attr_objc_kindof:
4948 return AttributeList::AT_ObjCKindOf;
4950 llvm_unreachable("unexpected attribute kind!");
4953 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4954 const AttributeList *attrs,
4955 const AttributeList *DeclAttrs = nullptr) {
4956 // DeclAttrs and attrs cannot be both empty.
4957 assert((attrs || DeclAttrs) &&
4958 "no type attributes in the expected location!");
4960 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4961 // Try to search for an attribute of matching kind in attrs list.
4962 while (attrs && attrs->getKind() != parsedKind)
4963 attrs = attrs->getNext();
4965 // No matching type attribute in attrs list found.
4966 // Try searching through C++11 attributes in the declarator attribute list.
4967 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4968 DeclAttrs->getKind() != parsedKind))
4969 DeclAttrs = DeclAttrs->getNext();
4973 assert(attrs && "no matching type attribute in expected location!");
4975 TL.setAttrNameLoc(attrs->getLoc());
4976 if (TL.hasAttrExprOperand()) {
4977 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4978 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4979 } else if (TL.hasAttrEnumOperand()) {
4980 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4981 "unexpected attribute operand kind");
4982 if (attrs->isArgIdent(0))
4983 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4985 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4988 // FIXME: preserve this information to here.
4989 if (TL.hasAttrOperand())
4990 TL.setAttrOperandParensRange(SourceRange());
4994 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4995 ASTContext &Context;
4999 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
5000 : Context(Context), DS(DS) {}
5002 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5003 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
5004 Visit(TL.getModifiedLoc());
5006 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5007 Visit(TL.getUnqualifiedLoc());
5009 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
5010 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5012 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
5013 TL.setNameLoc(DS.getTypeSpecTypeLoc());
5014 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
5015 // addition field. What we have is good enough for dispay of location
5016 // of 'fixit' on interface name.
5017 TL.setNameEndLoc(DS.getLocEnd());
5019 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
5020 TypeSourceInfo *RepTInfo = nullptr;
5021 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5022 TL.copy(RepTInfo->getTypeLoc());
5024 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5025 TypeSourceInfo *RepTInfo = nullptr;
5026 Sema::GetTypeFromParser(DS.getRepAsType(), &RepTInfo);
5027 TL.copy(RepTInfo->getTypeLoc());
5029 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
5030 TypeSourceInfo *TInfo = nullptr;
5031 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5033 // If we got no declarator info from previous Sema routines,
5034 // just fill with the typespec loc.
5036 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
5040 TypeLoc OldTL = TInfo->getTypeLoc();
5041 if (TInfo->getType()->getAs<ElaboratedType>()) {
5042 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
5043 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
5044 .castAs<TemplateSpecializationTypeLoc>();
5047 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
5048 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
5052 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
5053 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
5054 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5055 TL.setParensRange(DS.getTypeofParensRange());
5057 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
5058 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
5059 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
5060 TL.setParensRange(DS.getTypeofParensRange());
5061 assert(DS.getRepAsType());
5062 TypeSourceInfo *TInfo = nullptr;
5063 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5064 TL.setUnderlyingTInfo(TInfo);
5066 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
5067 // FIXME: This holds only because we only have one unary transform.
5068 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
5069 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5070 TL.setParensRange(DS.getTypeofParensRange());
5071 assert(DS.getRepAsType());
5072 TypeSourceInfo *TInfo = nullptr;
5073 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5074 TL.setUnderlyingTInfo(TInfo);
5076 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
5077 // By default, use the source location of the type specifier.
5078 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
5079 if (TL.needsExtraLocalData()) {
5080 // Set info for the written builtin specifiers.
5081 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
5082 // Try to have a meaningful source location.
5083 if (TL.getWrittenSignSpec() != TSS_unspecified)
5084 TL.expandBuiltinRange(DS.getTypeSpecSignLoc());
5085 if (TL.getWrittenWidthSpec() != TSW_unspecified)
5086 TL.expandBuiltinRange(DS.getTypeSpecWidthRange());
5089 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
5090 ElaboratedTypeKeyword Keyword
5091 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
5092 if (DS.getTypeSpecType() == TST_typename) {
5093 TypeSourceInfo *TInfo = nullptr;
5094 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5096 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
5100 TL.setElaboratedKeywordLoc(Keyword != ETK_None
5101 ? DS.getTypeSpecTypeLoc()
5102 : SourceLocation());
5103 const CXXScopeSpec& SS = DS.getTypeSpecScope();
5104 TL.setQualifierLoc(SS.getWithLocInContext(Context));
5105 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
5107 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
5108 assert(DS.getTypeSpecType() == TST_typename);
5109 TypeSourceInfo *TInfo = nullptr;
5110 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5112 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
5114 void VisitDependentTemplateSpecializationTypeLoc(
5115 DependentTemplateSpecializationTypeLoc TL) {
5116 assert(DS.getTypeSpecType() == TST_typename);
5117 TypeSourceInfo *TInfo = nullptr;
5118 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5121 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
5123 void VisitTagTypeLoc(TagTypeLoc TL) {
5124 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
5126 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
5127 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
5128 // or an _Atomic qualifier.
5129 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
5130 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5131 TL.setParensRange(DS.getTypeofParensRange());
5133 TypeSourceInfo *TInfo = nullptr;
5134 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5136 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5138 TL.setKWLoc(DS.getAtomicSpecLoc());
5139 // No parens, to indicate this was spelled as an _Atomic qualifier.
5140 TL.setParensRange(SourceRange());
5141 Visit(TL.getValueLoc());
5145 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5146 TL.setKWLoc(DS.getTypeSpecTypeLoc());
5148 TypeSourceInfo *TInfo = nullptr;
5149 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
5150 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
5153 void VisitTypeLoc(TypeLoc TL) {
5154 // FIXME: add other typespec types and change this to an assert.
5155 TL.initialize(Context, DS.getTypeSpecTypeLoc());
5159 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
5160 ASTContext &Context;
5161 const DeclaratorChunk &Chunk;
5164 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
5165 : Context(Context), Chunk(Chunk) {}
5167 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
5168 llvm_unreachable("qualified type locs not expected here!");
5170 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
5171 llvm_unreachable("decayed type locs not expected here!");
5174 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
5175 fillAttributedTypeLoc(TL, Chunk.getAttrs());
5177 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
5180 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
5181 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
5182 TL.setCaretLoc(Chunk.Loc);
5184 void VisitPointerTypeLoc(PointerTypeLoc TL) {
5185 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5186 TL.setStarLoc(Chunk.Loc);
5188 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
5189 assert(Chunk.Kind == DeclaratorChunk::Pointer);
5190 TL.setStarLoc(Chunk.Loc);
5192 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
5193 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
5194 const CXXScopeSpec& SS = Chunk.Mem.Scope();
5195 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
5197 const Type* ClsTy = TL.getClass();
5198 QualType ClsQT = QualType(ClsTy, 0);
5199 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
5200 // Now copy source location info into the type loc component.
5201 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
5202 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
5203 case NestedNameSpecifier::Identifier:
5204 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
5206 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
5207 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
5208 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
5209 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
5213 case NestedNameSpecifier::TypeSpec:
5214 case NestedNameSpecifier::TypeSpecWithTemplate:
5215 if (isa<ElaboratedType>(ClsTy)) {
5216 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
5217 ETLoc.setElaboratedKeywordLoc(SourceLocation());
5218 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
5219 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
5220 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
5222 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
5226 case NestedNameSpecifier::Namespace:
5227 case NestedNameSpecifier::NamespaceAlias:
5228 case NestedNameSpecifier::Global:
5229 case NestedNameSpecifier::Super:
5230 llvm_unreachable("Nested-name-specifier must name a type");
5233 // Finally fill in MemberPointerLocInfo fields.
5234 TL.setStarLoc(Chunk.Loc);
5235 TL.setClassTInfo(ClsTInfo);
5237 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
5238 assert(Chunk.Kind == DeclaratorChunk::Reference);
5239 // 'Amp' is misleading: this might have been originally
5240 /// spelled with AmpAmp.
5241 TL.setAmpLoc(Chunk.Loc);
5243 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
5244 assert(Chunk.Kind == DeclaratorChunk::Reference);
5245 assert(!Chunk.Ref.LValueRef);
5246 TL.setAmpAmpLoc(Chunk.Loc);
5248 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
5249 assert(Chunk.Kind == DeclaratorChunk::Array);
5250 TL.setLBracketLoc(Chunk.Loc);
5251 TL.setRBracketLoc(Chunk.EndLoc);
5252 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
5254 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
5255 assert(Chunk.Kind == DeclaratorChunk::Function);
5256 TL.setLocalRangeBegin(Chunk.Loc);
5257 TL.setLocalRangeEnd(Chunk.EndLoc);
5259 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
5260 TL.setLParenLoc(FTI.getLParenLoc());
5261 TL.setRParenLoc(FTI.getRParenLoc());
5262 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
5263 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
5264 TL.setParam(tpi++, Param);
5266 TL.setExceptionSpecRange(FTI.getExceptionSpecRange());
5268 void VisitParenTypeLoc(ParenTypeLoc TL) {
5269 assert(Chunk.Kind == DeclaratorChunk::Paren);
5270 TL.setLParenLoc(Chunk.Loc);
5271 TL.setRParenLoc(Chunk.EndLoc);
5273 void VisitPipeTypeLoc(PipeTypeLoc TL) {
5274 assert(Chunk.Kind == DeclaratorChunk::Pipe);
5275 TL.setKWLoc(Chunk.Loc);
5278 void VisitTypeLoc(TypeLoc TL) {
5279 llvm_unreachable("unsupported TypeLoc kind in declarator!");
5282 } // end anonymous namespace
5284 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
5286 switch (Chunk.Kind) {
5287 case DeclaratorChunk::Function:
5288 case DeclaratorChunk::Array:
5289 case DeclaratorChunk::Paren:
5290 case DeclaratorChunk::Pipe:
5291 llvm_unreachable("cannot be _Atomic qualified");
5293 case DeclaratorChunk::Pointer:
5294 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
5297 case DeclaratorChunk::BlockPointer:
5298 case DeclaratorChunk::Reference:
5299 case DeclaratorChunk::MemberPointer:
5300 // FIXME: Provide a source location for the _Atomic keyword.
5305 ATL.setParensRange(SourceRange());
5308 /// \brief Create and instantiate a TypeSourceInfo with type source information.
5310 /// \param T QualType referring to the type as written in source code.
5312 /// \param ReturnTypeInfo For declarators whose return type does not show
5313 /// up in the normal place in the declaration specifiers (such as a C++
5314 /// conversion function), this pointer will refer to a type source information
5315 /// for that return type.
5317 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
5318 TypeSourceInfo *ReturnTypeInfo) {
5319 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
5320 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
5321 const AttributeList *DeclAttrs = D.getAttributes();
5323 // Handle parameter packs whose type is a pack expansion.
5324 if (isa<PackExpansionType>(T)) {
5325 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
5326 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5329 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
5330 // An AtomicTypeLoc might be produced by an atomic qualifier in this
5331 // declarator chunk.
5332 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
5333 fillAtomicQualLoc(ATL, D.getTypeObject(i));
5334 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
5337 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
5338 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
5339 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5342 // FIXME: Ordering here?
5343 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
5344 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
5346 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
5347 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
5350 // If we have different source information for the return type, use
5351 // that. This really only applies to C++ conversion functions.
5352 if (ReturnTypeInfo) {
5353 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
5354 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
5355 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
5357 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
5363 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
5364 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
5365 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
5366 // and Sema during declaration parsing. Try deallocating/caching them when
5367 // it's appropriate, instead of allocating them and keeping them around.
5368 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
5370 new (LocT) LocInfoType(T, TInfo);
5371 assert(LocT->getTypeClass() != T->getTypeClass() &&
5372 "LocInfoType's TypeClass conflicts with an existing Type class");
5373 return ParsedType::make(QualType(LocT, 0));
5376 void LocInfoType::getAsStringInternal(std::string &Str,
5377 const PrintingPolicy &Policy) const {
5378 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
5379 " was used directly instead of getting the QualType through"
5380 " GetTypeFromParser");
5383 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
5384 // C99 6.7.6: Type names have no identifier. This is already validated by
5386 assert(D.getIdentifier() == nullptr &&
5387 "Type name should have no identifier!");
5389 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5390 QualType T = TInfo->getType();
5391 if (D.isInvalidType())
5394 // Make sure there are no unused decl attributes on the declarator.
5395 // We don't want to do this for ObjC parameters because we're going
5396 // to apply them to the actual parameter declaration.
5397 // Likewise, we don't want to do this for alias declarations, because
5398 // we are actually going to build a declaration from this eventually.
5399 if (D.getContext() != Declarator::ObjCParameterContext &&
5400 D.getContext() != Declarator::AliasDeclContext &&
5401 D.getContext() != Declarator::AliasTemplateContext)
5402 checkUnusedDeclAttributes(D);
5404 if (getLangOpts().CPlusPlus) {
5405 // Check that there are no default arguments (C++ only).
5406 CheckExtraCXXDefaultArguments(D);
5409 return CreateParsedType(T, TInfo);
5412 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
5413 QualType T = Context.getObjCInstanceType();
5414 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
5415 return CreateParsedType(T, TInfo);
5418 //===----------------------------------------------------------------------===//
5419 // Type Attribute Processing
5420 //===----------------------------------------------------------------------===//
5422 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
5423 /// specified type. The attribute contains 1 argument, the id of the address
5424 /// space for the type.
5425 static void HandleAddressSpaceTypeAttribute(QualType &Type,
5426 const AttributeList &Attr, Sema &S){
5428 // If this type is already address space qualified, reject it.
5429 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
5430 // qualifiers for two or more different address spaces."
5431 if (Type.getAddressSpace()) {
5432 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
5437 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
5438 // qualified by an address-space qualifier."
5439 if (Type->isFunctionType()) {
5440 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
5446 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
5447 // Check the attribute arguments.
5448 if (Attr.getNumArgs() != 1) {
5449 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5450 << Attr.getName() << 1;
5454 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5455 llvm::APSInt addrSpace(32);
5456 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
5457 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
5458 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5459 << Attr.getName() << AANT_ArgumentIntegerConstant
5460 << ASArgExpr->getSourceRange();
5466 if (addrSpace.isSigned()) {
5467 if (addrSpace.isNegative()) {
5468 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
5469 << ASArgExpr->getSourceRange();
5473 addrSpace.setIsSigned(false);
5475 llvm::APSInt max(addrSpace.getBitWidth());
5476 max = Qualifiers::MaxAddressSpace;
5477 if (addrSpace > max) {
5478 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
5479 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
5483 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
5485 // The keyword-based type attributes imply which address space to use.
5486 switch (Attr.getKind()) {
5487 case AttributeList::AT_OpenCLGlobalAddressSpace:
5488 ASIdx = LangAS::opencl_global; break;
5489 case AttributeList::AT_OpenCLLocalAddressSpace:
5490 ASIdx = LangAS::opencl_local; break;
5491 case AttributeList::AT_OpenCLConstantAddressSpace:
5492 ASIdx = LangAS::opencl_constant; break;
5493 case AttributeList::AT_OpenCLGenericAddressSpace:
5494 ASIdx = LangAS::opencl_generic; break;
5496 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
5501 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
5504 /// Does this type have a "direct" ownership qualifier? That is,
5505 /// is it written like "__strong id", as opposed to something like
5506 /// "typeof(foo)", where that happens to be strong?
5507 static bool hasDirectOwnershipQualifier(QualType type) {
5508 // Fast path: no qualifier at all.
5509 assert(type.getQualifiers().hasObjCLifetime());
5513 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
5514 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
5517 type = attr->getModifiedType();
5519 // X *__strong (...)
5520 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
5521 type = paren->getInnerType();
5523 // That's it for things we want to complain about. In particular,
5524 // we do not want to look through typedefs, typeof(expr),
5525 // typeof(type), or any other way that the type is somehow
5534 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
5535 /// attribute on the specified type.
5537 /// Returns 'true' if the attribute was handled.
5538 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
5539 AttributeList &attr,
5541 bool NonObjCPointer = false;
5543 if (!type->isDependentType() && !type->isUndeducedType()) {
5544 if (const PointerType *ptr = type->getAs<PointerType>()) {
5545 QualType pointee = ptr->getPointeeType();
5546 if (pointee->isObjCRetainableType() || pointee->isPointerType())
5548 // It is important not to lose the source info that there was an attribute
5549 // applied to non-objc pointer. We will create an attributed type but
5550 // its type will be the same as the original type.
5551 NonObjCPointer = true;
5552 } else if (!type->isObjCRetainableType()) {
5556 // Don't accept an ownership attribute in the declspec if it would
5557 // just be the return type of a block pointer.
5558 if (state.isProcessingDeclSpec()) {
5559 Declarator &D = state.getDeclarator();
5560 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
5561 /*onlyBlockPointers=*/true))
5566 Sema &S = state.getSema();
5567 SourceLocation AttrLoc = attr.getLoc();
5568 if (AttrLoc.isMacroID())
5569 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
5571 if (!attr.isArgIdent(0)) {
5572 S.Diag(AttrLoc, diag::err_attribute_argument_type)
5573 << attr.getName() << AANT_ArgumentString;
5578 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5579 Qualifiers::ObjCLifetime lifetime;
5580 if (II->isStr("none"))
5581 lifetime = Qualifiers::OCL_ExplicitNone;
5582 else if (II->isStr("strong"))
5583 lifetime = Qualifiers::OCL_Strong;
5584 else if (II->isStr("weak"))
5585 lifetime = Qualifiers::OCL_Weak;
5586 else if (II->isStr("autoreleasing"))
5587 lifetime = Qualifiers::OCL_Autoreleasing;
5589 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
5590 << attr.getName() << II;
5595 // Just ignore lifetime attributes other than __weak and __unsafe_unretained
5596 // outside of ARC mode.
5597 if (!S.getLangOpts().ObjCAutoRefCount &&
5598 lifetime != Qualifiers::OCL_Weak &&
5599 lifetime != Qualifiers::OCL_ExplicitNone) {
5603 SplitQualType underlyingType = type.split();
5605 // Check for redundant/conflicting ownership qualifiers.
5606 if (Qualifiers::ObjCLifetime previousLifetime
5607 = type.getQualifiers().getObjCLifetime()) {
5608 // If it's written directly, that's an error.
5609 if (hasDirectOwnershipQualifier(type)) {
5610 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
5615 // Otherwise, if the qualifiers actually conflict, pull sugar off
5616 // and remove the ObjCLifetime qualifiers.
5617 if (previousLifetime != lifetime) {
5618 // It's possible to have multiple local ObjCLifetime qualifiers. We
5619 // can't stop after we reach a type that is directly qualified.
5620 const Type *prevTy = nullptr;
5621 while (!prevTy || prevTy != underlyingType.Ty) {
5622 prevTy = underlyingType.Ty;
5623 underlyingType = underlyingType.getSingleStepDesugaredType();
5625 underlyingType.Quals.removeObjCLifetime();
5629 underlyingType.Quals.addObjCLifetime(lifetime);
5631 if (NonObjCPointer) {
5632 StringRef name = attr.getName()->getName();
5634 case Qualifiers::OCL_None:
5635 case Qualifiers::OCL_ExplicitNone:
5637 case Qualifiers::OCL_Strong: name = "__strong"; break;
5638 case Qualifiers::OCL_Weak: name = "__weak"; break;
5639 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
5641 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
5642 << TDS_ObjCObjOrBlock << type;
5645 // Don't actually add the __unsafe_unretained qualifier in non-ARC files,
5646 // because having both 'T' and '__unsafe_unretained T' exist in the type
5647 // system causes unfortunate widespread consistency problems. (For example,
5648 // they're not considered compatible types, and we mangle them identicially
5649 // as template arguments.) These problems are all individually fixable,
5650 // but it's easier to just not add the qualifier and instead sniff it out
5651 // in specific places using isObjCInertUnsafeUnretainedType().
5653 // Doing this does means we miss some trivial consistency checks that
5654 // would've triggered in ARC, but that's better than trying to solve all
5655 // the coexistence problems with __unsafe_unretained.
5656 if (!S.getLangOpts().ObjCAutoRefCount &&
5657 lifetime == Qualifiers::OCL_ExplicitNone) {
5658 type = S.Context.getAttributedType(
5659 AttributedType::attr_objc_inert_unsafe_unretained,
5664 QualType origType = type;
5665 if (!NonObjCPointer)
5666 type = S.Context.getQualifiedType(underlyingType);
5668 // If we have a valid source location for the attribute, use an
5669 // AttributedType instead.
5670 if (AttrLoc.isValid())
5671 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
5674 auto diagnoseOrDelay = [](Sema &S, SourceLocation loc,
5675 unsigned diagnostic, QualType type) {
5676 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
5677 S.DelayedDiagnostics.add(
5678 sema::DelayedDiagnostic::makeForbiddenType(
5679 S.getSourceManager().getExpansionLoc(loc),
5680 diagnostic, type, /*ignored*/ 0));
5682 S.Diag(loc, diagnostic);
5686 // Sometimes, __weak isn't allowed.
5687 if (lifetime == Qualifiers::OCL_Weak &&
5688 !S.getLangOpts().ObjCWeak && !NonObjCPointer) {
5690 // Use a specialized diagnostic if the runtime just doesn't support them.
5691 unsigned diagnostic =
5692 (S.getLangOpts().ObjCWeakRuntime ? diag::err_arc_weak_disabled
5693 : diag::err_arc_weak_no_runtime);
5695 // In any case, delay the diagnostic until we know what we're parsing.
5696 diagnoseOrDelay(S, AttrLoc, diagnostic, type);
5702 // Forbid __weak for class objects marked as
5703 // objc_arc_weak_reference_unavailable
5704 if (lifetime == Qualifiers::OCL_Weak) {
5705 if (const ObjCObjectPointerType *ObjT =
5706 type->getAs<ObjCObjectPointerType>()) {
5707 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
5708 if (Class->isArcWeakrefUnavailable()) {
5709 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
5710 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
5711 diag::note_class_declared);
5720 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
5721 /// attribute on the specified type. Returns true to indicate that
5722 /// the attribute was handled, false to indicate that the type does
5723 /// not permit the attribute.
5724 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
5725 AttributeList &attr,
5727 Sema &S = state.getSema();
5729 // Delay if this isn't some kind of pointer.
5730 if (!type->isPointerType() &&
5731 !type->isObjCObjectPointerType() &&
5732 !type->isBlockPointerType())
5735 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
5736 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
5741 // Check the attribute arguments.
5742 if (!attr.isArgIdent(0)) {
5743 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
5744 << attr.getName() << AANT_ArgumentString;
5748 Qualifiers::GC GCAttr;
5749 if (attr.getNumArgs() > 1) {
5750 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5751 << attr.getName() << 1;
5756 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
5757 if (II->isStr("weak"))
5758 GCAttr = Qualifiers::Weak;
5759 else if (II->isStr("strong"))
5760 GCAttr = Qualifiers::Strong;
5762 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
5763 << attr.getName() << II;
5768 QualType origType = type;
5769 type = S.Context.getObjCGCQualType(origType, GCAttr);
5771 // Make an attributed type to preserve the source information.
5772 if (attr.getLoc().isValid())
5773 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
5780 /// A helper class to unwrap a type down to a function for the
5781 /// purposes of applying attributes there.
5784 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
5785 /// if (unwrapped.isFunctionType()) {
5786 /// const FunctionType *fn = unwrapped.get();
5787 /// // change fn somehow
5788 /// T = unwrapped.wrap(fn);
5790 struct FunctionTypeUnwrapper {
5802 const FunctionType *Fn;
5803 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
5805 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
5807 const Type *Ty = T.getTypePtr();
5808 if (isa<FunctionType>(Ty)) {
5809 Fn = cast<FunctionType>(Ty);
5811 } else if (isa<ParenType>(Ty)) {
5812 T = cast<ParenType>(Ty)->getInnerType();
5813 Stack.push_back(Parens);
5814 } else if (isa<PointerType>(Ty)) {
5815 T = cast<PointerType>(Ty)->getPointeeType();
5816 Stack.push_back(Pointer);
5817 } else if (isa<BlockPointerType>(Ty)) {
5818 T = cast<BlockPointerType>(Ty)->getPointeeType();
5819 Stack.push_back(BlockPointer);
5820 } else if (isa<MemberPointerType>(Ty)) {
5821 T = cast<MemberPointerType>(Ty)->getPointeeType();
5822 Stack.push_back(MemberPointer);
5823 } else if (isa<ReferenceType>(Ty)) {
5824 T = cast<ReferenceType>(Ty)->getPointeeType();
5825 Stack.push_back(Reference);
5826 } else if (isa<AttributedType>(Ty)) {
5827 T = cast<AttributedType>(Ty)->getEquivalentType();
5828 Stack.push_back(Attributed);
5830 const Type *DTy = Ty->getUnqualifiedDesugaredType();
5836 T = QualType(DTy, 0);
5837 Stack.push_back(Desugar);
5842 bool isFunctionType() const { return (Fn != nullptr); }
5843 const FunctionType *get() const { return Fn; }
5845 QualType wrap(Sema &S, const FunctionType *New) {
5846 // If T wasn't modified from the unwrapped type, do nothing.
5847 if (New == get()) return Original;
5850 return wrap(S.Context, Original, 0);
5854 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
5855 if (I == Stack.size())
5856 return C.getQualifiedType(Fn, Old.getQualifiers());
5858 // Build up the inner type, applying the qualifiers from the old
5859 // type to the new type.
5860 SplitQualType SplitOld = Old.split();
5862 // As a special case, tail-recurse if there are no qualifiers.
5863 if (SplitOld.Quals.empty())
5864 return wrap(C, SplitOld.Ty, I);
5865 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
5868 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
5869 if (I == Stack.size()) return QualType(Fn, 0);
5871 switch (static_cast<WrapKind>(Stack[I++])) {
5873 // This is the point at which we potentially lose source
5875 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
5878 return wrap(C, cast<AttributedType>(Old)->getEquivalentType(), I);
5881 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
5882 return C.getParenType(New);
5886 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
5887 return C.getPointerType(New);
5890 case BlockPointer: {
5891 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
5892 return C.getBlockPointerType(New);
5895 case MemberPointer: {
5896 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
5897 QualType New = wrap(C, OldMPT->getPointeeType(), I);
5898 return C.getMemberPointerType(New, OldMPT->getClass());
5902 const ReferenceType *OldRef = cast<ReferenceType>(Old);
5903 QualType New = wrap(C, OldRef->getPointeeType(), I);
5904 if (isa<LValueReferenceType>(OldRef))
5905 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
5907 return C.getRValueReferenceType(New);
5911 llvm_unreachable("unknown wrapping kind");
5914 } // end anonymous namespace
5916 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
5917 AttributeList &Attr,
5919 Sema &S = State.getSema();
5921 AttributeList::Kind Kind = Attr.getKind();
5922 QualType Desugared = Type;
5923 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5925 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5927 // You cannot specify duplicate type attributes, so if the attribute has
5928 // already been applied, flag it.
5929 if (getAttrListKind(CurAttrKind) == Kind) {
5930 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5935 // You cannot have both __sptr and __uptr on the same type, nor can you
5936 // have __ptr32 and __ptr64.
5937 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5938 Kind == AttributeList::AT_Ptr64) ||
5939 (CurAttrKind == AttributedType::attr_ptr64 &&
5940 Kind == AttributeList::AT_Ptr32)) {
5941 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5942 << "'__ptr32'" << "'__ptr64'";
5944 } else if ((CurAttrKind == AttributedType::attr_sptr &&
5945 Kind == AttributeList::AT_UPtr) ||
5946 (CurAttrKind == AttributedType::attr_uptr &&
5947 Kind == AttributeList::AT_SPtr)) {
5948 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5949 << "'__sptr'" << "'__uptr'";
5953 Desugared = AT->getEquivalentType();
5954 AT = dyn_cast<AttributedType>(Desugared);
5957 // Pointer type qualifiers can only operate on pointer types, but not
5958 // pointer-to-member types.
5959 if (!isa<PointerType>(Desugared)) {
5960 if (Type->isMemberPointerType())
5961 S.Diag(Attr.getLoc(), diag::err_attribute_no_member_pointers)
5964 S.Diag(Attr.getLoc(), diag::err_attribute_pointers_only)
5965 << Attr.getName() << 0;
5969 AttributedType::Kind TAK;
5971 default: llvm_unreachable("Unknown attribute kind");
5972 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5973 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5974 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5975 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5978 Type = S.Context.getAttributedType(TAK, Type, Type);
5982 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5983 NullabilityKind nullability,
5984 SourceLocation nullabilityLoc,
5985 bool isContextSensitive,
5986 bool allowOnArrayType) {
5987 recordNullabilitySeen(*this, nullabilityLoc);
5989 // Check for existing nullability attributes on the type.
5990 QualType desugared = type;
5991 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5992 // Check whether there is already a null
5993 if (auto existingNullability = attributed->getImmediateNullability()) {
5994 // Duplicated nullability.
5995 if (nullability == *existingNullability) {
5996 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5997 << DiagNullabilityKind(nullability, isContextSensitive)
5998 << FixItHint::CreateRemoval(nullabilityLoc);
6003 // Conflicting nullability.
6004 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6005 << DiagNullabilityKind(nullability, isContextSensitive)
6006 << DiagNullabilityKind(*existingNullability, false);
6010 desugared = attributed->getModifiedType();
6013 // If there is already a different nullability specifier, complain.
6014 // This (unlike the code above) looks through typedefs that might
6015 // have nullability specifiers on them, which means we cannot
6016 // provide a useful Fix-It.
6017 if (auto existingNullability = desugared->getNullability(Context)) {
6018 if (nullability != *existingNullability) {
6019 Diag(nullabilityLoc, diag::err_nullability_conflicting)
6020 << DiagNullabilityKind(nullability, isContextSensitive)
6021 << DiagNullabilityKind(*existingNullability, false);
6023 // Try to find the typedef with the existing nullability specifier.
6024 if (auto typedefType = desugared->getAs<TypedefType>()) {
6025 TypedefNameDecl *typedefDecl = typedefType->getDecl();
6026 QualType underlyingType = typedefDecl->getUnderlyingType();
6027 if (auto typedefNullability
6028 = AttributedType::stripOuterNullability(underlyingType)) {
6029 if (*typedefNullability == *existingNullability) {
6030 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
6031 << DiagNullabilityKind(*existingNullability, false);
6040 // If this definitely isn't a pointer type, reject the specifier.
6041 if (!desugared->canHaveNullability() &&
6042 !(allowOnArrayType && desugared->isArrayType())) {
6043 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
6044 << DiagNullabilityKind(nullability, isContextSensitive) << type;
6048 // For the context-sensitive keywords/Objective-C property
6049 // attributes, require that the type be a single-level pointer.
6050 if (isContextSensitive) {
6051 // Make sure that the pointee isn't itself a pointer type.
6052 const Type *pointeeType;
6053 if (desugared->isArrayType())
6054 pointeeType = desugared->getArrayElementTypeNoTypeQual();
6056 pointeeType = desugared->getPointeeType().getTypePtr();
6058 if (pointeeType->isAnyPointerType() ||
6059 pointeeType->isObjCObjectPointerType() ||
6060 pointeeType->isMemberPointerType()) {
6061 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
6062 << DiagNullabilityKind(nullability, true)
6064 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
6065 << DiagNullabilityKind(nullability, false)
6067 << FixItHint::CreateReplacement(nullabilityLoc,
6068 getNullabilitySpelling(nullability));
6073 // Form the attributed type.
6074 type = Context.getAttributedType(
6075 AttributedType::getNullabilityAttrKind(nullability), type, type);
6079 bool Sema::checkObjCKindOfType(QualType &type, SourceLocation loc) {
6080 if (isa<ObjCTypeParamType>(type)) {
6081 // Build the attributed type to record where __kindof occurred.
6082 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6087 // Find out if it's an Objective-C object or object pointer type;
6088 const ObjCObjectPointerType *ptrType = type->getAs<ObjCObjectPointerType>();
6089 const ObjCObjectType *objType = ptrType ? ptrType->getObjectType()
6090 : type->getAs<ObjCObjectType>();
6092 // If not, we can't apply __kindof.
6094 // FIXME: Handle dependent types that aren't yet object types.
6095 Diag(loc, diag::err_objc_kindof_nonobject)
6100 // Rebuild the "equivalent" type, which pushes __kindof down into
6102 // There is no need to apply kindof on an unqualified id type.
6103 QualType equivType = Context.getObjCObjectType(
6104 objType->getBaseType(), objType->getTypeArgsAsWritten(),
6105 objType->getProtocols(),
6106 /*isKindOf=*/objType->isObjCUnqualifiedId() ? false : true);
6108 // If we started with an object pointer type, rebuild it.
6110 equivType = Context.getObjCObjectPointerType(equivType);
6111 if (auto nullability = type->getNullability(Context)) {
6112 auto attrKind = AttributedType::getNullabilityAttrKind(*nullability);
6113 equivType = Context.getAttributedType(attrKind, equivType, equivType);
6117 // Build the attributed type to record where __kindof occurred.
6118 type = Context.getAttributedType(AttributedType::attr_objc_kindof,
6125 /// Map a nullability attribute kind to a nullability kind.
6126 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
6128 case AttributeList::AT_TypeNonNull:
6129 return NullabilityKind::NonNull;
6131 case AttributeList::AT_TypeNullable:
6132 return NullabilityKind::Nullable;
6134 case AttributeList::AT_TypeNullUnspecified:
6135 return NullabilityKind::Unspecified;
6138 llvm_unreachable("not a nullability attribute kind");
6142 /// Distribute a nullability type attribute that cannot be applied to
6143 /// the type specifier to a pointer, block pointer, or member pointer
6144 /// declarator, complaining if necessary.
6146 /// \returns true if the nullability annotation was distributed, false
6148 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
6150 AttributeList &attr) {
6151 Declarator &declarator = state.getDeclarator();
6153 /// Attempt to move the attribute to the specified chunk.
6154 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
6155 // If there is already a nullability attribute there, don't add
6157 if (hasNullabilityAttr(chunk.getAttrListRef()))
6160 // Complain about the nullability qualifier being in the wrong
6167 PK_MemberFunctionPointer,
6169 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
6171 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
6172 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
6174 auto diag = state.getSema().Diag(attr.getLoc(),
6175 diag::warn_nullability_declspec)
6176 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
6177 attr.isContextSensitiveKeywordAttribute())
6179 << static_cast<unsigned>(pointerKind);
6181 // FIXME: MemberPointer chunks don't carry the location of the *.
6182 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
6183 diag << FixItHint::CreateRemoval(attr.getLoc())
6184 << FixItHint::CreateInsertion(
6185 state.getSema().getPreprocessor()
6186 .getLocForEndOfToken(chunk.Loc),
6187 " " + attr.getName()->getName().str() + " ");
6190 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
6191 chunk.getAttrListRef());
6195 // Move it to the outermost pointer, member pointer, or block
6196 // pointer declarator.
6197 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
6198 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
6199 switch (chunk.Kind) {
6200 case DeclaratorChunk::Pointer:
6201 case DeclaratorChunk::BlockPointer:
6202 case DeclaratorChunk::MemberPointer:
6203 return moveToChunk(chunk, false);
6205 case DeclaratorChunk::Paren:
6206 case DeclaratorChunk::Array:
6209 case DeclaratorChunk::Function:
6210 // Try to move past the return type to a function/block/member
6211 // function pointer.
6212 if (DeclaratorChunk *dest = maybeMovePastReturnType(
6214 /*onlyBlockPointers=*/false)) {
6215 return moveToChunk(*dest, true);
6220 // Don't walk through these.
6221 case DeclaratorChunk::Reference:
6222 case DeclaratorChunk::Pipe:
6230 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
6231 assert(!Attr.isInvalid());
6232 switch (Attr.getKind()) {
6234 llvm_unreachable("not a calling convention attribute");
6235 case AttributeList::AT_CDecl:
6236 return AttributedType::attr_cdecl;
6237 case AttributeList::AT_FastCall:
6238 return AttributedType::attr_fastcall;
6239 case AttributeList::AT_StdCall:
6240 return AttributedType::attr_stdcall;
6241 case AttributeList::AT_ThisCall:
6242 return AttributedType::attr_thiscall;
6243 case AttributeList::AT_RegCall:
6244 return AttributedType::attr_regcall;
6245 case AttributeList::AT_Pascal:
6246 return AttributedType::attr_pascal;
6247 case AttributeList::AT_SwiftCall:
6248 return AttributedType::attr_swiftcall;
6249 case AttributeList::AT_VectorCall:
6250 return AttributedType::attr_vectorcall;
6251 case AttributeList::AT_Pcs: {
6252 // The attribute may have had a fixit applied where we treated an
6253 // identifier as a string literal. The contents of the string are valid,
6254 // but the form may not be.
6256 if (Attr.isArgExpr(0))
6257 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
6259 Str = Attr.getArgAsIdent(0)->Ident->getName();
6260 return llvm::StringSwitch<AttributedType::Kind>(Str)
6261 .Case("aapcs", AttributedType::attr_pcs)
6262 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
6264 case AttributeList::AT_IntelOclBicc:
6265 return AttributedType::attr_inteloclbicc;
6266 case AttributeList::AT_MSABI:
6267 return AttributedType::attr_ms_abi;
6268 case AttributeList::AT_SysVABI:
6269 return AttributedType::attr_sysv_abi;
6270 case AttributeList::AT_PreserveMost:
6271 return AttributedType::attr_preserve_most;
6272 case AttributeList::AT_PreserveAll:
6273 return AttributedType::attr_preserve_all;
6275 llvm_unreachable("unexpected attribute kind!");
6278 /// Process an individual function attribute. Returns true to
6279 /// indicate that the attribute was handled, false if it wasn't.
6280 static bool handleFunctionTypeAttr(TypeProcessingState &state,
6281 AttributeList &attr,
6283 Sema &S = state.getSema();
6285 FunctionTypeUnwrapper unwrapped(S, type);
6287 if (attr.getKind() == AttributeList::AT_NoReturn) {
6288 if (S.CheckNoReturnAttr(attr))
6291 // Delay if this is not a function type.
6292 if (!unwrapped.isFunctionType())
6295 // Otherwise we can process right away.
6296 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
6297 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6301 // ns_returns_retained is not always a type attribute, but if we got
6302 // here, we're treating it as one right now.
6303 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
6304 assert(S.getLangOpts().ObjCAutoRefCount &&
6305 "ns_returns_retained treated as type attribute in non-ARC");
6306 if (attr.getNumArgs()) return true;
6308 // Delay if this is not a function type.
6309 if (!unwrapped.isFunctionType())
6312 FunctionType::ExtInfo EI
6313 = unwrapped.get()->getExtInfo().withProducesResult(true);
6314 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6318 if (attr.getKind() == AttributeList::AT_Regparm) {
6320 if (S.CheckRegparmAttr(attr, value))
6323 // Delay if this is not a function type.
6324 if (!unwrapped.isFunctionType())
6327 // Diagnose regparm with fastcall.
6328 const FunctionType *fn = unwrapped.get();
6329 CallingConv CC = fn->getCallConv();
6330 if (CC == CC_X86FastCall) {
6331 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6332 << FunctionType::getNameForCallConv(CC)
6338 FunctionType::ExtInfo EI =
6339 unwrapped.get()->getExtInfo().withRegParm(value);
6340 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6344 // Delay if the type didn't work out to a function.
6345 if (!unwrapped.isFunctionType()) return false;
6347 // Otherwise, a calling convention.
6349 if (S.CheckCallingConvAttr(attr, CC))
6352 const FunctionType *fn = unwrapped.get();
6353 CallingConv CCOld = fn->getCallConv();
6354 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
6357 // Error out on when there's already an attribute on the type
6358 // and the CCs don't match.
6359 const AttributedType *AT = S.getCallingConvAttributedType(type);
6360 if (AT && AT->getAttrKind() != CCAttrKind) {
6361 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6362 << FunctionType::getNameForCallConv(CC)
6363 << FunctionType::getNameForCallConv(CCOld);
6369 // Diagnose use of variadic functions with calling conventions that
6370 // don't support them (e.g. because they're callee-cleanup).
6371 // We delay warning about this on unprototyped function declarations
6372 // until after redeclaration checking, just in case we pick up a
6373 // prototype that way. And apparently we also "delay" warning about
6374 // unprototyped function types in general, despite not necessarily having
6375 // much ability to diagnose it later.
6376 if (!supportsVariadicCall(CC)) {
6377 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
6378 if (FnP && FnP->isVariadic()) {
6379 unsigned DiagID = diag::err_cconv_varargs;
6381 // stdcall and fastcall are ignored with a warning for GCC and MS
6383 bool IsInvalid = true;
6384 if (CC == CC_X86StdCall || CC == CC_X86FastCall) {
6385 DiagID = diag::warn_cconv_varargs;
6389 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
6390 if (IsInvalid) attr.setInvalid();
6395 // Also diagnose fastcall with regparm.
6396 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
6397 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
6398 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
6403 // Modify the CC from the wrapped function type, wrap it all back, and then
6404 // wrap the whole thing in an AttributedType as written. The modified type
6405 // might have a different CC if we ignored the attribute.
6406 QualType Equivalent;
6410 auto EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
6412 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
6414 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
6418 bool Sema::hasExplicitCallingConv(QualType &T) {
6419 QualType R = T.IgnoreParens();
6420 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
6421 if (AT->isCallingConv())
6423 R = AT->getModifiedType().IgnoreParens();
6428 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic, bool IsCtorOrDtor,
6429 SourceLocation Loc) {
6430 FunctionTypeUnwrapper Unwrapped(*this, T);
6431 const FunctionType *FT = Unwrapped.get();
6432 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
6433 cast<FunctionProtoType>(FT)->isVariadic());
6434 CallingConv CurCC = FT->getCallConv();
6435 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
6440 // MS compiler ignores explicit calling convention attributes on structors. We
6441 // should do the same.
6442 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && IsCtorOrDtor) {
6443 // Issue a warning on ignored calling convention -- except of __stdcall.
6444 // Again, this is what MS compiler does.
6445 if (CurCC != CC_X86StdCall)
6446 Diag(Loc, diag::warn_cconv_structors)
6447 << FunctionType::getNameForCallConv(CurCC);
6448 // Default adjustment.
6450 // Only adjust types with the default convention. For example, on Windows
6451 // we should adjust a __cdecl type to __thiscall for instance methods, and a
6452 // __thiscall type to __cdecl for static methods.
6453 CallingConv DefaultCC =
6454 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
6456 if (CurCC != DefaultCC || DefaultCC == ToCC)
6459 if (hasExplicitCallingConv(T))
6463 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
6464 QualType Wrapped = Unwrapped.wrap(*this, FT);
6465 T = Context.getAdjustedType(T, Wrapped);
6468 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
6469 /// and float scalars, although arrays, pointers, and function return values are
6470 /// allowed in conjunction with this construct. Aggregates with this attribute
6471 /// are invalid, even if they are of the same size as a corresponding scalar.
6472 /// The raw attribute should contain precisely 1 argument, the vector size for
6473 /// the variable, measured in bytes. If curType and rawAttr are well formed,
6474 /// this routine will return a new vector type.
6475 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
6477 // Check the attribute arguments.
6478 if (Attr.getNumArgs() != 1) {
6479 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6480 << Attr.getName() << 1;
6484 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6485 llvm::APSInt vecSize(32);
6486 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
6487 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
6488 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6489 << Attr.getName() << AANT_ArgumentIntegerConstant
6490 << sizeExpr->getSourceRange();
6494 // The base type must be integer (not Boolean or enumeration) or float, and
6495 // can't already be a vector.
6496 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
6497 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
6498 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6502 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6503 // vecSize is specified in bytes - convert to bits.
6504 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
6506 // the vector size needs to be an integral multiple of the type size.
6507 if (vectorSize % typeSize) {
6508 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
6509 << sizeExpr->getSourceRange();
6513 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
6514 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
6515 << sizeExpr->getSourceRange();
6519 if (vectorSize == 0) {
6520 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
6521 << sizeExpr->getSourceRange();
6526 // Success! Instantiate the vector type, the number of elements is > 0, and
6527 // not required to be a power of 2, unlike GCC.
6528 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
6529 VectorType::GenericVector);
6532 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
6534 static void HandleExtVectorTypeAttr(QualType &CurType,
6535 const AttributeList &Attr,
6537 // check the attribute arguments.
6538 if (Attr.getNumArgs() != 1) {
6539 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6540 << Attr.getName() << 1;
6546 // Special case where the argument is a template id.
6547 if (Attr.isArgIdent(0)) {
6549 SourceLocation TemplateKWLoc;
6551 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
6553 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
6555 if (Size.isInvalid())
6558 sizeExpr = Size.get();
6560 sizeExpr = Attr.getArgAsExpr(0);
6563 // Create the vector type.
6564 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
6569 static bool isPermittedNeonBaseType(QualType &Ty,
6570 VectorType::VectorKind VecKind, Sema &S) {
6571 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
6575 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
6577 // Signed poly is mathematically wrong, but has been baked into some ABIs by
6579 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
6580 Triple.getArch() == llvm::Triple::aarch64_be;
6581 if (VecKind == VectorType::NeonPolyVector) {
6582 if (IsPolyUnsigned) {
6583 // AArch64 polynomial vectors are unsigned and support poly64.
6584 return BTy->getKind() == BuiltinType::UChar ||
6585 BTy->getKind() == BuiltinType::UShort ||
6586 BTy->getKind() == BuiltinType::ULong ||
6587 BTy->getKind() == BuiltinType::ULongLong;
6589 // AArch32 polynomial vector are signed.
6590 return BTy->getKind() == BuiltinType::SChar ||
6591 BTy->getKind() == BuiltinType::Short;
6595 // Non-polynomial vector types: the usual suspects are allowed, as well as
6596 // float64_t on AArch64.
6597 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
6598 Triple.getArch() == llvm::Triple::aarch64_be;
6600 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
6603 return BTy->getKind() == BuiltinType::SChar ||
6604 BTy->getKind() == BuiltinType::UChar ||
6605 BTy->getKind() == BuiltinType::Short ||
6606 BTy->getKind() == BuiltinType::UShort ||
6607 BTy->getKind() == BuiltinType::Int ||
6608 BTy->getKind() == BuiltinType::UInt ||
6609 BTy->getKind() == BuiltinType::Long ||
6610 BTy->getKind() == BuiltinType::ULong ||
6611 BTy->getKind() == BuiltinType::LongLong ||
6612 BTy->getKind() == BuiltinType::ULongLong ||
6613 BTy->getKind() == BuiltinType::Float ||
6614 BTy->getKind() == BuiltinType::Half;
6617 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
6618 /// "neon_polyvector_type" attributes are used to create vector types that
6619 /// are mangled according to ARM's ABI. Otherwise, these types are identical
6620 /// to those created with the "vector_size" attribute. Unlike "vector_size"
6621 /// the argument to these Neon attributes is the number of vector elements,
6622 /// not the vector size in bytes. The vector width and element type must
6623 /// match one of the standard Neon vector types.
6624 static void HandleNeonVectorTypeAttr(QualType& CurType,
6625 const AttributeList &Attr, Sema &S,
6626 VectorType::VectorKind VecKind) {
6627 // Target must have NEON
6628 if (!S.Context.getTargetInfo().hasFeature("neon")) {
6629 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
6633 // Check the attribute arguments.
6634 if (Attr.getNumArgs() != 1) {
6635 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
6636 << Attr.getName() << 1;
6640 // The number of elements must be an ICE.
6641 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
6642 llvm::APSInt numEltsInt(32);
6643 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
6644 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
6645 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
6646 << Attr.getName() << AANT_ArgumentIntegerConstant
6647 << numEltsExpr->getSourceRange();
6651 // Only certain element types are supported for Neon vectors.
6652 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
6653 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
6658 // The total size of the vector must be 64 or 128 bits.
6659 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
6660 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
6661 unsigned vecSize = typeSize * numElts;
6662 if (vecSize != 64 && vecSize != 128) {
6663 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
6668 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
6671 /// Handle OpenCL Access Qualifier Attribute.
6672 static void HandleOpenCLAccessAttr(QualType &CurType, const AttributeList &Attr,
6674 // OpenCL v2.0 s6.6 - Access qualifier can be used only for image and pipe type.
6675 if (!(CurType->isImageType() || CurType->isPipeType())) {
6676 S.Diag(Attr.getLoc(), diag::err_opencl_invalid_access_qualifier);
6681 if (const TypedefType* TypedefTy = CurType->getAs<TypedefType>()) {
6682 QualType PointeeTy = TypedefTy->desugar();
6683 S.Diag(Attr.getLoc(), diag::err_opencl_multiple_access_qualifiers);
6685 std::string PrevAccessQual;
6686 switch (cast<BuiltinType>(PointeeTy.getTypePtr())->getKind()) {
6687 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6688 case BuiltinType::Id: \
6689 PrevAccessQual = #Access; \
6691 #include "clang/Basic/OpenCLImageTypes.def"
6693 assert(0 && "Unable to find corresponding image type.");
6696 S.Diag(TypedefTy->getDecl()->getLocStart(),
6697 diag::note_opencl_typedef_access_qualifier) << PrevAccessQual;
6698 } else if (CurType->isPipeType()) {
6699 if (Attr.getSemanticSpelling() == OpenCLAccessAttr::Keyword_write_only) {
6700 QualType ElemType = CurType->getAs<PipeType>()->getElementType();
6701 CurType = S.Context.getWritePipeType(ElemType);
6706 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
6707 TypeAttrLocation TAL, AttributeList *attrs) {
6708 // Scan through and apply attributes to this type where it makes sense. Some
6709 // attributes (such as __address_space__, __vector_size__, etc) apply to the
6710 // type, but others can be present in the type specifiers even though they
6711 // apply to the decl. Here we apply type attributes and ignore the rest.
6713 bool hasOpenCLAddressSpace = false;
6715 AttributeList &attr = *attrs;
6716 attrs = attr.getNext(); // reset to the next here due to early loop continue
6719 // Skip attributes that were marked to be invalid.
6720 if (attr.isInvalid())
6723 if (attr.isCXX11Attribute()) {
6724 // [[gnu::...]] attributes are treated as declaration attributes, so may
6725 // not appertain to a DeclaratorChunk, even if we handle them as type
6727 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
6728 if (TAL == TAL_DeclChunk) {
6729 state.getSema().Diag(attr.getLoc(),
6730 diag::warn_cxx11_gnu_attribute_on_type)
6734 } else if (TAL != TAL_DeclChunk) {
6735 // Otherwise, only consider type processing for a C++11 attribute if
6736 // it's actually been applied to a type.
6741 // If this is an attribute we can handle, do so now,
6742 // otherwise, add it to the FnAttrs list for rechaining.
6743 switch (attr.getKind()) {
6745 // A C++11 attribute on a declarator chunk must appertain to a type.
6746 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
6747 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
6749 attr.setUsedAsTypeAttr();
6753 case AttributeList::UnknownAttribute:
6754 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
6755 state.getSema().Diag(attr.getLoc(),
6756 diag::warn_unknown_attribute_ignored)
6760 case AttributeList::IgnoredAttribute:
6763 case AttributeList::AT_MayAlias:
6764 // FIXME: This attribute needs to actually be handled, but if we ignore
6765 // it it breaks large amounts of Linux software.
6766 attr.setUsedAsTypeAttr();
6768 case AttributeList::AT_OpenCLPrivateAddressSpace:
6769 case AttributeList::AT_OpenCLGlobalAddressSpace:
6770 case AttributeList::AT_OpenCLLocalAddressSpace:
6771 case AttributeList::AT_OpenCLConstantAddressSpace:
6772 case AttributeList::AT_OpenCLGenericAddressSpace:
6773 case AttributeList::AT_AddressSpace:
6774 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
6775 attr.setUsedAsTypeAttr();
6776 hasOpenCLAddressSpace = true;
6778 OBJC_POINTER_TYPE_ATTRS_CASELIST:
6779 if (!handleObjCPointerTypeAttr(state, attr, type))
6780 distributeObjCPointerTypeAttr(state, attr, type);
6781 attr.setUsedAsTypeAttr();
6783 case AttributeList::AT_VectorSize:
6784 HandleVectorSizeAttr(type, attr, state.getSema());
6785 attr.setUsedAsTypeAttr();
6787 case AttributeList::AT_ExtVectorType:
6788 HandleExtVectorTypeAttr(type, attr, state.getSema());
6789 attr.setUsedAsTypeAttr();
6791 case AttributeList::AT_NeonVectorType:
6792 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6793 VectorType::NeonVector);
6794 attr.setUsedAsTypeAttr();
6796 case AttributeList::AT_NeonPolyVectorType:
6797 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
6798 VectorType::NeonPolyVector);
6799 attr.setUsedAsTypeAttr();
6801 case AttributeList::AT_OpenCLAccess:
6802 HandleOpenCLAccessAttr(type, attr, state.getSema());
6803 attr.setUsedAsTypeAttr();
6806 MS_TYPE_ATTRS_CASELIST:
6807 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
6808 attr.setUsedAsTypeAttr();
6812 NULLABILITY_TYPE_ATTRS_CASELIST:
6813 // Either add nullability here or try to distribute it. We
6814 // don't want to distribute the nullability specifier past any
6815 // dependent type, because that complicates the user model.
6816 if (type->canHaveNullability() || type->isDependentType() ||
6817 type->isArrayType() ||
6818 !distributeNullabilityTypeAttr(state, type, attr)) {
6820 if (TAL == TAL_DeclChunk)
6821 endIndex = state.getCurrentChunkIndex();
6823 endIndex = state.getDeclarator().getNumTypeObjects();
6824 bool allowOnArrayType =
6825 state.getDeclarator().isPrototypeContext() &&
6826 !hasOuterPointerLikeChunk(state.getDeclarator(), endIndex);
6827 if (state.getSema().checkNullabilityTypeSpecifier(
6829 mapNullabilityAttrKind(attr.getKind()),
6831 attr.isContextSensitiveKeywordAttribute(),
6832 allowOnArrayType)) {
6836 attr.setUsedAsTypeAttr();
6840 case AttributeList::AT_ObjCKindOf:
6841 // '__kindof' must be part of the decl-specifiers.
6848 state.getSema().Diag(attr.getLoc(),
6849 diag::err_objc_kindof_wrong_position)
6850 << FixItHint::CreateRemoval(attr.getLoc())
6851 << FixItHint::CreateInsertion(
6852 state.getDeclarator().getDeclSpec().getLocStart(), "__kindof ");
6856 // Apply it regardless.
6857 if (state.getSema().checkObjCKindOfType(type, attr.getLoc()))
6859 attr.setUsedAsTypeAttr();
6862 case AttributeList::AT_NSReturnsRetained:
6863 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
6865 // fallthrough into the function attrs
6867 FUNCTION_TYPE_ATTRS_CASELIST:
6868 attr.setUsedAsTypeAttr();
6870 // Never process function type attributes as part of the
6871 // declaration-specifiers.
6872 if (TAL == TAL_DeclSpec)
6873 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
6875 // Otherwise, handle the possible delays.
6876 else if (!handleFunctionTypeAttr(state, attr, type))
6877 distributeFunctionTypeAttr(state, attr, type);
6882 // If address space is not set, OpenCL 2.0 defines non private default
6883 // address spaces for some cases:
6884 // OpenCL 2.0, section 6.5:
6885 // The address space for a variable at program scope or a static variable
6886 // inside a function can either be __global or __constant, but defaults to
6887 // __global if not specified.
6889 // Pointers that are declared without pointing to a named address space point
6890 // to the generic address space.
6891 if (state.getSema().getLangOpts().OpenCLVersion >= 200 &&
6892 !hasOpenCLAddressSpace && type.getAddressSpace() == 0 &&
6893 (TAL == TAL_DeclSpec || TAL == TAL_DeclChunk)) {
6894 Declarator &D = state.getDeclarator();
6895 if (state.getCurrentChunkIndex() > 0 &&
6896 D.getTypeObject(state.getCurrentChunkIndex() - 1).Kind ==
6897 DeclaratorChunk::Pointer) {
6898 type = state.getSema().Context.getAddrSpaceQualType(
6899 type, LangAS::opencl_generic);
6900 } else if (state.getCurrentChunkIndex() == 0 &&
6901 D.getContext() == Declarator::FileContext &&
6902 !D.isFunctionDeclarator() && !D.isFunctionDefinition() &&
6903 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
6904 !type->isSamplerT())
6905 type = state.getSema().Context.getAddrSpaceQualType(
6906 type, LangAS::opencl_global);
6907 else if (state.getCurrentChunkIndex() == 0 &&
6908 D.getContext() == Declarator::BlockContext &&
6909 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
6910 type = state.getSema().Context.getAddrSpaceQualType(
6911 type, LangAS::opencl_global);
6915 void Sema::completeExprArrayBound(Expr *E) {
6916 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6917 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6918 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
6919 SourceLocation PointOfInstantiation = E->getExprLoc();
6921 if (MemberSpecializationInfo *MSInfo =
6922 Var->getMemberSpecializationInfo()) {
6923 // If we don't already have a point of instantiation, this is it.
6924 if (MSInfo->getPointOfInstantiation().isInvalid()) {
6925 MSInfo->setPointOfInstantiation(PointOfInstantiation);
6927 // This is a modification of an existing AST node. Notify
6929 if (ASTMutationListener *L = getASTMutationListener())
6930 L->StaticDataMemberInstantiated(Var);
6933 VarTemplateSpecializationDecl *VarSpec =
6934 cast<VarTemplateSpecializationDecl>(Var);
6935 if (VarSpec->getPointOfInstantiation().isInvalid())
6936 VarSpec->setPointOfInstantiation(PointOfInstantiation);
6939 InstantiateVariableDefinition(PointOfInstantiation, Var);
6941 // Update the type to the newly instantiated definition's type both
6942 // here and within the expression.
6943 if (VarDecl *Def = Var->getDefinition()) {
6945 QualType T = Def->getType();
6947 // FIXME: Update the type on all intervening expressions.
6951 // We still go on to try to complete the type independently, as it
6952 // may also require instantiations or diagnostics if it remains
6959 /// \brief Ensure that the type of the given expression is complete.
6961 /// This routine checks whether the expression \p E has a complete type. If the
6962 /// expression refers to an instantiable construct, that instantiation is
6963 /// performed as needed to complete its type. Furthermore
6964 /// Sema::RequireCompleteType is called for the expression's type (or in the
6965 /// case of a reference type, the referred-to type).
6967 /// \param E The expression whose type is required to be complete.
6968 /// \param Diagnoser The object that will emit a diagnostic if the type is
6971 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
6973 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser) {
6974 QualType T = E->getType();
6976 // Incomplete array types may be completed by the initializer attached to
6977 // their definitions. For static data members of class templates and for
6978 // variable templates, we need to instantiate the definition to get this
6979 // initializer and complete the type.
6980 if (T->isIncompleteArrayType()) {
6981 completeExprArrayBound(E);
6985 // FIXME: Are there other cases which require instantiating something other
6986 // than the type to complete the type of an expression?
6988 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
6991 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
6992 BoundTypeDiagnoser<> Diagnoser(DiagID);
6993 return RequireCompleteExprType(E, Diagnoser);
6996 /// @brief Ensure that the type T is a complete type.
6998 /// This routine checks whether the type @p T is complete in any
6999 /// context where a complete type is required. If @p T is a complete
7000 /// type, returns false. If @p T is a class template specialization,
7001 /// this routine then attempts to perform class template
7002 /// instantiation. If instantiation fails, or if @p T is incomplete
7003 /// and cannot be completed, issues the diagnostic @p diag (giving it
7004 /// the type @p T) and returns true.
7006 /// @param Loc The location in the source that the incomplete type
7007 /// diagnostic should refer to.
7009 /// @param T The type that this routine is examining for completeness.
7011 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
7012 /// @c false otherwise.
7013 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7014 TypeDiagnoser &Diagnoser) {
7015 if (RequireCompleteTypeImpl(Loc, T, &Diagnoser))
7017 if (const TagType *Tag = T->getAs<TagType>()) {
7018 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
7019 Tag->getDecl()->setCompleteDefinitionRequired();
7020 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
7026 /// \brief Determine whether there is any declaration of \p D that was ever a
7027 /// definition (perhaps before module merging) and is currently visible.
7028 /// \param D The definition of the entity.
7029 /// \param Suggested Filled in with the declaration that should be made visible
7030 /// in order to provide a definition of this entity.
7031 /// \param OnlyNeedComplete If \c true, we only need the type to be complete,
7032 /// not defined. This only matters for enums with a fixed underlying
7033 /// type, since in all other cases, a type is complete if and only if it
7035 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested,
7036 bool OnlyNeedComplete) {
7037 // Easy case: if we don't have modules, all declarations are visible.
7038 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
7041 // If this definition was instantiated from a template, map back to the
7042 // pattern from which it was instantiated.
7043 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
7044 // We're in the middle of defining it; this definition should be treated
7047 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
7048 if (auto *Pattern = RD->getTemplateInstantiationPattern())
7050 D = RD->getDefinition();
7051 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
7052 if (auto *Pattern = ED->getTemplateInstantiationPattern())
7054 if (OnlyNeedComplete && ED->isFixed()) {
7055 // If the enum has a fixed underlying type, and we're only looking for a
7056 // complete type (not a definition), any visible declaration of it will
7058 *Suggested = nullptr;
7059 for (auto *Redecl : ED->redecls()) {
7060 if (isVisible(Redecl))
7062 if (Redecl->isThisDeclarationADefinition() ||
7063 (Redecl->isCanonicalDecl() && !*Suggested))
7064 *Suggested = Redecl;
7068 D = ED->getDefinition();
7069 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
7070 if (auto *Pattern = FD->getTemplateInstantiationPattern())
7072 D = FD->getDefinition();
7073 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
7074 if (auto *Pattern = VD->getTemplateInstantiationPattern())
7076 D = VD->getDefinition();
7078 assert(D && "missing definition for pattern of instantiated definition");
7084 // The external source may have additional definitions of this entity that are
7085 // visible, so complete the redeclaration chain now and ask again.
7086 if (auto *Source = Context.getExternalSource()) {
7087 Source->CompleteRedeclChain(D);
7088 return isVisible(D);
7094 /// Locks in the inheritance model for the given class and all of its bases.
7095 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
7096 RD = RD->getMostRecentDecl();
7097 if (!RD->hasAttr<MSInheritanceAttr>()) {
7098 MSInheritanceAttr::Spelling IM;
7100 switch (S.MSPointerToMemberRepresentationMethod) {
7101 case LangOptions::PPTMK_BestCase:
7102 IM = RD->calculateInheritanceModel();
7104 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
7105 IM = MSInheritanceAttr::Keyword_single_inheritance;
7107 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
7108 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
7110 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
7111 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
7115 RD->addAttr(MSInheritanceAttr::CreateImplicit(
7116 S.getASTContext(), IM,
7117 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
7118 LangOptions::PPTMK_BestCase,
7119 S.ImplicitMSInheritanceAttrLoc.isValid()
7120 ? S.ImplicitMSInheritanceAttrLoc
7121 : RD->getSourceRange()));
7122 S.Consumer.AssignInheritanceModel(RD);
7126 /// \brief The implementation of RequireCompleteType
7127 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
7128 TypeDiagnoser *Diagnoser) {
7129 // FIXME: Add this assertion to make sure we always get instantiation points.
7130 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
7131 // FIXME: Add this assertion to help us flush out problems with
7132 // checking for dependent types and type-dependent expressions.
7134 // assert(!T->isDependentType() &&
7135 // "Can't ask whether a dependent type is complete");
7137 // We lock in the inheritance model once somebody has asked us to ensure
7138 // that a pointer-to-member type is complete.
7139 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
7140 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
7141 if (!MPTy->getClass()->isDependentType()) {
7142 (void)isCompleteType(Loc, QualType(MPTy->getClass(), 0));
7143 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
7148 NamedDecl *Def = nullptr;
7149 bool Incomplete = T->isIncompleteType(&Def);
7151 // Check that any necessary explicit specializations are visible. For an
7152 // enum, we just need the declaration, so don't check this.
7153 if (Def && !isa<EnumDecl>(Def))
7154 checkSpecializationVisibility(Loc, Def);
7156 // If we have a complete type, we're done.
7158 // If we know about the definition but it is not visible, complain.
7159 NamedDecl *SuggestedDef = nullptr;
7161 !hasVisibleDefinition(Def, &SuggestedDef, /*OnlyNeedComplete*/true)) {
7162 // If the user is going to see an error here, recover by making the
7163 // definition visible.
7164 bool TreatAsComplete = Diagnoser && !isSFINAEContext();
7166 diagnoseMissingImport(Loc, SuggestedDef, MissingImportKind::Definition,
7167 /*Recover*/TreatAsComplete);
7168 return !TreatAsComplete;
7174 const TagType *Tag = T->getAs<TagType>();
7175 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
7177 // If there's an unimported definition of this type in a module (for
7178 // instance, because we forward declared it, then imported the definition),
7179 // import that definition now.
7181 // FIXME: What about other cases where an import extends a redeclaration
7182 // chain for a declaration that can be accessed through a mechanism other
7183 // than name lookup (eg, referenced in a template, or a variable whose type
7184 // could be completed by the module)?
7186 // FIXME: Should we map through to the base array element type before
7187 // checking for a tag type?
7190 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
7192 // Avoid diagnosing invalid decls as incomplete.
7193 if (D->isInvalidDecl())
7196 // Give the external AST source a chance to complete the type.
7197 if (auto *Source = Context.getExternalSource()) {
7199 Source->CompleteType(Tag->getDecl());
7201 Source->CompleteType(IFace->getDecl());
7203 // If the external source completed the type, go through the motions
7204 // again to ensure we're allowed to use the completed type.
7205 if (!T->isIncompleteType())
7206 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7210 // If we have a class template specialization or a class member of a
7211 // class template specialization, or an array with known size of such,
7212 // try to instantiate it.
7213 QualType MaybeTemplate = T;
7214 while (const ConstantArrayType *Array
7215 = Context.getAsConstantArrayType(MaybeTemplate))
7216 MaybeTemplate = Array->getElementType();
7217 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
7218 bool Instantiated = false;
7219 bool Diagnosed = false;
7220 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
7221 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
7222 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
7223 Diagnosed = InstantiateClassTemplateSpecialization(
7224 Loc, ClassTemplateSpec, TSK_ImplicitInstantiation,
7225 /*Complain=*/Diagnoser);
7226 Instantiated = true;
7228 } else if (CXXRecordDecl *Rec
7229 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
7230 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
7231 if (!Rec->isBeingDefined() && Pattern) {
7232 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
7233 assert(MSI && "Missing member specialization information?");
7234 // This record was instantiated from a class within a template.
7235 if (MSI->getTemplateSpecializationKind() !=
7236 TSK_ExplicitSpecialization) {
7237 Diagnosed = InstantiateClass(Loc, Rec, Pattern,
7238 getTemplateInstantiationArgs(Rec),
7239 TSK_ImplicitInstantiation,
7240 /*Complain=*/Diagnoser);
7241 Instantiated = true;
7247 // Instantiate* might have already complained that the template is not
7248 // defined, if we asked it to.
7249 if (Diagnoser && Diagnosed)
7251 // If we instantiated a definition, check that it's usable, even if
7252 // instantiation produced an error, so that repeated calls to this
7253 // function give consistent answers.
7254 if (!T->isIncompleteType())
7255 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
7259 // FIXME: If we didn't instantiate a definition because of an explicit
7260 // specialization declaration, check that it's visible.
7265 Diagnoser->diagnose(*this, Loc, T);
7267 // If the type was a forward declaration of a class/struct/union
7268 // type, produce a note.
7269 if (Tag && !Tag->getDecl()->isInvalidDecl())
7270 Diag(Tag->getDecl()->getLocation(),
7271 Tag->isBeingDefined() ? diag::note_type_being_defined
7272 : diag::note_forward_declaration)
7273 << QualType(Tag, 0);
7275 // If the Objective-C class was a forward declaration, produce a note.
7276 if (IFace && !IFace->getDecl()->isInvalidDecl())
7277 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
7279 // If we have external information that we can use to suggest a fix,
7282 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
7287 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
7289 BoundTypeDiagnoser<> Diagnoser(DiagID);
7290 return RequireCompleteType(Loc, T, Diagnoser);
7293 /// \brief Get diagnostic %select index for tag kind for
7294 /// literal type diagnostic message.
7295 /// WARNING: Indexes apply to particular diagnostics only!
7297 /// \returns diagnostic %select index.
7298 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
7300 case TTK_Struct: return 0;
7301 case TTK_Interface: return 1;
7302 case TTK_Class: return 2;
7303 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
7307 /// @brief Ensure that the type T is a literal type.
7309 /// This routine checks whether the type @p T is a literal type. If @p T is an
7310 /// incomplete type, an attempt is made to complete it. If @p T is a literal
7311 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
7312 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
7313 /// it the type @p T), along with notes explaining why the type is not a
7314 /// literal type, and returns true.
7316 /// @param Loc The location in the source that the non-literal type
7317 /// diagnostic should refer to.
7319 /// @param T The type that this routine is examining for literalness.
7321 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
7323 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
7324 /// @c false otherwise.
7325 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
7326 TypeDiagnoser &Diagnoser) {
7327 assert(!T->isDependentType() && "type should not be dependent");
7329 QualType ElemType = Context.getBaseElementType(T);
7330 if ((isCompleteType(Loc, ElemType) || ElemType->isVoidType()) &&
7331 T->isLiteralType(Context))
7334 Diagnoser.diagnose(*this, Loc, T);
7336 if (T->isVariableArrayType())
7339 const RecordType *RT = ElemType->getAs<RecordType>();
7343 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
7345 // A partially-defined class type can't be a literal type, because a literal
7346 // class type must have a trivial destructor (which can't be checked until
7347 // the class definition is complete).
7348 if (RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T))
7351 // If the class has virtual base classes, then it's not an aggregate, and
7352 // cannot have any constexpr constructors or a trivial default constructor,
7353 // so is non-literal. This is better to diagnose than the resulting absence
7354 // of constexpr constructors.
7355 if (RD->getNumVBases()) {
7356 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
7357 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
7358 for (const auto &I : RD->vbases())
7359 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
7360 << I.getSourceRange();
7361 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
7362 !RD->hasTrivialDefaultConstructor()) {
7363 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
7364 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
7365 for (const auto &I : RD->bases()) {
7366 if (!I.getType()->isLiteralType(Context)) {
7367 Diag(I.getLocStart(),
7368 diag::note_non_literal_base_class)
7369 << RD << I.getType() << I.getSourceRange();
7373 for (const auto *I : RD->fields()) {
7374 if (!I->getType()->isLiteralType(Context) ||
7375 I->getType().isVolatileQualified()) {
7376 Diag(I->getLocation(), diag::note_non_literal_field)
7377 << RD << I << I->getType()
7378 << I->getType().isVolatileQualified();
7382 } else if (!RD->hasTrivialDestructor()) {
7383 // All fields and bases are of literal types, so have trivial destructors.
7384 // If this class's destructor is non-trivial it must be user-declared.
7385 CXXDestructorDecl *Dtor = RD->getDestructor();
7386 assert(Dtor && "class has literal fields and bases but no dtor?");
7390 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
7391 diag::note_non_literal_user_provided_dtor :
7392 diag::note_non_literal_nontrivial_dtor) << RD;
7393 if (!Dtor->isUserProvided())
7394 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
7400 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
7401 BoundTypeDiagnoser<> Diagnoser(DiagID);
7402 return RequireLiteralType(Loc, T, Diagnoser);
7405 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
7406 /// and qualified by the nested-name-specifier contained in SS.
7407 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
7408 const CXXScopeSpec &SS, QualType T) {
7411 NestedNameSpecifier *NNS;
7413 NNS = SS.getScopeRep();
7415 if (Keyword == ETK_None)
7419 return Context.getElaboratedType(Keyword, NNS, T);
7422 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
7423 ExprResult ER = CheckPlaceholderExpr(E);
7424 if (ER.isInvalid()) return QualType();
7427 if (!getLangOpts().CPlusPlus && E->refersToBitField())
7428 Diag(E->getExprLoc(), diag::err_sizeof_alignof_typeof_bitfield) << 2;
7430 if (!E->isTypeDependent()) {
7431 QualType T = E->getType();
7432 if (const TagType *TT = T->getAs<TagType>())
7433 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
7435 return Context.getTypeOfExprType(E);
7438 /// getDecltypeForExpr - Given an expr, will return the decltype for
7439 /// that expression, according to the rules in C++11
7440 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
7441 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
7442 if (E->isTypeDependent())
7443 return S.Context.DependentTy;
7445 // C++11 [dcl.type.simple]p4:
7446 // The type denoted by decltype(e) is defined as follows:
7448 // - if e is an unparenthesized id-expression or an unparenthesized class
7449 // member access (5.2.5), decltype(e) is the type of the entity named
7450 // by e. If there is no such entity, or if e names a set of overloaded
7451 // functions, the program is ill-formed;
7453 // We apply the same rules for Objective-C ivar and property references.
7454 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
7455 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
7456 return VD->getType();
7457 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
7458 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
7459 return FD->getType();
7460 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
7461 return IR->getDecl()->getType();
7462 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
7463 if (PR->isExplicitProperty())
7464 return PR->getExplicitProperty()->getType();
7465 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
7466 return PE->getType();
7469 // C++11 [expr.lambda.prim]p18:
7470 // Every occurrence of decltype((x)) where x is a possibly
7471 // parenthesized id-expression that names an entity of automatic
7472 // storage duration is treated as if x were transformed into an
7473 // access to a corresponding data member of the closure type that
7474 // would have been declared if x were an odr-use of the denoted
7476 using namespace sema;
7477 if (S.getCurLambda()) {
7478 if (isa<ParenExpr>(E)) {
7479 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
7480 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
7481 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
7483 return S.Context.getLValueReferenceType(T);
7490 // C++11 [dcl.type.simple]p4:
7492 QualType T = E->getType();
7493 switch (E->getValueKind()) {
7494 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
7496 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
7497 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
7499 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
7500 // - otherwise, decltype(e) is the type of e.
7501 case VK_RValue: break;
7507 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
7508 bool AsUnevaluated) {
7509 ExprResult ER = CheckPlaceholderExpr(E);
7510 if (ER.isInvalid()) return QualType();
7513 if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
7514 E->HasSideEffects(Context, false)) {
7515 // The expression operand for decltype is in an unevaluated expression
7516 // context, so side effects could result in unintended consequences.
7517 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
7520 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
7523 QualType Sema::BuildUnaryTransformType(QualType BaseType,
7524 UnaryTransformType::UTTKind UKind,
7525 SourceLocation Loc) {
7527 case UnaryTransformType::EnumUnderlyingType:
7528 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
7529 Diag(Loc, diag::err_only_enums_have_underlying_types);
7532 QualType Underlying = BaseType;
7533 if (!BaseType->isDependentType()) {
7534 // The enum could be incomplete if we're parsing its definition or
7535 // recovering from an error.
7536 NamedDecl *FwdDecl = nullptr;
7537 if (BaseType->isIncompleteType(&FwdDecl)) {
7538 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
7539 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
7543 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
7544 assert(ED && "EnumType has no EnumDecl");
7546 DiagnoseUseOfDecl(ED, Loc);
7548 Underlying = ED->getIntegerType();
7549 assert(!Underlying.isNull());
7551 return Context.getUnaryTransformType(BaseType, Underlying,
7552 UnaryTransformType::EnumUnderlyingType);
7555 llvm_unreachable("unknown unary transform type");
7558 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
7559 if (!T->isDependentType()) {
7560 // FIXME: It isn't entirely clear whether incomplete atomic types
7561 // are allowed or not; for simplicity, ban them for the moment.
7562 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
7565 int DisallowedKind = -1;
7566 if (T->isArrayType())
7568 else if (T->isFunctionType())
7570 else if (T->isReferenceType())
7572 else if (T->isAtomicType())
7574 else if (T.hasQualifiers())
7576 else if (!T.isTriviallyCopyableType(Context))
7577 // Some other non-trivially-copyable type (probably a C++ class)
7580 if (DisallowedKind != -1) {
7581 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
7585 // FIXME: Do we need any handling for ARC here?
7588 // Build the pointer type.
7589 return Context.getAtomicType(T);