1 //===--- SemaType.cpp - Semantic Analysis for Types -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements type-related semantic analysis.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "TypeLocBuilder.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/TypeLoc.h"
24 #include "clang/AST/TypeLocVisitor.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Basic/PartialDiagnostic.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Parse/ParseDiagnostic.h"
30 #include "clang/Sema/DeclSpec.h"
31 #include "clang/Sema/DelayedDiagnostic.h"
32 #include "clang/Sema/Lookup.h"
33 #include "clang/Sema/ScopeInfo.h"
34 #include "clang/Sema/Template.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallString.h"
37 #include "llvm/Support/ErrorHandling.h"
39 using namespace clang;
41 enum TypeDiagSelector {
47 /// isOmittedBlockReturnType - Return true if this declarator is missing a
48 /// return type because this is a omitted return type on a block literal.
49 static bool isOmittedBlockReturnType(const Declarator &D) {
50 if (D.getContext() != Declarator::BlockLiteralContext ||
51 D.getDeclSpec().hasTypeSpecifier())
54 if (D.getNumTypeObjects() == 0)
55 return true; // ^{ ... }
57 if (D.getNumTypeObjects() == 1 &&
58 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
59 return true; // ^(int X, float Y) { ... }
64 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
65 /// doesn't apply to the given type.
66 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
68 TypeDiagSelector WhichType;
69 bool useExpansionLoc = true;
70 switch (attr.getKind()) {
71 case AttributeList::AT_ObjCGC: WhichType = TDS_Pointer; break;
72 case AttributeList::AT_ObjCOwnership: WhichType = TDS_ObjCObjOrBlock; break;
74 // Assume everything else was a function attribute.
75 WhichType = TDS_Function;
76 useExpansionLoc = false;
80 SourceLocation loc = attr.getLoc();
81 StringRef name = attr.getName()->getName();
83 // The GC attributes are usually written with macros; special-case them.
84 IdentifierInfo *II = attr.isArgIdent(0) ? attr.getArgAsIdent(0)->Ident
86 if (useExpansionLoc && loc.isMacroID() && II) {
87 if (II->isStr("strong")) {
88 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
89 } else if (II->isStr("weak")) {
90 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
94 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
98 // objc_gc applies to Objective-C pointers or, otherwise, to the
99 // smallest available pointer type (i.e. 'void*' in 'void**').
100 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
101 case AttributeList::AT_ObjCGC: \
102 case AttributeList::AT_ObjCOwnership
104 // Function type attributes.
105 #define FUNCTION_TYPE_ATTRS_CASELIST \
106 case AttributeList::AT_NoReturn: \
107 case AttributeList::AT_CDecl: \
108 case AttributeList::AT_FastCall: \
109 case AttributeList::AT_StdCall: \
110 case AttributeList::AT_ThisCall: \
111 case AttributeList::AT_Pascal: \
112 case AttributeList::AT_VectorCall: \
113 case AttributeList::AT_MSABI: \
114 case AttributeList::AT_SysVABI: \
115 case AttributeList::AT_Regparm: \
116 case AttributeList::AT_Pcs: \
117 case AttributeList::AT_IntelOclBicc
119 // Microsoft-specific type qualifiers.
120 #define MS_TYPE_ATTRS_CASELIST \
121 case AttributeList::AT_Ptr32: \
122 case AttributeList::AT_Ptr64: \
123 case AttributeList::AT_SPtr: \
124 case AttributeList::AT_UPtr
126 // Nullability qualifiers.
127 #define NULLABILITY_TYPE_ATTRS_CASELIST \
128 case AttributeList::AT_TypeNonNull: \
129 case AttributeList::AT_TypeNullable: \
130 case AttributeList::AT_TypeNullUnspecified
133 /// An object which stores processing state for the entire
134 /// GetTypeForDeclarator process.
135 class TypeProcessingState {
138 /// The declarator being processed.
139 Declarator &declarator;
141 /// The index of the declarator chunk we're currently processing.
142 /// May be the total number of valid chunks, indicating the
146 /// Whether there are non-trivial modifications to the decl spec.
149 /// Whether we saved the attributes in the decl spec.
152 /// The original set of attributes on the DeclSpec.
153 SmallVector<AttributeList*, 2> savedAttrs;
155 /// A list of attributes to diagnose the uselessness of when the
156 /// processing is complete.
157 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
160 TypeProcessingState(Sema &sema, Declarator &declarator)
161 : sema(sema), declarator(declarator),
162 chunkIndex(declarator.getNumTypeObjects()),
163 trivial(true), hasSavedAttrs(false) {}
165 Sema &getSema() const {
169 Declarator &getDeclarator() const {
173 bool isProcessingDeclSpec() const {
174 return chunkIndex == declarator.getNumTypeObjects();
177 unsigned getCurrentChunkIndex() const {
181 void setCurrentChunkIndex(unsigned idx) {
182 assert(idx <= declarator.getNumTypeObjects());
186 AttributeList *&getCurrentAttrListRef() const {
187 if (isProcessingDeclSpec())
188 return getMutableDeclSpec().getAttributes().getListRef();
189 return declarator.getTypeObject(chunkIndex).getAttrListRef();
192 /// Save the current set of attributes on the DeclSpec.
193 void saveDeclSpecAttrs() {
194 // Don't try to save them multiple times.
195 if (hasSavedAttrs) return;
197 DeclSpec &spec = getMutableDeclSpec();
198 for (AttributeList *attr = spec.getAttributes().getList(); attr;
199 attr = attr->getNext())
200 savedAttrs.push_back(attr);
201 trivial &= savedAttrs.empty();
202 hasSavedAttrs = true;
205 /// Record that we had nowhere to put the given type attribute.
206 /// We will diagnose such attributes later.
207 void addIgnoredTypeAttr(AttributeList &attr) {
208 ignoredTypeAttrs.push_back(&attr);
211 /// Diagnose all the ignored type attributes, given that the
212 /// declarator worked out to the given type.
213 void diagnoseIgnoredTypeAttrs(QualType type) const {
214 for (SmallVectorImpl<AttributeList*>::const_iterator
215 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
217 diagnoseBadTypeAttribute(getSema(), **i, type);
220 ~TypeProcessingState() {
223 restoreDeclSpecAttrs();
227 DeclSpec &getMutableDeclSpec() const {
228 return const_cast<DeclSpec&>(declarator.getDeclSpec());
231 void restoreDeclSpecAttrs() {
232 assert(hasSavedAttrs);
234 if (savedAttrs.empty()) {
235 getMutableDeclSpec().getAttributes().set(nullptr);
239 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
240 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
241 savedAttrs[i]->setNext(savedAttrs[i+1]);
242 savedAttrs.back()->setNext(nullptr);
247 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
252 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
254 head = attr.getNext();
258 AttributeList *cur = head;
260 assert(cur && cur->getNext() && "ran out of attrs?");
261 if (cur->getNext() == &attr) {
262 cur->setNext(attr.getNext());
265 cur = cur->getNext();
269 static void moveAttrFromListToList(AttributeList &attr,
270 AttributeList *&fromList,
271 AttributeList *&toList) {
272 spliceAttrOutOfList(attr, fromList);
273 spliceAttrIntoList(attr, toList);
276 /// The location of a type attribute.
277 enum TypeAttrLocation {
278 /// The attribute is in the decl-specifier-seq.
280 /// The attribute is part of a DeclaratorChunk.
282 /// The attribute is immediately after the declaration's name.
286 static void processTypeAttrs(TypeProcessingState &state,
287 QualType &type, TypeAttrLocation TAL,
288 AttributeList *attrs);
290 static bool handleFunctionTypeAttr(TypeProcessingState &state,
294 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
298 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
299 AttributeList &attr, QualType &type);
301 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
302 AttributeList &attr, QualType &type);
304 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
305 AttributeList &attr, QualType &type) {
306 if (attr.getKind() == AttributeList::AT_ObjCGC)
307 return handleObjCGCTypeAttr(state, attr, type);
308 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
309 return handleObjCOwnershipTypeAttr(state, attr, type);
312 /// Given the index of a declarator chunk, check whether that chunk
313 /// directly specifies the return type of a function and, if so, find
314 /// an appropriate place for it.
316 /// \param i - a notional index which the search will start
317 /// immediately inside
319 /// \param onlyBlockPointers Whether we should only look into block
320 /// pointer types (vs. all pointer types).
321 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
323 bool onlyBlockPointers) {
324 assert(i <= declarator.getNumTypeObjects());
326 DeclaratorChunk *result = nullptr;
328 // First, look inwards past parens for a function declarator.
329 for (; i != 0; --i) {
330 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
331 switch (fnChunk.Kind) {
332 case DeclaratorChunk::Paren:
335 // If we find anything except a function, bail out.
336 case DeclaratorChunk::Pointer:
337 case DeclaratorChunk::BlockPointer:
338 case DeclaratorChunk::Array:
339 case DeclaratorChunk::Reference:
340 case DeclaratorChunk::MemberPointer:
343 // If we do find a function declarator, scan inwards from that,
344 // looking for a (block-)pointer declarator.
345 case DeclaratorChunk::Function:
346 for (--i; i != 0; --i) {
347 DeclaratorChunk &ptrChunk = declarator.getTypeObject(i-1);
348 switch (ptrChunk.Kind) {
349 case DeclaratorChunk::Paren:
350 case DeclaratorChunk::Array:
351 case DeclaratorChunk::Function:
352 case DeclaratorChunk::Reference:
355 case DeclaratorChunk::MemberPointer:
356 case DeclaratorChunk::Pointer:
357 if (onlyBlockPointers)
362 case DeclaratorChunk::BlockPointer:
366 llvm_unreachable("bad declarator chunk kind");
369 // If we run out of declarators doing that, we're done.
372 llvm_unreachable("bad declarator chunk kind");
374 // Okay, reconsider from our new point.
378 // Ran out of chunks, bail out.
382 /// Given that an objc_gc attribute was written somewhere on a
383 /// declaration *other* than on the declarator itself (for which, use
384 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
385 /// didn't apply in whatever position it was written in, try to move
386 /// it to a more appropriate position.
387 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
390 Declarator &declarator = state.getDeclarator();
392 // Move it to the outermost normal or block pointer declarator.
393 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
394 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
395 switch (chunk.Kind) {
396 case DeclaratorChunk::Pointer:
397 case DeclaratorChunk::BlockPointer: {
398 // But don't move an ARC ownership attribute to the return type
400 DeclaratorChunk *destChunk = nullptr;
401 if (state.isProcessingDeclSpec() &&
402 attr.getKind() == AttributeList::AT_ObjCOwnership)
403 destChunk = maybeMovePastReturnType(declarator, i - 1,
404 /*onlyBlockPointers=*/true);
405 if (!destChunk) destChunk = &chunk;
407 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
408 destChunk->getAttrListRef());
412 case DeclaratorChunk::Paren:
413 case DeclaratorChunk::Array:
416 // We may be starting at the return type of a block.
417 case DeclaratorChunk::Function:
418 if (state.isProcessingDeclSpec() &&
419 attr.getKind() == AttributeList::AT_ObjCOwnership) {
420 if (DeclaratorChunk *dest = maybeMovePastReturnType(
422 /*onlyBlockPointers=*/true)) {
423 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
424 dest->getAttrListRef());
430 // Don't walk through these.
431 case DeclaratorChunk::Reference:
432 case DeclaratorChunk::MemberPointer:
438 diagnoseBadTypeAttribute(state.getSema(), attr, type);
441 /// Distribute an objc_gc type attribute that was written on the
444 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
446 QualType &declSpecType) {
447 Declarator &declarator = state.getDeclarator();
449 // objc_gc goes on the innermost pointer to something that's not a
451 unsigned innermost = -1U;
452 bool considerDeclSpec = true;
453 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
454 DeclaratorChunk &chunk = declarator.getTypeObject(i);
455 switch (chunk.Kind) {
456 case DeclaratorChunk::Pointer:
457 case DeclaratorChunk::BlockPointer:
461 case DeclaratorChunk::Reference:
462 case DeclaratorChunk::MemberPointer:
463 case DeclaratorChunk::Paren:
464 case DeclaratorChunk::Array:
467 case DeclaratorChunk::Function:
468 considerDeclSpec = false;
474 // That might actually be the decl spec if we weren't blocked by
475 // anything in the declarator.
476 if (considerDeclSpec) {
477 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
478 // Splice the attribute into the decl spec. Prevents the
479 // attribute from being applied multiple times and gives
480 // the source-location-filler something to work with.
481 state.saveDeclSpecAttrs();
482 moveAttrFromListToList(attr, declarator.getAttrListRef(),
483 declarator.getMutableDeclSpec().getAttributes().getListRef());
488 // Otherwise, if we found an appropriate chunk, splice the attribute
490 if (innermost != -1U) {
491 moveAttrFromListToList(attr, declarator.getAttrListRef(),
492 declarator.getTypeObject(innermost).getAttrListRef());
496 // Otherwise, diagnose when we're done building the type.
497 spliceAttrOutOfList(attr, declarator.getAttrListRef());
498 state.addIgnoredTypeAttr(attr);
501 /// A function type attribute was written somewhere in a declaration
502 /// *other* than on the declarator itself or in the decl spec. Given
503 /// that it didn't apply in whatever position it was written in, try
504 /// to move it to a more appropriate position.
505 static void distributeFunctionTypeAttr(TypeProcessingState &state,
508 Declarator &declarator = state.getDeclarator();
510 // Try to push the attribute from the return type of a function to
511 // the function itself.
512 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
513 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
514 switch (chunk.Kind) {
515 case DeclaratorChunk::Function:
516 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
517 chunk.getAttrListRef());
520 case DeclaratorChunk::Paren:
521 case DeclaratorChunk::Pointer:
522 case DeclaratorChunk::BlockPointer:
523 case DeclaratorChunk::Array:
524 case DeclaratorChunk::Reference:
525 case DeclaratorChunk::MemberPointer:
530 diagnoseBadTypeAttribute(state.getSema(), attr, type);
533 /// Try to distribute a function type attribute to the innermost
534 /// function chunk or type. Returns true if the attribute was
535 /// distributed, false if no location was found.
537 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
539 AttributeList *&attrList,
540 QualType &declSpecType) {
541 Declarator &declarator = state.getDeclarator();
543 // Put it on the innermost function chunk, if there is one.
544 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
545 DeclaratorChunk &chunk = declarator.getTypeObject(i);
546 if (chunk.Kind != DeclaratorChunk::Function) continue;
548 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
552 return handleFunctionTypeAttr(state, attr, declSpecType);
555 /// A function type attribute was written in the decl spec. Try to
556 /// apply it somewhere.
558 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
560 QualType &declSpecType) {
561 state.saveDeclSpecAttrs();
563 // C++11 attributes before the decl specifiers actually appertain to
564 // the declarators. Move them straight there. We don't support the
565 // 'put them wherever you like' semantics we allow for GNU attributes.
566 if (attr.isCXX11Attribute()) {
567 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
568 state.getDeclarator().getAttrListRef());
572 // Try to distribute to the innermost.
573 if (distributeFunctionTypeAttrToInnermost(state, attr,
574 state.getCurrentAttrListRef(),
578 // If that failed, diagnose the bad attribute when the declarator is
580 state.addIgnoredTypeAttr(attr);
583 /// A function type attribute was written on the declarator. Try to
584 /// apply it somewhere.
586 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
588 QualType &declSpecType) {
589 Declarator &declarator = state.getDeclarator();
591 // Try to distribute to the innermost.
592 if (distributeFunctionTypeAttrToInnermost(state, attr,
593 declarator.getAttrListRef(),
597 // If that failed, diagnose the bad attribute when the declarator is
599 spliceAttrOutOfList(attr, declarator.getAttrListRef());
600 state.addIgnoredTypeAttr(attr);
603 /// \brief Given that there are attributes written on the declarator
604 /// itself, try to distribute any type attributes to the appropriate
605 /// declarator chunk.
607 /// These are attributes like the following:
610 /// but not necessarily this:
612 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
613 QualType &declSpecType) {
614 // Collect all the type attributes from the declarator itself.
615 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
616 AttributeList *attr = state.getDeclarator().getAttributes();
619 next = attr->getNext();
621 // Do not distribute C++11 attributes. They have strict rules for what
622 // they appertain to.
623 if (attr->isCXX11Attribute())
626 switch (attr->getKind()) {
627 OBJC_POINTER_TYPE_ATTRS_CASELIST:
628 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
631 case AttributeList::AT_NSReturnsRetained:
632 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
636 FUNCTION_TYPE_ATTRS_CASELIST:
637 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
640 MS_TYPE_ATTRS_CASELIST:
641 // Microsoft type attributes cannot go after the declarator-id.
644 NULLABILITY_TYPE_ATTRS_CASELIST:
645 // Nullability specifiers cannot go after the declarator-id.
651 } while ((attr = next));
654 /// Add a synthetic '()' to a block-literal declarator if it is
655 /// required, given the return type.
656 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
657 QualType declSpecType) {
658 Declarator &declarator = state.getDeclarator();
660 // First, check whether the declarator would produce a function,
661 // i.e. whether the innermost semantic chunk is a function.
662 if (declarator.isFunctionDeclarator()) {
663 // If so, make that declarator a prototyped declarator.
664 declarator.getFunctionTypeInfo().hasPrototype = true;
668 // If there are any type objects, the type as written won't name a
669 // function, regardless of the decl spec type. This is because a
670 // block signature declarator is always an abstract-declarator, and
671 // abstract-declarators can't just be parentheses chunks. Therefore
672 // we need to build a function chunk unless there are no type
673 // objects and the decl spec type is a function.
674 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
677 // Note that there *are* cases with invalid declarators where
678 // declarators consist solely of parentheses. In general, these
679 // occur only in failed efforts to make function declarators, so
680 // faking up the function chunk is still the right thing to do.
682 // Otherwise, we need to fake up a function declarator.
683 SourceLocation loc = declarator.getLocStart();
685 // ...and *prepend* it to the declarator.
686 SourceLocation NoLoc;
687 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
689 /*IsAmbiguous=*/false,
693 /*EllipsisLoc=*/NoLoc,
696 /*RefQualifierIsLvalueRef=*/true,
697 /*RefQualifierLoc=*/NoLoc,
698 /*ConstQualifierLoc=*/NoLoc,
699 /*VolatileQualifierLoc=*/NoLoc,
700 /*RestrictQualifierLoc=*/NoLoc,
701 /*MutableLoc=*/NoLoc, EST_None,
703 /*Exceptions=*/nullptr,
704 /*ExceptionRanges=*/nullptr,
706 /*NoexceptExpr=*/nullptr,
707 /*ExceptionSpecTokens=*/nullptr,
708 loc, loc, declarator));
710 // For consistency, make sure the state still has us as processing
712 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
713 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
716 static void diagnoseAndRemoveTypeQualifiers(Sema &S, const DeclSpec &DS,
721 // If this occurs outside a template instantiation, warn the user about
722 // it; they probably didn't mean to specify a redundant qualifier.
723 typedef std::pair<DeclSpec::TQ, SourceLocation> QualLoc;
724 for (QualLoc Qual : {QualLoc(DeclSpec::TQ_const, DS.getConstSpecLoc()),
725 QualLoc(DeclSpec::TQ_volatile, DS.getVolatileSpecLoc()),
726 QualLoc(DeclSpec::TQ_atomic, DS.getAtomicSpecLoc())}) {
727 if (!(RemoveTQs & Qual.first))
730 if (S.ActiveTemplateInstantiations.empty()) {
731 if (TypeQuals & Qual.first)
732 S.Diag(Qual.second, DiagID)
733 << DeclSpec::getSpecifierName(Qual.first) << TypeSoFar
734 << FixItHint::CreateRemoval(Qual.second);
737 TypeQuals &= ~Qual.first;
741 /// \brief Convert the specified declspec to the appropriate type
743 /// \param state Specifies the declarator containing the declaration specifier
744 /// to be converted, along with other associated processing state.
745 /// \returns The type described by the declaration specifiers. This function
746 /// never returns null.
747 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
748 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
751 Sema &S = state.getSema();
752 Declarator &declarator = state.getDeclarator();
753 const DeclSpec &DS = declarator.getDeclSpec();
754 SourceLocation DeclLoc = declarator.getIdentifierLoc();
755 if (DeclLoc.isInvalid())
756 DeclLoc = DS.getLocStart();
758 ASTContext &Context = S.Context;
761 switch (DS.getTypeSpecType()) {
762 case DeclSpec::TST_void:
763 Result = Context.VoidTy;
765 case DeclSpec::TST_char:
766 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
767 Result = Context.CharTy;
768 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
769 Result = Context.SignedCharTy;
771 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
772 "Unknown TSS value");
773 Result = Context.UnsignedCharTy;
776 case DeclSpec::TST_wchar:
777 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
778 Result = Context.WCharTy;
779 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
780 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
781 << DS.getSpecifierName(DS.getTypeSpecType(),
782 Context.getPrintingPolicy());
783 Result = Context.getSignedWCharType();
785 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
786 "Unknown TSS value");
787 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
788 << DS.getSpecifierName(DS.getTypeSpecType(),
789 Context.getPrintingPolicy());
790 Result = Context.getUnsignedWCharType();
793 case DeclSpec::TST_char16:
794 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
795 "Unknown TSS value");
796 Result = Context.Char16Ty;
798 case DeclSpec::TST_char32:
799 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
800 "Unknown TSS value");
801 Result = Context.Char32Ty;
803 case DeclSpec::TST_unspecified:
804 // "<proto1,proto2>" is an objc qualified ID with a missing id.
805 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
806 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
807 (ObjCProtocolDecl*const*)PQ,
808 DS.getNumProtocolQualifiers());
809 Result = Context.getObjCObjectPointerType(Result);
813 // If this is a missing declspec in a block literal return context, then it
814 // is inferred from the return statements inside the block.
815 // The declspec is always missing in a lambda expr context; it is either
816 // specified with a trailing return type or inferred.
817 if (S.getLangOpts().CPlusPlus14 &&
818 declarator.getContext() == Declarator::LambdaExprContext) {
819 // In C++1y, a lambda's implicit return type is 'auto'.
820 Result = Context.getAutoDeductType();
822 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
823 isOmittedBlockReturnType(declarator)) {
824 Result = Context.DependentTy;
828 // Unspecified typespec defaults to int in C90. However, the C90 grammar
829 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
830 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
831 // Note that the one exception to this is function definitions, which are
832 // allowed to be completely missing a declspec. This is handled in the
833 // parser already though by it pretending to have seen an 'int' in this
835 if (S.getLangOpts().ImplicitInt) {
836 // In C89 mode, we only warn if there is a completely missing declspec
837 // when one is not allowed.
839 S.Diag(DeclLoc, diag::ext_missing_declspec)
840 << DS.getSourceRange()
841 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
843 } else if (!DS.hasTypeSpecifier()) {
844 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
845 // "At least one type specifier shall be given in the declaration
846 // specifiers in each declaration, and in the specifier-qualifier list in
847 // each struct declaration and type name."
848 if (S.getLangOpts().CPlusPlus) {
849 S.Diag(DeclLoc, diag::err_missing_type_specifier)
850 << DS.getSourceRange();
852 // When this occurs in C++ code, often something is very broken with the
853 // value being declared, poison it as invalid so we don't get chains of
855 declarator.setInvalidType(true);
857 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
858 << DS.getSourceRange();
863 case DeclSpec::TST_int: {
864 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
865 switch (DS.getTypeSpecWidth()) {
866 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
867 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
868 case DeclSpec::TSW_long: Result = Context.LongTy; break;
869 case DeclSpec::TSW_longlong:
870 Result = Context.LongLongTy;
872 // 'long long' is a C99 or C++11 feature.
873 if (!S.getLangOpts().C99) {
874 if (S.getLangOpts().CPlusPlus)
875 S.Diag(DS.getTypeSpecWidthLoc(),
876 S.getLangOpts().CPlusPlus11 ?
877 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
879 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
884 switch (DS.getTypeSpecWidth()) {
885 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
886 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
887 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
888 case DeclSpec::TSW_longlong:
889 Result = Context.UnsignedLongLongTy;
891 // 'long long' is a C99 or C++11 feature.
892 if (!S.getLangOpts().C99) {
893 if (S.getLangOpts().CPlusPlus)
894 S.Diag(DS.getTypeSpecWidthLoc(),
895 S.getLangOpts().CPlusPlus11 ?
896 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
898 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
905 case DeclSpec::TST_int128:
906 if (!S.Context.getTargetInfo().hasInt128Type())
907 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
908 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
909 Result = Context.UnsignedInt128Ty;
911 Result = Context.Int128Ty;
913 case DeclSpec::TST_half: Result = Context.HalfTy; break;
914 case DeclSpec::TST_float: Result = Context.FloatTy; break;
915 case DeclSpec::TST_double:
916 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
917 Result = Context.LongDoubleTy;
919 Result = Context.DoubleTy;
921 if (S.getLangOpts().OpenCL &&
922 !((S.getLangOpts().OpenCLVersion >= 120) ||
923 S.getOpenCLOptions().cl_khr_fp64)) {
924 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
925 << Result << "cl_khr_fp64";
926 declarator.setInvalidType(true);
929 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
930 case DeclSpec::TST_decimal32: // _Decimal32
931 case DeclSpec::TST_decimal64: // _Decimal64
932 case DeclSpec::TST_decimal128: // _Decimal128
933 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
934 Result = Context.IntTy;
935 declarator.setInvalidType(true);
937 case DeclSpec::TST_class:
938 case DeclSpec::TST_enum:
939 case DeclSpec::TST_union:
940 case DeclSpec::TST_struct:
941 case DeclSpec::TST_interface: {
942 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
944 // This can happen in C++ with ambiguous lookups.
945 Result = Context.IntTy;
946 declarator.setInvalidType(true);
950 // If the type is deprecated or unavailable, diagnose it.
951 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
953 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
954 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
956 // TypeQuals handled by caller.
957 Result = Context.getTypeDeclType(D);
959 // In both C and C++, make an ElaboratedType.
960 ElaboratedTypeKeyword Keyword
961 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
962 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
965 case DeclSpec::TST_typename: {
966 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
967 DS.getTypeSpecSign() == 0 &&
968 "Can't handle qualifiers on typedef names yet!");
969 Result = S.GetTypeFromParser(DS.getRepAsType());
971 declarator.setInvalidType(true);
972 else if (DeclSpec::ProtocolQualifierListTy PQ
973 = DS.getProtocolQualifiers()) {
974 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
975 // Silently drop any existing protocol qualifiers.
976 // TODO: determine whether that's the right thing to do.
977 if (ObjT->getNumProtocols())
978 Result = ObjT->getBaseType();
980 if (DS.getNumProtocolQualifiers())
981 Result = Context.getObjCObjectType(Result,
982 (ObjCProtocolDecl*const*) PQ,
983 DS.getNumProtocolQualifiers());
984 } else if (Result->isObjCIdType()) {
986 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
987 (ObjCProtocolDecl*const*) PQ,
988 DS.getNumProtocolQualifiers());
989 Result = Context.getObjCObjectPointerType(Result);
990 } else if (Result->isObjCClassType()) {
991 // Class<protocol-list>
992 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
993 (ObjCProtocolDecl*const*) PQ,
994 DS.getNumProtocolQualifiers());
995 Result = Context.getObjCObjectPointerType(Result);
997 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
998 << DS.getSourceRange();
999 declarator.setInvalidType(true);
1001 } else if (S.getLangOpts().OpenCL) {
1002 if (const AtomicType *AT = Result->getAs<AtomicType>()) {
1003 const BuiltinType *BT = AT->getValueType()->getAs<BuiltinType>();
1004 bool NoExtTypes = BT && (BT->getKind() == BuiltinType::Int ||
1005 BT->getKind() == BuiltinType::UInt ||
1006 BT->getKind() == BuiltinType::Float);
1007 if (!S.getOpenCLOptions().cl_khr_int64_base_atomics && !NoExtTypes) {
1008 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1009 << Result << "cl_khr_int64_base_atomics";
1010 declarator.setInvalidType(true);
1012 if (!S.getOpenCLOptions().cl_khr_int64_extended_atomics &&
1014 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1015 << Result << "cl_khr_int64_extended_atomics";
1016 declarator.setInvalidType(true);
1018 if (!S.getOpenCLOptions().cl_khr_fp64 && BT &&
1019 BT->getKind() == BuiltinType::Double) {
1020 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_type_requires_extension)
1021 << Result << "cl_khr_fp64";
1022 declarator.setInvalidType(true);
1027 // TypeQuals handled by caller.
1030 case DeclSpec::TST_typeofType:
1031 // FIXME: Preserve type source info.
1032 Result = S.GetTypeFromParser(DS.getRepAsType());
1033 assert(!Result.isNull() && "Didn't get a type for typeof?");
1034 if (!Result->isDependentType())
1035 if (const TagType *TT = Result->getAs<TagType>())
1036 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
1037 // TypeQuals handled by caller.
1038 Result = Context.getTypeOfType(Result);
1040 case DeclSpec::TST_typeofExpr: {
1041 Expr *E = DS.getRepAsExpr();
1042 assert(E && "Didn't get an expression for typeof?");
1043 // TypeQuals handled by caller.
1044 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
1045 if (Result.isNull()) {
1046 Result = Context.IntTy;
1047 declarator.setInvalidType(true);
1051 case DeclSpec::TST_decltype: {
1052 Expr *E = DS.getRepAsExpr();
1053 assert(E && "Didn't get an expression for decltype?");
1054 // TypeQuals handled by caller.
1055 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
1056 if (Result.isNull()) {
1057 Result = Context.IntTy;
1058 declarator.setInvalidType(true);
1062 case DeclSpec::TST_underlyingType:
1063 Result = S.GetTypeFromParser(DS.getRepAsType());
1064 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
1065 Result = S.BuildUnaryTransformType(Result,
1066 UnaryTransformType::EnumUnderlyingType,
1067 DS.getTypeSpecTypeLoc());
1068 if (Result.isNull()) {
1069 Result = Context.IntTy;
1070 declarator.setInvalidType(true);
1074 case DeclSpec::TST_auto:
1075 // TypeQuals handled by caller.
1076 // If auto is mentioned in a lambda parameter context, convert it to a
1077 // template parameter type immediately, with the appropriate depth and
1078 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1079 // being analyzed (which tracks the invented type template parameter).
1080 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1081 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1082 assert(LSI && "No LambdaScopeInfo on the stack!");
1083 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1084 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1085 const bool IsParameterPack = declarator.hasEllipsis();
1087 // Turns out we must create the TemplateTypeParmDecl here to
1088 // retrieve the corresponding template parameter type.
1089 TemplateTypeParmDecl *CorrespondingTemplateParam =
1090 TemplateTypeParmDecl::Create(Context,
1091 // Temporarily add to the TranslationUnit DeclContext. When the
1092 // associated TemplateParameterList is attached to a template
1093 // declaration (such as FunctionTemplateDecl), the DeclContext
1094 // for each template parameter gets updated appropriately via
1095 // a call to AdoptTemplateParameterList.
1096 Context.getTranslationUnitDecl(),
1097 /*KeyLoc*/ SourceLocation(),
1098 /*NameLoc*/ declarator.getLocStart(),
1099 TemplateParameterDepth,
1100 AutoParameterPosition, // our template param index
1101 /* Identifier*/ nullptr, false, IsParameterPack);
1102 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1103 // Replace the 'auto' in the function parameter with this invented
1104 // template type parameter.
1105 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1107 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1111 case DeclSpec::TST_decltype_auto:
1112 Result = Context.getAutoType(QualType(),
1113 /*decltype(auto)*/true,
1114 /*IsDependent*/ false);
1117 case DeclSpec::TST_unknown_anytype:
1118 Result = Context.UnknownAnyTy;
1121 case DeclSpec::TST_atomic:
1122 Result = S.GetTypeFromParser(DS.getRepAsType());
1123 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1124 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1125 if (Result.isNull()) {
1126 Result = Context.IntTy;
1127 declarator.setInvalidType(true);
1131 case DeclSpec::TST_error:
1132 Result = Context.IntTy;
1133 declarator.setInvalidType(true);
1137 // Handle complex types.
1138 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1139 if (S.getLangOpts().Freestanding)
1140 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1141 Result = Context.getComplexType(Result);
1142 } else if (DS.isTypeAltiVecVector()) {
1143 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1144 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1145 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1146 if (DS.isTypeAltiVecPixel())
1147 VecKind = VectorType::AltiVecPixel;
1148 else if (DS.isTypeAltiVecBool())
1149 VecKind = VectorType::AltiVecBool;
1150 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1153 // FIXME: Imaginary.
1154 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1155 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1157 // Before we process any type attributes, synthesize a block literal
1158 // function declarator if necessary.
1159 if (declarator.getContext() == Declarator::BlockLiteralContext)
1160 maybeSynthesizeBlockSignature(state, Result);
1162 // Apply any type attributes from the decl spec. This may cause the
1163 // list of type attributes to be temporarily saved while the type
1164 // attributes are pushed around.
1165 if (AttributeList *attrs = DS.getAttributes().getList())
1166 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1168 // Apply const/volatile/restrict qualifiers to T.
1169 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1170 // Warn about CV qualifiers on function types.
1172 // If the specification of a function type includes any type qualifiers,
1173 // the behavior is undefined.
1174 // C++11 [dcl.fct]p7:
1175 // The effect of a cv-qualifier-seq in a function declarator is not the
1176 // same as adding cv-qualification on top of the function type. In the
1177 // latter case, the cv-qualifiers are ignored.
1178 if (TypeQuals && Result->isFunctionType()) {
1179 diagnoseAndRemoveTypeQualifiers(
1180 S, DS, TypeQuals, Result, DeclSpec::TQ_const | DeclSpec::TQ_volatile,
1181 S.getLangOpts().CPlusPlus
1182 ? diag::warn_typecheck_function_qualifiers_ignored
1183 : diag::warn_typecheck_function_qualifiers_unspecified);
1184 // No diagnostic for 'restrict' or '_Atomic' applied to a
1185 // function type; we'll diagnose those later, in BuildQualifiedType.
1188 // C++11 [dcl.ref]p1:
1189 // Cv-qualified references are ill-formed except when the
1190 // cv-qualifiers are introduced through the use of a typedef-name
1191 // or decltype-specifier, in which case the cv-qualifiers are ignored.
1193 // There don't appear to be any other contexts in which a cv-qualified
1194 // reference type could be formed, so the 'ill-formed' clause here appears
1196 if (TypeQuals && Result->isReferenceType()) {
1197 diagnoseAndRemoveTypeQualifiers(
1198 S, DS, TypeQuals, Result,
1199 DeclSpec::TQ_const | DeclSpec::TQ_volatile | DeclSpec::TQ_atomic,
1200 diag::warn_typecheck_reference_qualifiers);
1203 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1204 // than once in the same specifier-list or qualifier-list, either directly
1205 // or via one or more typedefs."
1206 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1207 && TypeQuals & Result.getCVRQualifiers()) {
1208 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1209 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1213 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1214 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1218 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1219 // produce a warning in this case.
1222 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1224 // If adding qualifiers fails, just use the unqualified type.
1225 if (Qualified.isNull())
1226 declarator.setInvalidType(true);
1231 assert(!Result.isNull() && "This function should not return a null type");
1235 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1237 return Entity.getAsString();
1242 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1243 Qualifiers Qs, const DeclSpec *DS) {
1247 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1248 // object or incomplete types shall not be restrict-qualified."
1249 if (Qs.hasRestrict()) {
1250 unsigned DiagID = 0;
1253 if (T->isAnyPointerType() || T->isReferenceType() ||
1254 T->isMemberPointerType()) {
1256 if (T->isObjCObjectPointerType())
1258 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1259 EltTy = PTy->getPointeeType();
1261 EltTy = T->getPointeeType();
1263 // If we have a pointer or reference, the pointee must have an object
1265 if (!EltTy->isIncompleteOrObjectType()) {
1266 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1269 } else if (!T->isDependentType()) {
1270 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1275 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1276 Qs.removeRestrict();
1280 return Context.getQualifiedType(T, Qs);
1283 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1284 unsigned CVRA, const DeclSpec *DS) {
1288 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1289 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1292 // If the same qualifier appears more than once in the same
1293 // specifier-qualifier-list, either directly or via one or more typedefs,
1294 // the behavior is the same as if it appeared only once.
1296 // It's not specified what happens when the _Atomic qualifier is applied to
1297 // a type specified with the _Atomic specifier, but we assume that this
1298 // should be treated as if the _Atomic qualifier appeared multiple times.
1299 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1301 // If other qualifiers appear along with the _Atomic qualifier in a
1302 // specifier-qualifier-list, the resulting type is the so-qualified
1305 // Don't need to worry about array types here, since _Atomic can't be
1306 // applied to such types.
1307 SplitQualType Split = T.getSplitUnqualifiedType();
1308 T = BuildAtomicType(QualType(Split.Ty, 0),
1309 DS ? DS->getAtomicSpecLoc() : Loc);
1312 Split.Quals.addCVRQualifiers(CVR);
1313 return BuildQualifiedType(T, Loc, Split.Quals);
1316 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1319 /// \brief Build a paren type including \p T.
1320 QualType Sema::BuildParenType(QualType T) {
1321 return Context.getParenType(T);
1324 /// Given that we're building a pointer or reference to the given
1325 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1328 // Bail out if retention is unrequired or already specified.
1329 if (!type->isObjCLifetimeType() ||
1330 type.getObjCLifetime() != Qualifiers::OCL_None)
1333 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1335 // If the object type is const-qualified, we can safely use
1336 // __unsafe_unretained. This is safe (because there are no read
1337 // barriers), and it'll be safe to coerce anything but __weak* to
1338 // the resulting type.
1339 if (type.isConstQualified()) {
1340 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1342 // Otherwise, check whether the static type does not require
1343 // retaining. This currently only triggers for Class (possibly
1344 // protocol-qualifed, and arrays thereof).
1345 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1346 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1348 // If we are in an unevaluated context, like sizeof, skip adding a
1350 } else if (S.isUnevaluatedContext()) {
1353 // If that failed, give an error and recover using __strong. __strong
1354 // is the option most likely to prevent spurious second-order diagnostics,
1355 // like when binding a reference to a field.
1357 // These types can show up in private ivars in system headers, so
1358 // we need this to not be an error in those cases. Instead we
1360 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1361 S.DelayedDiagnostics.add(
1362 sema::DelayedDiagnostic::makeForbiddenType(loc,
1363 diag::err_arc_indirect_no_ownership, type, isReference));
1365 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1367 implicitLifetime = Qualifiers::OCL_Strong;
1369 assert(implicitLifetime && "didn't infer any lifetime!");
1372 qs.addObjCLifetime(implicitLifetime);
1373 return S.Context.getQualifiedType(type, qs);
1376 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
1378 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1380 switch (FnTy->getRefQualifier()) {
1401 /// Kinds of declarator that cannot contain a qualified function type.
1403 /// C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6:
1404 /// a function type with a cv-qualifier or a ref-qualifier can only appear
1405 /// at the topmost level of a type.
1407 /// Parens and member pointers are permitted. We don't diagnose array and
1408 /// function declarators, because they don't allow function types at all.
1410 /// The values of this enum are used in diagnostics.
1411 enum QualifiedFunctionKind { QFK_BlockPointer, QFK_Pointer, QFK_Reference };
1414 /// Check whether the type T is a qualified function type, and if it is,
1415 /// diagnose that it cannot be contained within the given kind of declarator.
1416 static bool checkQualifiedFunction(Sema &S, QualType T, SourceLocation Loc,
1417 QualifiedFunctionKind QFK) {
1418 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
1419 const FunctionProtoType *FPT = T->getAs<FunctionProtoType>();
1420 if (!FPT || (FPT->getTypeQuals() == 0 && FPT->getRefQualifier() == RQ_None))
1423 S.Diag(Loc, diag::err_compound_qualified_function_type)
1424 << QFK << isa<FunctionType>(T.IgnoreParens()) << T
1425 << getFunctionQualifiersAsString(FPT);
1429 /// \brief Build a pointer type.
1431 /// \param T The type to which we'll be building a pointer.
1433 /// \param Loc The location of the entity whose type involves this
1434 /// pointer type or, if there is no such entity, the location of the
1435 /// type that will have pointer type.
1437 /// \param Entity The name of the entity that involves the pointer
1440 /// \returns A suitable pointer type, if there are no
1441 /// errors. Otherwise, returns a NULL type.
1442 QualType Sema::BuildPointerType(QualType T,
1443 SourceLocation Loc, DeclarationName Entity) {
1444 if (T->isReferenceType()) {
1445 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1446 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1447 << getPrintableNameForEntity(Entity) << T;
1451 if (checkQualifiedFunction(*this, T, Loc, QFK_Pointer))
1454 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1456 // In ARC, it is forbidden to build pointers to unqualified pointers.
1457 if (getLangOpts().ObjCAutoRefCount)
1458 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1460 // Build the pointer type.
1461 return Context.getPointerType(T);
1464 /// \brief Build a reference type.
1466 /// \param T The type to which we'll be building a reference.
1468 /// \param Loc The location of the entity whose type involves this
1469 /// reference type or, if there is no such entity, the location of the
1470 /// type that will have reference type.
1472 /// \param Entity The name of the entity that involves the reference
1475 /// \returns A suitable reference type, if there are no
1476 /// errors. Otherwise, returns a NULL type.
1477 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1479 DeclarationName Entity) {
1480 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1481 "Unresolved overloaded function type");
1483 // C++0x [dcl.ref]p6:
1484 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1485 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1486 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1487 // the type "lvalue reference to T", while an attempt to create the type
1488 // "rvalue reference to cv TR" creates the type TR.
1489 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1491 // C++ [dcl.ref]p4: There shall be no references to references.
1493 // According to C++ DR 106, references to references are only
1494 // diagnosed when they are written directly (e.g., "int & &"),
1495 // but not when they happen via a typedef:
1497 // typedef int& intref;
1498 // typedef intref& intref2;
1500 // Parser::ParseDeclaratorInternal diagnoses the case where
1501 // references are written directly; here, we handle the
1502 // collapsing of references-to-references as described in C++0x.
1503 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1506 // A declarator that specifies the type "reference to cv void"
1508 if (T->isVoidType()) {
1509 Diag(Loc, diag::err_reference_to_void);
1513 if (checkQualifiedFunction(*this, T, Loc, QFK_Reference))
1516 // In ARC, it is forbidden to build references to unqualified pointers.
1517 if (getLangOpts().ObjCAutoRefCount)
1518 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1520 // Handle restrict on references.
1522 return Context.getLValueReferenceType(T, SpelledAsLValue);
1523 return Context.getRValueReferenceType(T);
1526 /// Check whether the specified array size makes the array type a VLA. If so,
1527 /// return true, if not, return the size of the array in SizeVal.
1528 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1529 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1530 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1531 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1533 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1535 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) override {
1538 void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) override {
1539 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1543 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1544 S.LangOpts.GNUMode).isInvalid();
1548 /// \brief Build an array type.
1550 /// \param T The type of each element in the array.
1552 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1554 /// \param ArraySize Expression describing the size of the array.
1556 /// \param Brackets The range from the opening '[' to the closing ']'.
1558 /// \param Entity The name of the entity that involves the array
1561 /// \returns A suitable array type, if there are no errors. Otherwise,
1562 /// returns a NULL type.
1563 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1564 Expr *ArraySize, unsigned Quals,
1565 SourceRange Brackets, DeclarationName Entity) {
1567 SourceLocation Loc = Brackets.getBegin();
1568 if (getLangOpts().CPlusPlus) {
1569 // C++ [dcl.array]p1:
1570 // T is called the array element type; this type shall not be a reference
1571 // type, the (possibly cv-qualified) type void, a function type or an
1572 // abstract class type.
1574 // C++ [dcl.array]p3:
1575 // When several "array of" specifications are adjacent, [...] only the
1576 // first of the constant expressions that specify the bounds of the arrays
1579 // Note: function types are handled in the common path with C.
1580 if (T->isReferenceType()) {
1581 Diag(Loc, diag::err_illegal_decl_array_of_references)
1582 << getPrintableNameForEntity(Entity) << T;
1586 if (T->isVoidType() || T->isIncompleteArrayType()) {
1587 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1591 if (RequireNonAbstractType(Brackets.getBegin(), T,
1592 diag::err_array_of_abstract_type))
1595 // Mentioning a member pointer type for an array type causes us to lock in
1596 // an inheritance model, even if it's inside an unused typedef.
1597 if (Context.getTargetInfo().getCXXABI().isMicrosoft())
1598 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>())
1599 if (!MPTy->getClass()->isDependentType())
1600 RequireCompleteType(Loc, T, 0);
1603 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1604 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1605 if (RequireCompleteType(Loc, T,
1606 diag::err_illegal_decl_array_incomplete_type))
1610 if (T->isFunctionType()) {
1611 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1612 << getPrintableNameForEntity(Entity) << T;
1616 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1617 // If the element type is a struct or union that contains a variadic
1618 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1619 if (EltTy->getDecl()->hasFlexibleArrayMember())
1620 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1621 } else if (T->isObjCObjectType()) {
1622 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1626 // Do placeholder conversions on the array size expression.
1627 if (ArraySize && ArraySize->hasPlaceholderType()) {
1628 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1629 if (Result.isInvalid()) return QualType();
1630 ArraySize = Result.get();
1633 // Do lvalue-to-rvalue conversions on the array size expression.
1634 if (ArraySize && !ArraySize->isRValue()) {
1635 ExprResult Result = DefaultLvalueConversion(ArraySize);
1636 if (Result.isInvalid())
1639 ArraySize = Result.get();
1642 // C99 6.7.5.2p1: The size expression shall have integer type.
1643 // C++11 allows contextual conversions to such types.
1644 if (!getLangOpts().CPlusPlus11 &&
1645 ArraySize && !ArraySize->isTypeDependent() &&
1646 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1647 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1648 << ArraySize->getType() << ArraySize->getSourceRange();
1652 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1654 if (ASM == ArrayType::Star)
1655 T = Context.getVariableArrayType(T, nullptr, ASM, Quals, Brackets);
1657 T = Context.getIncompleteArrayType(T, ASM, Quals);
1658 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1659 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1660 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1661 !T->isConstantSizeType()) ||
1662 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1663 // Even in C++11, don't allow contextual conversions in the array bound
1665 if (getLangOpts().CPlusPlus11 &&
1666 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1667 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1668 << ArraySize->getType() << ArraySize->getSourceRange();
1672 // C99: an array with an element type that has a non-constant-size is a VLA.
1673 // C99: an array with a non-ICE size is a VLA. We accept any expression
1674 // that we can fold to a non-zero positive value as an extension.
1675 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1677 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1678 // have a value greater than zero.
1679 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1681 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1682 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1684 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1685 << ArraySize->getSourceRange();
1688 if (ConstVal == 0) {
1689 // GCC accepts zero sized static arrays. We allow them when
1690 // we're not in a SFINAE context.
1691 Diag(ArraySize->getLocStart(),
1692 isSFINAEContext()? diag::err_typecheck_zero_array_size
1693 : diag::ext_typecheck_zero_array_size)
1694 << ArraySize->getSourceRange();
1696 if (ASM == ArrayType::Static) {
1697 Diag(ArraySize->getLocStart(),
1698 diag::warn_typecheck_zero_static_array_size)
1699 << ArraySize->getSourceRange();
1700 ASM = ArrayType::Normal;
1702 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1703 !T->isIncompleteType() && !T->isUndeducedType()) {
1704 // Is the array too large?
1705 unsigned ActiveSizeBits
1706 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1707 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1708 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1709 << ConstVal.toString(10)
1710 << ArraySize->getSourceRange();
1715 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1718 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1719 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1720 Diag(Loc, diag::err_opencl_vla);
1723 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1724 if (!getLangOpts().C99) {
1725 if (T->isVariableArrayType()) {
1726 // Prohibit the use of non-POD types in VLAs.
1727 QualType BaseT = Context.getBaseElementType(T);
1728 if (!T->isDependentType() &&
1729 !RequireCompleteType(Loc, BaseT, 0) &&
1730 !BaseT.isPODType(Context) &&
1731 !BaseT->isObjCLifetimeType()) {
1732 Diag(Loc, diag::err_vla_non_pod)
1736 // Prohibit the use of VLAs during template argument deduction.
1737 else if (isSFINAEContext()) {
1738 Diag(Loc, diag::err_vla_in_sfinae);
1741 // Just extwarn about VLAs.
1743 Diag(Loc, diag::ext_vla);
1744 } else if (ASM != ArrayType::Normal || Quals != 0)
1746 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1747 : diag::ext_c99_array_usage) << ASM;
1750 if (T->isVariableArrayType()) {
1751 // Warn about VLAs for -Wvla.
1752 Diag(Loc, diag::warn_vla_used);
1758 /// \brief Build an ext-vector type.
1760 /// Run the required checks for the extended vector type.
1761 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1762 SourceLocation AttrLoc) {
1763 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1764 // in conjunction with complex types (pointers, arrays, functions, etc.).
1765 if (!T->isDependentType() &&
1766 !T->isIntegerType() && !T->isRealFloatingType()) {
1767 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1771 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1772 llvm::APSInt vecSize(32);
1773 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1774 Diag(AttrLoc, diag::err_attribute_argument_type)
1775 << "ext_vector_type" << AANT_ArgumentIntegerConstant
1776 << ArraySize->getSourceRange();
1780 // unlike gcc's vector_size attribute, the size is specified as the
1781 // number of elements, not the number of bytes.
1782 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1784 if (vectorSize == 0) {
1785 Diag(AttrLoc, diag::err_attribute_zero_size)
1786 << ArraySize->getSourceRange();
1790 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1791 Diag(AttrLoc, diag::err_attribute_size_too_large)
1792 << ArraySize->getSourceRange();
1796 return Context.getExtVectorType(T, vectorSize);
1799 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1802 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1803 if (T->isArrayType() || T->isFunctionType()) {
1804 Diag(Loc, diag::err_func_returning_array_function)
1805 << T->isFunctionType() << T;
1809 // Functions cannot return half FP.
1810 if (T->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1811 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1812 FixItHint::CreateInsertion(Loc, "*");
1816 // Methods cannot return interface types. All ObjC objects are
1817 // passed by reference.
1818 if (T->isObjCObjectType()) {
1819 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1826 QualType Sema::BuildFunctionType(QualType T,
1827 MutableArrayRef<QualType> ParamTypes,
1828 SourceLocation Loc, DeclarationName Entity,
1829 const FunctionProtoType::ExtProtoInfo &EPI) {
1830 bool Invalid = false;
1832 Invalid |= CheckFunctionReturnType(T, Loc);
1834 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1835 // FIXME: Loc is too inprecise here, should use proper locations for args.
1836 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1837 if (ParamType->isVoidType()) {
1838 Diag(Loc, diag::err_param_with_void_type);
1840 } else if (ParamType->isHalfType() && !getLangOpts().HalfArgsAndReturns) {
1841 // Disallow half FP arguments.
1842 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1843 FixItHint::CreateInsertion(Loc, "*");
1847 ParamTypes[Idx] = ParamType;
1853 return Context.getFunctionType(T, ParamTypes, EPI);
1856 /// \brief Build a member pointer type \c T Class::*.
1858 /// \param T the type to which the member pointer refers.
1859 /// \param Class the class type into which the member pointer points.
1860 /// \param Loc the location where this type begins
1861 /// \param Entity the name of the entity that will have this member pointer type
1863 /// \returns a member pointer type, if successful, or a NULL type if there was
1865 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1867 DeclarationName Entity) {
1868 // Verify that we're not building a pointer to pointer to function with
1869 // exception specification.
1870 if (CheckDistantExceptionSpec(T)) {
1871 Diag(Loc, diag::err_distant_exception_spec);
1875 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1876 // with reference type, or "cv void."
1877 if (T->isReferenceType()) {
1878 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1879 << getPrintableNameForEntity(Entity) << T;
1883 if (T->isVoidType()) {
1884 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1885 << getPrintableNameForEntity(Entity);
1889 if (!Class->isDependentType() && !Class->isRecordType()) {
1890 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1894 // Adjust the default free function calling convention to the default method
1895 // calling convention.
1896 if (T->isFunctionType())
1897 adjustMemberFunctionCC(T, /*IsStatic=*/false);
1899 return Context.getMemberPointerType(T, Class.getTypePtr());
1902 /// \brief Build a block pointer type.
1904 /// \param T The type to which we'll be building a block pointer.
1906 /// \param Loc The source location, used for diagnostics.
1908 /// \param Entity The name of the entity that involves the block pointer
1911 /// \returns A suitable block pointer type, if there are no
1912 /// errors. Otherwise, returns a NULL type.
1913 QualType Sema::BuildBlockPointerType(QualType T,
1915 DeclarationName Entity) {
1916 if (!T->isFunctionType()) {
1917 Diag(Loc, diag::err_nonfunction_block_type);
1921 if (checkQualifiedFunction(*this, T, Loc, QFK_BlockPointer))
1924 return Context.getBlockPointerType(T);
1927 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1928 QualType QT = Ty.get();
1930 if (TInfo) *TInfo = nullptr;
1934 TypeSourceInfo *DI = nullptr;
1935 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1936 QT = LIT->getType();
1937 DI = LIT->getTypeSourceInfo();
1940 if (TInfo) *TInfo = DI;
1944 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1945 Qualifiers::ObjCLifetime ownership,
1946 unsigned chunkIndex);
1948 /// Given that this is the declaration of a parameter under ARC,
1949 /// attempt to infer attributes and such for pointer-to-whatever
1951 static void inferARCWriteback(TypeProcessingState &state,
1952 QualType &declSpecType) {
1953 Sema &S = state.getSema();
1954 Declarator &declarator = state.getDeclarator();
1956 // TODO: should we care about decl qualifiers?
1958 // Check whether the declarator has the expected form. We walk
1959 // from the inside out in order to make the block logic work.
1960 unsigned outermostPointerIndex = 0;
1961 bool isBlockPointer = false;
1962 unsigned numPointers = 0;
1963 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1964 unsigned chunkIndex = i;
1965 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1966 switch (chunk.Kind) {
1967 case DeclaratorChunk::Paren:
1971 case DeclaratorChunk::Reference:
1972 case DeclaratorChunk::Pointer:
1973 // Count the number of pointers. Treat references
1974 // interchangeably as pointers; if they're mis-ordered, normal
1975 // type building will discover that.
1976 outermostPointerIndex = chunkIndex;
1980 case DeclaratorChunk::BlockPointer:
1981 // If we have a pointer to block pointer, that's an acceptable
1982 // indirect reference; anything else is not an application of
1984 if (numPointers != 1) return;
1986 outermostPointerIndex = chunkIndex;
1987 isBlockPointer = true;
1989 // We don't care about pointer structure in return values here.
1992 case DeclaratorChunk::Array: // suppress if written (id[])?
1993 case DeclaratorChunk::Function:
1994 case DeclaratorChunk::MemberPointer:
2000 // If we have *one* pointer, then we want to throw the qualifier on
2001 // the declaration-specifiers, which means that it needs to be a
2002 // retainable object type.
2003 if (numPointers == 1) {
2004 // If it's not a retainable object type, the rule doesn't apply.
2005 if (!declSpecType->isObjCRetainableType()) return;
2007 // If it already has lifetime, don't do anything.
2008 if (declSpecType.getObjCLifetime()) return;
2010 // Otherwise, modify the type in-place.
2013 if (declSpecType->isObjCARCImplicitlyUnretainedType())
2014 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
2016 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
2017 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
2019 // If we have *two* pointers, then we want to throw the qualifier on
2020 // the outermost pointer.
2021 } else if (numPointers == 2) {
2022 // If we don't have a block pointer, we need to check whether the
2023 // declaration-specifiers gave us something that will turn into a
2024 // retainable object pointer after we slap the first pointer on it.
2025 if (!isBlockPointer && !declSpecType->isObjCObjectType())
2028 // Look for an explicit lifetime attribute there.
2029 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
2030 if (chunk.Kind != DeclaratorChunk::Pointer &&
2031 chunk.Kind != DeclaratorChunk::BlockPointer)
2033 for (const AttributeList *attr = chunk.getAttrs(); attr;
2034 attr = attr->getNext())
2035 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
2038 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
2039 outermostPointerIndex);
2041 // Any other number of pointers/references does not trigger the rule.
2044 // TODO: mark whether we did this inference?
2047 void Sema::diagnoseIgnoredQualifiers(unsigned DiagID, unsigned Quals,
2048 SourceLocation FallbackLoc,
2049 SourceLocation ConstQualLoc,
2050 SourceLocation VolatileQualLoc,
2051 SourceLocation RestrictQualLoc,
2052 SourceLocation AtomicQualLoc) {
2060 } const QualKinds[4] = {
2061 { DeclSpec::TQ_const, "const", ConstQualLoc },
2062 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
2063 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
2064 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
2067 SmallString<32> QualStr;
2068 unsigned NumQuals = 0;
2070 FixItHint FixIts[4];
2072 // Build a string naming the redundant qualifiers.
2073 for (unsigned I = 0; I != 4; ++I) {
2074 if (Quals & QualKinds[I].Mask) {
2075 if (!QualStr.empty()) QualStr += ' ';
2076 QualStr += QualKinds[I].Name;
2078 // If we have a location for the qualifier, offer a fixit.
2079 SourceLocation QualLoc = QualKinds[I].Loc;
2080 if (!QualLoc.isInvalid()) {
2081 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2082 if (Loc.isInvalid() ||
2083 getSourceManager().isBeforeInTranslationUnit(QualLoc, Loc))
2091 Diag(Loc.isInvalid() ? FallbackLoc : Loc, DiagID)
2092 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2095 // Diagnose pointless type qualifiers on the return type of a function.
2096 static void diagnoseRedundantReturnTypeQualifiers(Sema &S, QualType RetTy,
2098 unsigned FunctionChunkIndex) {
2099 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2100 // FIXME: TypeSourceInfo doesn't preserve location information for
2102 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2103 RetTy.getLocalCVRQualifiers(),
2104 D.getIdentifierLoc());
2108 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2109 End = D.getNumTypeObjects();
2110 OuterChunkIndex != End; ++OuterChunkIndex) {
2111 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2112 switch (OuterChunk.Kind) {
2113 case DeclaratorChunk::Paren:
2116 case DeclaratorChunk::Pointer: {
2117 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2118 S.diagnoseIgnoredQualifiers(
2119 diag::warn_qual_return_type,
2122 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2123 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2124 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2125 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2129 case DeclaratorChunk::Function:
2130 case DeclaratorChunk::BlockPointer:
2131 case DeclaratorChunk::Reference:
2132 case DeclaratorChunk::Array:
2133 case DeclaratorChunk::MemberPointer:
2134 // FIXME: We can't currently provide an accurate source location and a
2135 // fix-it hint for these.
2136 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2137 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2138 RetTy.getCVRQualifiers() | AtomicQual,
2139 D.getIdentifierLoc());
2143 llvm_unreachable("unknown declarator chunk kind");
2146 // If the qualifiers come from a conversion function type, don't diagnose
2147 // them -- they're not necessarily redundant, since such a conversion
2148 // operator can be explicitly called as "x.operator const int()".
2149 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2152 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2153 // which are present there.
2154 S.diagnoseIgnoredQualifiers(diag::warn_qual_return_type,
2155 D.getDeclSpec().getTypeQualifiers(),
2156 D.getIdentifierLoc(),
2157 D.getDeclSpec().getConstSpecLoc(),
2158 D.getDeclSpec().getVolatileSpecLoc(),
2159 D.getDeclSpec().getRestrictSpecLoc(),
2160 D.getDeclSpec().getAtomicSpecLoc());
2163 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2164 TypeSourceInfo *&ReturnTypeInfo) {
2165 Sema &SemaRef = state.getSema();
2166 Declarator &D = state.getDeclarator();
2168 ReturnTypeInfo = nullptr;
2170 // The TagDecl owned by the DeclSpec.
2171 TagDecl *OwnedTagDecl = nullptr;
2173 bool ContainsPlaceholderType = false;
2175 switch (D.getName().getKind()) {
2176 case UnqualifiedId::IK_ImplicitSelfParam:
2177 case UnqualifiedId::IK_OperatorFunctionId:
2178 case UnqualifiedId::IK_Identifier:
2179 case UnqualifiedId::IK_LiteralOperatorId:
2180 case UnqualifiedId::IK_TemplateId:
2181 T = ConvertDeclSpecToType(state);
2182 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2184 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2185 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2186 // Owned declaration is embedded in declarator.
2187 OwnedTagDecl->setEmbeddedInDeclarator(true);
2191 case UnqualifiedId::IK_ConstructorName:
2192 case UnqualifiedId::IK_ConstructorTemplateId:
2193 case UnqualifiedId::IK_DestructorName:
2194 // Constructors and destructors don't have return types. Use
2196 T = SemaRef.Context.VoidTy;
2197 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2198 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2201 case UnqualifiedId::IK_ConversionFunctionId:
2202 // The result type of a conversion function is the type that it
2204 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2206 ContainsPlaceholderType = T->getContainedAutoType();
2210 if (D.getAttributes())
2211 distributeTypeAttrsFromDeclarator(state, T);
2213 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2214 // In C++11, a function declarator using 'auto' must have a trailing return
2215 // type (this is checked later) and we can skip this. In other languages
2216 // using auto, we need to check regardless.
2217 // C++14 In generic lambdas allow 'auto' in their parameters.
2218 if (ContainsPlaceholderType &&
2219 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2222 switch (D.getContext()) {
2223 case Declarator::KNRTypeListContext:
2224 llvm_unreachable("K&R type lists aren't allowed in C++");
2225 case Declarator::LambdaExprContext:
2226 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2227 case Declarator::ObjCParameterContext:
2228 case Declarator::ObjCResultContext:
2229 case Declarator::PrototypeContext:
2232 case Declarator::LambdaExprParameterContext:
2233 if (!(SemaRef.getLangOpts().CPlusPlus14
2234 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2237 case Declarator::MemberContext:
2238 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2240 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2241 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2242 case TTK_Struct: Error = 1; /* Struct member */ break;
2243 case TTK_Union: Error = 2; /* Union member */ break;
2244 case TTK_Class: Error = 3; /* Class member */ break;
2245 case TTK_Interface: Error = 4; /* Interface member */ break;
2248 case Declarator::CXXCatchContext:
2249 case Declarator::ObjCCatchContext:
2250 Error = 5; // Exception declaration
2252 case Declarator::TemplateParamContext:
2253 Error = 6; // Template parameter
2255 case Declarator::BlockLiteralContext:
2256 Error = 7; // Block literal
2258 case Declarator::TemplateTypeArgContext:
2259 Error = 8; // Template type argument
2261 case Declarator::AliasDeclContext:
2262 case Declarator::AliasTemplateContext:
2263 Error = 10; // Type alias
2265 case Declarator::TrailingReturnContext:
2266 if (!SemaRef.getLangOpts().CPlusPlus14)
2267 Error = 11; // Function return type
2269 case Declarator::ConversionIdContext:
2270 if (!SemaRef.getLangOpts().CPlusPlus14)
2271 Error = 12; // conversion-type-id
2273 case Declarator::TypeNameContext:
2274 Error = 13; // Generic
2276 case Declarator::FileContext:
2277 case Declarator::BlockContext:
2278 case Declarator::ForContext:
2279 case Declarator::ConditionContext:
2280 case Declarator::CXXNewContext:
2284 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2287 // In Objective-C it is an error to use 'auto' on a function declarator.
2288 if (D.isFunctionDeclarator())
2291 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2292 // contains a trailing return type. That is only legal at the outermost
2293 // level. Check all declarator chunks (outermost first) anyway, to give
2294 // better diagnostics.
2295 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2296 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2297 unsigned chunkIndex = e - i - 1;
2298 state.setCurrentChunkIndex(chunkIndex);
2299 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2300 if (DeclType.Kind == DeclaratorChunk::Function) {
2301 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2302 if (FTI.hasTrailingReturnType()) {
2310 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2311 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2312 AutoRange = D.getName().getSourceRange();
2315 const bool IsDeclTypeAuto =
2316 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2317 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2318 << IsDeclTypeAuto << Error << AutoRange;
2319 T = SemaRef.Context.IntTy;
2320 D.setInvalidType(true);
2322 SemaRef.Diag(AutoRange.getBegin(),
2323 diag::warn_cxx98_compat_auto_type_specifier)
2327 if (SemaRef.getLangOpts().CPlusPlus &&
2328 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2329 // Check the contexts where C++ forbids the declaration of a new class
2330 // or enumeration in a type-specifier-seq.
2331 switch (D.getContext()) {
2332 case Declarator::TrailingReturnContext:
2333 // Class and enumeration definitions are syntactically not allowed in
2334 // trailing return types.
2335 llvm_unreachable("parser should not have allowed this");
2337 case Declarator::FileContext:
2338 case Declarator::MemberContext:
2339 case Declarator::BlockContext:
2340 case Declarator::ForContext:
2341 case Declarator::BlockLiteralContext:
2342 case Declarator::LambdaExprContext:
2343 // C++11 [dcl.type]p3:
2344 // A type-specifier-seq shall not define a class or enumeration unless
2345 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2346 // the declaration of a template-declaration.
2347 case Declarator::AliasDeclContext:
2349 case Declarator::AliasTemplateContext:
2350 SemaRef.Diag(OwnedTagDecl->getLocation(),
2351 diag::err_type_defined_in_alias_template)
2352 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2353 D.setInvalidType(true);
2355 case Declarator::TypeNameContext:
2356 case Declarator::ConversionIdContext:
2357 case Declarator::TemplateParamContext:
2358 case Declarator::CXXNewContext:
2359 case Declarator::CXXCatchContext:
2360 case Declarator::ObjCCatchContext:
2361 case Declarator::TemplateTypeArgContext:
2362 SemaRef.Diag(OwnedTagDecl->getLocation(),
2363 diag::err_type_defined_in_type_specifier)
2364 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2365 D.setInvalidType(true);
2367 case Declarator::PrototypeContext:
2368 case Declarator::LambdaExprParameterContext:
2369 case Declarator::ObjCParameterContext:
2370 case Declarator::ObjCResultContext:
2371 case Declarator::KNRTypeListContext:
2373 // Types shall not be defined in return or parameter types.
2374 SemaRef.Diag(OwnedTagDecl->getLocation(),
2375 diag::err_type_defined_in_param_type)
2376 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2377 D.setInvalidType(true);
2379 case Declarator::ConditionContext:
2381 // The type-specifier-seq shall not contain typedef and shall not declare
2382 // a new class or enumeration.
2383 SemaRef.Diag(OwnedTagDecl->getLocation(),
2384 diag::err_type_defined_in_condition);
2385 D.setInvalidType(true);
2390 assert(!T.isNull() && "This function should not return a null type");
2394 /// Produce an appropriate diagnostic for an ambiguity between a function
2395 /// declarator and a C++ direct-initializer.
2396 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2397 DeclaratorChunk &DeclType, QualType RT) {
2398 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2399 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2401 // If the return type is void there is no ambiguity.
2402 if (RT->isVoidType())
2405 // An initializer for a non-class type can have at most one argument.
2406 if (!RT->isRecordType() && FTI.NumParams > 1)
2409 // An initializer for a reference must have exactly one argument.
2410 if (RT->isReferenceType() && FTI.NumParams != 1)
2413 // Only warn if this declarator is declaring a function at block scope, and
2414 // doesn't have a storage class (such as 'extern') specified.
2415 if (!D.isFunctionDeclarator() ||
2416 D.getFunctionDefinitionKind() != FDK_Declaration ||
2417 !S.CurContext->isFunctionOrMethod() ||
2418 D.getDeclSpec().getStorageClassSpec()
2419 != DeclSpec::SCS_unspecified)
2422 // Inside a condition, a direct initializer is not permitted. We allow one to
2423 // be parsed in order to give better diagnostics in condition parsing.
2424 if (D.getContext() == Declarator::ConditionContext)
2427 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2429 S.Diag(DeclType.Loc,
2430 FTI.NumParams ? diag::warn_parens_disambiguated_as_function_declaration
2431 : diag::warn_empty_parens_are_function_decl)
2434 // If the declaration looks like:
2437 // and name lookup finds a function named 'f', then the ',' was
2438 // probably intended to be a ';'.
2439 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2440 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2441 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2442 if (Comma.getFileID() != Name.getFileID() ||
2443 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2444 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2445 Sema::LookupOrdinaryName);
2446 if (S.LookupName(Result, S.getCurScope()))
2447 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2448 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2449 << D.getIdentifier();
2453 if (FTI.NumParams > 0) {
2454 // For a declaration with parameters, eg. "T var(T());", suggest adding
2455 // parens around the first parameter to turn the declaration into a
2456 // variable declaration.
2457 SourceRange Range = FTI.Params[0].Param->getSourceRange();
2458 SourceLocation B = Range.getBegin();
2459 SourceLocation E = S.getLocForEndOfToken(Range.getEnd());
2460 // FIXME: Maybe we should suggest adding braces instead of parens
2461 // in C++11 for classes that don't have an initializer_list constructor.
2462 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2463 << FixItHint::CreateInsertion(B, "(")
2464 << FixItHint::CreateInsertion(E, ")");
2466 // For a declaration without parameters, eg. "T var();", suggest replacing
2467 // the parens with an initializer to turn the declaration into a variable
2469 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2471 // Empty parens mean value-initialization, and no parens mean
2472 // default initialization. These are equivalent if the default
2473 // constructor is user-provided or if zero-initialization is a
2475 if (RD && RD->hasDefinition() &&
2476 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2477 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2478 << FixItHint::CreateRemoval(ParenRange);
2481 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2482 if (Init.empty() && S.LangOpts.CPlusPlus11)
2485 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2486 << FixItHint::CreateReplacement(ParenRange, Init);
2491 /// Helper for figuring out the default CC for a function declarator type. If
2492 /// this is the outermost chunk, then we can determine the CC from the
2493 /// declarator context. If not, then this could be either a member function
2494 /// type or normal function type.
2496 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2497 const DeclaratorChunk::FunctionTypeInfo &FTI,
2498 unsigned ChunkIndex) {
2499 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2501 bool IsCXXInstanceMethod = false;
2503 if (S.getLangOpts().CPlusPlus) {
2504 // Look inwards through parentheses to see if this chunk will form a
2505 // member pointer type or if we're the declarator. Any type attributes
2506 // between here and there will override the CC we choose here.
2507 unsigned I = ChunkIndex;
2508 bool FoundNonParen = false;
2509 while (I && !FoundNonParen) {
2511 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2512 FoundNonParen = true;
2515 if (FoundNonParen) {
2516 // If we're not the declarator, we're a regular function type unless we're
2517 // in a member pointer.
2518 IsCXXInstanceMethod =
2519 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2520 } else if (D.getContext() == Declarator::LambdaExprContext) {
2521 // This can only be a call operator for a lambda, which is an instance
2523 IsCXXInstanceMethod = true;
2525 // We're the innermost decl chunk, so must be a function declarator.
2526 assert(D.isFunctionDeclarator());
2528 // If we're inside a record, we're declaring a method, but it could be
2529 // explicitly or implicitly static.
2530 IsCXXInstanceMethod =
2531 D.isFirstDeclarationOfMember() &&
2532 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2533 !D.isStaticMember();
2537 CallingConv CC = S.Context.getDefaultCallingConvention(FTI.isVariadic,
2538 IsCXXInstanceMethod);
2540 // Attribute AT_OpenCLKernel affects the calling convention only on
2541 // the SPIR target, hence it cannot be treated as a calling
2542 // convention attribute. This is the simplest place to infer
2543 // "spir_kernel" for OpenCL kernels on SPIR.
2544 if (CC == CC_SpirFunction) {
2545 for (const AttributeList *Attr = D.getDeclSpec().getAttributes().getList();
2546 Attr; Attr = Attr->getNext()) {
2547 if (Attr->getKind() == AttributeList::AT_OpenCLKernel) {
2558 /// A simple notion of pointer kinds, which matches up with the various
2559 /// pointer declarators.
2560 enum class SimplePointerKind {
2567 IdentifierInfo *Sema::getNullabilityKeyword(NullabilityKind nullability) {
2568 switch (nullability) {
2569 case NullabilityKind::NonNull:
2570 if (!Ident__Nonnull)
2571 Ident__Nonnull = PP.getIdentifierInfo("_Nonnull");
2572 return Ident__Nonnull;
2574 case NullabilityKind::Nullable:
2575 if (!Ident__Nullable)
2576 Ident__Nullable = PP.getIdentifierInfo("_Nullable");
2577 return Ident__Nullable;
2579 case NullabilityKind::Unspecified:
2580 if (!Ident__Null_unspecified)
2581 Ident__Null_unspecified = PP.getIdentifierInfo("_Null_unspecified");
2582 return Ident__Null_unspecified;
2584 llvm_unreachable("Unknown nullability kind.");
2587 /// Retrieve the identifier "NSError".
2588 IdentifierInfo *Sema::getNSErrorIdent() {
2590 Ident_NSError = PP.getIdentifierInfo("NSError");
2592 return Ident_NSError;
2595 /// Check whether there is a nullability attribute of any kind in the given
2597 static bool hasNullabilityAttr(const AttributeList *attrs) {
2598 for (const AttributeList *attr = attrs; attr;
2599 attr = attr->getNext()) {
2600 if (attr->getKind() == AttributeList::AT_TypeNonNull ||
2601 attr->getKind() == AttributeList::AT_TypeNullable ||
2602 attr->getKind() == AttributeList::AT_TypeNullUnspecified)
2610 /// Describes the kind of a pointer a declarator describes.
2611 enum class PointerDeclaratorKind {
2614 // Single-level pointer.
2616 // Multi-level pointer (of any pointer kind).
2619 MaybePointerToCFRef,
2623 NSErrorPointerPointer,
2627 /// Classify the given declarator, whose type-specified is \c type, based on
2628 /// what kind of pointer it refers to.
2630 /// This is used to determine the default nullability.
2631 static PointerDeclaratorKind classifyPointerDeclarator(Sema &S,
2633 Declarator &declarator) {
2634 unsigned numNormalPointers = 0;
2636 // For any dependent type, we consider it a non-pointer.
2637 if (type->isDependentType())
2638 return PointerDeclaratorKind::NonPointer;
2640 // Look through the declarator chunks to identify pointers.
2641 for (unsigned i = 0, n = declarator.getNumTypeObjects(); i != n; ++i) {
2642 DeclaratorChunk &chunk = declarator.getTypeObject(i);
2643 switch (chunk.Kind) {
2644 case DeclaratorChunk::Array:
2645 case DeclaratorChunk::Function:
2648 case DeclaratorChunk::BlockPointer:
2649 case DeclaratorChunk::MemberPointer:
2650 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2651 : PointerDeclaratorKind::SingleLevelPointer;
2653 case DeclaratorChunk::Paren:
2654 case DeclaratorChunk::Reference:
2657 case DeclaratorChunk::Pointer:
2658 ++numNormalPointers;
2659 if (numNormalPointers > 2)
2660 return PointerDeclaratorKind::MultiLevelPointer;
2665 // Then, dig into the type specifier itself.
2666 unsigned numTypeSpecifierPointers = 0;
2668 // Decompose normal pointers.
2669 if (auto ptrType = type->getAs<PointerType>()) {
2670 ++numNormalPointers;
2672 if (numNormalPointers > 2)
2673 return PointerDeclaratorKind::MultiLevelPointer;
2675 type = ptrType->getPointeeType();
2676 ++numTypeSpecifierPointers;
2680 // Decompose block pointers.
2681 if (type->getAs<BlockPointerType>()) {
2682 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2683 : PointerDeclaratorKind::SingleLevelPointer;
2686 // Decompose member pointers.
2687 if (type->getAs<MemberPointerType>()) {
2688 return numNormalPointers > 0 ? PointerDeclaratorKind::MultiLevelPointer
2689 : PointerDeclaratorKind::SingleLevelPointer;
2692 // Look at Objective-C object pointers.
2693 if (auto objcObjectPtr = type->getAs<ObjCObjectPointerType>()) {
2694 ++numNormalPointers;
2695 ++numTypeSpecifierPointers;
2697 // If this is NSError**, report that.
2698 if (auto objcClassDecl = objcObjectPtr->getInterfaceDecl()) {
2699 if (objcClassDecl->getIdentifier() == S.getNSErrorIdent() &&
2700 numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
2701 return PointerDeclaratorKind::NSErrorPointerPointer;
2708 // Look at Objective-C class types.
2709 if (auto objcClass = type->getAs<ObjCInterfaceType>()) {
2710 if (objcClass->getInterface()->getIdentifier() == S.getNSErrorIdent()) {
2711 if (numNormalPointers == 2 && numTypeSpecifierPointers < 2)
2712 return PointerDeclaratorKind::NSErrorPointerPointer;;
2718 // If at this point we haven't seen a pointer, we won't see one.
2719 if (numNormalPointers == 0)
2720 return PointerDeclaratorKind::NonPointer;
2722 if (auto recordType = type->getAs<RecordType>()) {
2723 RecordDecl *recordDecl = recordType->getDecl();
2725 bool isCFError = false;
2727 // If we already know about CFError, test it directly.
2728 isCFError = (S.CFError == recordDecl);
2730 // Check whether this is CFError, which we identify based on its bridge
2732 if (recordDecl->getTagKind() == TTK_Struct && numNormalPointers > 0) {
2733 if (auto bridgeAttr = recordDecl->getAttr<ObjCBridgeAttr>()) {
2734 if (bridgeAttr->getBridgedType() == S.getNSErrorIdent()) {
2735 S.CFError = recordDecl;
2742 // If this is CFErrorRef*, report it as such.
2743 if (isCFError && numNormalPointers == 2 && numTypeSpecifierPointers < 2) {
2744 return PointerDeclaratorKind::CFErrorRefPointer;
2753 switch (numNormalPointers) {
2755 return PointerDeclaratorKind::NonPointer;
2758 return PointerDeclaratorKind::SingleLevelPointer;
2761 return PointerDeclaratorKind::MaybePointerToCFRef;
2764 return PointerDeclaratorKind::MultiLevelPointer;
2768 static FileID getNullabilityCompletenessCheckFileID(Sema &S,
2769 SourceLocation loc) {
2770 // If we're anywhere in a function, method, or closure context, don't perform
2771 // completeness checks.
2772 for (DeclContext *ctx = S.CurContext; ctx; ctx = ctx->getParent()) {
2773 if (ctx->isFunctionOrMethod())
2776 if (ctx->isFileContext())
2780 // We only care about the expansion location.
2781 loc = S.SourceMgr.getExpansionLoc(loc);
2782 FileID file = S.SourceMgr.getFileID(loc);
2783 if (file.isInvalid())
2786 // Retrieve file information.
2787 bool invalid = false;
2788 const SrcMgr::SLocEntry &sloc = S.SourceMgr.getSLocEntry(file, &invalid);
2789 if (invalid || !sloc.isFile())
2792 // We don't want to perform completeness checks on the main file or in
2794 const SrcMgr::FileInfo &fileInfo = sloc.getFile();
2795 if (fileInfo.getIncludeLoc().isInvalid())
2797 if (fileInfo.getFileCharacteristic() != SrcMgr::C_User &&
2798 S.Diags.getSuppressSystemWarnings()) {
2805 /// Check for consistent use of nullability.
2806 static void checkNullabilityConsistency(TypeProcessingState &state,
2807 SimplePointerKind pointerKind,
2808 SourceLocation pointerLoc) {
2809 Sema &S = state.getSema();
2811 // Determine which file we're performing consistency checking for.
2812 FileID file = getNullabilityCompletenessCheckFileID(S, pointerLoc);
2813 if (file.isInvalid())
2816 // If we haven't seen any type nullability in this file, we won't warn now
2818 FileNullability &fileNullability = S.NullabilityMap[file];
2819 if (!fileNullability.SawTypeNullability) {
2820 // If this is the first pointer declarator in the file, record it.
2821 if (fileNullability.PointerLoc.isInvalid() &&
2822 !S.Context.getDiagnostics().isIgnored(diag::warn_nullability_missing,
2824 fileNullability.PointerLoc = pointerLoc;
2825 fileNullability.PointerKind = static_cast<unsigned>(pointerKind);
2831 // Complain about missing nullability.
2832 S.Diag(pointerLoc, diag::warn_nullability_missing)
2833 << static_cast<unsigned>(pointerKind);
2836 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2837 QualType declSpecType,
2838 TypeSourceInfo *TInfo) {
2839 // The TypeSourceInfo that this function returns will not be a null type.
2840 // If there is an error, this function will fill in a dummy type as fallback.
2841 QualType T = declSpecType;
2842 Declarator &D = state.getDeclarator();
2843 Sema &S = state.getSema();
2844 ASTContext &Context = S.Context;
2845 const LangOptions &LangOpts = S.getLangOpts();
2847 // The name we're declaring, if any.
2848 DeclarationName Name;
2849 if (D.getIdentifier())
2850 Name = D.getIdentifier();
2852 // Does this declaration declare a typedef-name?
2853 bool IsTypedefName =
2854 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2855 D.getContext() == Declarator::AliasDeclContext ||
2856 D.getContext() == Declarator::AliasTemplateContext;
2858 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2859 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2860 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2861 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2863 // If T is 'decltype(auto)', the only declarators we can have are parens
2864 // and at most one function declarator if this is a function declaration.
2865 if (const AutoType *AT = T->getAs<AutoType>()) {
2866 if (AT->isDecltypeAuto()) {
2867 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2868 unsigned Index = E - I - 1;
2869 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2870 unsigned DiagId = diag::err_decltype_auto_compound_type;
2871 unsigned DiagKind = 0;
2872 switch (DeclChunk.Kind) {
2873 case DeclaratorChunk::Paren:
2875 case DeclaratorChunk::Function: {
2877 if (D.isFunctionDeclarationContext() &&
2878 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2880 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2883 case DeclaratorChunk::Pointer:
2884 case DeclaratorChunk::BlockPointer:
2885 case DeclaratorChunk::MemberPointer:
2888 case DeclaratorChunk::Reference:
2891 case DeclaratorChunk::Array:
2896 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2897 D.setInvalidType(true);
2903 // Determine whether we should infer _Nonnull on pointer types.
2904 Optional<NullabilityKind> inferNullability;
2905 bool inferNullabilityCS = false;
2906 bool inferNullabilityInnerOnly = false;
2907 bool inferNullabilityInnerOnlyComplete = false;
2909 // Are we in an assume-nonnull region?
2910 bool inAssumeNonNullRegion = false;
2911 if (S.PP.getPragmaAssumeNonNullLoc().isValid() &&
2912 !state.getDeclarator().isObjCWeakProperty() &&
2913 !S.deduceWeakPropertyFromType(T)) {
2914 inAssumeNonNullRegion = true;
2915 // Determine which file we saw the assume-nonnull region in.
2916 FileID file = getNullabilityCompletenessCheckFileID(
2917 S, S.PP.getPragmaAssumeNonNullLoc());
2918 if (!file.isInvalid()) {
2919 FileNullability &fileNullability = S.NullabilityMap[file];
2921 // If we haven't seen any type nullability before, now we have.
2922 if (!fileNullability.SawTypeNullability) {
2923 if (fileNullability.PointerLoc.isValid()) {
2924 S.Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
2925 << static_cast<unsigned>(fileNullability.PointerKind);
2928 fileNullability.SawTypeNullability = true;
2933 // Whether to complain about missing nullability specifiers or not.
2937 /// Complain on the inner pointers (but not the outermost
2940 /// Complain about any pointers that don't have nullability
2941 /// specified or inferred.
2943 } complainAboutMissingNullability = CAMN_No;
2944 unsigned NumPointersRemaining = 0;
2946 if (IsTypedefName) {
2947 // For typedefs, we do not infer any nullability (the default),
2948 // and we only complain about missing nullability specifiers on
2950 complainAboutMissingNullability = CAMN_InnerPointers;
2952 if (T->canHaveNullability() && !T->getNullability(S.Context)) {
2953 ++NumPointersRemaining;
2956 for (unsigned i = 0, n = D.getNumTypeObjects(); i != n; ++i) {
2957 DeclaratorChunk &chunk = D.getTypeObject(i);
2958 switch (chunk.Kind) {
2959 case DeclaratorChunk::Array:
2960 case DeclaratorChunk::Function:
2963 case DeclaratorChunk::BlockPointer:
2964 case DeclaratorChunk::MemberPointer:
2965 ++NumPointersRemaining;
2968 case DeclaratorChunk::Paren:
2969 case DeclaratorChunk::Reference:
2972 case DeclaratorChunk::Pointer:
2973 ++NumPointersRemaining;
2978 bool isFunctionOrMethod = false;
2979 switch (auto context = state.getDeclarator().getContext()) {
2980 case Declarator::ObjCParameterContext:
2981 case Declarator::ObjCResultContext:
2982 case Declarator::PrototypeContext:
2983 case Declarator::TrailingReturnContext:
2984 isFunctionOrMethod = true;
2987 case Declarator::MemberContext:
2988 if (state.getDeclarator().isObjCIvar() && !isFunctionOrMethod) {
2989 complainAboutMissingNullability = CAMN_No;
2994 case Declarator::FileContext:
2995 case Declarator::KNRTypeListContext:
2996 complainAboutMissingNullability = CAMN_Yes;
2998 // Nullability inference depends on the type and declarator.
2999 switch (classifyPointerDeclarator(S, T, D)) {
3000 case PointerDeclaratorKind::NonPointer:
3001 case PointerDeclaratorKind::MultiLevelPointer:
3002 // Cannot infer nullability.
3005 case PointerDeclaratorKind::SingleLevelPointer:
3006 // Infer _Nonnull if we are in an assumes-nonnull region.
3007 if (inAssumeNonNullRegion) {
3008 inferNullability = NullabilityKind::NonNull;
3009 inferNullabilityCS = (context == Declarator::ObjCParameterContext ||
3010 context == Declarator::ObjCResultContext);
3014 case PointerDeclaratorKind::CFErrorRefPointer:
3015 case PointerDeclaratorKind::NSErrorPointerPointer:
3016 // Within a function or method signature, infer _Nullable at both
3018 if (isFunctionOrMethod && inAssumeNonNullRegion)
3019 inferNullability = NullabilityKind::Nullable;
3022 case PointerDeclaratorKind::MaybePointerToCFRef:
3023 if (isFunctionOrMethod) {
3024 // On pointer-to-pointer parameters marked cf_returns_retained or
3025 // cf_returns_not_retained, if the outer pointer is explicit then
3026 // infer the inner pointer as _Nullable.
3027 auto hasCFReturnsAttr = [](const AttributeList *NextAttr) -> bool {
3029 if (NextAttr->getKind() == AttributeList::AT_CFReturnsRetained ||
3030 NextAttr->getKind() == AttributeList::AT_CFReturnsNotRetained)
3032 NextAttr = NextAttr->getNext();
3036 if (const auto *InnermostChunk = D.getInnermostNonParenChunk()) {
3037 if (hasCFReturnsAttr(D.getAttributes()) ||
3038 hasCFReturnsAttr(InnermostChunk->getAttrs()) ||
3039 hasCFReturnsAttr(D.getDeclSpec().getAttributes().getList())) {
3040 inferNullability = NullabilityKind::Nullable;
3041 inferNullabilityInnerOnly = true;
3049 case Declarator::ConversionIdContext:
3050 complainAboutMissingNullability = CAMN_Yes;
3053 case Declarator::AliasDeclContext:
3054 case Declarator::AliasTemplateContext:
3055 case Declarator::BlockContext:
3056 case Declarator::BlockLiteralContext:
3057 case Declarator::ConditionContext:
3058 case Declarator::CXXCatchContext:
3059 case Declarator::CXXNewContext:
3060 case Declarator::ForContext:
3061 case Declarator::LambdaExprContext:
3062 case Declarator::LambdaExprParameterContext:
3063 case Declarator::ObjCCatchContext:
3064 case Declarator::TemplateParamContext:
3065 case Declarator::TemplateTypeArgContext:
3066 case Declarator::TypeNameContext:
3067 // Don't infer in these contexts.
3072 // Local function that checks the nullability for a given pointer declarator.
3073 // Returns true if _Nonnull was inferred.
3074 auto inferPointerNullability = [&](SimplePointerKind pointerKind,
3075 SourceLocation pointerLoc,
3076 AttributeList *&attrs) -> AttributeList * {
3077 // We've seen a pointer.
3078 if (NumPointersRemaining > 0)
3079 --NumPointersRemaining;
3081 // If a nullability attribute is present, there's nothing to do.
3082 if (hasNullabilityAttr(attrs))
3085 // If we're supposed to infer nullability, do so now.
3086 if (inferNullability && !inferNullabilityInnerOnlyComplete) {
3087 AttributeList::Syntax syntax
3088 = inferNullabilityCS ? AttributeList::AS_ContextSensitiveKeyword
3089 : AttributeList::AS_Keyword;
3090 AttributeList *nullabilityAttr = state.getDeclarator().getAttributePool()
3092 S.getNullabilityKeyword(
3094 SourceRange(pointerLoc),
3095 nullptr, SourceLocation(),
3096 nullptr, 0, syntax);
3098 spliceAttrIntoList(*nullabilityAttr, attrs);
3100 if (inferNullabilityInnerOnly)
3101 inferNullabilityInnerOnlyComplete = true;
3102 return nullabilityAttr;
3105 // If we're supposed to complain about missing nullability, do so
3106 // now if it's truly missing.
3107 switch (complainAboutMissingNullability) {
3111 case CAMN_InnerPointers:
3112 if (NumPointersRemaining == 0)
3117 checkNullabilityConsistency(state, pointerKind, pointerLoc);
3123 // If the type itself could have nullability but does not, infer pointer
3124 // nullability and perform consistency checking.
3125 if (T->canHaveNullability() && S.ActiveTemplateInstantiations.empty() &&
3126 !T->getNullability(S.Context)) {
3127 SimplePointerKind pointerKind = SimplePointerKind::Pointer;
3128 if (T->isBlockPointerType())
3129 pointerKind = SimplePointerKind::BlockPointer;
3130 else if (T->isMemberPointerType())
3131 pointerKind = SimplePointerKind::MemberPointer;
3133 if (auto *attr = inferPointerNullability(
3134 pointerKind, D.getDeclSpec().getTypeSpecTypeLoc(),
3135 D.getMutableDeclSpec().getAttributes().getListRef())) {
3136 T = Context.getAttributedType(
3137 AttributedType::getNullabilityAttrKind(*inferNullability), T, T);
3138 attr->setUsedAsTypeAttr();
3142 // Walk the DeclTypeInfo, building the recursive type as we go.
3143 // DeclTypeInfos are ordered from the identifier out, which is
3144 // opposite of what we want :).
3145 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3146 unsigned chunkIndex = e - i - 1;
3147 state.setCurrentChunkIndex(chunkIndex);
3148 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
3149 IsQualifiedFunction &= DeclType.Kind == DeclaratorChunk::Paren;
3150 switch (DeclType.Kind) {
3151 case DeclaratorChunk::Paren:
3152 T = S.BuildParenType(T);
3154 case DeclaratorChunk::BlockPointer:
3155 // If blocks are disabled, emit an error.
3156 if (!LangOpts.Blocks)
3157 S.Diag(DeclType.Loc, diag::err_blocks_disable);
3159 // Handle pointer nullability.
3160 inferPointerNullability(SimplePointerKind::BlockPointer,
3161 DeclType.Loc, DeclType.getAttrListRef());
3163 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
3164 if (DeclType.Cls.TypeQuals)
3165 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
3167 case DeclaratorChunk::Pointer:
3168 // Verify that we're not building a pointer to pointer to function with
3169 // exception specification.
3170 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3171 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3172 D.setInvalidType(true);
3173 // Build the type anyway.
3176 // Handle pointer nullability
3177 inferPointerNullability(SimplePointerKind::Pointer, DeclType.Loc,
3178 DeclType.getAttrListRef());
3180 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
3181 T = Context.getObjCObjectPointerType(T);
3182 if (DeclType.Ptr.TypeQuals)
3183 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3186 T = S.BuildPointerType(T, DeclType.Loc, Name);
3187 if (DeclType.Ptr.TypeQuals)
3188 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
3191 case DeclaratorChunk::Reference: {
3192 // Verify that we're not building a reference to pointer to function with
3193 // exception specification.
3194 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3195 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3196 D.setInvalidType(true);
3197 // Build the type anyway.
3199 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
3201 if (DeclType.Ref.HasRestrict)
3202 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
3205 case DeclaratorChunk::Array: {
3206 // Verify that we're not building an array of pointers to function with
3207 // exception specification.
3208 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
3209 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
3210 D.setInvalidType(true);
3211 // Build the type anyway.
3213 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
3214 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
3215 ArrayType::ArraySizeModifier ASM;
3217 ASM = ArrayType::Star;
3218 else if (ATI.hasStatic)
3219 ASM = ArrayType::Static;
3221 ASM = ArrayType::Normal;
3222 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
3223 // FIXME: This check isn't quite right: it allows star in prototypes
3224 // for function definitions, and disallows some edge cases detailed
3225 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
3226 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
3227 ASM = ArrayType::Normal;
3228 D.setInvalidType(true);
3231 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
3232 // shall appear only in a declaration of a function parameter with an
3234 if (ASM == ArrayType::Static || ATI.TypeQuals) {
3235 if (!(D.isPrototypeContext() ||
3236 D.getContext() == Declarator::KNRTypeListContext)) {
3237 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
3238 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3239 // Remove the 'static' and the type qualifiers.
3240 if (ASM == ArrayType::Static)
3241 ASM = ArrayType::Normal;
3243 D.setInvalidType(true);
3246 // C99 6.7.5.2p1: ... and then only in the outermost array type
3248 unsigned x = chunkIndex;
3250 // Walk outwards along the declarator chunks.
3252 const DeclaratorChunk &DC = D.getTypeObject(x);
3254 case DeclaratorChunk::Paren:
3256 case DeclaratorChunk::Array:
3257 case DeclaratorChunk::Pointer:
3258 case DeclaratorChunk::Reference:
3259 case DeclaratorChunk::MemberPointer:
3260 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
3261 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
3262 if (ASM == ArrayType::Static)
3263 ASM = ArrayType::Normal;
3265 D.setInvalidType(true);
3267 case DeclaratorChunk::Function:
3268 case DeclaratorChunk::BlockPointer:
3269 // These are invalid anyway, so just ignore.
3274 const AutoType *AT = T->getContainedAutoType();
3275 // Allow arrays of auto if we are a generic lambda parameter.
3276 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
3277 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
3278 // We've already diagnosed this for decltype(auto).
3279 if (!AT->isDecltypeAuto())
3280 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
3281 << getPrintableNameForEntity(Name) << T;
3286 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
3287 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
3290 case DeclaratorChunk::Function: {
3291 // If the function declarator has a prototype (i.e. it is not () and
3292 // does not have a K&R-style identifier list), then the arguments are part
3293 // of the type, otherwise the argument list is ().
3294 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
3295 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
3297 // Check for auto functions and trailing return type and adjust the
3298 // return type accordingly.
3299 if (!D.isInvalidType()) {
3300 // trailing-return-type is only required if we're declaring a function,
3301 // and not, for instance, a pointer to a function.
3302 if (D.getDeclSpec().containsPlaceholderType() &&
3303 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
3304 !S.getLangOpts().CPlusPlus14) {
3305 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3306 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto
3307 ? diag::err_auto_missing_trailing_return
3308 : diag::err_deduced_return_type);
3310 D.setInvalidType(true);
3311 } else if (FTI.hasTrailingReturnType()) {
3312 // T must be exactly 'auto' at this point. See CWG issue 681.
3313 if (isa<ParenType>(T)) {
3314 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3315 diag::err_trailing_return_in_parens)
3316 << T << D.getDeclSpec().getSourceRange();
3317 D.setInvalidType(true);
3318 } else if (D.getContext() != Declarator::LambdaExprContext &&
3319 (T.hasQualifiers() || !isa<AutoType>(T) ||
3320 cast<AutoType>(T)->isDecltypeAuto())) {
3321 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
3322 diag::err_trailing_return_without_auto)
3323 << T << D.getDeclSpec().getSourceRange();
3324 D.setInvalidType(true);
3326 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
3328 // An error occurred parsing the trailing return type.
3330 D.setInvalidType(true);
3335 // C99 6.7.5.3p1: The return type may not be a function or array type.
3336 // For conversion functions, we'll diagnose this particular error later.
3337 if ((T->isArrayType() || T->isFunctionType()) &&
3338 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
3339 unsigned diagID = diag::err_func_returning_array_function;
3340 // Last processing chunk in block context means this function chunk
3341 // represents the block.
3342 if (chunkIndex == 0 &&
3343 D.getContext() == Declarator::BlockLiteralContext)
3344 diagID = diag::err_block_returning_array_function;
3345 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
3347 D.setInvalidType(true);
3350 // Do not allow returning half FP value.
3351 // FIXME: This really should be in BuildFunctionType.
3352 if (T->isHalfType()) {
3353 if (S.getLangOpts().OpenCL) {
3354 if (!S.getOpenCLOptions().cl_khr_fp16) {
3355 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
3356 D.setInvalidType(true);
3358 } else if (!S.getLangOpts().HalfArgsAndReturns) {
3359 S.Diag(D.getIdentifierLoc(),
3360 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
3361 D.setInvalidType(true);
3365 // Methods cannot return interface types. All ObjC objects are
3366 // passed by reference.
3367 if (T->isObjCObjectType()) {
3368 SourceLocation DiagLoc, FixitLoc;
3370 DiagLoc = TInfo->getTypeLoc().getLocStart();
3371 FixitLoc = S.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
3373 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
3374 FixitLoc = S.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
3376 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
3378 << FixItHint::CreateInsertion(FixitLoc, "*");
3380 T = Context.getObjCObjectPointerType(T);
3383 TLB.pushFullCopy(TInfo->getTypeLoc());
3384 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
3385 TLoc.setStarLoc(FixitLoc);
3386 TInfo = TLB.getTypeSourceInfo(Context, T);
3389 D.setInvalidType(true);
3392 // cv-qualifiers on return types are pointless except when the type is a
3393 // class type in C++.
3394 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
3395 !(S.getLangOpts().CPlusPlus &&
3396 (T->isDependentType() || T->isRecordType()))) {
3397 if (T->isVoidType() && !S.getLangOpts().CPlusPlus &&
3398 D.getFunctionDefinitionKind() == FDK_Definition) {
3399 // [6.9.1/3] qualified void return is invalid on a C
3400 // function definition. Apparently ok on declarations and
3401 // in C++ though (!)
3402 S.Diag(DeclType.Loc, diag::err_func_returning_qualified_void) << T;
3404 diagnoseRedundantReturnTypeQualifiers(S, T, D, chunkIndex);
3407 // Objective-C ARC ownership qualifiers are ignored on the function
3408 // return type (by type canonicalization). Complain if this attribute
3409 // was written here.
3410 if (T.getQualifiers().hasObjCLifetime()) {
3411 SourceLocation AttrLoc;
3412 if (chunkIndex + 1 < D.getNumTypeObjects()) {
3413 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
3414 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
3415 Attr; Attr = Attr->getNext()) {
3416 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3417 AttrLoc = Attr->getLoc();
3422 if (AttrLoc.isInvalid()) {
3423 for (const AttributeList *Attr
3424 = D.getDeclSpec().getAttributes().getList();
3425 Attr; Attr = Attr->getNext()) {
3426 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
3427 AttrLoc = Attr->getLoc();
3433 if (AttrLoc.isValid()) {
3434 // The ownership attributes are almost always written via
3436 // __strong/__weak/__autoreleasing/__unsafe_unretained.
3437 if (AttrLoc.isMacroID())
3438 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
3440 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
3441 << T.getQualifiers().getObjCLifetime();
3445 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
3447 // Types shall not be defined in return or parameter types.
3448 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
3449 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
3450 << Context.getTypeDeclType(Tag);
3453 // Exception specs are not allowed in typedefs. Complain, but add it
3455 if (IsTypedefName && FTI.getExceptionSpecType())
3456 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
3457 << (D.getContext() == Declarator::AliasDeclContext ||
3458 D.getContext() == Declarator::AliasTemplateContext);
3460 // If we see "T var();" or "T var(T());" at block scope, it is probably
3461 // an attempt to initialize a variable, not a function declaration.
3462 if (FTI.isAmbiguous)
3463 warnAboutAmbiguousFunction(S, D, DeclType, T);
3465 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
3467 if (!FTI.NumParams && !FTI.isVariadic && !LangOpts.CPlusPlus) {
3468 // Simple void foo(), where the incoming T is the result type.
3469 T = Context.getFunctionNoProtoType(T, EI);
3471 // We allow a zero-parameter variadic function in C if the
3472 // function is marked with the "overloadable" attribute. Scan
3473 // for this attribute now.
3474 if (!FTI.NumParams && FTI.isVariadic && !LangOpts.CPlusPlus) {
3475 bool Overloadable = false;
3476 for (const AttributeList *Attrs = D.getAttributes();
3477 Attrs; Attrs = Attrs->getNext()) {
3478 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
3479 Overloadable = true;
3485 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_param);
3488 if (FTI.NumParams && FTI.Params[0].Param == nullptr) {
3489 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
3491 S.Diag(FTI.Params[0].IdentLoc,
3492 diag::err_ident_list_in_fn_declaration);
3493 D.setInvalidType(true);
3494 // Recover by creating a K&R-style function type.
3495 T = Context.getFunctionNoProtoType(T, EI);
3499 FunctionProtoType::ExtProtoInfo EPI;
3501 EPI.Variadic = FTI.isVariadic;
3502 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
3503 EPI.TypeQuals = FTI.TypeQuals;
3504 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
3505 : FTI.RefQualifierIsLValueRef? RQ_LValue
3508 // Otherwise, we have a function with a parameter list that is
3509 // potentially variadic.
3510 SmallVector<QualType, 16> ParamTys;
3511 ParamTys.reserve(FTI.NumParams);
3513 SmallVector<bool, 16> ConsumedParameters;
3514 ConsumedParameters.reserve(FTI.NumParams);
3515 bool HasAnyConsumedParameters = false;
3517 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
3518 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
3519 QualType ParamTy = Param->getType();
3520 assert(!ParamTy.isNull() && "Couldn't parse type?");
3522 // Look for 'void'. void is allowed only as a single parameter to a
3523 // function with no other parameters (C99 6.7.5.3p10). We record
3524 // int(void) as a FunctionProtoType with an empty parameter list.
3525 if (ParamTy->isVoidType()) {
3526 // If this is something like 'float(int, void)', reject it. 'void'
3527 // is an incomplete type (C99 6.2.5p19) and function decls cannot
3528 // have parameters of incomplete type.
3529 if (FTI.NumParams != 1 || FTI.isVariadic) {
3530 S.Diag(DeclType.Loc, diag::err_void_only_param);
3531 ParamTy = Context.IntTy;
3532 Param->setType(ParamTy);
3533 } else if (FTI.Params[i].Ident) {
3534 // Reject, but continue to parse 'int(void abc)'.
3535 S.Diag(FTI.Params[i].IdentLoc, diag::err_param_with_void_type);
3536 ParamTy = Context.IntTy;
3537 Param->setType(ParamTy);
3539 // Reject, but continue to parse 'float(const void)'.
3540 if (ParamTy.hasQualifiers())
3541 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
3543 // Do not add 'void' to the list.
3546 } else if (ParamTy->isHalfType()) {
3547 // Disallow half FP parameters.
3548 // FIXME: This really should be in BuildFunctionType.
3549 if (S.getLangOpts().OpenCL) {
3550 if (!S.getOpenCLOptions().cl_khr_fp16) {
3551 S.Diag(Param->getLocation(),
3552 diag::err_opencl_half_param) << ParamTy;
3554 Param->setInvalidDecl();
3556 } else if (!S.getLangOpts().HalfArgsAndReturns) {
3557 S.Diag(Param->getLocation(),
3558 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
3561 } else if (!FTI.hasPrototype) {
3562 if (ParamTy->isPromotableIntegerType()) {
3563 ParamTy = Context.getPromotedIntegerType(ParamTy);
3564 Param->setKNRPromoted(true);
3565 } else if (const BuiltinType* BTy = ParamTy->getAs<BuiltinType>()) {
3566 if (BTy->getKind() == BuiltinType::Float) {
3567 ParamTy = Context.DoubleTy;
3568 Param->setKNRPromoted(true);
3573 if (LangOpts.ObjCAutoRefCount) {
3574 bool Consumed = Param->hasAttr<NSConsumedAttr>();
3575 ConsumedParameters.push_back(Consumed);
3576 HasAnyConsumedParameters |= Consumed;
3579 ParamTys.push_back(ParamTy);
3582 if (HasAnyConsumedParameters)
3583 EPI.ConsumedParameters = ConsumedParameters.data();
3585 SmallVector<QualType, 4> Exceptions;
3586 SmallVector<ParsedType, 2> DynamicExceptions;
3587 SmallVector<SourceRange, 2> DynamicExceptionRanges;
3588 Expr *NoexceptExpr = nullptr;
3590 if (FTI.getExceptionSpecType() == EST_Dynamic) {
3591 // FIXME: It's rather inefficient to have to split into two vectors
3593 unsigned N = FTI.NumExceptions;
3594 DynamicExceptions.reserve(N);
3595 DynamicExceptionRanges.reserve(N);
3596 for (unsigned I = 0; I != N; ++I) {
3597 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3598 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3600 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3601 NoexceptExpr = FTI.NoexceptExpr;
3604 S.checkExceptionSpecification(D.isFunctionDeclarationContext(),
3605 FTI.getExceptionSpecType(),
3607 DynamicExceptionRanges,
3612 T = Context.getFunctionType(T, ParamTys, EPI);
3617 case DeclaratorChunk::MemberPointer:
3618 // The scope spec must refer to a class, or be dependent.
3619 CXXScopeSpec &SS = DeclType.Mem.Scope();
3622 // Handle pointer nullability.
3623 inferPointerNullability(SimplePointerKind::MemberPointer,
3624 DeclType.Loc, DeclType.getAttrListRef());
3626 if (SS.isInvalid()) {
3627 // Avoid emitting extra errors if we already errored on the scope.
3628 D.setInvalidType(true);
3629 } else if (S.isDependentScopeSpecifier(SS) ||
3630 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3631 NestedNameSpecifier *NNS = SS.getScopeRep();
3632 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3633 switch (NNS->getKind()) {
3634 case NestedNameSpecifier::Identifier:
3635 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3636 NNS->getAsIdentifier());
3639 case NestedNameSpecifier::Namespace:
3640 case NestedNameSpecifier::NamespaceAlias:
3641 case NestedNameSpecifier::Global:
3642 case NestedNameSpecifier::Super:
3643 llvm_unreachable("Nested-name-specifier must name a type");
3645 case NestedNameSpecifier::TypeSpec:
3646 case NestedNameSpecifier::TypeSpecWithTemplate:
3647 ClsType = QualType(NNS->getAsType(), 0);
3648 // Note: if the NNS has a prefix and ClsType is a nondependent
3649 // TemplateSpecializationType, then the NNS prefix is NOT included
3650 // in ClsType; hence we wrap ClsType into an ElaboratedType.
3651 // NOTE: in particular, no wrap occurs if ClsType already is an
3652 // Elaborated, DependentName, or DependentTemplateSpecialization.
3653 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3654 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3658 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3659 diag::err_illegal_decl_mempointer_in_nonclass)
3660 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3661 << DeclType.Mem.Scope().getRange();
3662 D.setInvalidType(true);
3665 if (!ClsType.isNull())
3666 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc,
3670 D.setInvalidType(true);
3671 } else if (DeclType.Mem.TypeQuals) {
3672 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3678 D.setInvalidType(true);
3682 // See if there are any attributes on this declarator chunk.
3683 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3684 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3687 assert(!T.isNull() && "T must not be null after this point");
3689 if (LangOpts.CPlusPlus && T->isFunctionType()) {
3690 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3691 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3694 // A cv-qualifier-seq shall only be part of the function type
3695 // for a nonstatic member function, the function type to which a pointer
3696 // to member refers, or the top-level function type of a function typedef
3699 // Core issue 547 also allows cv-qualifiers on function types that are
3700 // top-level template type arguments.
3702 if (!D.getCXXScopeSpec().isSet()) {
3703 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3704 D.getContext() != Declarator::LambdaExprContext) ||
3705 D.getDeclSpec().isFriendSpecified());
3707 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3708 FreeFunction = (DC && !DC->isRecord());
3711 // C++11 [dcl.fct]p6 (w/DR1417):
3712 // An attempt to specify a function type with a cv-qualifier-seq or a
3713 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3714 // - the function type for a non-static member function,
3715 // - the function type to which a pointer to member refers,
3716 // - the top-level function type of a function typedef declaration or
3717 // alias-declaration,
3718 // - the type-id in the default argument of a type-parameter, or
3719 // - the type-id of a template-argument for a type-parameter
3721 // FIXME: Checking this here is insufficient. We accept-invalid on:
3723 // template<typename T> struct S { void f(T); };
3724 // S<int() const> s;
3726 // ... for instance.
3727 if (IsQualifiedFunction &&
3729 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3731 D.getContext() != Declarator::TemplateTypeArgContext) {
3732 SourceLocation Loc = D.getLocStart();
3733 SourceRange RemovalRange;
3735 if (D.isFunctionDeclarator(I)) {
3736 SmallVector<SourceLocation, 4> RemovalLocs;
3737 const DeclaratorChunk &Chunk = D.getTypeObject(I);
3738 assert(Chunk.Kind == DeclaratorChunk::Function);
3739 if (Chunk.Fun.hasRefQualifier())
3740 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3741 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3742 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3743 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3744 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3745 if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3746 RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3747 if (!RemovalLocs.empty()) {
3748 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3749 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3750 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3751 Loc = RemovalLocs.front();
3755 S.Diag(Loc, diag::err_invalid_qualified_function_type)
3756 << FreeFunction << D.isFunctionDeclarator() << T
3757 << getFunctionQualifiersAsString(FnTy)
3758 << FixItHint::CreateRemoval(RemovalRange);
3760 // Strip the cv-qualifiers and ref-qualifiers from the type.
3761 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3763 EPI.RefQualifier = RQ_None;
3765 T = Context.getFunctionType(FnTy->getReturnType(), FnTy->getParamTypes(),
3767 // Rebuild any parens around the identifier in the function type.
3768 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3769 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3771 T = S.BuildParenType(T);
3776 // Apply any undistributed attributes from the declarator.
3777 if (AttributeList *attrs = D.getAttributes())
3778 processTypeAttrs(state, T, TAL_DeclName, attrs);
3780 // Diagnose any ignored type attributes.
3781 state.diagnoseIgnoredTypeAttrs(T);
3783 // C++0x [dcl.constexpr]p9:
3784 // A constexpr specifier used in an object declaration declares the object
3786 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3790 // If there was an ellipsis in the declarator, the declaration declares a
3791 // parameter pack whose type may be a pack expansion type.
3792 if (D.hasEllipsis()) {
3793 // C++0x [dcl.fct]p13:
3794 // A declarator-id or abstract-declarator containing an ellipsis shall
3795 // only be used in a parameter-declaration. Such a parameter-declaration
3796 // is a parameter pack (14.5.3). [...]
3797 switch (D.getContext()) {
3798 case Declarator::PrototypeContext:
3799 case Declarator::LambdaExprParameterContext:
3800 // C++0x [dcl.fct]p13:
3801 // [...] When it is part of a parameter-declaration-clause, the
3802 // parameter pack is a function parameter pack (14.5.3). The type T
3803 // of the declarator-id of the function parameter pack shall contain
3804 // a template parameter pack; each template parameter pack in T is
3805 // expanded by the function parameter pack.
3807 // We represent function parameter packs as function parameters whose
3808 // type is a pack expansion.
3809 if (!T->containsUnexpandedParameterPack()) {
3810 S.Diag(D.getEllipsisLoc(),
3811 diag::err_function_parameter_pack_without_parameter_packs)
3812 << T << D.getSourceRange();
3813 D.setEllipsisLoc(SourceLocation());
3815 T = Context.getPackExpansionType(T, None);
3818 case Declarator::TemplateParamContext:
3819 // C++0x [temp.param]p15:
3820 // If a template-parameter is a [...] is a parameter-declaration that
3821 // declares a parameter pack (8.3.5), then the template-parameter is a
3822 // template parameter pack (14.5.3).
3824 // Note: core issue 778 clarifies that, if there are any unexpanded
3825 // parameter packs in the type of the non-type template parameter, then
3826 // it expands those parameter packs.
3827 if (T->containsUnexpandedParameterPack())
3828 T = Context.getPackExpansionType(T, None);
3830 S.Diag(D.getEllipsisLoc(),
3831 LangOpts.CPlusPlus11
3832 ? diag::warn_cxx98_compat_variadic_templates
3833 : diag::ext_variadic_templates);
3836 case Declarator::FileContext:
3837 case Declarator::KNRTypeListContext:
3838 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3839 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
3840 case Declarator::TypeNameContext:
3841 case Declarator::CXXNewContext:
3842 case Declarator::AliasDeclContext:
3843 case Declarator::AliasTemplateContext:
3844 case Declarator::MemberContext:
3845 case Declarator::BlockContext:
3846 case Declarator::ForContext:
3847 case Declarator::ConditionContext:
3848 case Declarator::CXXCatchContext:
3849 case Declarator::ObjCCatchContext:
3850 case Declarator::BlockLiteralContext:
3851 case Declarator::LambdaExprContext:
3852 case Declarator::ConversionIdContext:
3853 case Declarator::TrailingReturnContext:
3854 case Declarator::TemplateTypeArgContext:
3855 // FIXME: We may want to allow parameter packs in block-literal contexts
3857 S.Diag(D.getEllipsisLoc(),
3858 diag::err_ellipsis_in_declarator_not_parameter);
3859 D.setEllipsisLoc(SourceLocation());
3864 assert(!T.isNull() && "T must not be null at the end of this function");
3865 if (D.isInvalidType())
3866 return Context.getTrivialTypeSourceInfo(T);
3868 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3871 /// GetTypeForDeclarator - Convert the type for the specified
3872 /// declarator to Type instances.
3874 /// The result of this call will never be null, but the associated
3875 /// type may be a null type if there's an unrecoverable error.
3876 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3877 // Determine the type of the declarator. Not all forms of declarator
3880 TypeProcessingState state(*this, D);
3882 TypeSourceInfo *ReturnTypeInfo = nullptr;
3883 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3885 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3886 inferARCWriteback(state, T);
3888 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3891 static void transferARCOwnershipToDeclSpec(Sema &S,
3892 QualType &declSpecTy,
3893 Qualifiers::ObjCLifetime ownership) {
3894 if (declSpecTy->isObjCRetainableType() &&
3895 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3897 qs.addObjCLifetime(ownership);
3898 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3902 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3903 Qualifiers::ObjCLifetime ownership,
3904 unsigned chunkIndex) {
3905 Sema &S = state.getSema();
3906 Declarator &D = state.getDeclarator();
3908 // Look for an explicit lifetime attribute.
3909 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3910 for (const AttributeList *attr = chunk.getAttrs(); attr;
3911 attr = attr->getNext())
3912 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3915 const char *attrStr = nullptr;
3916 switch (ownership) {
3917 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3918 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3919 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3920 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3921 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3924 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3925 Arg->Ident = &S.Context.Idents.get(attrStr);
3926 Arg->Loc = SourceLocation();
3928 ArgsUnion Args(Arg);
3930 // If there wasn't one, add one (with an invalid source location
3931 // so that we don't make an AttributedType for it).
3932 AttributeList *attr = D.getAttributePool()
3933 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3934 /*scope*/ nullptr, SourceLocation(),
3935 /*args*/ &Args, 1, AttributeList::AS_GNU);
3936 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3938 // TODO: mark whether we did this inference?
3941 /// \brief Used for transferring ownership in casts resulting in l-values.
3942 static void transferARCOwnership(TypeProcessingState &state,
3943 QualType &declSpecTy,
3944 Qualifiers::ObjCLifetime ownership) {
3945 Sema &S = state.getSema();
3946 Declarator &D = state.getDeclarator();
3949 bool hasIndirection = false;
3950 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3951 DeclaratorChunk &chunk = D.getTypeObject(i);
3952 switch (chunk.Kind) {
3953 case DeclaratorChunk::Paren:
3957 case DeclaratorChunk::Array:
3958 case DeclaratorChunk::Reference:
3959 case DeclaratorChunk::Pointer:
3961 hasIndirection = true;
3965 case DeclaratorChunk::BlockPointer:
3967 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3970 case DeclaratorChunk::Function:
3971 case DeclaratorChunk::MemberPointer:
3979 DeclaratorChunk &chunk = D.getTypeObject(inner);
3980 if (chunk.Kind == DeclaratorChunk::Pointer) {
3981 if (declSpecTy->isObjCRetainableType())
3982 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3983 if (declSpecTy->isObjCObjectType() && hasIndirection)
3984 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3986 assert(chunk.Kind == DeclaratorChunk::Array ||
3987 chunk.Kind == DeclaratorChunk::Reference);
3988 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3992 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3993 TypeProcessingState state(*this, D);
3995 TypeSourceInfo *ReturnTypeInfo = nullptr;
3996 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3998 if (getLangOpts().ObjCAutoRefCount) {
3999 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
4000 if (ownership != Qualifiers::OCL_None)
4001 transferARCOwnership(state, declSpecTy, ownership);
4004 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
4007 /// Map an AttributedType::Kind to an AttributeList::Kind.
4008 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
4010 case AttributedType::attr_address_space:
4011 return AttributeList::AT_AddressSpace;
4012 case AttributedType::attr_regparm:
4013 return AttributeList::AT_Regparm;
4014 case AttributedType::attr_vector_size:
4015 return AttributeList::AT_VectorSize;
4016 case AttributedType::attr_neon_vector_type:
4017 return AttributeList::AT_NeonVectorType;
4018 case AttributedType::attr_neon_polyvector_type:
4019 return AttributeList::AT_NeonPolyVectorType;
4020 case AttributedType::attr_objc_gc:
4021 return AttributeList::AT_ObjCGC;
4022 case AttributedType::attr_objc_ownership:
4023 return AttributeList::AT_ObjCOwnership;
4024 case AttributedType::attr_noreturn:
4025 return AttributeList::AT_NoReturn;
4026 case AttributedType::attr_cdecl:
4027 return AttributeList::AT_CDecl;
4028 case AttributedType::attr_fastcall:
4029 return AttributeList::AT_FastCall;
4030 case AttributedType::attr_stdcall:
4031 return AttributeList::AT_StdCall;
4032 case AttributedType::attr_thiscall:
4033 return AttributeList::AT_ThisCall;
4034 case AttributedType::attr_pascal:
4035 return AttributeList::AT_Pascal;
4036 case AttributedType::attr_vectorcall:
4037 return AttributeList::AT_VectorCall;
4038 case AttributedType::attr_pcs:
4039 case AttributedType::attr_pcs_vfp:
4040 return AttributeList::AT_Pcs;
4041 case AttributedType::attr_inteloclbicc:
4042 return AttributeList::AT_IntelOclBicc;
4043 case AttributedType::attr_ms_abi:
4044 return AttributeList::AT_MSABI;
4045 case AttributedType::attr_sysv_abi:
4046 return AttributeList::AT_SysVABI;
4047 case AttributedType::attr_ptr32:
4048 return AttributeList::AT_Ptr32;
4049 case AttributedType::attr_ptr64:
4050 return AttributeList::AT_Ptr64;
4051 case AttributedType::attr_sptr:
4052 return AttributeList::AT_SPtr;
4053 case AttributedType::attr_uptr:
4054 return AttributeList::AT_UPtr;
4055 case AttributedType::attr_nonnull:
4056 return AttributeList::AT_TypeNonNull;
4057 case AttributedType::attr_nullable:
4058 return AttributeList::AT_TypeNullable;
4059 case AttributedType::attr_null_unspecified:
4060 return AttributeList::AT_TypeNullUnspecified;
4062 llvm_unreachable("unexpected attribute kind!");
4065 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
4066 const AttributeList *attrs,
4067 const AttributeList *DeclAttrs = nullptr) {
4068 // DeclAttrs and attrs cannot be both empty.
4069 assert((attrs || DeclAttrs) &&
4070 "no type attributes in the expected location!");
4072 AttributeList::Kind parsedKind = getAttrListKind(TL.getAttrKind());
4073 // Try to search for an attribute of matching kind in attrs list.
4074 while (attrs && attrs->getKind() != parsedKind)
4075 attrs = attrs->getNext();
4077 // No matching type attribute in attrs list found.
4078 // Try searching through C++11 attributes in the declarator attribute list.
4079 while (DeclAttrs && (!DeclAttrs->isCXX11Attribute() ||
4080 DeclAttrs->getKind() != parsedKind))
4081 DeclAttrs = DeclAttrs->getNext();
4085 assert(attrs && "no matching type attribute in expected location!");
4087 TL.setAttrNameLoc(attrs->getLoc());
4088 if (TL.hasAttrExprOperand()) {
4089 assert(attrs->isArgExpr(0) && "mismatched attribute operand kind");
4090 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
4091 } else if (TL.hasAttrEnumOperand()) {
4092 assert((attrs->isArgIdent(0) || attrs->isArgExpr(0)) &&
4093 "unexpected attribute operand kind");
4094 if (attrs->isArgIdent(0))
4095 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
4097 TL.setAttrEnumOperandLoc(attrs->getArgAsExpr(0)->getExprLoc());
4100 // FIXME: preserve this information to here.
4101 if (TL.hasAttrOperand())
4102 TL.setAttrOperandParensRange(SourceRange());
4106 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
4107 ASTContext &Context;
4111 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
4112 : Context(Context), DS(DS) {}
4114 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4115 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
4116 Visit(TL.getModifiedLoc());
4118 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4119 Visit(TL.getUnqualifiedLoc());
4121 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
4122 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4124 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
4125 TL.setNameLoc(DS.getTypeSpecTypeLoc());
4126 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
4127 // addition field. What we have is good enough for dispay of location
4128 // of 'fixit' on interface name.
4129 TL.setNameEndLoc(DS.getLocEnd());
4131 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
4132 // Handle the base type, which might not have been written explicitly.
4133 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
4134 TL.setHasBaseTypeAsWritten(false);
4135 TL.getBaseLoc().initialize(Context, SourceLocation());
4137 TL.setHasBaseTypeAsWritten(true);
4138 Visit(TL.getBaseLoc());
4141 // Protocol qualifiers.
4142 if (DS.getProtocolQualifiers()) {
4143 assert(TL.getNumProtocols() > 0);
4144 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
4145 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
4146 TL.setRAngleLoc(DS.getSourceRange().getEnd());
4147 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
4148 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
4150 assert(TL.getNumProtocols() == 0);
4151 TL.setLAngleLoc(SourceLocation());
4152 TL.setRAngleLoc(SourceLocation());
4155 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4156 TL.setStarLoc(SourceLocation());
4157 Visit(TL.getPointeeLoc());
4159 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
4160 TypeSourceInfo *TInfo = nullptr;
4161 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4163 // If we got no declarator info from previous Sema routines,
4164 // just fill with the typespec loc.
4166 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
4170 TypeLoc OldTL = TInfo->getTypeLoc();
4171 if (TInfo->getType()->getAs<ElaboratedType>()) {
4172 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
4173 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
4174 .castAs<TemplateSpecializationTypeLoc>();
4177 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
4178 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
4182 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
4183 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
4184 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4185 TL.setParensRange(DS.getTypeofParensRange());
4187 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
4188 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
4189 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
4190 TL.setParensRange(DS.getTypeofParensRange());
4191 assert(DS.getRepAsType());
4192 TypeSourceInfo *TInfo = nullptr;
4193 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4194 TL.setUnderlyingTInfo(TInfo);
4196 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
4197 // FIXME: This holds only because we only have one unary transform.
4198 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
4199 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4200 TL.setParensRange(DS.getTypeofParensRange());
4201 assert(DS.getRepAsType());
4202 TypeSourceInfo *TInfo = nullptr;
4203 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4204 TL.setUnderlyingTInfo(TInfo);
4206 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
4207 // By default, use the source location of the type specifier.
4208 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
4209 if (TL.needsExtraLocalData()) {
4210 // Set info for the written builtin specifiers.
4211 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
4212 // Try to have a meaningful source location.
4213 if (TL.getWrittenSignSpec() != TSS_unspecified)
4214 // Sign spec loc overrides the others (e.g., 'unsigned long').
4215 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
4216 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
4217 // Width spec loc overrides type spec loc (e.g., 'short int').
4218 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
4221 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
4222 ElaboratedTypeKeyword Keyword
4223 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
4224 if (DS.getTypeSpecType() == TST_typename) {
4225 TypeSourceInfo *TInfo = nullptr;
4226 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4228 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
4232 TL.setElaboratedKeywordLoc(Keyword != ETK_None
4233 ? DS.getTypeSpecTypeLoc()
4234 : SourceLocation());
4235 const CXXScopeSpec& SS = DS.getTypeSpecScope();
4236 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4237 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
4239 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
4240 assert(DS.getTypeSpecType() == TST_typename);
4241 TypeSourceInfo *TInfo = nullptr;
4242 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4244 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
4246 void VisitDependentTemplateSpecializationTypeLoc(
4247 DependentTemplateSpecializationTypeLoc TL) {
4248 assert(DS.getTypeSpecType() == TST_typename);
4249 TypeSourceInfo *TInfo = nullptr;
4250 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4253 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
4255 void VisitTagTypeLoc(TagTypeLoc TL) {
4256 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
4258 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
4259 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
4260 // or an _Atomic qualifier.
4261 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
4262 TL.setKWLoc(DS.getTypeSpecTypeLoc());
4263 TL.setParensRange(DS.getTypeofParensRange());
4265 TypeSourceInfo *TInfo = nullptr;
4266 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
4268 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
4270 TL.setKWLoc(DS.getAtomicSpecLoc());
4271 // No parens, to indicate this was spelled as an _Atomic qualifier.
4272 TL.setParensRange(SourceRange());
4273 Visit(TL.getValueLoc());
4277 void VisitTypeLoc(TypeLoc TL) {
4278 // FIXME: add other typespec types and change this to an assert.
4279 TL.initialize(Context, DS.getTypeSpecTypeLoc());
4283 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
4284 ASTContext &Context;
4285 const DeclaratorChunk &Chunk;
4288 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
4289 : Context(Context), Chunk(Chunk) {}
4291 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
4292 llvm_unreachable("qualified type locs not expected here!");
4294 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
4295 llvm_unreachable("decayed type locs not expected here!");
4298 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
4299 fillAttributedTypeLoc(TL, Chunk.getAttrs());
4301 void VisitAdjustedTypeLoc(AdjustedTypeLoc TL) {
4304 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
4305 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
4306 TL.setCaretLoc(Chunk.Loc);
4308 void VisitPointerTypeLoc(PointerTypeLoc TL) {
4309 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4310 TL.setStarLoc(Chunk.Loc);
4312 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
4313 assert(Chunk.Kind == DeclaratorChunk::Pointer);
4314 TL.setStarLoc(Chunk.Loc);
4316 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
4317 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
4318 const CXXScopeSpec& SS = Chunk.Mem.Scope();
4319 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
4321 const Type* ClsTy = TL.getClass();
4322 QualType ClsQT = QualType(ClsTy, 0);
4323 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
4324 // Now copy source location info into the type loc component.
4325 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
4326 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
4327 case NestedNameSpecifier::Identifier:
4328 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
4330 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
4331 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
4332 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
4333 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
4337 case NestedNameSpecifier::TypeSpec:
4338 case NestedNameSpecifier::TypeSpecWithTemplate:
4339 if (isa<ElaboratedType>(ClsTy)) {
4340 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
4341 ETLoc.setElaboratedKeywordLoc(SourceLocation());
4342 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
4343 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
4344 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
4346 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
4350 case NestedNameSpecifier::Namespace:
4351 case NestedNameSpecifier::NamespaceAlias:
4352 case NestedNameSpecifier::Global:
4353 case NestedNameSpecifier::Super:
4354 llvm_unreachable("Nested-name-specifier must name a type");
4357 // Finally fill in MemberPointerLocInfo fields.
4358 TL.setStarLoc(Chunk.Loc);
4359 TL.setClassTInfo(ClsTInfo);
4361 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
4362 assert(Chunk.Kind == DeclaratorChunk::Reference);
4363 // 'Amp' is misleading: this might have been originally
4364 /// spelled with AmpAmp.
4365 TL.setAmpLoc(Chunk.Loc);
4367 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
4368 assert(Chunk.Kind == DeclaratorChunk::Reference);
4369 assert(!Chunk.Ref.LValueRef);
4370 TL.setAmpAmpLoc(Chunk.Loc);
4372 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
4373 assert(Chunk.Kind == DeclaratorChunk::Array);
4374 TL.setLBracketLoc(Chunk.Loc);
4375 TL.setRBracketLoc(Chunk.EndLoc);
4376 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
4378 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
4379 assert(Chunk.Kind == DeclaratorChunk::Function);
4380 TL.setLocalRangeBegin(Chunk.Loc);
4381 TL.setLocalRangeEnd(Chunk.EndLoc);
4383 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
4384 TL.setLParenLoc(FTI.getLParenLoc());
4385 TL.setRParenLoc(FTI.getRParenLoc());
4386 for (unsigned i = 0, e = TL.getNumParams(), tpi = 0; i != e; ++i) {
4387 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
4388 TL.setParam(tpi++, Param);
4390 // FIXME: exception specs
4392 void VisitParenTypeLoc(ParenTypeLoc TL) {
4393 assert(Chunk.Kind == DeclaratorChunk::Paren);
4394 TL.setLParenLoc(Chunk.Loc);
4395 TL.setRParenLoc(Chunk.EndLoc);
4398 void VisitTypeLoc(TypeLoc TL) {
4399 llvm_unreachable("unsupported TypeLoc kind in declarator!");
4404 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
4406 switch (Chunk.Kind) {
4407 case DeclaratorChunk::Function:
4408 case DeclaratorChunk::Array:
4409 case DeclaratorChunk::Paren:
4410 llvm_unreachable("cannot be _Atomic qualified");
4412 case DeclaratorChunk::Pointer:
4413 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
4416 case DeclaratorChunk::BlockPointer:
4417 case DeclaratorChunk::Reference:
4418 case DeclaratorChunk::MemberPointer:
4419 // FIXME: Provide a source location for the _Atomic keyword.
4424 ATL.setParensRange(SourceRange());
4427 /// \brief Create and instantiate a TypeSourceInfo with type source information.
4429 /// \param T QualType referring to the type as written in source code.
4431 /// \param ReturnTypeInfo For declarators whose return type does not show
4432 /// up in the normal place in the declaration specifiers (such as a C++
4433 /// conversion function), this pointer will refer to a type source information
4434 /// for that return type.
4436 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
4437 TypeSourceInfo *ReturnTypeInfo) {
4438 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
4439 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
4440 const AttributeList *DeclAttrs = D.getAttributes();
4442 // Handle parameter packs whose type is a pack expansion.
4443 if (isa<PackExpansionType>(T)) {
4444 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
4445 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4448 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
4449 // An AtomicTypeLoc might be produced by an atomic qualifier in this
4450 // declarator chunk.
4451 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
4452 fillAtomicQualLoc(ATL, D.getTypeObject(i));
4453 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
4456 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
4457 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs(), DeclAttrs);
4458 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4461 // FIXME: Ordering here?
4462 while (AdjustedTypeLoc TL = CurrTL.getAs<AdjustedTypeLoc>())
4463 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
4465 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
4466 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
4469 // If we have different source information for the return type, use
4470 // that. This really only applies to C++ conversion functions.
4471 if (ReturnTypeInfo) {
4472 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
4473 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
4474 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
4476 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
4482 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
4483 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
4484 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
4485 // and Sema during declaration parsing. Try deallocating/caching them when
4486 // it's appropriate, instead of allocating them and keeping them around.
4487 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
4489 new (LocT) LocInfoType(T, TInfo);
4490 assert(LocT->getTypeClass() != T->getTypeClass() &&
4491 "LocInfoType's TypeClass conflicts with an existing Type class");
4492 return ParsedType::make(QualType(LocT, 0));
4495 void LocInfoType::getAsStringInternal(std::string &Str,
4496 const PrintingPolicy &Policy) const {
4497 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
4498 " was used directly instead of getting the QualType through"
4499 " GetTypeFromParser");
4502 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
4503 // C99 6.7.6: Type names have no identifier. This is already validated by
4505 assert(D.getIdentifier() == nullptr &&
4506 "Type name should have no identifier!");
4508 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4509 QualType T = TInfo->getType();
4510 if (D.isInvalidType())
4513 // Make sure there are no unused decl attributes on the declarator.
4514 // We don't want to do this for ObjC parameters because we're going
4515 // to apply them to the actual parameter declaration.
4516 // Likewise, we don't want to do this for alias declarations, because
4517 // we are actually going to build a declaration from this eventually.
4518 if (D.getContext() != Declarator::ObjCParameterContext &&
4519 D.getContext() != Declarator::AliasDeclContext &&
4520 D.getContext() != Declarator::AliasTemplateContext)
4521 checkUnusedDeclAttributes(D);
4523 if (getLangOpts().CPlusPlus) {
4524 // Check that there are no default arguments (C++ only).
4525 CheckExtraCXXDefaultArguments(D);
4528 return CreateParsedType(T, TInfo);
4531 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
4532 QualType T = Context.getObjCInstanceType();
4533 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
4534 return CreateParsedType(T, TInfo);
4538 //===----------------------------------------------------------------------===//
4539 // Type Attribute Processing
4540 //===----------------------------------------------------------------------===//
4542 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
4543 /// specified type. The attribute contains 1 argument, the id of the address
4544 /// space for the type.
4545 static void HandleAddressSpaceTypeAttribute(QualType &Type,
4546 const AttributeList &Attr, Sema &S){
4548 // If this type is already address space qualified, reject it.
4549 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
4550 // qualifiers for two or more different address spaces."
4551 if (Type.getAddressSpace()) {
4552 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
4557 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
4558 // qualified by an address-space qualifier."
4559 if (Type->isFunctionType()) {
4560 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
4566 if (Attr.getKind() == AttributeList::AT_AddressSpace) {
4567 // Check the attribute arguments.
4568 if (Attr.getNumArgs() != 1) {
4569 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4570 << Attr.getName() << 1;
4574 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4575 llvm::APSInt addrSpace(32);
4576 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
4577 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
4578 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4579 << Attr.getName() << AANT_ArgumentIntegerConstant
4580 << ASArgExpr->getSourceRange();
4586 if (addrSpace.isSigned()) {
4587 if (addrSpace.isNegative()) {
4588 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
4589 << ASArgExpr->getSourceRange();
4593 addrSpace.setIsSigned(false);
4595 llvm::APSInt max(addrSpace.getBitWidth());
4596 max = Qualifiers::MaxAddressSpace;
4597 if (addrSpace > max) {
4598 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
4599 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
4603 ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
4605 // The keyword-based type attributes imply which address space to use.
4606 switch (Attr.getKind()) {
4607 case AttributeList::AT_OpenCLGlobalAddressSpace:
4608 ASIdx = LangAS::opencl_global; break;
4609 case AttributeList::AT_OpenCLLocalAddressSpace:
4610 ASIdx = LangAS::opencl_local; break;
4611 case AttributeList::AT_OpenCLConstantAddressSpace:
4612 ASIdx = LangAS::opencl_constant; break;
4613 case AttributeList::AT_OpenCLGenericAddressSpace:
4614 ASIdx = LangAS::opencl_generic; break;
4616 assert(Attr.getKind() == AttributeList::AT_OpenCLPrivateAddressSpace);
4621 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
4624 /// Does this type have a "direct" ownership qualifier? That is,
4625 /// is it written like "__strong id", as opposed to something like
4626 /// "typeof(foo)", where that happens to be strong?
4627 static bool hasDirectOwnershipQualifier(QualType type) {
4628 // Fast path: no qualifier at all.
4629 assert(type.getQualifiers().hasObjCLifetime());
4633 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
4634 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
4637 type = attr->getModifiedType();
4639 // X *__strong (...)
4640 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
4641 type = paren->getInnerType();
4643 // That's it for things we want to complain about. In particular,
4644 // we do not want to look through typedefs, typeof(expr),
4645 // typeof(type), or any other way that the type is somehow
4654 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4655 /// attribute on the specified type.
4657 /// Returns 'true' if the attribute was handled.
4658 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4659 AttributeList &attr,
4661 bool NonObjCPointer = false;
4663 if (!type->isDependentType() && !type->isUndeducedType()) {
4664 if (const PointerType *ptr = type->getAs<PointerType>()) {
4665 QualType pointee = ptr->getPointeeType();
4666 if (pointee->isObjCRetainableType() || pointee->isPointerType())
4668 // It is important not to lose the source info that there was an attribute
4669 // applied to non-objc pointer. We will create an attributed type but
4670 // its type will be the same as the original type.
4671 NonObjCPointer = true;
4672 } else if (!type->isObjCRetainableType()) {
4676 // Don't accept an ownership attribute in the declspec if it would
4677 // just be the return type of a block pointer.
4678 if (state.isProcessingDeclSpec()) {
4679 Declarator &D = state.getDeclarator();
4680 if (maybeMovePastReturnType(D, D.getNumTypeObjects(),
4681 /*onlyBlockPointers=*/true))
4686 Sema &S = state.getSema();
4687 SourceLocation AttrLoc = attr.getLoc();
4688 if (AttrLoc.isMacroID())
4689 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4691 if (!attr.isArgIdent(0)) {
4692 S.Diag(AttrLoc, diag::err_attribute_argument_type)
4693 << attr.getName() << AANT_ArgumentString;
4698 // Consume lifetime attributes without further comment outside of
4700 if (!S.getLangOpts().ObjCAutoRefCount)
4703 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4704 Qualifiers::ObjCLifetime lifetime;
4705 if (II->isStr("none"))
4706 lifetime = Qualifiers::OCL_ExplicitNone;
4707 else if (II->isStr("strong"))
4708 lifetime = Qualifiers::OCL_Strong;
4709 else if (II->isStr("weak"))
4710 lifetime = Qualifiers::OCL_Weak;
4711 else if (II->isStr("autoreleasing"))
4712 lifetime = Qualifiers::OCL_Autoreleasing;
4714 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4715 << attr.getName() << II;
4720 SplitQualType underlyingType = type.split();
4722 // Check for redundant/conflicting ownership qualifiers.
4723 if (Qualifiers::ObjCLifetime previousLifetime
4724 = type.getQualifiers().getObjCLifetime()) {
4725 // If it's written directly, that's an error.
4726 if (hasDirectOwnershipQualifier(type)) {
4727 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4732 // Otherwise, if the qualifiers actually conflict, pull sugar off
4733 // until we reach a type that is directly qualified.
4734 if (previousLifetime != lifetime) {
4735 // This should always terminate: the canonical type is
4736 // qualified, so some bit of sugar must be hiding it.
4737 while (!underlyingType.Quals.hasObjCLifetime()) {
4738 underlyingType = underlyingType.getSingleStepDesugaredType();
4740 underlyingType.Quals.removeObjCLifetime();
4744 underlyingType.Quals.addObjCLifetime(lifetime);
4746 if (NonObjCPointer) {
4747 StringRef name = attr.getName()->getName();
4749 case Qualifiers::OCL_None:
4750 case Qualifiers::OCL_ExplicitNone:
4752 case Qualifiers::OCL_Strong: name = "__strong"; break;
4753 case Qualifiers::OCL_Weak: name = "__weak"; break;
4754 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4756 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4757 << TDS_ObjCObjOrBlock << type;
4760 QualType origType = type;
4761 if (!NonObjCPointer)
4762 type = S.Context.getQualifiedType(underlyingType);
4764 // If we have a valid source location for the attribute, use an
4765 // AttributedType instead.
4766 if (AttrLoc.isValid())
4767 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4770 // Forbid __weak if the runtime doesn't support it.
4771 if (lifetime == Qualifiers::OCL_Weak &&
4772 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4774 // Actually, delay this until we know what we're parsing.
4775 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4776 S.DelayedDiagnostics.add(
4777 sema::DelayedDiagnostic::makeForbiddenType(
4778 S.getSourceManager().getExpansionLoc(AttrLoc),
4779 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4781 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4788 // Forbid __weak for class objects marked as
4789 // objc_arc_weak_reference_unavailable
4790 if (lifetime == Qualifiers::OCL_Weak) {
4791 if (const ObjCObjectPointerType *ObjT =
4792 type->getAs<ObjCObjectPointerType>()) {
4793 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4794 if (Class->isArcWeakrefUnavailable()) {
4795 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4796 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4797 diag::note_class_declared);
4806 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4807 /// attribute on the specified type. Returns true to indicate that
4808 /// the attribute was handled, false to indicate that the type does
4809 /// not permit the attribute.
4810 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4811 AttributeList &attr,
4813 Sema &S = state.getSema();
4815 // Delay if this isn't some kind of pointer.
4816 if (!type->isPointerType() &&
4817 !type->isObjCObjectPointerType() &&
4818 !type->isBlockPointerType())
4821 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4822 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4827 // Check the attribute arguments.
4828 if (!attr.isArgIdent(0)) {
4829 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4830 << attr.getName() << AANT_ArgumentString;
4834 Qualifiers::GC GCAttr;
4835 if (attr.getNumArgs() > 1) {
4836 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4837 << attr.getName() << 1;
4842 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4843 if (II->isStr("weak"))
4844 GCAttr = Qualifiers::Weak;
4845 else if (II->isStr("strong"))
4846 GCAttr = Qualifiers::Strong;
4848 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4849 << attr.getName() << II;
4854 QualType origType = type;
4855 type = S.Context.getObjCGCQualType(origType, GCAttr);
4857 // Make an attributed type to preserve the source information.
4858 if (attr.getLoc().isValid())
4859 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4866 /// A helper class to unwrap a type down to a function for the
4867 /// purposes of applying attributes there.
4870 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
4871 /// if (unwrapped.isFunctionType()) {
4872 /// const FunctionType *fn = unwrapped.get();
4873 /// // change fn somehow
4874 /// T = unwrapped.wrap(fn);
4876 struct FunctionTypeUnwrapper {
4887 const FunctionType *Fn;
4888 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4890 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4892 const Type *Ty = T.getTypePtr();
4893 if (isa<FunctionType>(Ty)) {
4894 Fn = cast<FunctionType>(Ty);
4896 } else if (isa<ParenType>(Ty)) {
4897 T = cast<ParenType>(Ty)->getInnerType();
4898 Stack.push_back(Parens);
4899 } else if (isa<PointerType>(Ty)) {
4900 T = cast<PointerType>(Ty)->getPointeeType();
4901 Stack.push_back(Pointer);
4902 } else if (isa<BlockPointerType>(Ty)) {
4903 T = cast<BlockPointerType>(Ty)->getPointeeType();
4904 Stack.push_back(BlockPointer);
4905 } else if (isa<MemberPointerType>(Ty)) {
4906 T = cast<MemberPointerType>(Ty)->getPointeeType();
4907 Stack.push_back(MemberPointer);
4908 } else if (isa<ReferenceType>(Ty)) {
4909 T = cast<ReferenceType>(Ty)->getPointeeType();
4910 Stack.push_back(Reference);
4912 const Type *DTy = Ty->getUnqualifiedDesugaredType();
4918 T = QualType(DTy, 0);
4919 Stack.push_back(Desugar);
4924 bool isFunctionType() const { return (Fn != nullptr); }
4925 const FunctionType *get() const { return Fn; }
4927 QualType wrap(Sema &S, const FunctionType *New) {
4928 // If T wasn't modified from the unwrapped type, do nothing.
4929 if (New == get()) return Original;
4932 return wrap(S.Context, Original, 0);
4936 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4937 if (I == Stack.size())
4938 return C.getQualifiedType(Fn, Old.getQualifiers());
4940 // Build up the inner type, applying the qualifiers from the old
4941 // type to the new type.
4942 SplitQualType SplitOld = Old.split();
4944 // As a special case, tail-recurse if there are no qualifiers.
4945 if (SplitOld.Quals.empty())
4946 return wrap(C, SplitOld.Ty, I);
4947 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4950 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4951 if (I == Stack.size()) return QualType(Fn, 0);
4953 switch (static_cast<WrapKind>(Stack[I++])) {
4955 // This is the point at which we potentially lose source
4957 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4960 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4961 return C.getParenType(New);
4965 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4966 return C.getPointerType(New);
4969 case BlockPointer: {
4970 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4971 return C.getBlockPointerType(New);
4974 case MemberPointer: {
4975 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4976 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4977 return C.getMemberPointerType(New, OldMPT->getClass());
4981 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4982 QualType New = wrap(C, OldRef->getPointeeType(), I);
4983 if (isa<LValueReferenceType>(OldRef))
4984 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4986 return C.getRValueReferenceType(New);
4990 llvm_unreachable("unknown wrapping kind");
4995 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4996 AttributeList &Attr,
4998 Sema &S = State.getSema();
5000 AttributeList::Kind Kind = Attr.getKind();
5001 QualType Desugared = Type;
5002 const AttributedType *AT = dyn_cast<AttributedType>(Type);
5004 AttributedType::Kind CurAttrKind = AT->getAttrKind();
5006 // You cannot specify duplicate type attributes, so if the attribute has
5007 // already been applied, flag it.
5008 if (getAttrListKind(CurAttrKind) == Kind) {
5009 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
5014 // You cannot have both __sptr and __uptr on the same type, nor can you
5015 // have __ptr32 and __ptr64.
5016 if ((CurAttrKind == AttributedType::attr_ptr32 &&
5017 Kind == AttributeList::AT_Ptr64) ||
5018 (CurAttrKind == AttributedType::attr_ptr64 &&
5019 Kind == AttributeList::AT_Ptr32)) {
5020 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5021 << "'__ptr32'" << "'__ptr64'";
5023 } else if ((CurAttrKind == AttributedType::attr_sptr &&
5024 Kind == AttributeList::AT_UPtr) ||
5025 (CurAttrKind == AttributedType::attr_uptr &&
5026 Kind == AttributeList::AT_SPtr)) {
5027 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
5028 << "'__sptr'" << "'__uptr'";
5032 Desugared = AT->getEquivalentType();
5033 AT = dyn_cast<AttributedType>(Desugared);
5036 // Pointer type qualifiers can only operate on pointer types, but not
5037 // pointer-to-member types.
5038 if (!isa<PointerType>(Desugared)) {
5039 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
5040 diag::err_attribute_no_member_pointers :
5041 diag::err_attribute_pointers_only) << Attr.getName();
5045 AttributedType::Kind TAK;
5047 default: llvm_unreachable("Unknown attribute kind");
5048 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
5049 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
5050 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
5051 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
5054 Type = S.Context.getAttributedType(TAK, Type, Type);
5058 bool Sema::checkNullabilityTypeSpecifier(QualType &type,
5059 NullabilityKind nullability,
5060 SourceLocation nullabilityLoc,
5061 bool isContextSensitive) {
5062 // We saw a nullability type specifier. If this is the first one for
5063 // this file, note that.
5064 FileID file = getNullabilityCompletenessCheckFileID(*this, nullabilityLoc);
5065 if (!file.isInvalid()) {
5066 FileNullability &fileNullability = NullabilityMap[file];
5067 if (!fileNullability.SawTypeNullability) {
5068 // If we have already seen a pointer declarator without a nullability
5069 // annotation, complain about it.
5070 if (fileNullability.PointerLoc.isValid()) {
5071 Diag(fileNullability.PointerLoc, diag::warn_nullability_missing)
5072 << static_cast<unsigned>(fileNullability.PointerKind);
5075 fileNullability.SawTypeNullability = true;
5079 // Check for existing nullability attributes on the type.
5080 QualType desugared = type;
5081 while (auto attributed = dyn_cast<AttributedType>(desugared.getTypePtr())) {
5082 // Check whether there is already a null
5083 if (auto existingNullability = attributed->getImmediateNullability()) {
5084 // Duplicated nullability.
5085 if (nullability == *existingNullability) {
5086 Diag(nullabilityLoc, diag::warn_nullability_duplicate)
5087 << DiagNullabilityKind(nullability, isContextSensitive)
5088 << FixItHint::CreateRemoval(nullabilityLoc);
5093 // Conflicting nullability.
5094 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5095 << DiagNullabilityKind(nullability, isContextSensitive)
5096 << DiagNullabilityKind(*existingNullability, false);
5100 desugared = attributed->getModifiedType();
5103 // If there is already a different nullability specifier, complain.
5104 // This (unlike the code above) looks through typedefs that might
5105 // have nullability specifiers on them, which means we cannot
5106 // provide a useful Fix-It.
5107 if (auto existingNullability = desugared->getNullability(Context)) {
5108 if (nullability != *existingNullability) {
5109 Diag(nullabilityLoc, diag::err_nullability_conflicting)
5110 << DiagNullabilityKind(nullability, isContextSensitive)
5111 << DiagNullabilityKind(*existingNullability, false);
5113 // Try to find the typedef with the existing nullability specifier.
5114 if (auto typedefType = desugared->getAs<TypedefType>()) {
5115 TypedefNameDecl *typedefDecl = typedefType->getDecl();
5116 QualType underlyingType = typedefDecl->getUnderlyingType();
5117 if (auto typedefNullability
5118 = AttributedType::stripOuterNullability(underlyingType)) {
5119 if (*typedefNullability == *existingNullability) {
5120 Diag(typedefDecl->getLocation(), diag::note_nullability_here)
5121 << DiagNullabilityKind(*existingNullability, false);
5130 // If this definitely isn't a pointer type, reject the specifier.
5131 if (!desugared->canHaveNullability()) {
5132 Diag(nullabilityLoc, diag::err_nullability_nonpointer)
5133 << DiagNullabilityKind(nullability, isContextSensitive) << type;
5137 // For the context-sensitive keywords/Objective-C property
5138 // attributes, require that the type be a single-level pointer.
5139 if (isContextSensitive) {
5140 // Make sure that the pointee isn't itself a pointer type.
5141 QualType pointeeType = desugared->getPointeeType();
5142 if (pointeeType->isAnyPointerType() ||
5143 pointeeType->isObjCObjectPointerType() ||
5144 pointeeType->isMemberPointerType()) {
5145 Diag(nullabilityLoc, diag::err_nullability_cs_multilevel)
5146 << DiagNullabilityKind(nullability, true)
5148 Diag(nullabilityLoc, diag::note_nullability_type_specifier)
5149 << DiagNullabilityKind(nullability, false)
5151 << FixItHint::CreateReplacement(nullabilityLoc,
5152 getNullabilitySpelling(nullability));
5157 // Form the attributed type.
5158 type = Context.getAttributedType(
5159 AttributedType::getNullabilityAttrKind(nullability), type, type);
5163 /// Map a nullability attribute kind to a nullability kind.
5164 static NullabilityKind mapNullabilityAttrKind(AttributeList::Kind kind) {
5166 case AttributeList::AT_TypeNonNull:
5167 return NullabilityKind::NonNull;
5169 case AttributeList::AT_TypeNullable:
5170 return NullabilityKind::Nullable;
5172 case AttributeList::AT_TypeNullUnspecified:
5173 return NullabilityKind::Unspecified;
5176 llvm_unreachable("not a nullability attribute kind");
5180 /// Distribute a nullability type attribute that cannot be applied to
5181 /// the type specifier to a pointer, block pointer, or member pointer
5182 /// declarator, complaining if necessary.
5184 /// \returns true if the nullability annotation was distributed, false
5186 static bool distributeNullabilityTypeAttr(TypeProcessingState &state,
5188 AttributeList &attr) {
5189 Declarator &declarator = state.getDeclarator();
5191 /// Attempt to move the attribute to the specified chunk.
5192 auto moveToChunk = [&](DeclaratorChunk &chunk, bool inFunction) -> bool {
5193 // If there is already a nullability attribute there, don't add
5195 if (hasNullabilityAttr(chunk.getAttrListRef()))
5198 // Complain about the nullability qualifier being in the wrong
5205 PK_MemberFunctionPointer,
5207 = chunk.Kind == DeclaratorChunk::Pointer ? (inFunction ? PK_FunctionPointer
5209 : chunk.Kind == DeclaratorChunk::BlockPointer ? PK_BlockPointer
5210 : inFunction? PK_MemberFunctionPointer : PK_MemberPointer;
5212 auto diag = state.getSema().Diag(attr.getLoc(),
5213 diag::warn_nullability_declspec)
5214 << DiagNullabilityKind(mapNullabilityAttrKind(attr.getKind()),
5215 attr.isContextSensitiveKeywordAttribute())
5217 << static_cast<unsigned>(pointerKind);
5219 // FIXME: MemberPointer chunks don't carry the location of the *.
5220 if (chunk.Kind != DeclaratorChunk::MemberPointer) {
5221 diag << FixItHint::CreateRemoval(attr.getLoc())
5222 << FixItHint::CreateInsertion(
5223 state.getSema().getPreprocessor()
5224 .getLocForEndOfToken(chunk.Loc),
5225 " " + attr.getName()->getName().str() + " ");
5228 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
5229 chunk.getAttrListRef());
5233 // Move it to the outermost pointer, member pointer, or block
5234 // pointer declarator.
5235 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
5236 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
5237 switch (chunk.Kind) {
5238 case DeclaratorChunk::Pointer:
5239 case DeclaratorChunk::BlockPointer:
5240 case DeclaratorChunk::MemberPointer:
5241 return moveToChunk(chunk, false);
5243 case DeclaratorChunk::Paren:
5244 case DeclaratorChunk::Array:
5247 case DeclaratorChunk::Function:
5248 // Try to move past the return type to a function/block/member
5249 // function pointer.
5250 if (DeclaratorChunk *dest = maybeMovePastReturnType(
5252 /*onlyBlockPointers=*/false)) {
5253 return moveToChunk(*dest, true);
5258 // Don't walk through these.
5259 case DeclaratorChunk::Reference:
5267 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
5268 assert(!Attr.isInvalid());
5269 switch (Attr.getKind()) {
5271 llvm_unreachable("not a calling convention attribute");
5272 case AttributeList::AT_CDecl:
5273 return AttributedType::attr_cdecl;
5274 case AttributeList::AT_FastCall:
5275 return AttributedType::attr_fastcall;
5276 case AttributeList::AT_StdCall:
5277 return AttributedType::attr_stdcall;
5278 case AttributeList::AT_ThisCall:
5279 return AttributedType::attr_thiscall;
5280 case AttributeList::AT_Pascal:
5281 return AttributedType::attr_pascal;
5282 case AttributeList::AT_VectorCall:
5283 return AttributedType::attr_vectorcall;
5284 case AttributeList::AT_Pcs: {
5285 // The attribute may have had a fixit applied where we treated an
5286 // identifier as a string literal. The contents of the string are valid,
5287 // but the form may not be.
5289 if (Attr.isArgExpr(0))
5290 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
5292 Str = Attr.getArgAsIdent(0)->Ident->getName();
5293 return llvm::StringSwitch<AttributedType::Kind>(Str)
5294 .Case("aapcs", AttributedType::attr_pcs)
5295 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
5297 case AttributeList::AT_IntelOclBicc:
5298 return AttributedType::attr_inteloclbicc;
5299 case AttributeList::AT_MSABI:
5300 return AttributedType::attr_ms_abi;
5301 case AttributeList::AT_SysVABI:
5302 return AttributedType::attr_sysv_abi;
5304 llvm_unreachable("unexpected attribute kind!");
5307 /// Process an individual function attribute. Returns true to
5308 /// indicate that the attribute was handled, false if it wasn't.
5309 static bool handleFunctionTypeAttr(TypeProcessingState &state,
5310 AttributeList &attr,
5312 Sema &S = state.getSema();
5314 FunctionTypeUnwrapper unwrapped(S, type);
5316 if (attr.getKind() == AttributeList::AT_NoReturn) {
5317 if (S.CheckNoReturnAttr(attr))
5320 // Delay if this is not a function type.
5321 if (!unwrapped.isFunctionType())
5324 // Otherwise we can process right away.
5325 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
5326 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5330 // ns_returns_retained is not always a type attribute, but if we got
5331 // here, we're treating it as one right now.
5332 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
5333 assert(S.getLangOpts().ObjCAutoRefCount &&
5334 "ns_returns_retained treated as type attribute in non-ARC");
5335 if (attr.getNumArgs()) return true;
5337 // Delay if this is not a function type.
5338 if (!unwrapped.isFunctionType())
5341 FunctionType::ExtInfo EI
5342 = unwrapped.get()->getExtInfo().withProducesResult(true);
5343 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5347 if (attr.getKind() == AttributeList::AT_Regparm) {
5349 if (S.CheckRegparmAttr(attr, value))
5352 // Delay if this is not a function type.
5353 if (!unwrapped.isFunctionType())
5356 // Diagnose regparm with fastcall.
5357 const FunctionType *fn = unwrapped.get();
5358 CallingConv CC = fn->getCallConv();
5359 if (CC == CC_X86FastCall) {
5360 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5361 << FunctionType::getNameForCallConv(CC)
5367 FunctionType::ExtInfo EI =
5368 unwrapped.get()->getExtInfo().withRegParm(value);
5369 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5373 // Delay if the type didn't work out to a function.
5374 if (!unwrapped.isFunctionType()) return false;
5376 // Otherwise, a calling convention.
5378 if (S.CheckCallingConvAttr(attr, CC))
5381 const FunctionType *fn = unwrapped.get();
5382 CallingConv CCOld = fn->getCallConv();
5383 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
5386 // Error out on when there's already an attribute on the type
5387 // and the CCs don't match.
5388 const AttributedType *AT = S.getCallingConvAttributedType(type);
5389 if (AT && AT->getAttrKind() != CCAttrKind) {
5390 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5391 << FunctionType::getNameForCallConv(CC)
5392 << FunctionType::getNameForCallConv(CCOld);
5398 // Diagnose use of callee-cleanup calling convention on variadic functions.
5399 if (!supportsVariadicCall(CC)) {
5400 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
5401 if (FnP && FnP->isVariadic()) {
5402 unsigned DiagID = diag::err_cconv_varargs;
5403 // stdcall and fastcall are ignored with a warning for GCC and MS
5405 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
5406 DiagID = diag::warn_cconv_varargs;
5408 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
5414 // Also diagnose fastcall with regparm.
5415 if (CC == CC_X86FastCall && fn->getHasRegParm()) {
5416 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
5417 << "regparm" << FunctionType::getNameForCallConv(CC_X86FastCall);
5422 // Modify the CC from the wrapped function type, wrap it all back, and then
5423 // wrap the whole thing in an AttributedType as written. The modified type
5424 // might have a different CC if we ignored the attribute.
5425 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
5426 QualType Equivalent =
5427 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
5428 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
5432 bool Sema::hasExplicitCallingConv(QualType &T) {
5433 QualType R = T.IgnoreParens();
5434 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
5435 if (AT->isCallingConv())
5437 R = AT->getModifiedType().IgnoreParens();
5442 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
5443 FunctionTypeUnwrapper Unwrapped(*this, T);
5444 const FunctionType *FT = Unwrapped.get();
5445 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
5446 cast<FunctionProtoType>(FT)->isVariadic());
5448 // Only adjust types with the default convention. For example, on Windows we
5449 // should adjust a __cdecl type to __thiscall for instance methods, and a
5450 // __thiscall type to __cdecl for static methods.
5451 CallingConv CurCC = FT->getCallConv();
5452 CallingConv FromCC =
5453 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
5454 CallingConv ToCC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
5455 if (CurCC != FromCC || FromCC == ToCC)
5458 if (hasExplicitCallingConv(T))
5461 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(ToCC));
5462 QualType Wrapped = Unwrapped.wrap(*this, FT);
5463 T = Context.getAdjustedType(T, Wrapped);
5466 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
5467 /// and float scalars, although arrays, pointers, and function return values are
5468 /// allowed in conjunction with this construct. Aggregates with this attribute
5469 /// are invalid, even if they are of the same size as a corresponding scalar.
5470 /// The raw attribute should contain precisely 1 argument, the vector size for
5471 /// the variable, measured in bytes. If curType and rawAttr are well formed,
5472 /// this routine will return a new vector type.
5473 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
5475 // Check the attribute arguments.
5476 if (Attr.getNumArgs() != 1) {
5477 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5478 << Attr.getName() << 1;
5482 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5483 llvm::APSInt vecSize(32);
5484 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
5485 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
5486 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5487 << Attr.getName() << AANT_ArgumentIntegerConstant
5488 << sizeExpr->getSourceRange();
5492 // The base type must be integer (not Boolean or enumeration) or float, and
5493 // can't already be a vector.
5494 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
5495 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
5496 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5500 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5501 // vecSize is specified in bytes - convert to bits.
5502 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
5504 // the vector size needs to be an integral multiple of the type size.
5505 if (vectorSize % typeSize) {
5506 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
5507 << sizeExpr->getSourceRange();
5511 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
5512 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
5513 << sizeExpr->getSourceRange();
5517 if (vectorSize == 0) {
5518 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
5519 << sizeExpr->getSourceRange();
5524 // Success! Instantiate the vector type, the number of elements is > 0, and
5525 // not required to be a power of 2, unlike GCC.
5526 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
5527 VectorType::GenericVector);
5530 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
5532 static void HandleExtVectorTypeAttr(QualType &CurType,
5533 const AttributeList &Attr,
5535 // check the attribute arguments.
5536 if (Attr.getNumArgs() != 1) {
5537 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5538 << Attr.getName() << 1;
5544 // Special case where the argument is a template id.
5545 if (Attr.isArgIdent(0)) {
5547 SourceLocation TemplateKWLoc;
5549 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
5551 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
5553 if (Size.isInvalid())
5556 sizeExpr = Size.get();
5558 sizeExpr = Attr.getArgAsExpr(0);
5561 // Create the vector type.
5562 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
5567 static bool isPermittedNeonBaseType(QualType &Ty,
5568 VectorType::VectorKind VecKind, Sema &S) {
5569 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
5573 llvm::Triple Triple = S.Context.getTargetInfo().getTriple();
5575 // Signed poly is mathematically wrong, but has been baked into some ABIs by
5577 bool IsPolyUnsigned = Triple.getArch() == llvm::Triple::aarch64 ||
5578 Triple.getArch() == llvm::Triple::aarch64_be;
5579 if (VecKind == VectorType::NeonPolyVector) {
5580 if (IsPolyUnsigned) {
5581 // AArch64 polynomial vectors are unsigned and support poly64.
5582 return BTy->getKind() == BuiltinType::UChar ||
5583 BTy->getKind() == BuiltinType::UShort ||
5584 BTy->getKind() == BuiltinType::ULong ||
5585 BTy->getKind() == BuiltinType::ULongLong;
5587 // AArch32 polynomial vector are signed.
5588 return BTy->getKind() == BuiltinType::SChar ||
5589 BTy->getKind() == BuiltinType::Short;
5593 // Non-polynomial vector types: the usual suspects are allowed, as well as
5594 // float64_t on AArch64.
5595 bool Is64Bit = Triple.getArch() == llvm::Triple::aarch64 ||
5596 Triple.getArch() == llvm::Triple::aarch64_be;
5598 if (Is64Bit && BTy->getKind() == BuiltinType::Double)
5601 return BTy->getKind() == BuiltinType::SChar ||
5602 BTy->getKind() == BuiltinType::UChar ||
5603 BTy->getKind() == BuiltinType::Short ||
5604 BTy->getKind() == BuiltinType::UShort ||
5605 BTy->getKind() == BuiltinType::Int ||
5606 BTy->getKind() == BuiltinType::UInt ||
5607 BTy->getKind() == BuiltinType::Long ||
5608 BTy->getKind() == BuiltinType::ULong ||
5609 BTy->getKind() == BuiltinType::LongLong ||
5610 BTy->getKind() == BuiltinType::ULongLong ||
5611 BTy->getKind() == BuiltinType::Float ||
5612 BTy->getKind() == BuiltinType::Half;
5615 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
5616 /// "neon_polyvector_type" attributes are used to create vector types that
5617 /// are mangled according to ARM's ABI. Otherwise, these types are identical
5618 /// to those created with the "vector_size" attribute. Unlike "vector_size"
5619 /// the argument to these Neon attributes is the number of vector elements,
5620 /// not the vector size in bytes. The vector width and element type must
5621 /// match one of the standard Neon vector types.
5622 static void HandleNeonVectorTypeAttr(QualType& CurType,
5623 const AttributeList &Attr, Sema &S,
5624 VectorType::VectorKind VecKind) {
5625 // Target must have NEON
5626 if (!S.Context.getTargetInfo().hasFeature("neon")) {
5627 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
5631 // Check the attribute arguments.
5632 if (Attr.getNumArgs() != 1) {
5633 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
5634 << Attr.getName() << 1;
5638 // The number of elements must be an ICE.
5639 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
5640 llvm::APSInt numEltsInt(32);
5641 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
5642 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
5643 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
5644 << Attr.getName() << AANT_ArgumentIntegerConstant
5645 << numEltsExpr->getSourceRange();
5649 // Only certain element types are supported for Neon vectors.
5650 if (!isPermittedNeonBaseType(CurType, VecKind, S)) {
5651 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
5656 // The total size of the vector must be 64 or 128 bits.
5657 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
5658 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
5659 unsigned vecSize = typeSize * numElts;
5660 if (vecSize != 64 && vecSize != 128) {
5661 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
5666 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
5669 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
5670 TypeAttrLocation TAL, AttributeList *attrs) {
5671 // Scan through and apply attributes to this type where it makes sense. Some
5672 // attributes (such as __address_space__, __vector_size__, etc) apply to the
5673 // type, but others can be present in the type specifiers even though they
5674 // apply to the decl. Here we apply type attributes and ignore the rest.
5676 AttributeList *next;
5678 AttributeList &attr = *attrs;
5679 next = attr.getNext();
5681 // Skip attributes that were marked to be invalid.
5682 if (attr.isInvalid())
5685 if (attr.isCXX11Attribute()) {
5686 // [[gnu::...]] attributes are treated as declaration attributes, so may
5687 // not appertain to a DeclaratorChunk, even if we handle them as type
5689 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
5690 if (TAL == TAL_DeclChunk) {
5691 state.getSema().Diag(attr.getLoc(),
5692 diag::warn_cxx11_gnu_attribute_on_type)
5696 } else if (TAL != TAL_DeclChunk) {
5697 // Otherwise, only consider type processing for a C++11 attribute if
5698 // it's actually been applied to a type.
5703 // If this is an attribute we can handle, do so now,
5704 // otherwise, add it to the FnAttrs list for rechaining.
5705 switch (attr.getKind()) {
5707 // A C++11 attribute on a declarator chunk must appertain to a type.
5708 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
5709 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
5711 attr.setUsedAsTypeAttr();
5715 case AttributeList::UnknownAttribute:
5716 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
5717 state.getSema().Diag(attr.getLoc(),
5718 diag::warn_unknown_attribute_ignored)
5722 case AttributeList::IgnoredAttribute:
5725 case AttributeList::AT_MayAlias:
5726 // FIXME: This attribute needs to actually be handled, but if we ignore
5727 // it it breaks large amounts of Linux software.
5728 attr.setUsedAsTypeAttr();
5730 case AttributeList::AT_OpenCLPrivateAddressSpace:
5731 case AttributeList::AT_OpenCLGlobalAddressSpace:
5732 case AttributeList::AT_OpenCLLocalAddressSpace:
5733 case AttributeList::AT_OpenCLConstantAddressSpace:
5734 case AttributeList::AT_OpenCLGenericAddressSpace:
5735 case AttributeList::AT_AddressSpace:
5736 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
5737 attr.setUsedAsTypeAttr();
5739 OBJC_POINTER_TYPE_ATTRS_CASELIST:
5740 if (!handleObjCPointerTypeAttr(state, attr, type))
5741 distributeObjCPointerTypeAttr(state, attr, type);
5742 attr.setUsedAsTypeAttr();
5744 case AttributeList::AT_VectorSize:
5745 HandleVectorSizeAttr(type, attr, state.getSema());
5746 attr.setUsedAsTypeAttr();
5748 case AttributeList::AT_ExtVectorType:
5749 HandleExtVectorTypeAttr(type, attr, state.getSema());
5750 attr.setUsedAsTypeAttr();
5752 case AttributeList::AT_NeonVectorType:
5753 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
5754 VectorType::NeonVector);
5755 attr.setUsedAsTypeAttr();
5757 case AttributeList::AT_NeonPolyVectorType:
5758 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
5759 VectorType::NeonPolyVector);
5760 attr.setUsedAsTypeAttr();
5762 case AttributeList::AT_OpenCLImageAccess:
5763 // FIXME: there should be some type checking happening here, I would
5764 // imagine, but the original handler's checking was entirely superfluous.
5765 attr.setUsedAsTypeAttr();
5768 MS_TYPE_ATTRS_CASELIST:
5769 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
5770 attr.setUsedAsTypeAttr();
5773 NULLABILITY_TYPE_ATTRS_CASELIST:
5774 // Either add nullability here or try to distribute it. We
5775 // don't want to distribute the nullability specifier past any
5776 // dependent type, because that complicates the user model.
5777 if (type->canHaveNullability() || type->isDependentType() ||
5778 !distributeNullabilityTypeAttr(state, type, attr)) {
5779 if (state.getSema().checkNullabilityTypeSpecifier(
5781 mapNullabilityAttrKind(attr.getKind()),
5783 attr.isContextSensitiveKeywordAttribute())) {
5787 attr.setUsedAsTypeAttr();
5791 case AttributeList::AT_NSReturnsRetained:
5792 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
5794 // fallthrough into the function attrs
5796 FUNCTION_TYPE_ATTRS_CASELIST:
5797 attr.setUsedAsTypeAttr();
5799 // Never process function type attributes as part of the
5800 // declaration-specifiers.
5801 if (TAL == TAL_DeclSpec)
5802 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
5804 // Otherwise, handle the possible delays.
5805 else if (!handleFunctionTypeAttr(state, attr, type))
5806 distributeFunctionTypeAttr(state, attr, type);
5809 } while ((attrs = next));
5812 /// \brief Ensure that the type of the given expression is complete.
5814 /// This routine checks whether the expression \p E has a complete type. If the
5815 /// expression refers to an instantiable construct, that instantiation is
5816 /// performed as needed to complete its type. Furthermore
5817 /// Sema::RequireCompleteType is called for the expression's type (or in the
5818 /// case of a reference type, the referred-to type).
5820 /// \param E The expression whose type is required to be complete.
5821 /// \param Diagnoser The object that will emit a diagnostic if the type is
5824 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
5826 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
5827 QualType T = E->getType();
5829 // Fast path the case where the type is already complete.
5830 if (!T->isIncompleteType())
5831 // FIXME: The definition might not be visible.
5834 // Incomplete array types may be completed by the initializer attached to
5835 // their definitions. For static data members of class templates and for
5836 // variable templates, we need to instantiate the definition to get this
5837 // initializer and complete the type.
5838 if (T->isIncompleteArrayType()) {
5839 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5840 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5841 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
5842 SourceLocation PointOfInstantiation = E->getExprLoc();
5844 if (MemberSpecializationInfo *MSInfo =
5845 Var->getMemberSpecializationInfo()) {
5846 // If we don't already have a point of instantiation, this is it.
5847 if (MSInfo->getPointOfInstantiation().isInvalid()) {
5848 MSInfo->setPointOfInstantiation(PointOfInstantiation);
5850 // This is a modification of an existing AST node. Notify
5852 if (ASTMutationListener *L = getASTMutationListener())
5853 L->StaticDataMemberInstantiated(Var);
5856 VarTemplateSpecializationDecl *VarSpec =
5857 cast<VarTemplateSpecializationDecl>(Var);
5858 if (VarSpec->getPointOfInstantiation().isInvalid())
5859 VarSpec->setPointOfInstantiation(PointOfInstantiation);
5862 InstantiateVariableDefinition(PointOfInstantiation, Var);
5864 // Update the type to the newly instantiated definition's type both
5865 // here and within the expression.
5866 if (VarDecl *Def = Var->getDefinition()) {
5873 // We still go on to try to complete the type independently, as it
5874 // may also require instantiations or diagnostics if it remains
5881 // FIXME: Are there other cases which require instantiating something other
5882 // than the type to complete the type of an expression?
5884 // Look through reference types and complete the referred type.
5885 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5886 T = Ref->getPointeeType();
5888 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5892 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5895 TypeDiagnoserDiag(unsigned DiagID)
5896 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5898 void diagnose(Sema &S, SourceLocation Loc, QualType T) override {
5899 if (Suppressed) return;
5900 S.Diag(Loc, DiagID) << T;
5905 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5906 TypeDiagnoserDiag Diagnoser(DiagID);
5907 return RequireCompleteExprType(E, Diagnoser);
5910 /// @brief Ensure that the type T is a complete type.
5912 /// This routine checks whether the type @p T is complete in any
5913 /// context where a complete type is required. If @p T is a complete
5914 /// type, returns false. If @p T is a class template specialization,
5915 /// this routine then attempts to perform class template
5916 /// instantiation. If instantiation fails, or if @p T is incomplete
5917 /// and cannot be completed, issues the diagnostic @p diag (giving it
5918 /// the type @p T) and returns true.
5920 /// @param Loc The location in the source that the incomplete type
5921 /// diagnostic should refer to.
5923 /// @param T The type that this routine is examining for completeness.
5925 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5926 /// @c false otherwise.
5927 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5928 TypeDiagnoser &Diagnoser) {
5929 if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5931 if (const TagType *Tag = T->getAs<TagType>()) {
5932 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5933 Tag->getDecl()->setCompleteDefinitionRequired();
5934 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5940 /// \brief Determine whether there is any declaration of \p D that was ever a
5941 /// definition (perhaps before module merging) and is currently visible.
5942 /// \param D The definition of the entity.
5943 /// \param Suggested Filled in with the declaration that should be made visible
5944 /// in order to provide a definition of this entity.
5945 bool Sema::hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested) {
5946 // Easy case: if we don't have modules, all declarations are visible.
5947 if (!getLangOpts().Modules && !getLangOpts().ModulesLocalVisibility)
5950 // If this definition was instantiated from a template, map back to the
5951 // pattern from which it was instantiated.
5952 if (isa<TagDecl>(D) && cast<TagDecl>(D)->isBeingDefined()) {
5953 // We're in the middle of defining it; this definition should be treated
5956 } else if (auto *RD = dyn_cast<CXXRecordDecl>(D)) {
5957 if (auto *Pattern = RD->getTemplateInstantiationPattern())
5959 D = RD->getDefinition();
5960 } else if (auto *ED = dyn_cast<EnumDecl>(D)) {
5961 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
5963 if (ED->isFixed()) {
5964 // If the enum has a fixed underlying type, any declaration of it will do.
5965 *Suggested = nullptr;
5966 for (auto *Redecl : ED->redecls()) {
5967 if (LookupResult::isVisible(*this, Redecl))
5969 if (Redecl->isThisDeclarationADefinition() ||
5970 (Redecl->isCanonicalDecl() && !*Suggested))
5971 *Suggested = Redecl;
5975 D = ED->getDefinition();
5977 assert(D && "missing definition for pattern of instantiated definition");
5980 if (LookupResult::isVisible(*this, D))
5983 // The external source may have additional definitions of this type that are
5984 // visible, so complete the redeclaration chain now and ask again.
5985 if (auto *Source = Context.getExternalSource()) {
5986 Source->CompleteRedeclChain(D);
5987 return LookupResult::isVisible(*this, D);
5993 /// Locks in the inheritance model for the given class and all of its bases.
5994 static void assignInheritanceModel(Sema &S, CXXRecordDecl *RD) {
5995 RD = RD->getMostRecentDecl();
5996 if (!RD->hasAttr<MSInheritanceAttr>()) {
5997 MSInheritanceAttr::Spelling IM;
5999 switch (S.MSPointerToMemberRepresentationMethod) {
6000 case LangOptions::PPTMK_BestCase:
6001 IM = RD->calculateInheritanceModel();
6003 case LangOptions::PPTMK_FullGeneralitySingleInheritance:
6004 IM = MSInheritanceAttr::Keyword_single_inheritance;
6006 case LangOptions::PPTMK_FullGeneralityMultipleInheritance:
6007 IM = MSInheritanceAttr::Keyword_multiple_inheritance;
6009 case LangOptions::PPTMK_FullGeneralityVirtualInheritance:
6010 IM = MSInheritanceAttr::Keyword_unspecified_inheritance;
6014 RD->addAttr(MSInheritanceAttr::CreateImplicit(
6015 S.getASTContext(), IM,
6016 /*BestCase=*/S.MSPointerToMemberRepresentationMethod ==
6017 LangOptions::PPTMK_BestCase,
6018 S.ImplicitMSInheritanceAttrLoc.isValid()
6019 ? S.ImplicitMSInheritanceAttrLoc
6020 : RD->getSourceRange()));
6024 /// \brief The implementation of RequireCompleteType
6025 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
6026 TypeDiagnoser &Diagnoser) {
6027 // FIXME: Add this assertion to make sure we always get instantiation points.
6028 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
6029 // FIXME: Add this assertion to help us flush out problems with
6030 // checking for dependent types and type-dependent expressions.
6032 // assert(!T->isDependentType() &&
6033 // "Can't ask whether a dependent type is complete");
6035 // If we have a complete type, we're done.
6036 NamedDecl *Def = nullptr;
6037 if (!T->isIncompleteType(&Def)) {
6038 // If we know about the definition but it is not visible, complain.
6039 NamedDecl *SuggestedDef = nullptr;
6040 if (!Diagnoser.Suppressed && Def &&
6041 !hasVisibleDefinition(Def, &SuggestedDef))
6042 diagnoseMissingImport(Loc, SuggestedDef, /*NeedDefinition*/true);
6044 // We lock in the inheritance model once somebody has asked us to ensure
6045 // that a pointer-to-member type is complete.
6046 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6047 if (const MemberPointerType *MPTy = T->getAs<MemberPointerType>()) {
6048 if (!MPTy->getClass()->isDependentType()) {
6049 RequireCompleteType(Loc, QualType(MPTy->getClass(), 0), 0);
6050 assignInheritanceModel(*this, MPTy->getMostRecentCXXRecordDecl());
6058 const TagType *Tag = T->getAs<TagType>();
6059 const ObjCInterfaceType *IFace = T->getAs<ObjCInterfaceType>();
6061 // If there's an unimported definition of this type in a module (for
6062 // instance, because we forward declared it, then imported the definition),
6063 // import that definition now.
6065 // FIXME: What about other cases where an import extends a redeclaration
6066 // chain for a declaration that can be accessed through a mechanism other
6067 // than name lookup (eg, referenced in a template, or a variable whose type
6068 // could be completed by the module)?
6071 Tag ? static_cast<NamedDecl *>(Tag->getDecl()) : IFace->getDecl();
6073 // Avoid diagnosing invalid decls as incomplete.
6074 if (D->isInvalidDecl())
6077 // Give the external AST source a chance to complete the type.
6078 if (auto *Source = Context.getExternalSource()) {
6080 Source->CompleteType(Tag->getDecl());
6082 Source->CompleteType(IFace->getDecl());
6084 // If the external source completed the type, go through the motions
6085 // again to ensure we're allowed to use the completed type.
6086 if (!T->isIncompleteType())
6087 return RequireCompleteTypeImpl(Loc, T, Diagnoser);
6091 // If we have a class template specialization or a class member of a
6092 // class template specialization, or an array with known size of such,
6093 // try to instantiate it.
6094 QualType MaybeTemplate = T;
6095 while (const ConstantArrayType *Array
6096 = Context.getAsConstantArrayType(MaybeTemplate))
6097 MaybeTemplate = Array->getElementType();
6098 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
6099 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
6100 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
6101 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
6102 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
6103 TSK_ImplicitInstantiation,
6104 /*Complain=*/!Diagnoser.Suppressed);
6105 } else if (CXXRecordDecl *Rec
6106 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
6107 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
6108 if (!Rec->isBeingDefined() && Pattern) {
6109 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
6110 assert(MSI && "Missing member specialization information?");
6111 // This record was instantiated from a class within a template.
6112 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
6113 return InstantiateClass(Loc, Rec, Pattern,
6114 getTemplateInstantiationArgs(Rec),
6115 TSK_ImplicitInstantiation,
6116 /*Complain=*/!Diagnoser.Suppressed);
6121 if (Diagnoser.Suppressed)
6124 // We have an incomplete type. Produce a diagnostic.
6125 if (Ident___float128 &&
6126 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
6127 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
6131 Diagnoser.diagnose(*this, Loc, T);
6133 // If the type was a forward declaration of a class/struct/union
6134 // type, produce a note.
6135 if (Tag && !Tag->getDecl()->isInvalidDecl())
6136 Diag(Tag->getDecl()->getLocation(),
6137 Tag->isBeingDefined() ? diag::note_type_being_defined
6138 : diag::note_forward_declaration)
6139 << QualType(Tag, 0);
6141 // If the Objective-C class was a forward declaration, produce a note.
6142 if (IFace && !IFace->getDecl()->isInvalidDecl())
6143 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
6145 // If we have external information that we can use to suggest a fix,
6148 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
6153 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
6155 TypeDiagnoserDiag Diagnoser(DiagID);
6156 return RequireCompleteType(Loc, T, Diagnoser);
6159 /// \brief Get diagnostic %select index for tag kind for
6160 /// literal type diagnostic message.
6161 /// WARNING: Indexes apply to particular diagnostics only!
6163 /// \returns diagnostic %select index.
6164 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
6166 case TTK_Struct: return 0;
6167 case TTK_Interface: return 1;
6168 case TTK_Class: return 2;
6169 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
6173 /// @brief Ensure that the type T is a literal type.
6175 /// This routine checks whether the type @p T is a literal type. If @p T is an
6176 /// incomplete type, an attempt is made to complete it. If @p T is a literal
6177 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
6178 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
6179 /// it the type @p T), along with notes explaining why the type is not a
6180 /// literal type, and returns true.
6182 /// @param Loc The location in the source that the non-literal type
6183 /// diagnostic should refer to.
6185 /// @param T The type that this routine is examining for literalness.
6187 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
6189 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
6190 /// @c false otherwise.
6191 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
6192 TypeDiagnoser &Diagnoser) {
6193 assert(!T->isDependentType() && "type should not be dependent");
6195 QualType ElemType = Context.getBaseElementType(T);
6196 RequireCompleteType(Loc, ElemType, 0);
6198 if (T->isLiteralType(Context))
6201 if (Diagnoser.Suppressed)
6204 Diagnoser.diagnose(*this, Loc, T);
6206 if (T->isVariableArrayType())
6209 const RecordType *RT = ElemType->getAs<RecordType>();
6213 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
6215 // A partially-defined class type can't be a literal type, because a literal
6216 // class type must have a trivial destructor (which can't be checked until
6217 // the class definition is complete).
6218 if (!RD->isCompleteDefinition()) {
6219 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
6223 // If the class has virtual base classes, then it's not an aggregate, and
6224 // cannot have any constexpr constructors or a trivial default constructor,
6225 // so is non-literal. This is better to diagnose than the resulting absence
6226 // of constexpr constructors.
6227 if (RD->getNumVBases()) {
6228 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
6229 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
6230 for (const auto &I : RD->vbases())
6231 Diag(I.getLocStart(), diag::note_constexpr_virtual_base_here)
6232 << I.getSourceRange();
6233 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
6234 !RD->hasTrivialDefaultConstructor()) {
6235 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
6236 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
6237 for (const auto &I : RD->bases()) {
6238 if (!I.getType()->isLiteralType(Context)) {
6239 Diag(I.getLocStart(),
6240 diag::note_non_literal_base_class)
6241 << RD << I.getType() << I.getSourceRange();
6245 for (const auto *I : RD->fields()) {
6246 if (!I->getType()->isLiteralType(Context) ||
6247 I->getType().isVolatileQualified()) {
6248 Diag(I->getLocation(), diag::note_non_literal_field)
6249 << RD << I << I->getType()
6250 << I->getType().isVolatileQualified();
6254 } else if (!RD->hasTrivialDestructor()) {
6255 // All fields and bases are of literal types, so have trivial destructors.
6256 // If this class's destructor is non-trivial it must be user-declared.
6257 CXXDestructorDecl *Dtor = RD->getDestructor();
6258 assert(Dtor && "class has literal fields and bases but no dtor?");
6262 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
6263 diag::note_non_literal_user_provided_dtor :
6264 diag::note_non_literal_nontrivial_dtor) << RD;
6265 if (!Dtor->isUserProvided())
6266 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
6272 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
6273 TypeDiagnoserDiag Diagnoser(DiagID);
6274 return RequireLiteralType(Loc, T, Diagnoser);
6277 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
6278 /// and qualified by the nested-name-specifier contained in SS.
6279 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
6280 const CXXScopeSpec &SS, QualType T) {
6283 NestedNameSpecifier *NNS;
6285 NNS = SS.getScopeRep();
6287 if (Keyword == ETK_None)
6291 return Context.getElaboratedType(Keyword, NNS, T);
6294 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
6295 ExprResult ER = CheckPlaceholderExpr(E);
6296 if (ER.isInvalid()) return QualType();
6299 if (!E->isTypeDependent()) {
6300 QualType T = E->getType();
6301 if (const TagType *TT = T->getAs<TagType>())
6302 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
6304 return Context.getTypeOfExprType(E);
6307 /// getDecltypeForExpr - Given an expr, will return the decltype for
6308 /// that expression, according to the rules in C++11
6309 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
6310 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
6311 if (E->isTypeDependent())
6312 return S.Context.DependentTy;
6314 // C++11 [dcl.type.simple]p4:
6315 // The type denoted by decltype(e) is defined as follows:
6317 // - if e is an unparenthesized id-expression or an unparenthesized class
6318 // member access (5.2.5), decltype(e) is the type of the entity named
6319 // by e. If there is no such entity, or if e names a set of overloaded
6320 // functions, the program is ill-formed;
6322 // We apply the same rules for Objective-C ivar and property references.
6323 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
6324 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
6325 return VD->getType();
6326 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
6327 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
6328 return FD->getType();
6329 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
6330 return IR->getDecl()->getType();
6331 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
6332 if (PR->isExplicitProperty())
6333 return PR->getExplicitProperty()->getType();
6334 } else if (auto *PE = dyn_cast<PredefinedExpr>(E)) {
6335 return PE->getType();
6338 // C++11 [expr.lambda.prim]p18:
6339 // Every occurrence of decltype((x)) where x is a possibly
6340 // parenthesized id-expression that names an entity of automatic
6341 // storage duration is treated as if x were transformed into an
6342 // access to a corresponding data member of the closure type that
6343 // would have been declared if x were an odr-use of the denoted
6345 using namespace sema;
6346 if (S.getCurLambda()) {
6347 if (isa<ParenExpr>(E)) {
6348 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
6349 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
6350 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
6352 return S.Context.getLValueReferenceType(T);
6359 // C++11 [dcl.type.simple]p4:
6361 QualType T = E->getType();
6362 switch (E->getValueKind()) {
6363 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
6365 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
6366 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
6368 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
6369 // - otherwise, decltype(e) is the type of e.
6370 case VK_RValue: break;
6376 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc,
6377 bool AsUnevaluated) {
6378 ExprResult ER = CheckPlaceholderExpr(E);
6379 if (ER.isInvalid()) return QualType();
6382 if (AsUnevaluated && ActiveTemplateInstantiations.empty() &&
6383 E->HasSideEffects(Context, false)) {
6384 // The expression operand for decltype is in an unevaluated expression
6385 // context, so side effects could result in unintended consequences.
6386 Diag(E->getExprLoc(), diag::warn_side_effects_unevaluated_context);
6389 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
6392 QualType Sema::BuildUnaryTransformType(QualType BaseType,
6393 UnaryTransformType::UTTKind UKind,
6394 SourceLocation Loc) {
6396 case UnaryTransformType::EnumUnderlyingType:
6397 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
6398 Diag(Loc, diag::err_only_enums_have_underlying_types);
6401 QualType Underlying = BaseType;
6402 if (!BaseType->isDependentType()) {
6403 // The enum could be incomplete if we're parsing its definition or
6404 // recovering from an error.
6405 NamedDecl *FwdDecl = nullptr;
6406 if (BaseType->isIncompleteType(&FwdDecl)) {
6407 Diag(Loc, diag::err_underlying_type_of_incomplete_enum) << BaseType;
6408 Diag(FwdDecl->getLocation(), diag::note_forward_declaration) << FwdDecl;
6412 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
6413 assert(ED && "EnumType has no EnumDecl");
6415 DiagnoseUseOfDecl(ED, Loc);
6417 Underlying = ED->getIntegerType();
6418 assert(!Underlying.isNull());
6420 return Context.getUnaryTransformType(BaseType, Underlying,
6421 UnaryTransformType::EnumUnderlyingType);
6424 llvm_unreachable("unknown unary transform type");
6427 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
6428 if (!T->isDependentType()) {
6429 // FIXME: It isn't entirely clear whether incomplete atomic types
6430 // are allowed or not; for simplicity, ban them for the moment.
6431 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
6434 int DisallowedKind = -1;
6435 if (T->isArrayType())
6437 else if (T->isFunctionType())
6439 else if (T->isReferenceType())
6441 else if (T->isAtomicType())
6443 else if (T.hasQualifiers())
6445 else if (!T.isTriviallyCopyableType(Context))
6446 // Some other non-trivially-copyable type (probably a C++ class)
6449 if (DisallowedKind != -1) {
6450 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
6454 // FIXME: Do we need any handling for ARC here?
6457 // Build the pointer type.
6458 return Context.getAtomicType(T);