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 "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/CXXInheritance.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/Basic/OpenCL.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Parse/ParseDiagnostic.h"
29 #include "clang/Sema/DeclSpec.h"
30 #include "clang/Sema/DelayedDiagnostic.h"
31 #include "clang/Sema/Lookup.h"
32 #include "clang/Sema/ScopeInfo.h"
33 #include "clang/Sema/Template.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SmallString.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "TypeLocBuilder.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 : 0;
85 if (useExpansionLoc && loc.isMacroID() && II) {
86 if (II->isStr("strong")) {
87 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
88 } else if (II->isStr("weak")) {
89 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
93 S.Diag(loc, diag::warn_type_attribute_wrong_type) << name << WhichType
97 // objc_gc applies to Objective-C pointers or, otherwise, to the
98 // smallest available pointer type (i.e. 'void*' in 'void**').
99 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
100 case AttributeList::AT_ObjCGC: \
101 case AttributeList::AT_ObjCOwnership
103 // Function type attributes.
104 #define FUNCTION_TYPE_ATTRS_CASELIST \
105 case AttributeList::AT_NoReturn: \
106 case AttributeList::AT_CDecl: \
107 case AttributeList::AT_FastCall: \
108 case AttributeList::AT_StdCall: \
109 case AttributeList::AT_ThisCall: \
110 case AttributeList::AT_Pascal: \
111 case AttributeList::AT_MSABI: \
112 case AttributeList::AT_SysVABI: \
113 case AttributeList::AT_Regparm: \
114 case AttributeList::AT_Pcs: \
115 case AttributeList::AT_PnaclCall: \
116 case AttributeList::AT_IntelOclBicc
118 // Microsoft-specific type qualifiers.
119 #define MS_TYPE_ATTRS_CASELIST \
120 case AttributeList::AT_Ptr32: \
121 case AttributeList::AT_Ptr64: \
122 case AttributeList::AT_SPtr: \
123 case AttributeList::AT_UPtr
126 /// An object which stores processing state for the entire
127 /// GetTypeForDeclarator process.
128 class TypeProcessingState {
131 /// The declarator being processed.
132 Declarator &declarator;
134 /// The index of the declarator chunk we're currently processing.
135 /// May be the total number of valid chunks, indicating the
139 /// Whether there are non-trivial modifications to the decl spec.
142 /// Whether we saved the attributes in the decl spec.
145 /// The original set of attributes on the DeclSpec.
146 SmallVector<AttributeList*, 2> savedAttrs;
148 /// A list of attributes to diagnose the uselessness of when the
149 /// processing is complete.
150 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
153 TypeProcessingState(Sema &sema, Declarator &declarator)
154 : sema(sema), declarator(declarator),
155 chunkIndex(declarator.getNumTypeObjects()),
156 trivial(true), hasSavedAttrs(false) {}
158 Sema &getSema() const {
162 Declarator &getDeclarator() const {
166 bool isProcessingDeclSpec() const {
167 return chunkIndex == declarator.getNumTypeObjects();
170 unsigned getCurrentChunkIndex() const {
174 void setCurrentChunkIndex(unsigned idx) {
175 assert(idx <= declarator.getNumTypeObjects());
179 AttributeList *&getCurrentAttrListRef() const {
180 if (isProcessingDeclSpec())
181 return getMutableDeclSpec().getAttributes().getListRef();
182 return declarator.getTypeObject(chunkIndex).getAttrListRef();
185 /// Save the current set of attributes on the DeclSpec.
186 void saveDeclSpecAttrs() {
187 // Don't try to save them multiple times.
188 if (hasSavedAttrs) return;
190 DeclSpec &spec = getMutableDeclSpec();
191 for (AttributeList *attr = spec.getAttributes().getList(); attr;
192 attr = attr->getNext())
193 savedAttrs.push_back(attr);
194 trivial &= savedAttrs.empty();
195 hasSavedAttrs = true;
198 /// Record that we had nowhere to put the given type attribute.
199 /// We will diagnose such attributes later.
200 void addIgnoredTypeAttr(AttributeList &attr) {
201 ignoredTypeAttrs.push_back(&attr);
204 /// Diagnose all the ignored type attributes, given that the
205 /// declarator worked out to the given type.
206 void diagnoseIgnoredTypeAttrs(QualType type) const {
207 for (SmallVectorImpl<AttributeList*>::const_iterator
208 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
210 diagnoseBadTypeAttribute(getSema(), **i, type);
213 ~TypeProcessingState() {
216 restoreDeclSpecAttrs();
220 DeclSpec &getMutableDeclSpec() const {
221 return const_cast<DeclSpec&>(declarator.getDeclSpec());
224 void restoreDeclSpecAttrs() {
225 assert(hasSavedAttrs);
227 if (savedAttrs.empty()) {
228 getMutableDeclSpec().getAttributes().set(0);
232 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
233 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
234 savedAttrs[i]->setNext(savedAttrs[i+1]);
235 savedAttrs.back()->setNext(0);
240 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
245 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
247 head = attr.getNext();
251 AttributeList *cur = head;
253 assert(cur && cur->getNext() && "ran out of attrs?");
254 if (cur->getNext() == &attr) {
255 cur->setNext(attr.getNext());
258 cur = cur->getNext();
262 static void moveAttrFromListToList(AttributeList &attr,
263 AttributeList *&fromList,
264 AttributeList *&toList) {
265 spliceAttrOutOfList(attr, fromList);
266 spliceAttrIntoList(attr, toList);
269 /// The location of a type attribute.
270 enum TypeAttrLocation {
271 /// The attribute is in the decl-specifier-seq.
273 /// The attribute is part of a DeclaratorChunk.
275 /// The attribute is immediately after the declaration's name.
279 static void processTypeAttrs(TypeProcessingState &state,
280 QualType &type, TypeAttrLocation TAL,
281 AttributeList *attrs);
283 static bool handleFunctionTypeAttr(TypeProcessingState &state,
287 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &state,
291 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
292 AttributeList &attr, QualType &type);
294 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
295 AttributeList &attr, QualType &type);
297 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
298 AttributeList &attr, QualType &type) {
299 if (attr.getKind() == AttributeList::AT_ObjCGC)
300 return handleObjCGCTypeAttr(state, attr, type);
301 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
302 return handleObjCOwnershipTypeAttr(state, attr, type);
305 /// Given the index of a declarator chunk, check whether that chunk
306 /// directly specifies the return type of a function and, if so, find
307 /// an appropriate place for it.
309 /// \param i - a notional index which the search will start
310 /// immediately inside
311 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
313 assert(i <= declarator.getNumTypeObjects());
315 DeclaratorChunk *result = 0;
317 // First, look inwards past parens for a function declarator.
318 for (; i != 0; --i) {
319 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
320 switch (fnChunk.Kind) {
321 case DeclaratorChunk::Paren:
324 // If we find anything except a function, bail out.
325 case DeclaratorChunk::Pointer:
326 case DeclaratorChunk::BlockPointer:
327 case DeclaratorChunk::Array:
328 case DeclaratorChunk::Reference:
329 case DeclaratorChunk::MemberPointer:
332 // If we do find a function declarator, scan inwards from that,
333 // looking for a block-pointer declarator.
334 case DeclaratorChunk::Function:
335 for (--i; i != 0; --i) {
336 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
337 switch (blockChunk.Kind) {
338 case DeclaratorChunk::Paren:
339 case DeclaratorChunk::Pointer:
340 case DeclaratorChunk::Array:
341 case DeclaratorChunk::Function:
342 case DeclaratorChunk::Reference:
343 case DeclaratorChunk::MemberPointer:
345 case DeclaratorChunk::BlockPointer:
346 result = &blockChunk;
349 llvm_unreachable("bad declarator chunk kind");
352 // If we run out of declarators doing that, we're done.
355 llvm_unreachable("bad declarator chunk kind");
357 // Okay, reconsider from our new point.
361 // Ran out of chunks, bail out.
365 /// Given that an objc_gc attribute was written somewhere on a
366 /// declaration *other* than on the declarator itself (for which, use
367 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
368 /// didn't apply in whatever position it was written in, try to move
369 /// it to a more appropriate position.
370 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
373 Declarator &declarator = state.getDeclarator();
375 // Move it to the outermost normal or block pointer declarator.
376 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
377 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
378 switch (chunk.Kind) {
379 case DeclaratorChunk::Pointer:
380 case DeclaratorChunk::BlockPointer: {
381 // But don't move an ARC ownership attribute to the return type
383 DeclaratorChunk *destChunk = 0;
384 if (state.isProcessingDeclSpec() &&
385 attr.getKind() == AttributeList::AT_ObjCOwnership)
386 destChunk = maybeMovePastReturnType(declarator, i - 1);
387 if (!destChunk) destChunk = &chunk;
389 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
390 destChunk->getAttrListRef());
394 case DeclaratorChunk::Paren:
395 case DeclaratorChunk::Array:
398 // We may be starting at the return type of a block.
399 case DeclaratorChunk::Function:
400 if (state.isProcessingDeclSpec() &&
401 attr.getKind() == AttributeList::AT_ObjCOwnership) {
402 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
403 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
404 dest->getAttrListRef());
410 // Don't walk through these.
411 case DeclaratorChunk::Reference:
412 case DeclaratorChunk::MemberPointer:
418 diagnoseBadTypeAttribute(state.getSema(), attr, type);
421 /// Distribute an objc_gc type attribute that was written on the
424 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
426 QualType &declSpecType) {
427 Declarator &declarator = state.getDeclarator();
429 // objc_gc goes on the innermost pointer to something that's not a
431 unsigned innermost = -1U;
432 bool considerDeclSpec = true;
433 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
434 DeclaratorChunk &chunk = declarator.getTypeObject(i);
435 switch (chunk.Kind) {
436 case DeclaratorChunk::Pointer:
437 case DeclaratorChunk::BlockPointer:
441 case DeclaratorChunk::Reference:
442 case DeclaratorChunk::MemberPointer:
443 case DeclaratorChunk::Paren:
444 case DeclaratorChunk::Array:
447 case DeclaratorChunk::Function:
448 considerDeclSpec = false;
454 // That might actually be the decl spec if we weren't blocked by
455 // anything in the declarator.
456 if (considerDeclSpec) {
457 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
458 // Splice the attribute into the decl spec. Prevents the
459 // attribute from being applied multiple times and gives
460 // the source-location-filler something to work with.
461 state.saveDeclSpecAttrs();
462 moveAttrFromListToList(attr, declarator.getAttrListRef(),
463 declarator.getMutableDeclSpec().getAttributes().getListRef());
468 // Otherwise, if we found an appropriate chunk, splice the attribute
470 if (innermost != -1U) {
471 moveAttrFromListToList(attr, declarator.getAttrListRef(),
472 declarator.getTypeObject(innermost).getAttrListRef());
476 // Otherwise, diagnose when we're done building the type.
477 spliceAttrOutOfList(attr, declarator.getAttrListRef());
478 state.addIgnoredTypeAttr(attr);
481 /// A function type attribute was written somewhere in a declaration
482 /// *other* than on the declarator itself or in the decl spec. Given
483 /// that it didn't apply in whatever position it was written in, try
484 /// to move it to a more appropriate position.
485 static void distributeFunctionTypeAttr(TypeProcessingState &state,
488 Declarator &declarator = state.getDeclarator();
490 // Try to push the attribute from the return type of a function to
491 // the function itself.
492 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
493 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
494 switch (chunk.Kind) {
495 case DeclaratorChunk::Function:
496 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
497 chunk.getAttrListRef());
500 case DeclaratorChunk::Paren:
501 case DeclaratorChunk::Pointer:
502 case DeclaratorChunk::BlockPointer:
503 case DeclaratorChunk::Array:
504 case DeclaratorChunk::Reference:
505 case DeclaratorChunk::MemberPointer:
510 diagnoseBadTypeAttribute(state.getSema(), attr, type);
513 /// Try to distribute a function type attribute to the innermost
514 /// function chunk or type. Returns true if the attribute was
515 /// distributed, false if no location was found.
517 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
519 AttributeList *&attrList,
520 QualType &declSpecType) {
521 Declarator &declarator = state.getDeclarator();
523 // Put it on the innermost function chunk, if there is one.
524 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
525 DeclaratorChunk &chunk = declarator.getTypeObject(i);
526 if (chunk.Kind != DeclaratorChunk::Function) continue;
528 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
532 return handleFunctionTypeAttr(state, attr, declSpecType);
535 /// A function type attribute was written in the decl spec. Try to
536 /// apply it somewhere.
538 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
540 QualType &declSpecType) {
541 state.saveDeclSpecAttrs();
543 // C++11 attributes before the decl specifiers actually appertain to
544 // the declarators. Move them straight there. We don't support the
545 // 'put them wherever you like' semantics we allow for GNU attributes.
546 if (attr.isCXX11Attribute()) {
547 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
548 state.getDeclarator().getAttrListRef());
552 // Try to distribute to the innermost.
553 if (distributeFunctionTypeAttrToInnermost(state, attr,
554 state.getCurrentAttrListRef(),
558 // If that failed, diagnose the bad attribute when the declarator is
560 state.addIgnoredTypeAttr(attr);
563 /// A function type attribute was written on the declarator. Try to
564 /// apply it somewhere.
566 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
568 QualType &declSpecType) {
569 Declarator &declarator = state.getDeclarator();
571 // Try to distribute to the innermost.
572 if (distributeFunctionTypeAttrToInnermost(state, attr,
573 declarator.getAttrListRef(),
577 // If that failed, diagnose the bad attribute when the declarator is
579 spliceAttrOutOfList(attr, declarator.getAttrListRef());
580 state.addIgnoredTypeAttr(attr);
583 /// \brief Given that there are attributes written on the declarator
584 /// itself, try to distribute any type attributes to the appropriate
585 /// declarator chunk.
587 /// These are attributes like the following:
590 /// but not necessarily this:
592 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
593 QualType &declSpecType) {
594 // Collect all the type attributes from the declarator itself.
595 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
596 AttributeList *attr = state.getDeclarator().getAttributes();
599 next = attr->getNext();
601 // Do not distribute C++11 attributes. They have strict rules for what
602 // they appertain to.
603 if (attr->isCXX11Attribute())
606 switch (attr->getKind()) {
607 OBJC_POINTER_TYPE_ATTRS_CASELIST:
608 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
611 case AttributeList::AT_NSReturnsRetained:
612 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
616 FUNCTION_TYPE_ATTRS_CASELIST:
617 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
620 MS_TYPE_ATTRS_CASELIST:
621 // Microsoft type attributes cannot go after the declarator-id.
627 } while ((attr = next));
630 /// Add a synthetic '()' to a block-literal declarator if it is
631 /// required, given the return type.
632 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
633 QualType declSpecType) {
634 Declarator &declarator = state.getDeclarator();
636 // First, check whether the declarator would produce a function,
637 // i.e. whether the innermost semantic chunk is a function.
638 if (declarator.isFunctionDeclarator()) {
639 // If so, make that declarator a prototyped declarator.
640 declarator.getFunctionTypeInfo().hasPrototype = true;
644 // If there are any type objects, the type as written won't name a
645 // function, regardless of the decl spec type. This is because a
646 // block signature declarator is always an abstract-declarator, and
647 // abstract-declarators can't just be parentheses chunks. Therefore
648 // we need to build a function chunk unless there are no type
649 // objects and the decl spec type is a function.
650 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
653 // Note that there *are* cases with invalid declarators where
654 // declarators consist solely of parentheses. In general, these
655 // occur only in failed efforts to make function declarators, so
656 // faking up the function chunk is still the right thing to do.
658 // Otherwise, we need to fake up a function declarator.
659 SourceLocation loc = declarator.getLocStart();
661 // ...and *prepend* it to the declarator.
662 SourceLocation NoLoc;
663 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
665 /*IsAmbiguous=*/false,
669 /*EllipsisLoc=*/NoLoc,
672 /*RefQualifierIsLvalueRef=*/true,
673 /*RefQualifierLoc=*/NoLoc,
674 /*ConstQualifierLoc=*/NoLoc,
675 /*VolatileQualifierLoc=*/NoLoc,
676 /*MutableLoc=*/NoLoc,
680 /*ExceptionRanges=*/0,
683 loc, loc, declarator));
685 // For consistency, make sure the state still has us as processing
687 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
688 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
691 /// \brief Convert the specified declspec to the appropriate type
693 /// \param state Specifies the declarator containing the declaration specifier
694 /// to be converted, along with other associated processing state.
695 /// \returns The type described by the declaration specifiers. This function
696 /// never returns null.
697 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
698 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
701 Sema &S = state.getSema();
702 Declarator &declarator = state.getDeclarator();
703 const DeclSpec &DS = declarator.getDeclSpec();
704 SourceLocation DeclLoc = declarator.getIdentifierLoc();
705 if (DeclLoc.isInvalid())
706 DeclLoc = DS.getLocStart();
708 ASTContext &Context = S.Context;
711 switch (DS.getTypeSpecType()) {
712 case DeclSpec::TST_void:
713 Result = Context.VoidTy;
715 case DeclSpec::TST_char:
716 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
717 Result = Context.CharTy;
718 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
719 Result = Context.SignedCharTy;
721 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
722 "Unknown TSS value");
723 Result = Context.UnsignedCharTy;
726 case DeclSpec::TST_wchar:
727 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
728 Result = Context.WCharTy;
729 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
730 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
731 << DS.getSpecifierName(DS.getTypeSpecType());
732 Result = Context.getSignedWCharType();
734 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
735 "Unknown TSS value");
736 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
737 << DS.getSpecifierName(DS.getTypeSpecType());
738 Result = Context.getUnsignedWCharType();
741 case DeclSpec::TST_char16:
742 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
743 "Unknown TSS value");
744 Result = Context.Char16Ty;
746 case DeclSpec::TST_char32:
747 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
748 "Unknown TSS value");
749 Result = Context.Char32Ty;
751 case DeclSpec::TST_unspecified:
752 // "<proto1,proto2>" is an objc qualified ID with a missing id.
753 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
754 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
755 (ObjCProtocolDecl*const*)PQ,
756 DS.getNumProtocolQualifiers());
757 Result = Context.getObjCObjectPointerType(Result);
761 // If this is a missing declspec in a block literal return context, then it
762 // is inferred from the return statements inside the block.
763 // The declspec is always missing in a lambda expr context; it is either
764 // specified with a trailing return type or inferred.
765 if (S.getLangOpts().CPlusPlus1y &&
766 declarator.getContext() == Declarator::LambdaExprContext) {
767 // In C++1y, a lambda's implicit return type is 'auto'.
768 Result = Context.getAutoDeductType();
770 } else if (declarator.getContext() == Declarator::LambdaExprContext ||
771 isOmittedBlockReturnType(declarator)) {
772 Result = Context.DependentTy;
776 // Unspecified typespec defaults to int in C90. However, the C90 grammar
777 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
778 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
779 // Note that the one exception to this is function definitions, which are
780 // allowed to be completely missing a declspec. This is handled in the
781 // parser already though by it pretending to have seen an 'int' in this
783 if (S.getLangOpts().ImplicitInt) {
784 // In C89 mode, we only warn if there is a completely missing declspec
785 // when one is not allowed.
787 S.Diag(DeclLoc, diag::ext_missing_declspec)
788 << DS.getSourceRange()
789 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
791 } else if (!DS.hasTypeSpecifier()) {
792 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
793 // "At least one type specifier shall be given in the declaration
794 // specifiers in each declaration, and in the specifier-qualifier list in
795 // each struct declaration and type name."
796 if (S.getLangOpts().CPlusPlus) {
797 S.Diag(DeclLoc, diag::err_missing_type_specifier)
798 << DS.getSourceRange();
800 // When this occurs in C++ code, often something is very broken with the
801 // value being declared, poison it as invalid so we don't get chains of
803 declarator.setInvalidType(true);
805 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
806 << DS.getSourceRange();
811 case DeclSpec::TST_int: {
812 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
813 switch (DS.getTypeSpecWidth()) {
814 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
815 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
816 case DeclSpec::TSW_long: Result = Context.LongTy; break;
817 case DeclSpec::TSW_longlong:
818 Result = Context.LongLongTy;
820 // 'long long' is a C99 or C++11 feature.
821 if (!S.getLangOpts().C99) {
822 if (S.getLangOpts().CPlusPlus)
823 S.Diag(DS.getTypeSpecWidthLoc(),
824 S.getLangOpts().CPlusPlus11 ?
825 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
827 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
832 switch (DS.getTypeSpecWidth()) {
833 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
834 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
835 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
836 case DeclSpec::TSW_longlong:
837 Result = Context.UnsignedLongLongTy;
839 // 'long long' is a C99 or C++11 feature.
840 if (!S.getLangOpts().C99) {
841 if (S.getLangOpts().CPlusPlus)
842 S.Diag(DS.getTypeSpecWidthLoc(),
843 S.getLangOpts().CPlusPlus11 ?
844 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
846 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
853 case DeclSpec::TST_int128:
854 if (!S.PP.getTargetInfo().hasInt128Type())
855 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
856 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
857 Result = Context.UnsignedInt128Ty;
859 Result = Context.Int128Ty;
861 case DeclSpec::TST_half: Result = Context.HalfTy; break;
862 case DeclSpec::TST_float: Result = Context.FloatTy; break;
863 case DeclSpec::TST_double:
864 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
865 Result = Context.LongDoubleTy;
867 Result = Context.DoubleTy;
869 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
870 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
871 declarator.setInvalidType(true);
874 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
875 case DeclSpec::TST_decimal32: // _Decimal32
876 case DeclSpec::TST_decimal64: // _Decimal64
877 case DeclSpec::TST_decimal128: // _Decimal128
878 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
879 Result = Context.IntTy;
880 declarator.setInvalidType(true);
882 case DeclSpec::TST_class:
883 case DeclSpec::TST_enum:
884 case DeclSpec::TST_union:
885 case DeclSpec::TST_struct:
886 case DeclSpec::TST_interface: {
887 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
889 // This can happen in C++ with ambiguous lookups.
890 Result = Context.IntTy;
891 declarator.setInvalidType(true);
895 // If the type is deprecated or unavailable, diagnose it.
896 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
898 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
899 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
901 // TypeQuals handled by caller.
902 Result = Context.getTypeDeclType(D);
904 // In both C and C++, make an ElaboratedType.
905 ElaboratedTypeKeyword Keyword
906 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
907 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
910 case DeclSpec::TST_typename: {
911 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
912 DS.getTypeSpecSign() == 0 &&
913 "Can't handle qualifiers on typedef names yet!");
914 Result = S.GetTypeFromParser(DS.getRepAsType());
916 declarator.setInvalidType(true);
917 else if (DeclSpec::ProtocolQualifierListTy PQ
918 = DS.getProtocolQualifiers()) {
919 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
920 // Silently drop any existing protocol qualifiers.
921 // TODO: determine whether that's the right thing to do.
922 if (ObjT->getNumProtocols())
923 Result = ObjT->getBaseType();
925 if (DS.getNumProtocolQualifiers())
926 Result = Context.getObjCObjectType(Result,
927 (ObjCProtocolDecl*const*) PQ,
928 DS.getNumProtocolQualifiers());
929 } else if (Result->isObjCIdType()) {
931 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
932 (ObjCProtocolDecl*const*) PQ,
933 DS.getNumProtocolQualifiers());
934 Result = Context.getObjCObjectPointerType(Result);
935 } else if (Result->isObjCClassType()) {
936 // Class<protocol-list>
937 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
938 (ObjCProtocolDecl*const*) PQ,
939 DS.getNumProtocolQualifiers());
940 Result = Context.getObjCObjectPointerType(Result);
942 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
943 << DS.getSourceRange();
944 declarator.setInvalidType(true);
948 // TypeQuals handled by caller.
951 case DeclSpec::TST_typeofType:
952 // FIXME: Preserve type source info.
953 Result = S.GetTypeFromParser(DS.getRepAsType());
954 assert(!Result.isNull() && "Didn't get a type for typeof?");
955 if (!Result->isDependentType())
956 if (const TagType *TT = Result->getAs<TagType>())
957 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
958 // TypeQuals handled by caller.
959 Result = Context.getTypeOfType(Result);
961 case DeclSpec::TST_typeofExpr: {
962 Expr *E = DS.getRepAsExpr();
963 assert(E && "Didn't get an expression for typeof?");
964 // TypeQuals handled by caller.
965 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
966 if (Result.isNull()) {
967 Result = Context.IntTy;
968 declarator.setInvalidType(true);
972 case DeclSpec::TST_decltype: {
973 Expr *E = DS.getRepAsExpr();
974 assert(E && "Didn't get an expression for decltype?");
975 // TypeQuals handled by caller.
976 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
977 if (Result.isNull()) {
978 Result = Context.IntTy;
979 declarator.setInvalidType(true);
983 case DeclSpec::TST_underlyingType:
984 Result = S.GetTypeFromParser(DS.getRepAsType());
985 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
986 Result = S.BuildUnaryTransformType(Result,
987 UnaryTransformType::EnumUnderlyingType,
988 DS.getTypeSpecTypeLoc());
989 if (Result.isNull()) {
990 Result = Context.IntTy;
991 declarator.setInvalidType(true);
995 case DeclSpec::TST_auto:
996 // TypeQuals handled by caller.
997 // If auto is mentioned in a lambda parameter context, convert it to a
998 // template parameter type immediately, with the appropriate depth and
999 // index, and update sema's state (LambdaScopeInfo) for the current lambda
1000 // being analyzed (which tracks the invented type template parameter).
1001 if (declarator.getContext() == Declarator::LambdaExprParameterContext) {
1002 sema::LambdaScopeInfo *LSI = S.getCurLambda();
1003 assert(LSI && "No LambdaScopeInfo on the stack!");
1004 const unsigned TemplateParameterDepth = LSI->AutoTemplateParameterDepth;
1005 const unsigned AutoParameterPosition = LSI->AutoTemplateParams.size();
1006 const bool IsParameterPack = declarator.hasEllipsis();
1008 // Create a name for the invented template parameter type.
1009 std::string InventedTemplateParamName = "$auto-";
1010 llvm::raw_string_ostream ss(InventedTemplateParamName);
1011 ss << TemplateParameterDepth;
1012 ss << "-" << AutoParameterPosition;
1015 IdentifierInfo& TemplateParamII = Context.Idents.get(
1016 InventedTemplateParamName.c_str());
1017 // Turns out we must create the TemplateTypeParmDecl here to
1018 // retrieve the corresponding template parameter type.
1019 TemplateTypeParmDecl *CorrespondingTemplateParam =
1020 TemplateTypeParmDecl::Create(Context,
1021 // Temporarily add to the TranslationUnit DeclContext. When the
1022 // associated TemplateParameterList is attached to a template
1023 // declaration (such as FunctionTemplateDecl), the DeclContext
1024 // for each template parameter gets updated appropriately via
1025 // a call to AdoptTemplateParameterList.
1026 Context.getTranslationUnitDecl(),
1027 /*KeyLoc*/ SourceLocation(),
1028 /*NameLoc*/ declarator.getLocStart(),
1029 TemplateParameterDepth,
1030 AutoParameterPosition, // our template param index
1031 /* Identifier*/ &TemplateParamII, false, IsParameterPack);
1032 LSI->AutoTemplateParams.push_back(CorrespondingTemplateParam);
1033 // Replace the 'auto' in the function parameter with this invented
1034 // template type parameter.
1035 Result = QualType(CorrespondingTemplateParam->getTypeForDecl(), 0);
1037 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false, false);
1041 case DeclSpec::TST_decltype_auto:
1042 Result = Context.getAutoType(QualType(),
1043 /*decltype(auto)*/true,
1044 /*IsDependent*/ false);
1047 case DeclSpec::TST_unknown_anytype:
1048 Result = Context.UnknownAnyTy;
1051 case DeclSpec::TST_atomic:
1052 Result = S.GetTypeFromParser(DS.getRepAsType());
1053 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1054 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1055 if (Result.isNull()) {
1056 Result = Context.IntTy;
1057 declarator.setInvalidType(true);
1061 case DeclSpec::TST_image1d_t:
1062 Result = Context.OCLImage1dTy;
1065 case DeclSpec::TST_image1d_array_t:
1066 Result = Context.OCLImage1dArrayTy;
1069 case DeclSpec::TST_image1d_buffer_t:
1070 Result = Context.OCLImage1dBufferTy;
1073 case DeclSpec::TST_image2d_t:
1074 Result = Context.OCLImage2dTy;
1077 case DeclSpec::TST_image2d_array_t:
1078 Result = Context.OCLImage2dArrayTy;
1081 case DeclSpec::TST_image3d_t:
1082 Result = Context.OCLImage3dTy;
1085 case DeclSpec::TST_sampler_t:
1086 Result = Context.OCLSamplerTy;
1089 case DeclSpec::TST_event_t:
1090 Result = Context.OCLEventTy;
1093 case DeclSpec::TST_error:
1094 Result = Context.IntTy;
1095 declarator.setInvalidType(true);
1099 // Handle complex types.
1100 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1101 if (S.getLangOpts().Freestanding)
1102 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1103 Result = Context.getComplexType(Result);
1104 } else if (DS.isTypeAltiVecVector()) {
1105 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1106 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1107 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1108 if (DS.isTypeAltiVecPixel())
1109 VecKind = VectorType::AltiVecPixel;
1110 else if (DS.isTypeAltiVecBool())
1111 VecKind = VectorType::AltiVecBool;
1112 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1115 // FIXME: Imaginary.
1116 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1117 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1119 // Before we process any type attributes, synthesize a block literal
1120 // function declarator if necessary.
1121 if (declarator.getContext() == Declarator::BlockLiteralContext)
1122 maybeSynthesizeBlockSignature(state, Result);
1124 // Apply any type attributes from the decl spec. This may cause the
1125 // list of type attributes to be temporarily saved while the type
1126 // attributes are pushed around.
1127 if (AttributeList *attrs = DS.getAttributes().getList())
1128 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1130 // Apply const/volatile/restrict qualifiers to T.
1131 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1133 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1134 // of a function type includes any type qualifiers, the behavior is
1136 if (Result->isFunctionType() && TypeQuals) {
1137 if (TypeQuals & DeclSpec::TQ_const)
1138 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1139 << Result << DS.getSourceRange();
1140 else if (TypeQuals & DeclSpec::TQ_volatile)
1141 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers)
1142 << Result << DS.getSourceRange();
1144 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1145 "Has CVRA quals but not C, V, R, or A?");
1146 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1147 // function type later, in BuildQualifiedType.
1152 // Cv-qualified references are ill-formed except when the
1153 // cv-qualifiers are introduced through the use of a typedef
1154 // (7.1.3) or of a template type argument (14.3), in which
1155 // case the cv-qualifiers are ignored.
1156 // FIXME: Shouldn't we be checking SCS_typedef here?
1157 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1158 TypeQuals && Result->isReferenceType()) {
1159 TypeQuals &= ~DeclSpec::TQ_const;
1160 TypeQuals &= ~DeclSpec::TQ_volatile;
1161 TypeQuals &= ~DeclSpec::TQ_atomic;
1164 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1165 // than once in the same specifier-list or qualifier-list, either directly
1166 // or via one or more typedefs."
1167 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1168 && TypeQuals & Result.getCVRQualifiers()) {
1169 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1170 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1174 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1175 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1179 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1180 // produce a warning in this case.
1183 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1185 // If adding qualifiers fails, just use the unqualified type.
1186 if (Qualified.isNull())
1187 declarator.setInvalidType(true);
1195 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1197 return Entity.getAsString();
1202 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1203 Qualifiers Qs, const DeclSpec *DS) {
1204 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1205 // object or incomplete types shall not be restrict-qualified."
1206 if (Qs.hasRestrict()) {
1207 unsigned DiagID = 0;
1210 if (T->isAnyPointerType() || T->isReferenceType() ||
1211 T->isMemberPointerType()) {
1213 if (T->isObjCObjectPointerType())
1215 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1216 EltTy = PTy->getPointeeType();
1218 EltTy = T->getPointeeType();
1220 // If we have a pointer or reference, the pointee must have an object
1222 if (!EltTy->isIncompleteOrObjectType()) {
1223 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1226 } else if (!T->isDependentType()) {
1227 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1232 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1233 Qs.removeRestrict();
1237 return Context.getQualifiedType(T, Qs);
1240 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1241 unsigned CVRA, const DeclSpec *DS) {
1242 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1243 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1246 // If the same qualifier appears more than once in the same
1247 // specifier-qualifier-list, either directly or via one or more typedefs,
1248 // the behavior is the same as if it appeared only once.
1250 // It's not specified what happens when the _Atomic qualifier is applied to
1251 // a type specified with the _Atomic specifier, but we assume that this
1252 // should be treated as if the _Atomic qualifier appeared multiple times.
1253 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1255 // If other qualifiers appear along with the _Atomic qualifier in a
1256 // specifier-qualifier-list, the resulting type is the so-qualified
1259 // Don't need to worry about array types here, since _Atomic can't be
1260 // applied to such types.
1261 SplitQualType Split = T.getSplitUnqualifiedType();
1262 T = BuildAtomicType(QualType(Split.Ty, 0),
1263 DS ? DS->getAtomicSpecLoc() : Loc);
1266 Split.Quals.addCVRQualifiers(CVR);
1267 return BuildQualifiedType(T, Loc, Split.Quals);
1270 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1273 /// \brief Build a paren type including \p T.
1274 QualType Sema::BuildParenType(QualType T) {
1275 return Context.getParenType(T);
1278 /// Given that we're building a pointer or reference to the given
1279 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1282 // Bail out if retention is unrequired or already specified.
1283 if (!type->isObjCLifetimeType() ||
1284 type.getObjCLifetime() != Qualifiers::OCL_None)
1287 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1289 // If the object type is const-qualified, we can safely use
1290 // __unsafe_unretained. This is safe (because there are no read
1291 // barriers), and it'll be safe to coerce anything but __weak* to
1292 // the resulting type.
1293 if (type.isConstQualified()) {
1294 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1296 // Otherwise, check whether the static type does not require
1297 // retaining. This currently only triggers for Class (possibly
1298 // protocol-qualifed, and arrays thereof).
1299 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1300 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1302 // If we are in an unevaluated context, like sizeof, skip adding a
1304 } else if (S.isUnevaluatedContext()) {
1307 // If that failed, give an error and recover using __strong. __strong
1308 // is the option most likely to prevent spurious second-order diagnostics,
1309 // like when binding a reference to a field.
1311 // These types can show up in private ivars in system headers, so
1312 // we need this to not be an error in those cases. Instead we
1314 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1315 S.DelayedDiagnostics.add(
1316 sema::DelayedDiagnostic::makeForbiddenType(loc,
1317 diag::err_arc_indirect_no_ownership, type, isReference));
1319 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1321 implicitLifetime = Qualifiers::OCL_Strong;
1323 assert(implicitLifetime && "didn't infer any lifetime!");
1326 qs.addObjCLifetime(implicitLifetime);
1327 return S.Context.getQualifiedType(type, qs);
1330 /// \brief Build a pointer type.
1332 /// \param T The type to which we'll be building a pointer.
1334 /// \param Loc The location of the entity whose type involves this
1335 /// pointer type or, if there is no such entity, the location of the
1336 /// type that will have pointer type.
1338 /// \param Entity The name of the entity that involves the pointer
1341 /// \returns A suitable pointer type, if there are no
1342 /// errors. Otherwise, returns a NULL type.
1343 QualType Sema::BuildPointerType(QualType T,
1344 SourceLocation Loc, DeclarationName Entity) {
1345 if (T->isReferenceType()) {
1346 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1347 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1348 << getPrintableNameForEntity(Entity) << T;
1352 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1354 // In ARC, it is forbidden to build pointers to unqualified pointers.
1355 if (getLangOpts().ObjCAutoRefCount)
1356 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1358 // Build the pointer type.
1359 return Context.getPointerType(T);
1362 /// \brief Build a reference type.
1364 /// \param T The type to which we'll be building a reference.
1366 /// \param Loc The location of the entity whose type involves this
1367 /// reference type or, if there is no such entity, the location of the
1368 /// type that will have reference type.
1370 /// \param Entity The name of the entity that involves the reference
1373 /// \returns A suitable reference type, if there are no
1374 /// errors. Otherwise, returns a NULL type.
1375 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1377 DeclarationName Entity) {
1378 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1379 "Unresolved overloaded function type");
1381 // C++0x [dcl.ref]p6:
1382 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1383 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1384 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1385 // the type "lvalue reference to T", while an attempt to create the type
1386 // "rvalue reference to cv TR" creates the type TR.
1387 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1389 // C++ [dcl.ref]p4: There shall be no references to references.
1391 // According to C++ DR 106, references to references are only
1392 // diagnosed when they are written directly (e.g., "int & &"),
1393 // but not when they happen via a typedef:
1395 // typedef int& intref;
1396 // typedef intref& intref2;
1398 // Parser::ParseDeclaratorInternal diagnoses the case where
1399 // references are written directly; here, we handle the
1400 // collapsing of references-to-references as described in C++0x.
1401 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1404 // A declarator that specifies the type "reference to cv void"
1406 if (T->isVoidType()) {
1407 Diag(Loc, diag::err_reference_to_void);
1411 // In ARC, it is forbidden to build references to unqualified pointers.
1412 if (getLangOpts().ObjCAutoRefCount)
1413 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1415 // Handle restrict on references.
1417 return Context.getLValueReferenceType(T, SpelledAsLValue);
1418 return Context.getRValueReferenceType(T);
1421 /// Check whether the specified array size makes the array type a VLA. If so,
1422 /// return true, if not, return the size of the array in SizeVal.
1423 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1424 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1425 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1426 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1428 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1430 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1433 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1434 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1438 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1439 S.LangOpts.GNUMode).isInvalid();
1443 /// \brief Build an array type.
1445 /// \param T The type of each element in the array.
1447 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1449 /// \param ArraySize Expression describing the size of the array.
1451 /// \param Brackets The range from the opening '[' to the closing ']'.
1453 /// \param Entity The name of the entity that involves the array
1456 /// \returns A suitable array type, if there are no errors. Otherwise,
1457 /// returns a NULL type.
1458 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1459 Expr *ArraySize, unsigned Quals,
1460 SourceRange Brackets, DeclarationName Entity) {
1462 SourceLocation Loc = Brackets.getBegin();
1463 if (getLangOpts().CPlusPlus) {
1464 // C++ [dcl.array]p1:
1465 // T is called the array element type; this type shall not be a reference
1466 // type, the (possibly cv-qualified) type void, a function type or an
1467 // abstract class type.
1469 // C++ [dcl.array]p3:
1470 // When several "array of" specifications are adjacent, [...] only the
1471 // first of the constant expressions that specify the bounds of the arrays
1474 // Note: function types are handled in the common path with C.
1475 if (T->isReferenceType()) {
1476 Diag(Loc, diag::err_illegal_decl_array_of_references)
1477 << getPrintableNameForEntity(Entity) << T;
1481 if (T->isVoidType() || T->isIncompleteArrayType()) {
1482 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1486 if (RequireNonAbstractType(Brackets.getBegin(), T,
1487 diag::err_array_of_abstract_type))
1491 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1492 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1493 if (RequireCompleteType(Loc, T,
1494 diag::err_illegal_decl_array_incomplete_type))
1498 if (T->isFunctionType()) {
1499 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1500 << getPrintableNameForEntity(Entity) << T;
1504 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1505 // If the element type is a struct or union that contains a variadic
1506 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1507 if (EltTy->getDecl()->hasFlexibleArrayMember())
1508 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1509 } else if (T->isObjCObjectType()) {
1510 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1514 // Do placeholder conversions on the array size expression.
1515 if (ArraySize && ArraySize->hasPlaceholderType()) {
1516 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1517 if (Result.isInvalid()) return QualType();
1518 ArraySize = Result.take();
1521 // Do lvalue-to-rvalue conversions on the array size expression.
1522 if (ArraySize && !ArraySize->isRValue()) {
1523 ExprResult Result = DefaultLvalueConversion(ArraySize);
1524 if (Result.isInvalid())
1527 ArraySize = Result.take();
1530 // C99 6.7.5.2p1: The size expression shall have integer type.
1531 // C++11 allows contextual conversions to such types.
1532 if (!getLangOpts().CPlusPlus11 &&
1533 ArraySize && !ArraySize->isTypeDependent() &&
1534 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1535 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1536 << ArraySize->getType() << ArraySize->getSourceRange();
1540 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1542 if (ASM == ArrayType::Star)
1543 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1545 T = Context.getIncompleteArrayType(T, ASM, Quals);
1546 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1547 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1548 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1549 !T->isConstantSizeType()) ||
1550 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1551 // Even in C++11, don't allow contextual conversions in the array bound
1553 if (getLangOpts().CPlusPlus11 &&
1554 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1555 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1556 << ArraySize->getType() << ArraySize->getSourceRange();
1560 // C99: an array with an element type that has a non-constant-size is a VLA.
1561 // C99: an array with a non-ICE size is a VLA. We accept any expression
1562 // that we can fold to a non-zero positive value as an extension.
1563 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1565 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1566 // have a value greater than zero.
1567 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1569 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1570 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1572 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1573 << ArraySize->getSourceRange();
1576 if (ConstVal == 0) {
1577 // GCC accepts zero sized static arrays. We allow them when
1578 // we're not in a SFINAE context.
1579 Diag(ArraySize->getLocStart(),
1580 isSFINAEContext()? diag::err_typecheck_zero_array_size
1581 : diag::ext_typecheck_zero_array_size)
1582 << ArraySize->getSourceRange();
1584 if (ASM == ArrayType::Static) {
1585 Diag(ArraySize->getLocStart(),
1586 diag::warn_typecheck_zero_static_array_size)
1587 << ArraySize->getSourceRange();
1588 ASM = ArrayType::Normal;
1590 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1591 !T->isIncompleteType() && !T->isUndeducedType()) {
1592 // Is the array too large?
1593 unsigned ActiveSizeBits
1594 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1595 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
1596 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1597 << ConstVal.toString(10)
1598 << ArraySize->getSourceRange();
1603 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1606 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1607 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1608 Diag(Loc, diag::err_opencl_vla);
1611 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1612 if (!getLangOpts().C99) {
1613 if (T->isVariableArrayType()) {
1614 // Prohibit the use of non-POD types in VLAs.
1615 QualType BaseT = Context.getBaseElementType(T);
1616 if (!T->isDependentType() &&
1617 !BaseT.isPODType(Context) &&
1618 !BaseT->isObjCLifetimeType()) {
1619 Diag(Loc, diag::err_vla_non_pod)
1623 // Prohibit the use of VLAs during template argument deduction.
1624 else if (isSFINAEContext()) {
1625 Diag(Loc, diag::err_vla_in_sfinae);
1628 // Just extwarn about VLAs.
1630 Diag(Loc, diag::ext_vla);
1631 } else if (ASM != ArrayType::Normal || Quals != 0)
1633 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1634 : diag::ext_c99_array_usage) << ASM;
1637 if (T->isVariableArrayType()) {
1638 // Warn about VLAs for -Wvla.
1639 Diag(Loc, diag::warn_vla_used);
1645 /// \brief Build an ext-vector type.
1647 /// Run the required checks for the extended vector type.
1648 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1649 SourceLocation AttrLoc) {
1650 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1651 // in conjunction with complex types (pointers, arrays, functions, etc.).
1652 if (!T->isDependentType() &&
1653 !T->isIntegerType() && !T->isRealFloatingType()) {
1654 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1658 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1659 llvm::APSInt vecSize(32);
1660 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1661 Diag(AttrLoc, diag::err_attribute_argument_type)
1662 << "ext_vector_type" << AANT_ArgumentIntegerConstant
1663 << ArraySize->getSourceRange();
1667 // unlike gcc's vector_size attribute, the size is specified as the
1668 // number of elements, not the number of bytes.
1669 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1671 if (vectorSize == 0) {
1672 Diag(AttrLoc, diag::err_attribute_zero_size)
1673 << ArraySize->getSourceRange();
1677 if (VectorType::isVectorSizeTooLarge(vectorSize)) {
1678 Diag(AttrLoc, diag::err_attribute_size_too_large)
1679 << ArraySize->getSourceRange();
1683 return Context.getExtVectorType(T, vectorSize);
1686 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1689 bool Sema::CheckFunctionReturnType(QualType T, SourceLocation Loc) {
1690 if (T->isArrayType() || T->isFunctionType()) {
1691 Diag(Loc, diag::err_func_returning_array_function)
1692 << T->isFunctionType() << T;
1696 // Functions cannot return half FP.
1697 if (T->isHalfType()) {
1698 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1699 FixItHint::CreateInsertion(Loc, "*");
1703 // Methods cannot return interface types. All ObjC objects are
1704 // passed by reference.
1705 if (T->isObjCObjectType()) {
1706 Diag(Loc, diag::err_object_cannot_be_passed_returned_by_value) << 0 << T;
1713 QualType Sema::BuildFunctionType(QualType T,
1714 llvm::MutableArrayRef<QualType> ParamTypes,
1715 SourceLocation Loc, DeclarationName Entity,
1716 const FunctionProtoType::ExtProtoInfo &EPI) {
1717 bool Invalid = false;
1719 Invalid |= CheckFunctionReturnType(T, Loc);
1721 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1722 // FIXME: Loc is too inprecise here, should use proper locations for args.
1723 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1724 if (ParamType->isVoidType()) {
1725 Diag(Loc, diag::err_param_with_void_type);
1727 } else if (ParamType->isHalfType()) {
1728 // Disallow half FP arguments.
1729 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1730 FixItHint::CreateInsertion(Loc, "*");
1734 ParamTypes[Idx] = ParamType;
1740 return Context.getFunctionType(T, ParamTypes, EPI);
1743 /// \brief Build a member pointer type \c T Class::*.
1745 /// \param T the type to which the member pointer refers.
1746 /// \param Class the class type into which the member pointer points.
1747 /// \param Loc the location where this type begins
1748 /// \param Entity the name of the entity that will have this member pointer type
1750 /// \returns a member pointer type, if successful, or a NULL type if there was
1752 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1754 DeclarationName Entity) {
1755 // Verify that we're not building a pointer to pointer to function with
1756 // exception specification.
1757 if (CheckDistantExceptionSpec(T)) {
1758 Diag(Loc, diag::err_distant_exception_spec);
1760 // FIXME: If we're doing this as part of template instantiation,
1761 // we should return immediately.
1763 // Build the type anyway, but use the canonical type so that the
1764 // exception specifiers are stripped off.
1765 T = Context.getCanonicalType(T);
1768 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1769 // with reference type, or "cv void."
1770 if (T->isReferenceType()) {
1771 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1772 << (Entity? Entity.getAsString() : "type name") << T;
1776 if (T->isVoidType()) {
1777 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1778 << (Entity? Entity.getAsString() : "type name");
1782 if (!Class->isDependentType() && !Class->isRecordType()) {
1783 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1787 // C++ allows the class type in a member pointer to be an incomplete type.
1788 // In the Microsoft ABI, the size of the member pointer can vary
1789 // according to the class type, which means that we really need a
1790 // complete type if possible, which means we need to instantiate templates.
1792 // If template instantiation fails or the type is just incomplete, we have to
1793 // add an extra slot to the member pointer. Yes, this does cause problems
1794 // when passing pointers between TUs that disagree about the size.
1795 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1796 CXXRecordDecl *RD = Class->getAsCXXRecordDecl();
1797 if (RD && !RD->hasAttr<MSInheritanceAttr>()) {
1798 // Lock in the inheritance model on the first use of a member pointer.
1799 // Otherwise we may disagree about the size at different points in the TU.
1800 // FIXME: MSVC picks a model on the first use that needs to know the size,
1801 // rather than on the first mention of the type, e.g. typedefs.
1802 if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) {
1803 // We know it doesn't have an attribute and it's incomplete, so use the
1804 // unspecified inheritance model. If we're in the record body, we can
1805 // figure out the inheritance model.
1806 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
1807 E = RD->redecls_end(); I != E; ++I) {
1808 I->addAttr(::new (Context) UnspecifiedInheritanceAttr(
1809 RD->getSourceRange(), Context));
1815 // FIXME: Adjust member function pointer calling conventions.
1817 return Context.getMemberPointerType(T, Class.getTypePtr());
1820 /// \brief Build a block pointer type.
1822 /// \param T The type to which we'll be building a block pointer.
1824 /// \param Loc The source location, used for diagnostics.
1826 /// \param Entity The name of the entity that involves the block pointer
1829 /// \returns A suitable block pointer type, if there are no
1830 /// errors. Otherwise, returns a NULL type.
1831 QualType Sema::BuildBlockPointerType(QualType T,
1833 DeclarationName Entity) {
1834 if (!T->isFunctionType()) {
1835 Diag(Loc, diag::err_nonfunction_block_type);
1839 return Context.getBlockPointerType(T);
1842 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1843 QualType QT = Ty.get();
1845 if (TInfo) *TInfo = 0;
1849 TypeSourceInfo *DI = 0;
1850 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1851 QT = LIT->getType();
1852 DI = LIT->getTypeSourceInfo();
1855 if (TInfo) *TInfo = DI;
1859 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1860 Qualifiers::ObjCLifetime ownership,
1861 unsigned chunkIndex);
1863 /// Given that this is the declaration of a parameter under ARC,
1864 /// attempt to infer attributes and such for pointer-to-whatever
1866 static void inferARCWriteback(TypeProcessingState &state,
1867 QualType &declSpecType) {
1868 Sema &S = state.getSema();
1869 Declarator &declarator = state.getDeclarator();
1871 // TODO: should we care about decl qualifiers?
1873 // Check whether the declarator has the expected form. We walk
1874 // from the inside out in order to make the block logic work.
1875 unsigned outermostPointerIndex = 0;
1876 bool isBlockPointer = false;
1877 unsigned numPointers = 0;
1878 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1879 unsigned chunkIndex = i;
1880 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1881 switch (chunk.Kind) {
1882 case DeclaratorChunk::Paren:
1886 case DeclaratorChunk::Reference:
1887 case DeclaratorChunk::Pointer:
1888 // Count the number of pointers. Treat references
1889 // interchangeably as pointers; if they're mis-ordered, normal
1890 // type building will discover that.
1891 outermostPointerIndex = chunkIndex;
1895 case DeclaratorChunk::BlockPointer:
1896 // If we have a pointer to block pointer, that's an acceptable
1897 // indirect reference; anything else is not an application of
1899 if (numPointers != 1) return;
1901 outermostPointerIndex = chunkIndex;
1902 isBlockPointer = true;
1904 // We don't care about pointer structure in return values here.
1907 case DeclaratorChunk::Array: // suppress if written (id[])?
1908 case DeclaratorChunk::Function:
1909 case DeclaratorChunk::MemberPointer:
1915 // If we have *one* pointer, then we want to throw the qualifier on
1916 // the declaration-specifiers, which means that it needs to be a
1917 // retainable object type.
1918 if (numPointers == 1) {
1919 // If it's not a retainable object type, the rule doesn't apply.
1920 if (!declSpecType->isObjCRetainableType()) return;
1922 // If it already has lifetime, don't do anything.
1923 if (declSpecType.getObjCLifetime()) return;
1925 // Otherwise, modify the type in-place.
1928 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1929 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1931 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1932 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1934 // If we have *two* pointers, then we want to throw the qualifier on
1935 // the outermost pointer.
1936 } else if (numPointers == 2) {
1937 // If we don't have a block pointer, we need to check whether the
1938 // declaration-specifiers gave us something that will turn into a
1939 // retainable object pointer after we slap the first pointer on it.
1940 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1943 // Look for an explicit lifetime attribute there.
1944 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1945 if (chunk.Kind != DeclaratorChunk::Pointer &&
1946 chunk.Kind != DeclaratorChunk::BlockPointer)
1948 for (const AttributeList *attr = chunk.getAttrs(); attr;
1949 attr = attr->getNext())
1950 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1953 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1954 outermostPointerIndex);
1956 // Any other number of pointers/references does not trigger the rule.
1959 // TODO: mark whether we did this inference?
1962 static void diagnoseIgnoredQualifiers(
1963 Sema &S, unsigned Quals,
1964 SourceLocation FallbackLoc,
1965 SourceLocation ConstQualLoc = SourceLocation(),
1966 SourceLocation VolatileQualLoc = SourceLocation(),
1967 SourceLocation RestrictQualLoc = SourceLocation(),
1968 SourceLocation AtomicQualLoc = SourceLocation()) {
1972 const SourceManager &SM = S.getSourceManager();
1978 } const QualKinds[4] = {
1979 { DeclSpec::TQ_const, "const", ConstQualLoc },
1980 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
1981 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
1982 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
1985 SmallString<32> QualStr;
1986 unsigned NumQuals = 0;
1988 FixItHint FixIts[4];
1990 // Build a string naming the redundant qualifiers.
1991 for (unsigned I = 0; I != 4; ++I) {
1992 if (Quals & QualKinds[I].Mask) {
1993 if (!QualStr.empty()) QualStr += ' ';
1994 QualStr += QualKinds[I].Name;
1996 // If we have a location for the qualifier, offer a fixit.
1997 SourceLocation QualLoc = QualKinds[I].Loc;
1998 if (!QualLoc.isInvalid()) {
1999 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
2000 if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc))
2008 S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type)
2009 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
2012 // Diagnose pointless type qualifiers on the return type of a function.
2013 static void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy,
2015 unsigned FunctionChunkIndex) {
2016 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
2017 // FIXME: TypeSourceInfo doesn't preserve location information for
2019 diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(),
2020 D.getIdentifierLoc());
2024 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
2025 End = D.getNumTypeObjects();
2026 OuterChunkIndex != End; ++OuterChunkIndex) {
2027 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
2028 switch (OuterChunk.Kind) {
2029 case DeclaratorChunk::Paren:
2032 case DeclaratorChunk::Pointer: {
2033 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
2034 diagnoseIgnoredQualifiers(
2037 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
2038 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
2039 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
2040 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
2044 case DeclaratorChunk::Function:
2045 case DeclaratorChunk::BlockPointer:
2046 case DeclaratorChunk::Reference:
2047 case DeclaratorChunk::Array:
2048 case DeclaratorChunk::MemberPointer:
2049 // FIXME: We can't currently provide an accurate source location and a
2050 // fix-it hint for these.
2051 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
2052 diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual,
2053 D.getIdentifierLoc());
2057 llvm_unreachable("unknown declarator chunk kind");
2060 // If the qualifiers come from a conversion function type, don't diagnose
2061 // them -- they're not necessarily redundant, since such a conversion
2062 // operator can be explicitly called as "x.operator const int()".
2063 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2066 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2067 // which are present there.
2068 diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(),
2069 D.getIdentifierLoc(),
2070 D.getDeclSpec().getConstSpecLoc(),
2071 D.getDeclSpec().getVolatileSpecLoc(),
2072 D.getDeclSpec().getRestrictSpecLoc(),
2073 D.getDeclSpec().getAtomicSpecLoc());
2076 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2077 TypeSourceInfo *&ReturnTypeInfo) {
2078 Sema &SemaRef = state.getSema();
2079 Declarator &D = state.getDeclarator();
2083 // The TagDecl owned by the DeclSpec.
2084 TagDecl *OwnedTagDecl = 0;
2086 bool ContainsPlaceholderType = false;
2088 switch (D.getName().getKind()) {
2089 case UnqualifiedId::IK_ImplicitSelfParam:
2090 case UnqualifiedId::IK_OperatorFunctionId:
2091 case UnqualifiedId::IK_Identifier:
2092 case UnqualifiedId::IK_LiteralOperatorId:
2093 case UnqualifiedId::IK_TemplateId:
2094 T = ConvertDeclSpecToType(state);
2095 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2097 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2098 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2099 // Owned declaration is embedded in declarator.
2100 OwnedTagDecl->setEmbeddedInDeclarator(true);
2104 case UnqualifiedId::IK_ConstructorName:
2105 case UnqualifiedId::IK_ConstructorTemplateId:
2106 case UnqualifiedId::IK_DestructorName:
2107 // Constructors and destructors don't have return types. Use
2109 T = SemaRef.Context.VoidTy;
2110 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2111 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2114 case UnqualifiedId::IK_ConversionFunctionId:
2115 // The result type of a conversion function is the type that it
2117 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2119 ContainsPlaceholderType = T->getContainedAutoType();
2123 if (D.getAttributes())
2124 distributeTypeAttrsFromDeclarator(state, T);
2126 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2127 // In C++11, a function declarator using 'auto' must have a trailing return
2128 // type (this is checked later) and we can skip this. In other languages
2129 // using auto, we need to check regardless.
2130 // C++14 In generic lambdas allow 'auto' in their parameters.
2131 if (ContainsPlaceholderType &&
2132 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2135 switch (D.getContext()) {
2136 case Declarator::KNRTypeListContext:
2137 llvm_unreachable("K&R type lists aren't allowed in C++");
2138 case Declarator::LambdaExprContext:
2139 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2140 case Declarator::ObjCParameterContext:
2141 case Declarator::ObjCResultContext:
2142 case Declarator::PrototypeContext:
2145 case Declarator::LambdaExprParameterContext:
2146 if (!(SemaRef.getLangOpts().CPlusPlus1y
2147 && D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto))
2150 case Declarator::MemberContext:
2151 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2153 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2154 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2155 case TTK_Struct: Error = 1; /* Struct member */ break;
2156 case TTK_Union: Error = 2; /* Union member */ break;
2157 case TTK_Class: Error = 3; /* Class member */ break;
2158 case TTK_Interface: Error = 4; /* Interface member */ break;
2161 case Declarator::CXXCatchContext:
2162 case Declarator::ObjCCatchContext:
2163 Error = 5; // Exception declaration
2165 case Declarator::TemplateParamContext:
2166 Error = 6; // Template parameter
2168 case Declarator::BlockLiteralContext:
2169 Error = 7; // Block literal
2171 case Declarator::TemplateTypeArgContext:
2172 Error = 8; // Template type argument
2174 case Declarator::AliasDeclContext:
2175 case Declarator::AliasTemplateContext:
2176 Error = 10; // Type alias
2178 case Declarator::TrailingReturnContext:
2179 if (!SemaRef.getLangOpts().CPlusPlus1y)
2180 Error = 11; // Function return type
2182 case Declarator::ConversionIdContext:
2183 if (!SemaRef.getLangOpts().CPlusPlus1y)
2184 Error = 12; // conversion-type-id
2186 case Declarator::TypeNameContext:
2187 Error = 13; // Generic
2189 case Declarator::FileContext:
2190 case Declarator::BlockContext:
2191 case Declarator::ForContext:
2192 case Declarator::ConditionContext:
2193 case Declarator::CXXNewContext:
2197 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2200 // In Objective-C it is an error to use 'auto' on a function declarator.
2201 if (D.isFunctionDeclarator())
2204 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2205 // contains a trailing return type. That is only legal at the outermost
2206 // level. Check all declarator chunks (outermost first) anyway, to give
2207 // better diagnostics.
2208 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2209 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2210 unsigned chunkIndex = e - i - 1;
2211 state.setCurrentChunkIndex(chunkIndex);
2212 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2213 if (DeclType.Kind == DeclaratorChunk::Function) {
2214 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2215 if (FTI.hasTrailingReturnType()) {
2223 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2224 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2225 AutoRange = D.getName().getSourceRange();
2228 const bool IsDeclTypeAuto =
2229 D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_decltype_auto;
2230 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2231 << IsDeclTypeAuto << Error << AutoRange;
2232 T = SemaRef.Context.IntTy;
2233 D.setInvalidType(true);
2235 SemaRef.Diag(AutoRange.getBegin(),
2236 diag::warn_cxx98_compat_auto_type_specifier)
2240 if (SemaRef.getLangOpts().CPlusPlus &&
2241 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2242 // Check the contexts where C++ forbids the declaration of a new class
2243 // or enumeration in a type-specifier-seq.
2244 switch (D.getContext()) {
2245 case Declarator::TrailingReturnContext:
2246 // Class and enumeration definitions are syntactically not allowed in
2247 // trailing return types.
2248 llvm_unreachable("parser should not have allowed this");
2250 case Declarator::FileContext:
2251 case Declarator::MemberContext:
2252 case Declarator::BlockContext:
2253 case Declarator::ForContext:
2254 case Declarator::BlockLiteralContext:
2255 case Declarator::LambdaExprContext:
2256 // C++11 [dcl.type]p3:
2257 // A type-specifier-seq shall not define a class or enumeration unless
2258 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2259 // the declaration of a template-declaration.
2260 case Declarator::AliasDeclContext:
2262 case Declarator::AliasTemplateContext:
2263 SemaRef.Diag(OwnedTagDecl->getLocation(),
2264 diag::err_type_defined_in_alias_template)
2265 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2266 D.setInvalidType(true);
2268 case Declarator::TypeNameContext:
2269 case Declarator::ConversionIdContext:
2270 case Declarator::TemplateParamContext:
2271 case Declarator::CXXNewContext:
2272 case Declarator::CXXCatchContext:
2273 case Declarator::ObjCCatchContext:
2274 case Declarator::TemplateTypeArgContext:
2275 SemaRef.Diag(OwnedTagDecl->getLocation(),
2276 diag::err_type_defined_in_type_specifier)
2277 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2278 D.setInvalidType(true);
2280 case Declarator::PrototypeContext:
2281 case Declarator::LambdaExprParameterContext:
2282 case Declarator::ObjCParameterContext:
2283 case Declarator::ObjCResultContext:
2284 case Declarator::KNRTypeListContext:
2286 // Types shall not be defined in return or parameter types.
2287 SemaRef.Diag(OwnedTagDecl->getLocation(),
2288 diag::err_type_defined_in_param_type)
2289 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2290 D.setInvalidType(true);
2292 case Declarator::ConditionContext:
2294 // The type-specifier-seq shall not contain typedef and shall not declare
2295 // a new class or enumeration.
2296 SemaRef.Diag(OwnedTagDecl->getLocation(),
2297 diag::err_type_defined_in_condition);
2298 D.setInvalidType(true);
2306 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2308 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2310 switch (FnTy->getRefQualifier()) {
2330 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2331 /// can be contained within the declarator chunk DeclType, and produce an
2332 /// appropriate diagnostic if not.
2333 static void checkQualifiedFunction(Sema &S, QualType T,
2334 DeclaratorChunk &DeclType) {
2335 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2336 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2339 switch (DeclType.Kind) {
2340 case DeclaratorChunk::Paren:
2341 case DeclaratorChunk::MemberPointer:
2342 // These cases are permitted.
2344 case DeclaratorChunk::Array:
2345 case DeclaratorChunk::Function:
2346 // These cases don't allow function types at all; no need to diagnose the
2347 // qualifiers separately.
2349 case DeclaratorChunk::BlockPointer:
2352 case DeclaratorChunk::Pointer:
2355 case DeclaratorChunk::Reference:
2360 assert(DiagKind != -1);
2361 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2362 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2363 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2366 /// Produce an approprioate diagnostic for an ambiguity between a function
2367 /// declarator and a C++ direct-initializer.
2368 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2369 DeclaratorChunk &DeclType, QualType RT) {
2370 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2371 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2373 // If the return type is void there is no ambiguity.
2374 if (RT->isVoidType())
2377 // An initializer for a non-class type can have at most one argument.
2378 if (!RT->isRecordType() && FTI.NumArgs > 1)
2381 // An initializer for a reference must have exactly one argument.
2382 if (RT->isReferenceType() && FTI.NumArgs != 1)
2385 // Only warn if this declarator is declaring a function at block scope, and
2386 // doesn't have a storage class (such as 'extern') specified.
2387 if (!D.isFunctionDeclarator() ||
2388 D.getFunctionDefinitionKind() != FDK_Declaration ||
2389 !S.CurContext->isFunctionOrMethod() ||
2390 D.getDeclSpec().getStorageClassSpec()
2391 != DeclSpec::SCS_unspecified)
2394 // Inside a condition, a direct initializer is not permitted. We allow one to
2395 // be parsed in order to give better diagnostics in condition parsing.
2396 if (D.getContext() == Declarator::ConditionContext)
2399 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2401 S.Diag(DeclType.Loc,
2402 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2403 : diag::warn_empty_parens_are_function_decl)
2406 // If the declaration looks like:
2409 // and name lookup finds a function named 'f', then the ',' was
2410 // probably intended to be a ';'.
2411 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2412 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2413 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2414 if (Comma.getFileID() != Name.getFileID() ||
2415 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2416 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2417 Sema::LookupOrdinaryName);
2418 if (S.LookupName(Result, S.getCurScope()))
2419 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2420 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2421 << D.getIdentifier();
2425 if (FTI.NumArgs > 0) {
2426 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2427 // around the first parameter to turn the declaration into a variable
2429 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2430 SourceLocation B = Range.getBegin();
2431 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2432 // FIXME: Maybe we should suggest adding braces instead of parens
2433 // in C++11 for classes that don't have an initializer_list constructor.
2434 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2435 << FixItHint::CreateInsertion(B, "(")
2436 << FixItHint::CreateInsertion(E, ")");
2438 // For a declaration without parameters, eg. "T var();", suggest replacing the
2439 // parens with an initializer to turn the declaration into a variable
2441 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2443 // Empty parens mean value-initialization, and no parens mean
2444 // default initialization. These are equivalent if the default
2445 // constructor is user-provided or if zero-initialization is a
2447 if (RD && RD->hasDefinition() &&
2448 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2449 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2450 << FixItHint::CreateRemoval(ParenRange);
2453 S.getFixItZeroInitializerForType(RT, ParenRange.getBegin());
2454 if (Init.empty() && S.LangOpts.CPlusPlus11)
2457 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2458 << FixItHint::CreateReplacement(ParenRange, Init);
2463 /// Helper for figuring out the default CC for a function declarator type. If
2464 /// this is the outermost chunk, then we can determine the CC from the
2465 /// declarator context. If not, then this could be either a member function
2466 /// type or normal function type.
2468 getCCForDeclaratorChunk(Sema &S, Declarator &D,
2469 const DeclaratorChunk::FunctionTypeInfo &FTI,
2470 unsigned ChunkIndex) {
2471 assert(D.getTypeObject(ChunkIndex).Kind == DeclaratorChunk::Function);
2473 bool IsCXXInstanceMethod = false;
2475 if (S.getLangOpts().CPlusPlus) {
2476 // Look inwards through parentheses to see if this chunk will form a
2477 // member pointer type or if we're the declarator. Any type attributes
2478 // between here and there will override the CC we choose here.
2479 unsigned I = ChunkIndex;
2480 bool FoundNonParen = false;
2481 while (I && !FoundNonParen) {
2483 if (D.getTypeObject(I).Kind != DeclaratorChunk::Paren)
2484 FoundNonParen = true;
2487 if (FoundNonParen) {
2488 // If we're not the declarator, we're a regular function type unless we're
2489 // in a member pointer.
2490 IsCXXInstanceMethod =
2491 D.getTypeObject(I).Kind == DeclaratorChunk::MemberPointer;
2493 // We're the innermost decl chunk, so must be a function declarator.
2494 assert(D.isFunctionDeclarator());
2496 // If we're inside a record, we're declaring a method, but it could be
2497 // explicitly or implicitly static.
2498 IsCXXInstanceMethod =
2499 D.isFirstDeclarationOfMember() &&
2500 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
2501 !D.isStaticMember();
2505 return S.Context.getDefaultCallingConvention(FTI.isVariadic,
2506 IsCXXInstanceMethod);
2509 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2510 QualType declSpecType,
2511 TypeSourceInfo *TInfo) {
2513 QualType T = declSpecType;
2514 Declarator &D = state.getDeclarator();
2515 Sema &S = state.getSema();
2516 ASTContext &Context = S.Context;
2517 const LangOptions &LangOpts = S.getLangOpts();
2519 // The name we're declaring, if any.
2520 DeclarationName Name;
2521 if (D.getIdentifier())
2522 Name = D.getIdentifier();
2524 // Does this declaration declare a typedef-name?
2525 bool IsTypedefName =
2526 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2527 D.getContext() == Declarator::AliasDeclContext ||
2528 D.getContext() == Declarator::AliasTemplateContext;
2530 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2531 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2532 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2533 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2535 // If T is 'decltype(auto)', the only declarators we can have are parens
2536 // and at most one function declarator if this is a function declaration.
2537 if (const AutoType *AT = T->getAs<AutoType>()) {
2538 if (AT->isDecltypeAuto()) {
2539 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2540 unsigned Index = E - I - 1;
2541 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2542 unsigned DiagId = diag::err_decltype_auto_compound_type;
2543 unsigned DiagKind = 0;
2544 switch (DeclChunk.Kind) {
2545 case DeclaratorChunk::Paren:
2547 case DeclaratorChunk::Function: {
2549 if (D.isFunctionDeclarationContext() &&
2550 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2552 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2555 case DeclaratorChunk::Pointer:
2556 case DeclaratorChunk::BlockPointer:
2557 case DeclaratorChunk::MemberPointer:
2560 case DeclaratorChunk::Reference:
2563 case DeclaratorChunk::Array:
2568 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2569 D.setInvalidType(true);
2575 // Walk the DeclTypeInfo, building the recursive type as we go.
2576 // DeclTypeInfos are ordered from the identifier out, which is
2577 // opposite of what we want :).
2578 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2579 unsigned chunkIndex = e - i - 1;
2580 state.setCurrentChunkIndex(chunkIndex);
2581 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2582 if (IsQualifiedFunction) {
2583 checkQualifiedFunction(S, T, DeclType);
2584 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2586 switch (DeclType.Kind) {
2587 case DeclaratorChunk::Paren:
2588 T = S.BuildParenType(T);
2590 case DeclaratorChunk::BlockPointer:
2591 // If blocks are disabled, emit an error.
2592 if (!LangOpts.Blocks)
2593 S.Diag(DeclType.Loc, diag::err_blocks_disable);
2595 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2596 if (DeclType.Cls.TypeQuals)
2597 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2599 case DeclaratorChunk::Pointer:
2600 // Verify that we're not building a pointer to pointer to function with
2601 // exception specification.
2602 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2603 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2604 D.setInvalidType(true);
2605 // Build the type anyway.
2607 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2608 T = Context.getObjCObjectPointerType(T);
2609 if (DeclType.Ptr.TypeQuals)
2610 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2613 T = S.BuildPointerType(T, DeclType.Loc, Name);
2614 if (DeclType.Ptr.TypeQuals)
2615 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2618 case DeclaratorChunk::Reference: {
2619 // Verify that we're not building a reference to pointer to function with
2620 // exception specification.
2621 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2622 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2623 D.setInvalidType(true);
2624 // Build the type anyway.
2626 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2629 if (DeclType.Ref.HasRestrict)
2630 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2633 case DeclaratorChunk::Array: {
2634 // Verify that we're not building an array of pointers to function with
2635 // exception specification.
2636 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2637 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2638 D.setInvalidType(true);
2639 // Build the type anyway.
2641 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2642 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2643 ArrayType::ArraySizeModifier ASM;
2645 ASM = ArrayType::Star;
2646 else if (ATI.hasStatic)
2647 ASM = ArrayType::Static;
2649 ASM = ArrayType::Normal;
2650 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2651 // FIXME: This check isn't quite right: it allows star in prototypes
2652 // for function definitions, and disallows some edge cases detailed
2653 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2654 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2655 ASM = ArrayType::Normal;
2656 D.setInvalidType(true);
2659 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2660 // shall appear only in a declaration of a function parameter with an
2662 if (ASM == ArrayType::Static || ATI.TypeQuals) {
2663 if (!(D.isPrototypeContext() ||
2664 D.getContext() == Declarator::KNRTypeListContext)) {
2665 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2666 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2667 // Remove the 'static' and the type qualifiers.
2668 if (ASM == ArrayType::Static)
2669 ASM = ArrayType::Normal;
2671 D.setInvalidType(true);
2674 // C99 6.7.5.2p1: ... and then only in the outermost array type
2676 unsigned x = chunkIndex;
2678 // Walk outwards along the declarator chunks.
2680 const DeclaratorChunk &DC = D.getTypeObject(x);
2682 case DeclaratorChunk::Paren:
2684 case DeclaratorChunk::Array:
2685 case DeclaratorChunk::Pointer:
2686 case DeclaratorChunk::Reference:
2687 case DeclaratorChunk::MemberPointer:
2688 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2689 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2690 if (ASM == ArrayType::Static)
2691 ASM = ArrayType::Normal;
2693 D.setInvalidType(true);
2695 case DeclaratorChunk::Function:
2696 case DeclaratorChunk::BlockPointer:
2697 // These are invalid anyway, so just ignore.
2702 const AutoType *AT = T->getContainedAutoType();
2703 // Allow arrays of auto if we are a generic lambda parameter.
2704 // i.e. [](auto (&array)[5]) { return array[0]; }; OK
2705 if (AT && D.getContext() != Declarator::LambdaExprParameterContext) {
2706 // We've already diagnosed this for decltype(auto).
2707 if (!AT->isDecltypeAuto())
2708 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2709 << getPrintableNameForEntity(Name) << T;
2714 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2715 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2718 case DeclaratorChunk::Function: {
2719 // If the function declarator has a prototype (i.e. it is not () and
2720 // does not have a K&R-style identifier list), then the arguments are part
2721 // of the type, otherwise the argument list is ().
2722 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2723 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2725 // Check for auto functions and trailing return type and adjust the
2726 // return type accordingly.
2727 if (!D.isInvalidType()) {
2728 // trailing-return-type is only required if we're declaring a function,
2729 // and not, for instance, a pointer to a function.
2730 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2731 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2732 !S.getLangOpts().CPlusPlus1y) {
2733 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2734 diag::err_auto_missing_trailing_return);
2736 D.setInvalidType(true);
2737 } else if (FTI.hasTrailingReturnType()) {
2738 // T must be exactly 'auto' at this point. See CWG issue 681.
2739 if (isa<ParenType>(T)) {
2740 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2741 diag::err_trailing_return_in_parens)
2742 << T << D.getDeclSpec().getSourceRange();
2743 D.setInvalidType(true);
2744 } else if (D.getContext() != Declarator::LambdaExprContext &&
2745 (T.hasQualifiers() || !isa<AutoType>(T) ||
2746 cast<AutoType>(T)->isDecltypeAuto())) {
2747 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2748 diag::err_trailing_return_without_auto)
2749 << T << D.getDeclSpec().getSourceRange();
2750 D.setInvalidType(true);
2752 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2754 // An error occurred parsing the trailing return type.
2756 D.setInvalidType(true);
2761 // C99 6.7.5.3p1: The return type may not be a function or array type.
2762 // For conversion functions, we'll diagnose this particular error later.
2763 if ((T->isArrayType() || T->isFunctionType()) &&
2764 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2765 unsigned diagID = diag::err_func_returning_array_function;
2766 // Last processing chunk in block context means this function chunk
2767 // represents the block.
2768 if (chunkIndex == 0 &&
2769 D.getContext() == Declarator::BlockLiteralContext)
2770 diagID = diag::err_block_returning_array_function;
2771 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2773 D.setInvalidType(true);
2776 // Do not allow returning half FP value.
2777 // FIXME: This really should be in BuildFunctionType.
2778 if (T->isHalfType()) {
2779 if (S.getLangOpts().OpenCL) {
2780 if (!S.getOpenCLOptions().cl_khr_fp16) {
2781 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2782 D.setInvalidType(true);
2785 S.Diag(D.getIdentifierLoc(),
2786 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2787 D.setInvalidType(true);
2791 // Methods cannot return interface types. All ObjC objects are
2792 // passed by reference.
2793 if (T->isObjCObjectType()) {
2794 SourceLocation DiagLoc, FixitLoc;
2796 DiagLoc = TInfo->getTypeLoc().getLocStart();
2797 FixitLoc = S.PP.getLocForEndOfToken(TInfo->getTypeLoc().getLocEnd());
2799 DiagLoc = D.getDeclSpec().getTypeSpecTypeLoc();
2800 FixitLoc = S.PP.getLocForEndOfToken(D.getDeclSpec().getLocEnd());
2802 S.Diag(DiagLoc, diag::err_object_cannot_be_passed_returned_by_value)
2804 << FixItHint::CreateInsertion(FixitLoc, "*");
2806 T = Context.getObjCObjectPointerType(T);
2809 TLB.pushFullCopy(TInfo->getTypeLoc());
2810 ObjCObjectPointerTypeLoc TLoc = TLB.push<ObjCObjectPointerTypeLoc>(T);
2811 TLoc.setStarLoc(FixitLoc);
2812 TInfo = TLB.getTypeSourceInfo(Context, T);
2815 D.setInvalidType(true);
2818 // cv-qualifiers on return types are pointless except when the type is a
2819 // class type in C++.
2820 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2821 !(S.getLangOpts().CPlusPlus &&
2822 (T->isDependentType() || T->isRecordType())))
2823 diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex);
2825 // Objective-C ARC ownership qualifiers are ignored on the function
2826 // return type (by type canonicalization). Complain if this attribute
2827 // was written here.
2828 if (T.getQualifiers().hasObjCLifetime()) {
2829 SourceLocation AttrLoc;
2830 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2831 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2832 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2833 Attr; Attr = Attr->getNext()) {
2834 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2835 AttrLoc = Attr->getLoc();
2840 if (AttrLoc.isInvalid()) {
2841 for (const AttributeList *Attr
2842 = D.getDeclSpec().getAttributes().getList();
2843 Attr; Attr = Attr->getNext()) {
2844 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2845 AttrLoc = Attr->getLoc();
2851 if (AttrLoc.isValid()) {
2852 // The ownership attributes are almost always written via
2854 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2855 if (AttrLoc.isMacroID())
2856 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2858 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2859 << T.getQualifiers().getObjCLifetime();
2863 if (LangOpts.CPlusPlus && D.getDeclSpec().hasTagDefinition()) {
2865 // Types shall not be defined in return or parameter types.
2866 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2867 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2868 << Context.getTypeDeclType(Tag);
2871 // Exception specs are not allowed in typedefs. Complain, but add it
2873 if (IsTypedefName && FTI.getExceptionSpecType())
2874 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2875 << (D.getContext() == Declarator::AliasDeclContext ||
2876 D.getContext() == Declarator::AliasTemplateContext);
2878 // If we see "T var();" or "T var(T());" at block scope, it is probably
2879 // an attempt to initialize a variable, not a function declaration.
2880 if (FTI.isAmbiguous)
2881 warnAboutAmbiguousFunction(S, D, DeclType, T);
2883 FunctionType::ExtInfo EI(getCCForDeclaratorChunk(S, D, FTI, chunkIndex));
2885 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2886 // Simple void foo(), where the incoming T is the result type.
2887 T = Context.getFunctionNoProtoType(T, EI);
2889 // We allow a zero-parameter variadic function in C if the
2890 // function is marked with the "overloadable" attribute. Scan
2891 // for this attribute now.
2892 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2893 bool Overloadable = false;
2894 for (const AttributeList *Attrs = D.getAttributes();
2895 Attrs; Attrs = Attrs->getNext()) {
2896 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2897 Overloadable = true;
2903 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2906 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2907 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2909 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2910 D.setInvalidType(true);
2911 // Recover by creating a K&R-style function type.
2912 T = Context.getFunctionNoProtoType(T, EI);
2916 FunctionProtoType::ExtProtoInfo EPI;
2918 EPI.Variadic = FTI.isVariadic;
2919 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2920 EPI.TypeQuals = FTI.TypeQuals;
2921 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2922 : FTI.RefQualifierIsLValueRef? RQ_LValue
2925 // Otherwise, we have a function with an argument list that is
2926 // potentially variadic.
2927 SmallVector<QualType, 16> ArgTys;
2928 ArgTys.reserve(FTI.NumArgs);
2930 SmallVector<bool, 16> ConsumedArguments;
2931 ConsumedArguments.reserve(FTI.NumArgs);
2932 bool HasAnyConsumedArguments = false;
2934 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2935 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2936 QualType ArgTy = Param->getType();
2937 assert(!ArgTy.isNull() && "Couldn't parse type?");
2939 // Look for 'void'. void is allowed only as a single argument to a
2940 // function with no other parameters (C99 6.7.5.3p10). We record
2941 // int(void) as a FunctionProtoType with an empty argument list.
2942 if (ArgTy->isVoidType()) {
2943 // If this is something like 'float(int, void)', reject it. 'void'
2944 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2945 // have arguments of incomplete type.
2946 if (FTI.NumArgs != 1 || FTI.isVariadic) {
2947 S.Diag(DeclType.Loc, diag::err_void_only_param);
2948 ArgTy = Context.IntTy;
2949 Param->setType(ArgTy);
2950 } else if (FTI.ArgInfo[i].Ident) {
2951 // Reject, but continue to parse 'int(void abc)'.
2952 S.Diag(FTI.ArgInfo[i].IdentLoc,
2953 diag::err_param_with_void_type);
2954 ArgTy = Context.IntTy;
2955 Param->setType(ArgTy);
2957 // Reject, but continue to parse 'float(const void)'.
2958 if (ArgTy.hasQualifiers())
2959 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2961 // Do not add 'void' to the ArgTys list.
2964 } else if (ArgTy->isHalfType()) {
2965 // Disallow half FP arguments.
2966 // FIXME: This really should be in BuildFunctionType.
2967 if (S.getLangOpts().OpenCL) {
2968 if (!S.getOpenCLOptions().cl_khr_fp16) {
2969 S.Diag(Param->getLocation(),
2970 diag::err_opencl_half_argument) << ArgTy;
2972 Param->setInvalidDecl();
2975 S.Diag(Param->getLocation(),
2976 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2979 } else if (!FTI.hasPrototype) {
2980 if (ArgTy->isPromotableIntegerType()) {
2981 ArgTy = Context.getPromotedIntegerType(ArgTy);
2982 Param->setKNRPromoted(true);
2983 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2984 if (BTy->getKind() == BuiltinType::Float) {
2985 ArgTy = Context.DoubleTy;
2986 Param->setKNRPromoted(true);
2991 if (LangOpts.ObjCAutoRefCount) {
2992 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2993 ConsumedArguments.push_back(Consumed);
2994 HasAnyConsumedArguments |= Consumed;
2997 ArgTys.push_back(ArgTy);
3000 if (HasAnyConsumedArguments)
3001 EPI.ConsumedArguments = ConsumedArguments.data();
3003 SmallVector<QualType, 4> Exceptions;
3004 SmallVector<ParsedType, 2> DynamicExceptions;
3005 SmallVector<SourceRange, 2> DynamicExceptionRanges;
3006 Expr *NoexceptExpr = 0;
3008 if (FTI.getExceptionSpecType() == EST_Dynamic) {
3009 // FIXME: It's rather inefficient to have to split into two vectors
3011 unsigned N = FTI.NumExceptions;
3012 DynamicExceptions.reserve(N);
3013 DynamicExceptionRanges.reserve(N);
3014 for (unsigned I = 0; I != N; ++I) {
3015 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
3016 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
3018 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
3019 NoexceptExpr = FTI.NoexceptExpr;
3022 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
3024 DynamicExceptionRanges,
3029 T = Context.getFunctionType(T, ArgTys, EPI);
3034 case DeclaratorChunk::MemberPointer:
3035 // The scope spec must refer to a class, or be dependent.
3036 CXXScopeSpec &SS = DeclType.Mem.Scope();
3038 if (SS.isInvalid()) {
3039 // Avoid emitting extra errors if we already errored on the scope.
3040 D.setInvalidType(true);
3041 } else if (S.isDependentScopeSpecifier(SS) ||
3042 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
3043 NestedNameSpecifier *NNS
3044 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
3045 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
3046 switch (NNS->getKind()) {
3047 case NestedNameSpecifier::Identifier:
3048 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
3049 NNS->getAsIdentifier());
3052 case NestedNameSpecifier::Namespace:
3053 case NestedNameSpecifier::NamespaceAlias:
3054 case NestedNameSpecifier::Global:
3055 llvm_unreachable("Nested-name-specifier must name a type");
3057 case NestedNameSpecifier::TypeSpec:
3058 case NestedNameSpecifier::TypeSpecWithTemplate:
3059 ClsType = QualType(NNS->getAsType(), 0);
3060 // Note: if the NNS has a prefix and ClsType is a nondependent
3061 // TemplateSpecializationType, then the NNS prefix is NOT included
3062 // in ClsType; hence we wrap ClsType into an ElaboratedType.
3063 // NOTE: in particular, no wrap occurs if ClsType already is an
3064 // Elaborated, DependentName, or DependentTemplateSpecialization.
3065 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
3066 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
3070 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
3071 diag::err_illegal_decl_mempointer_in_nonclass)
3072 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
3073 << DeclType.Mem.Scope().getRange();
3074 D.setInvalidType(true);
3077 if (!ClsType.isNull())
3078 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
3081 D.setInvalidType(true);
3082 } else if (DeclType.Mem.TypeQuals) {
3083 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
3089 D.setInvalidType(true);
3093 // See if there are any attributes on this declarator chunk.
3094 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
3095 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
3098 if (LangOpts.CPlusPlus && T->isFunctionType()) {
3099 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
3100 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
3103 // A cv-qualifier-seq shall only be part of the function type
3104 // for a nonstatic member function, the function type to which a pointer
3105 // to member refers, or the top-level function type of a function typedef
3108 // Core issue 547 also allows cv-qualifiers on function types that are
3109 // top-level template type arguments.
3111 if (!D.getCXXScopeSpec().isSet()) {
3112 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
3113 D.getContext() != Declarator::LambdaExprContext) ||
3114 D.getDeclSpec().isFriendSpecified());
3116 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
3117 FreeFunction = (DC && !DC->isRecord());
3120 // C++11 [dcl.fct]p6 (w/DR1417):
3121 // An attempt to specify a function type with a cv-qualifier-seq or a
3122 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
3123 // - the function type for a non-static member function,
3124 // - the function type to which a pointer to member refers,
3125 // - the top-level function type of a function typedef declaration or
3126 // alias-declaration,
3127 // - the type-id in the default argument of a type-parameter, or
3128 // - the type-id of a template-argument for a type-parameter
3129 if (IsQualifiedFunction &&
3131 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
3133 D.getContext() != Declarator::TemplateTypeArgContext) {
3134 SourceLocation Loc = D.getLocStart();
3135 SourceRange RemovalRange;
3137 if (D.isFunctionDeclarator(I)) {
3138 SmallVector<SourceLocation, 4> RemovalLocs;
3139 const DeclaratorChunk &Chunk = D.getTypeObject(I);
3140 assert(Chunk.Kind == DeclaratorChunk::Function);
3141 if (Chunk.Fun.hasRefQualifier())
3142 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
3143 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
3144 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
3145 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3146 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3147 // FIXME: We do not track the location of the __restrict qualifier.
3148 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3149 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3150 if (!RemovalLocs.empty()) {
3151 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3152 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3153 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3154 Loc = RemovalLocs.front();
3158 S.Diag(Loc, diag::err_invalid_qualified_function_type)
3159 << FreeFunction << D.isFunctionDeclarator() << T
3160 << getFunctionQualifiersAsString(FnTy)
3161 << FixItHint::CreateRemoval(RemovalRange);
3163 // Strip the cv-qualifiers and ref-qualifiers from the type.
3164 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3166 EPI.RefQualifier = RQ_None;
3168 T = Context.getFunctionType(FnTy->getResultType(), FnTy->getArgTypes(),
3170 // Rebuild any parens around the identifier in the function type.
3171 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3172 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3174 T = S.BuildParenType(T);
3179 // Apply any undistributed attributes from the declarator.
3181 if (AttributeList *attrs = D.getAttributes())
3182 processTypeAttrs(state, T, TAL_DeclName, attrs);
3184 // Diagnose any ignored type attributes.
3185 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
3187 // C++0x [dcl.constexpr]p9:
3188 // A constexpr specifier used in an object declaration declares the object
3190 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3194 // If there was an ellipsis in the declarator, the declaration declares a
3195 // parameter pack whose type may be a pack expansion type.
3196 if (D.hasEllipsis() && !T.isNull()) {
3197 // C++0x [dcl.fct]p13:
3198 // A declarator-id or abstract-declarator containing an ellipsis shall
3199 // only be used in a parameter-declaration. Such a parameter-declaration
3200 // is a parameter pack (14.5.3). [...]
3201 switch (D.getContext()) {
3202 case Declarator::PrototypeContext:
3203 case Declarator::LambdaExprParameterContext:
3204 // C++0x [dcl.fct]p13:
3205 // [...] When it is part of a parameter-declaration-clause, the
3206 // parameter pack is a function parameter pack (14.5.3). The type T
3207 // of the declarator-id of the function parameter pack shall contain
3208 // a template parameter pack; each template parameter pack in T is
3209 // expanded by the function parameter pack.
3211 // We represent function parameter packs as function parameters whose
3212 // type is a pack expansion.
3213 if (!T->containsUnexpandedParameterPack()) {
3214 S.Diag(D.getEllipsisLoc(),
3215 diag::err_function_parameter_pack_without_parameter_packs)
3216 << T << D.getSourceRange();
3217 D.setEllipsisLoc(SourceLocation());
3219 T = Context.getPackExpansionType(T, None);
3222 case Declarator::TemplateParamContext:
3223 // C++0x [temp.param]p15:
3224 // If a template-parameter is a [...] is a parameter-declaration that
3225 // declares a parameter pack (8.3.5), then the template-parameter is a
3226 // template parameter pack (14.5.3).
3228 // Note: core issue 778 clarifies that, if there are any unexpanded
3229 // parameter packs in the type of the non-type template parameter, then
3230 // it expands those parameter packs.
3231 if (T->containsUnexpandedParameterPack())
3232 T = Context.getPackExpansionType(T, None);
3234 S.Diag(D.getEllipsisLoc(),
3235 LangOpts.CPlusPlus11
3236 ? diag::warn_cxx98_compat_variadic_templates
3237 : diag::ext_variadic_templates);
3240 case Declarator::FileContext:
3241 case Declarator::KNRTypeListContext:
3242 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3243 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
3244 case Declarator::TypeNameContext:
3245 case Declarator::CXXNewContext:
3246 case Declarator::AliasDeclContext:
3247 case Declarator::AliasTemplateContext:
3248 case Declarator::MemberContext:
3249 case Declarator::BlockContext:
3250 case Declarator::ForContext:
3251 case Declarator::ConditionContext:
3252 case Declarator::CXXCatchContext:
3253 case Declarator::ObjCCatchContext:
3254 case Declarator::BlockLiteralContext:
3255 case Declarator::LambdaExprContext:
3256 case Declarator::ConversionIdContext:
3257 case Declarator::TrailingReturnContext:
3258 case Declarator::TemplateTypeArgContext:
3259 // FIXME: We may want to allow parameter packs in block-literal contexts
3261 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
3262 D.setEllipsisLoc(SourceLocation());
3268 return Context.getNullTypeSourceInfo();
3269 else if (D.isInvalidType())
3270 return Context.getTrivialTypeSourceInfo(T);
3272 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3275 /// GetTypeForDeclarator - Convert the type for the specified
3276 /// declarator to Type instances.
3278 /// The result of this call will never be null, but the associated
3279 /// type may be a null type if there's an unrecoverable error.
3280 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3281 // Determine the type of the declarator. Not all forms of declarator
3284 TypeProcessingState state(*this, D);
3286 TypeSourceInfo *ReturnTypeInfo = 0;
3287 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3289 return Context.getNullTypeSourceInfo();
3291 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3292 inferARCWriteback(state, T);
3294 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3297 static void transferARCOwnershipToDeclSpec(Sema &S,
3298 QualType &declSpecTy,
3299 Qualifiers::ObjCLifetime ownership) {
3300 if (declSpecTy->isObjCRetainableType() &&
3301 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3303 qs.addObjCLifetime(ownership);
3304 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3308 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3309 Qualifiers::ObjCLifetime ownership,
3310 unsigned chunkIndex) {
3311 Sema &S = state.getSema();
3312 Declarator &D = state.getDeclarator();
3314 // Look for an explicit lifetime attribute.
3315 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3316 for (const AttributeList *attr = chunk.getAttrs(); attr;
3317 attr = attr->getNext())
3318 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3321 const char *attrStr = 0;
3322 switch (ownership) {
3323 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3324 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3325 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3326 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3327 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3330 IdentifierLoc *Arg = new (S.Context) IdentifierLoc;
3331 Arg->Ident = &S.Context.Idents.get(attrStr);
3332 Arg->Loc = SourceLocation();
3334 ArgsUnion Args(Arg);
3336 // If there wasn't one, add one (with an invalid source location
3337 // so that we don't make an AttributedType for it).
3338 AttributeList *attr = D.getAttributePool()
3339 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3340 /*scope*/ 0, SourceLocation(),
3341 /*args*/ &Args, 1, AttributeList::AS_GNU);
3342 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3344 // TODO: mark whether we did this inference?
3347 /// \brief Used for transferring ownership in casts resulting in l-values.
3348 static void transferARCOwnership(TypeProcessingState &state,
3349 QualType &declSpecTy,
3350 Qualifiers::ObjCLifetime ownership) {
3351 Sema &S = state.getSema();
3352 Declarator &D = state.getDeclarator();
3355 bool hasIndirection = false;
3356 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3357 DeclaratorChunk &chunk = D.getTypeObject(i);
3358 switch (chunk.Kind) {
3359 case DeclaratorChunk::Paren:
3363 case DeclaratorChunk::Array:
3364 case DeclaratorChunk::Reference:
3365 case DeclaratorChunk::Pointer:
3367 hasIndirection = true;
3371 case DeclaratorChunk::BlockPointer:
3373 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3376 case DeclaratorChunk::Function:
3377 case DeclaratorChunk::MemberPointer:
3385 DeclaratorChunk &chunk = D.getTypeObject(inner);
3386 if (chunk.Kind == DeclaratorChunk::Pointer) {
3387 if (declSpecTy->isObjCRetainableType())
3388 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3389 if (declSpecTy->isObjCObjectType() && hasIndirection)
3390 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3392 assert(chunk.Kind == DeclaratorChunk::Array ||
3393 chunk.Kind == DeclaratorChunk::Reference);
3394 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3398 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3399 TypeProcessingState state(*this, D);
3401 TypeSourceInfo *ReturnTypeInfo = 0;
3402 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3403 if (declSpecTy.isNull())
3404 return Context.getNullTypeSourceInfo();
3406 if (getLangOpts().ObjCAutoRefCount) {
3407 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3408 if (ownership != Qualifiers::OCL_None)
3409 transferARCOwnership(state, declSpecTy, ownership);
3412 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3415 /// Map an AttributedType::Kind to an AttributeList::Kind.
3416 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3418 case AttributedType::attr_address_space:
3419 return AttributeList::AT_AddressSpace;
3420 case AttributedType::attr_regparm:
3421 return AttributeList::AT_Regparm;
3422 case AttributedType::attr_vector_size:
3423 return AttributeList::AT_VectorSize;
3424 case AttributedType::attr_neon_vector_type:
3425 return AttributeList::AT_NeonVectorType;
3426 case AttributedType::attr_neon_polyvector_type:
3427 return AttributeList::AT_NeonPolyVectorType;
3428 case AttributedType::attr_objc_gc:
3429 return AttributeList::AT_ObjCGC;
3430 case AttributedType::attr_objc_ownership:
3431 return AttributeList::AT_ObjCOwnership;
3432 case AttributedType::attr_noreturn:
3433 return AttributeList::AT_NoReturn;
3434 case AttributedType::attr_cdecl:
3435 return AttributeList::AT_CDecl;
3436 case AttributedType::attr_fastcall:
3437 return AttributeList::AT_FastCall;
3438 case AttributedType::attr_stdcall:
3439 return AttributeList::AT_StdCall;
3440 case AttributedType::attr_thiscall:
3441 return AttributeList::AT_ThisCall;
3442 case AttributedType::attr_pascal:
3443 return AttributeList::AT_Pascal;
3444 case AttributedType::attr_pcs:
3445 case AttributedType::attr_pcs_vfp:
3446 return AttributeList::AT_Pcs;
3447 case AttributedType::attr_pnaclcall:
3448 return AttributeList::AT_PnaclCall;
3449 case AttributedType::attr_inteloclbicc:
3450 return AttributeList::AT_IntelOclBicc;
3451 case AttributedType::attr_ms_abi:
3452 return AttributeList::AT_MSABI;
3453 case AttributedType::attr_sysv_abi:
3454 return AttributeList::AT_SysVABI;
3455 case AttributedType::attr_ptr32:
3456 return AttributeList::AT_Ptr32;
3457 case AttributedType::attr_ptr64:
3458 return AttributeList::AT_Ptr64;
3459 case AttributedType::attr_sptr:
3460 return AttributeList::AT_SPtr;
3461 case AttributedType::attr_uptr:
3462 return AttributeList::AT_UPtr;
3464 llvm_unreachable("unexpected attribute kind!");
3467 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3468 const AttributeList *attrs) {
3469 AttributedType::Kind kind = TL.getAttrKind();
3471 assert(attrs && "no type attributes in the expected location!");
3472 AttributeList::Kind parsedKind = getAttrListKind(kind);
3473 while (attrs->getKind() != parsedKind) {
3474 attrs = attrs->getNext();
3475 assert(attrs && "no matching attribute in expected location!");
3478 TL.setAttrNameLoc(attrs->getLoc());
3479 if (TL.hasAttrExprOperand() && attrs->isArgExpr(0))
3480 TL.setAttrExprOperand(attrs->getArgAsExpr(0));
3481 else if (TL.hasAttrEnumOperand() && attrs->isArgIdent(0))
3482 TL.setAttrEnumOperandLoc(attrs->getArgAsIdent(0)->Loc);
3484 // FIXME: preserve this information to here.
3485 if (TL.hasAttrOperand())
3486 TL.setAttrOperandParensRange(SourceRange());
3490 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3491 ASTContext &Context;
3495 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3496 : Context(Context), DS(DS) {}
3498 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3499 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3500 Visit(TL.getModifiedLoc());
3502 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3503 Visit(TL.getUnqualifiedLoc());
3505 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3506 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3508 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3509 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3510 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3511 // addition field. What we have is good enough for dispay of location
3512 // of 'fixit' on interface name.
3513 TL.setNameEndLoc(DS.getLocEnd());
3515 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3516 // Handle the base type, which might not have been written explicitly.
3517 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3518 TL.setHasBaseTypeAsWritten(false);
3519 TL.getBaseLoc().initialize(Context, SourceLocation());
3521 TL.setHasBaseTypeAsWritten(true);
3522 Visit(TL.getBaseLoc());
3525 // Protocol qualifiers.
3526 if (DS.getProtocolQualifiers()) {
3527 assert(TL.getNumProtocols() > 0);
3528 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3529 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3530 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3531 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3532 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3534 assert(TL.getNumProtocols() == 0);
3535 TL.setLAngleLoc(SourceLocation());
3536 TL.setRAngleLoc(SourceLocation());
3539 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3540 TL.setStarLoc(SourceLocation());
3541 Visit(TL.getPointeeLoc());
3543 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3544 TypeSourceInfo *TInfo = 0;
3545 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3547 // If we got no declarator info from previous Sema routines,
3548 // just fill with the typespec loc.
3550 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3554 TypeLoc OldTL = TInfo->getTypeLoc();
3555 if (TInfo->getType()->getAs<ElaboratedType>()) {
3556 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3557 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3558 .castAs<TemplateSpecializationTypeLoc>();
3561 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3562 assert(TL.getRAngleLoc() == OldTL.castAs<TemplateSpecializationTypeLoc>().getRAngleLoc());
3566 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3567 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3568 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3569 TL.setParensRange(DS.getTypeofParensRange());
3571 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3572 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3573 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3574 TL.setParensRange(DS.getTypeofParensRange());
3575 assert(DS.getRepAsType());
3576 TypeSourceInfo *TInfo = 0;
3577 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3578 TL.setUnderlyingTInfo(TInfo);
3580 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3581 // FIXME: This holds only because we only have one unary transform.
3582 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3583 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3584 TL.setParensRange(DS.getTypeofParensRange());
3585 assert(DS.getRepAsType());
3586 TypeSourceInfo *TInfo = 0;
3587 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3588 TL.setUnderlyingTInfo(TInfo);
3590 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3591 // By default, use the source location of the type specifier.
3592 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3593 if (TL.needsExtraLocalData()) {
3594 // Set info for the written builtin specifiers.
3595 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3596 // Try to have a meaningful source location.
3597 if (TL.getWrittenSignSpec() != TSS_unspecified)
3598 // Sign spec loc overrides the others (e.g., 'unsigned long').
3599 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3600 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3601 // Width spec loc overrides type spec loc (e.g., 'short int').
3602 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3605 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3606 ElaboratedTypeKeyword Keyword
3607 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3608 if (DS.getTypeSpecType() == TST_typename) {
3609 TypeSourceInfo *TInfo = 0;
3610 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3612 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3616 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3617 ? DS.getTypeSpecTypeLoc()
3618 : SourceLocation());
3619 const CXXScopeSpec& SS = DS.getTypeSpecScope();
3620 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3621 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3623 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3624 assert(DS.getTypeSpecType() == TST_typename);
3625 TypeSourceInfo *TInfo = 0;
3626 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3628 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3630 void VisitDependentTemplateSpecializationTypeLoc(
3631 DependentTemplateSpecializationTypeLoc TL) {
3632 assert(DS.getTypeSpecType() == TST_typename);
3633 TypeSourceInfo *TInfo = 0;
3634 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3637 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3639 void VisitTagTypeLoc(TagTypeLoc TL) {
3640 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3642 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3643 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3644 // or an _Atomic qualifier.
3645 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3646 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3647 TL.setParensRange(DS.getTypeofParensRange());
3649 TypeSourceInfo *TInfo = 0;
3650 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3652 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3654 TL.setKWLoc(DS.getAtomicSpecLoc());
3655 // No parens, to indicate this was spelled as an _Atomic qualifier.
3656 TL.setParensRange(SourceRange());
3657 Visit(TL.getValueLoc());
3661 void VisitTypeLoc(TypeLoc TL) {
3662 // FIXME: add other typespec types and change this to an assert.
3663 TL.initialize(Context, DS.getTypeSpecTypeLoc());
3667 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3668 ASTContext &Context;
3669 const DeclaratorChunk &Chunk;
3672 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3673 : Context(Context), Chunk(Chunk) {}
3675 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3676 llvm_unreachable("qualified type locs not expected here!");
3678 void VisitDecayedTypeLoc(DecayedTypeLoc TL) {
3679 llvm_unreachable("decayed type locs not expected here!");
3682 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3683 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3685 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3686 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3687 TL.setCaretLoc(Chunk.Loc);
3689 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3690 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3691 TL.setStarLoc(Chunk.Loc);
3693 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3694 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3695 TL.setStarLoc(Chunk.Loc);
3697 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3698 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3699 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3700 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3702 const Type* ClsTy = TL.getClass();
3703 QualType ClsQT = QualType(ClsTy, 0);
3704 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3705 // Now copy source location info into the type loc component.
3706 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3707 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3708 case NestedNameSpecifier::Identifier:
3709 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3711 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3712 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3713 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3714 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3718 case NestedNameSpecifier::TypeSpec:
3719 case NestedNameSpecifier::TypeSpecWithTemplate:
3720 if (isa<ElaboratedType>(ClsTy)) {
3721 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3722 ETLoc.setElaboratedKeywordLoc(SourceLocation());
3723 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3724 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3725 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3727 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3731 case NestedNameSpecifier::Namespace:
3732 case NestedNameSpecifier::NamespaceAlias:
3733 case NestedNameSpecifier::Global:
3734 llvm_unreachable("Nested-name-specifier must name a type");
3737 // Finally fill in MemberPointerLocInfo fields.
3738 TL.setStarLoc(Chunk.Loc);
3739 TL.setClassTInfo(ClsTInfo);
3741 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3742 assert(Chunk.Kind == DeclaratorChunk::Reference);
3743 // 'Amp' is misleading: this might have been originally
3744 /// spelled with AmpAmp.
3745 TL.setAmpLoc(Chunk.Loc);
3747 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3748 assert(Chunk.Kind == DeclaratorChunk::Reference);
3749 assert(!Chunk.Ref.LValueRef);
3750 TL.setAmpAmpLoc(Chunk.Loc);
3752 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3753 assert(Chunk.Kind == DeclaratorChunk::Array);
3754 TL.setLBracketLoc(Chunk.Loc);
3755 TL.setRBracketLoc(Chunk.EndLoc);
3756 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3758 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3759 assert(Chunk.Kind == DeclaratorChunk::Function);
3760 TL.setLocalRangeBegin(Chunk.Loc);
3761 TL.setLocalRangeEnd(Chunk.EndLoc);
3763 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3764 TL.setLParenLoc(FTI.getLParenLoc());
3765 TL.setRParenLoc(FTI.getRParenLoc());
3766 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3767 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3768 TL.setArg(tpi++, Param);
3770 // FIXME: exception specs
3772 void VisitParenTypeLoc(ParenTypeLoc TL) {
3773 assert(Chunk.Kind == DeclaratorChunk::Paren);
3774 TL.setLParenLoc(Chunk.Loc);
3775 TL.setRParenLoc(Chunk.EndLoc);
3778 void VisitTypeLoc(TypeLoc TL) {
3779 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3784 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3786 switch (Chunk.Kind) {
3787 case DeclaratorChunk::Function:
3788 case DeclaratorChunk::Array:
3789 case DeclaratorChunk::Paren:
3790 llvm_unreachable("cannot be _Atomic qualified");
3792 case DeclaratorChunk::Pointer:
3793 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3796 case DeclaratorChunk::BlockPointer:
3797 case DeclaratorChunk::Reference:
3798 case DeclaratorChunk::MemberPointer:
3799 // FIXME: Provide a source location for the _Atomic keyword.
3804 ATL.setParensRange(SourceRange());
3807 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3809 /// \param T QualType referring to the type as written in source code.
3811 /// \param ReturnTypeInfo For declarators whose return type does not show
3812 /// up in the normal place in the declaration specifiers (such as a C++
3813 /// conversion function), this pointer will refer to a type source information
3814 /// for that return type.
3816 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3817 TypeSourceInfo *ReturnTypeInfo) {
3818 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3819 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3821 // Handle parameter packs whose type is a pack expansion.
3822 if (isa<PackExpansionType>(T)) {
3823 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3824 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3827 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3828 // An AtomicTypeLoc might be produced by an atomic qualifier in this
3829 // declarator chunk.
3830 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3831 fillAtomicQualLoc(ATL, D.getTypeObject(i));
3832 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3835 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3836 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3837 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3840 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3841 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3844 // If we have different source information for the return type, use
3845 // that. This really only applies to C++ conversion functions.
3846 if (ReturnTypeInfo) {
3847 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3848 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3849 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3851 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3857 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3858 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3859 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3860 // and Sema during declaration parsing. Try deallocating/caching them when
3861 // it's appropriate, instead of allocating them and keeping them around.
3862 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3864 new (LocT) LocInfoType(T, TInfo);
3865 assert(LocT->getTypeClass() != T->getTypeClass() &&
3866 "LocInfoType's TypeClass conflicts with an existing Type class");
3867 return ParsedType::make(QualType(LocT, 0));
3870 void LocInfoType::getAsStringInternal(std::string &Str,
3871 const PrintingPolicy &Policy) const {
3872 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3873 " was used directly instead of getting the QualType through"
3874 " GetTypeFromParser");
3877 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3878 // C99 6.7.6: Type names have no identifier. This is already validated by
3880 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3882 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3883 QualType T = TInfo->getType();
3884 if (D.isInvalidType())
3887 // Make sure there are no unused decl attributes on the declarator.
3888 // We don't want to do this for ObjC parameters because we're going
3889 // to apply them to the actual parameter declaration.
3890 // Likewise, we don't want to do this for alias declarations, because
3891 // we are actually going to build a declaration from this eventually.
3892 if (D.getContext() != Declarator::ObjCParameterContext &&
3893 D.getContext() != Declarator::AliasDeclContext &&
3894 D.getContext() != Declarator::AliasTemplateContext)
3895 checkUnusedDeclAttributes(D);
3897 if (getLangOpts().CPlusPlus) {
3898 // Check that there are no default arguments (C++ only).
3899 CheckExtraCXXDefaultArguments(D);
3902 return CreateParsedType(T, TInfo);
3905 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3906 QualType T = Context.getObjCInstanceType();
3907 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3908 return CreateParsedType(T, TInfo);
3912 //===----------------------------------------------------------------------===//
3913 // Type Attribute Processing
3914 //===----------------------------------------------------------------------===//
3916 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3917 /// specified type. The attribute contains 1 argument, the id of the address
3918 /// space for the type.
3919 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3920 const AttributeList &Attr, Sema &S){
3922 // If this type is already address space qualified, reject it.
3923 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3924 // qualifiers for two or more different address spaces."
3925 if (Type.getAddressSpace()) {
3926 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3931 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3932 // qualified by an address-space qualifier."
3933 if (Type->isFunctionType()) {
3934 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3939 // Check the attribute arguments.
3940 if (Attr.getNumArgs() != 1) {
3941 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
3942 << Attr.getName() << 1;
3946 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
3947 llvm::APSInt addrSpace(32);
3948 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3949 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3950 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
3951 << Attr.getName() << AANT_ArgumentIntegerConstant
3952 << ASArgExpr->getSourceRange();
3958 if (addrSpace.isSigned()) {
3959 if (addrSpace.isNegative()) {
3960 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3961 << ASArgExpr->getSourceRange();
3965 addrSpace.setIsSigned(false);
3967 llvm::APSInt max(addrSpace.getBitWidth());
3968 max = Qualifiers::MaxAddressSpace;
3969 if (addrSpace > max) {
3970 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3971 << int(Qualifiers::MaxAddressSpace) << ASArgExpr->getSourceRange();
3976 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3977 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3980 /// Does this type have a "direct" ownership qualifier? That is,
3981 /// is it written like "__strong id", as opposed to something like
3982 /// "typeof(foo)", where that happens to be strong?
3983 static bool hasDirectOwnershipQualifier(QualType type) {
3984 // Fast path: no qualifier at all.
3985 assert(type.getQualifiers().hasObjCLifetime());
3989 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3990 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3993 type = attr->getModifiedType();
3995 // X *__strong (...)
3996 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3997 type = paren->getInnerType();
3999 // That's it for things we want to complain about. In particular,
4000 // we do not want to look through typedefs, typeof(expr),
4001 // typeof(type), or any other way that the type is somehow
4010 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
4011 /// attribute on the specified type.
4013 /// Returns 'true' if the attribute was handled.
4014 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
4015 AttributeList &attr,
4017 bool NonObjCPointer = false;
4019 if (!type->isDependentType() && !type->isUndeducedType()) {
4020 if (const PointerType *ptr = type->getAs<PointerType>()) {
4021 QualType pointee = ptr->getPointeeType();
4022 if (pointee->isObjCRetainableType() || pointee->isPointerType())
4024 // It is important not to lose the source info that there was an attribute
4025 // applied to non-objc pointer. We will create an attributed type but
4026 // its type will be the same as the original type.
4027 NonObjCPointer = true;
4028 } else if (!type->isObjCRetainableType()) {
4032 // Don't accept an ownership attribute in the declspec if it would
4033 // just be the return type of a block pointer.
4034 if (state.isProcessingDeclSpec()) {
4035 Declarator &D = state.getDeclarator();
4036 if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
4041 Sema &S = state.getSema();
4042 SourceLocation AttrLoc = attr.getLoc();
4043 if (AttrLoc.isMacroID())
4044 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
4046 if (!attr.isArgIdent(0)) {
4047 S.Diag(AttrLoc, diag::err_attribute_argument_type)
4048 << attr.getName() << AANT_ArgumentString;
4053 // Consume lifetime attributes without further comment outside of
4055 if (!S.getLangOpts().ObjCAutoRefCount)
4058 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4059 Qualifiers::ObjCLifetime lifetime;
4060 if (II->isStr("none"))
4061 lifetime = Qualifiers::OCL_ExplicitNone;
4062 else if (II->isStr("strong"))
4063 lifetime = Qualifiers::OCL_Strong;
4064 else if (II->isStr("weak"))
4065 lifetime = Qualifiers::OCL_Weak;
4066 else if (II->isStr("autoreleasing"))
4067 lifetime = Qualifiers::OCL_Autoreleasing;
4069 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
4070 << attr.getName() << II;
4075 SplitQualType underlyingType = type.split();
4077 // Check for redundant/conflicting ownership qualifiers.
4078 if (Qualifiers::ObjCLifetime previousLifetime
4079 = type.getQualifiers().getObjCLifetime()) {
4080 // If it's written directly, that's an error.
4081 if (hasDirectOwnershipQualifier(type)) {
4082 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
4087 // Otherwise, if the qualifiers actually conflict, pull sugar off
4088 // until we reach a type that is directly qualified.
4089 if (previousLifetime != lifetime) {
4090 // This should always terminate: the canonical type is
4091 // qualified, so some bit of sugar must be hiding it.
4092 while (!underlyingType.Quals.hasObjCLifetime()) {
4093 underlyingType = underlyingType.getSingleStepDesugaredType();
4095 underlyingType.Quals.removeObjCLifetime();
4099 underlyingType.Quals.addObjCLifetime(lifetime);
4101 if (NonObjCPointer) {
4102 StringRef name = attr.getName()->getName();
4104 case Qualifiers::OCL_None:
4105 case Qualifiers::OCL_ExplicitNone:
4107 case Qualifiers::OCL_Strong: name = "__strong"; break;
4108 case Qualifiers::OCL_Weak: name = "__weak"; break;
4109 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
4111 S.Diag(AttrLoc, diag::warn_type_attribute_wrong_type) << name
4112 << TDS_ObjCObjOrBlock << type;
4115 QualType origType = type;
4116 if (!NonObjCPointer)
4117 type = S.Context.getQualifiedType(underlyingType);
4119 // If we have a valid source location for the attribute, use an
4120 // AttributedType instead.
4121 if (AttrLoc.isValid())
4122 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
4125 // Forbid __weak if the runtime doesn't support it.
4126 if (lifetime == Qualifiers::OCL_Weak &&
4127 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
4129 // Actually, delay this until we know what we're parsing.
4130 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
4131 S.DelayedDiagnostics.add(
4132 sema::DelayedDiagnostic::makeForbiddenType(
4133 S.getSourceManager().getExpansionLoc(AttrLoc),
4134 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
4136 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
4143 // Forbid __weak for class objects marked as
4144 // objc_arc_weak_reference_unavailable
4145 if (lifetime == Qualifiers::OCL_Weak) {
4146 if (const ObjCObjectPointerType *ObjT =
4147 type->getAs<ObjCObjectPointerType>()) {
4148 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
4149 if (Class->isArcWeakrefUnavailable()) {
4150 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
4151 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
4152 diag::note_class_declared);
4161 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
4162 /// attribute on the specified type. Returns true to indicate that
4163 /// the attribute was handled, false to indicate that the type does
4164 /// not permit the attribute.
4165 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4166 AttributeList &attr,
4168 Sema &S = state.getSema();
4170 // Delay if this isn't some kind of pointer.
4171 if (!type->isPointerType() &&
4172 !type->isObjCObjectPointerType() &&
4173 !type->isBlockPointerType())
4176 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4177 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4182 // Check the attribute arguments.
4183 if (!attr.isArgIdent(0)) {
4184 S.Diag(attr.getLoc(), diag::err_attribute_argument_type)
4185 << attr.getName() << AANT_ArgumentString;
4189 Qualifiers::GC GCAttr;
4190 if (attr.getNumArgs() > 1) {
4191 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4192 << attr.getName() << 1;
4197 IdentifierInfo *II = attr.getArgAsIdent(0)->Ident;
4198 if (II->isStr("weak"))
4199 GCAttr = Qualifiers::Weak;
4200 else if (II->isStr("strong"))
4201 GCAttr = Qualifiers::Strong;
4203 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4204 << attr.getName() << II;
4209 QualType origType = type;
4210 type = S.Context.getObjCGCQualType(origType, GCAttr);
4212 // Make an attributed type to preserve the source information.
4213 if (attr.getLoc().isValid())
4214 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4221 /// A helper class to unwrap a type down to a function for the
4222 /// purposes of applying attributes there.
4225 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
4226 /// if (unwrapped.isFunctionType()) {
4227 /// const FunctionType *fn = unwrapped.get();
4228 /// // change fn somehow
4229 /// T = unwrapped.wrap(fn);
4231 struct FunctionTypeUnwrapper {
4242 const FunctionType *Fn;
4243 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4245 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4247 const Type *Ty = T.getTypePtr();
4248 if (isa<FunctionType>(Ty)) {
4249 Fn = cast<FunctionType>(Ty);
4251 } else if (isa<ParenType>(Ty)) {
4252 T = cast<ParenType>(Ty)->getInnerType();
4253 Stack.push_back(Parens);
4254 } else if (isa<PointerType>(Ty)) {
4255 T = cast<PointerType>(Ty)->getPointeeType();
4256 Stack.push_back(Pointer);
4257 } else if (isa<BlockPointerType>(Ty)) {
4258 T = cast<BlockPointerType>(Ty)->getPointeeType();
4259 Stack.push_back(BlockPointer);
4260 } else if (isa<MemberPointerType>(Ty)) {
4261 T = cast<MemberPointerType>(Ty)->getPointeeType();
4262 Stack.push_back(MemberPointer);
4263 } else if (isa<ReferenceType>(Ty)) {
4264 T = cast<ReferenceType>(Ty)->getPointeeType();
4265 Stack.push_back(Reference);
4267 const Type *DTy = Ty->getUnqualifiedDesugaredType();
4273 T = QualType(DTy, 0);
4274 Stack.push_back(Desugar);
4279 bool isFunctionType() const { return (Fn != 0); }
4280 const FunctionType *get() const { return Fn; }
4282 QualType wrap(Sema &S, const FunctionType *New) {
4283 // If T wasn't modified from the unwrapped type, do nothing.
4284 if (New == get()) return Original;
4287 return wrap(S.Context, Original, 0);
4291 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4292 if (I == Stack.size())
4293 return C.getQualifiedType(Fn, Old.getQualifiers());
4295 // Build up the inner type, applying the qualifiers from the old
4296 // type to the new type.
4297 SplitQualType SplitOld = Old.split();
4299 // As a special case, tail-recurse if there are no qualifiers.
4300 if (SplitOld.Quals.empty())
4301 return wrap(C, SplitOld.Ty, I);
4302 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4305 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4306 if (I == Stack.size()) return QualType(Fn, 0);
4308 switch (static_cast<WrapKind>(Stack[I++])) {
4310 // This is the point at which we potentially lose source
4312 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4315 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4316 return C.getParenType(New);
4320 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4321 return C.getPointerType(New);
4324 case BlockPointer: {
4325 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4326 return C.getBlockPointerType(New);
4329 case MemberPointer: {
4330 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4331 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4332 return C.getMemberPointerType(New, OldMPT->getClass());
4336 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4337 QualType New = wrap(C, OldRef->getPointeeType(), I);
4338 if (isa<LValueReferenceType>(OldRef))
4339 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4341 return C.getRValueReferenceType(New);
4345 llvm_unreachable("unknown wrapping kind");
4350 static bool handleMSPointerTypeQualifierAttr(TypeProcessingState &State,
4351 AttributeList &Attr,
4353 Sema &S = State.getSema();
4355 AttributeList::Kind Kind = Attr.getKind();
4356 QualType Desugared = Type;
4357 const AttributedType *AT = dyn_cast<AttributedType>(Type);
4359 AttributedType::Kind CurAttrKind = AT->getAttrKind();
4361 // You cannot specify duplicate type attributes, so if the attribute has
4362 // already been applied, flag it.
4363 if (getAttrListKind(CurAttrKind) == Kind) {
4364 S.Diag(Attr.getLoc(), diag::warn_duplicate_attribute_exact)
4369 // You cannot have both __sptr and __uptr on the same type, nor can you
4370 // have __ptr32 and __ptr64.
4371 if ((CurAttrKind == AttributedType::attr_ptr32 &&
4372 Kind == AttributeList::AT_Ptr64) ||
4373 (CurAttrKind == AttributedType::attr_ptr64 &&
4374 Kind == AttributeList::AT_Ptr32)) {
4375 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4376 << "'__ptr32'" << "'__ptr64'";
4378 } else if ((CurAttrKind == AttributedType::attr_sptr &&
4379 Kind == AttributeList::AT_UPtr) ||
4380 (CurAttrKind == AttributedType::attr_uptr &&
4381 Kind == AttributeList::AT_SPtr)) {
4382 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible)
4383 << "'__sptr'" << "'__uptr'";
4387 Desugared = AT->getEquivalentType();
4388 AT = dyn_cast<AttributedType>(Desugared);
4391 // Pointer type qualifiers can only operate on pointer types, but not
4392 // pointer-to-member types.
4393 if (!isa<PointerType>(Desugared)) {
4394 S.Diag(Attr.getLoc(), Type->isMemberPointerType() ?
4395 diag::err_attribute_no_member_pointers :
4396 diag::err_attribute_pointers_only) << Attr.getName();
4400 AttributedType::Kind TAK;
4402 default: llvm_unreachable("Unknown attribute kind");
4403 case AttributeList::AT_Ptr32: TAK = AttributedType::attr_ptr32; break;
4404 case AttributeList::AT_Ptr64: TAK = AttributedType::attr_ptr64; break;
4405 case AttributeList::AT_SPtr: TAK = AttributedType::attr_sptr; break;
4406 case AttributeList::AT_UPtr: TAK = AttributedType::attr_uptr; break;
4409 Type = S.Context.getAttributedType(TAK, Type, Type);
4413 static AttributedType::Kind getCCTypeAttrKind(AttributeList &Attr) {
4414 assert(!Attr.isInvalid());
4415 switch (Attr.getKind()) {
4417 llvm_unreachable("not a calling convention attribute");
4418 case AttributeList::AT_CDecl:
4419 return AttributedType::attr_cdecl;
4420 case AttributeList::AT_FastCall:
4421 return AttributedType::attr_fastcall;
4422 case AttributeList::AT_StdCall:
4423 return AttributedType::attr_stdcall;
4424 case AttributeList::AT_ThisCall:
4425 return AttributedType::attr_thiscall;
4426 case AttributeList::AT_Pascal:
4427 return AttributedType::attr_pascal;
4428 case AttributeList::AT_Pcs: {
4429 // The attribute may have had a fixit applied where we treated an
4430 // identifier as a string literal. The contents of the string are valid,
4431 // but the form may not be.
4433 if (Attr.isArgExpr(0))
4434 Str = cast<StringLiteral>(Attr.getArgAsExpr(0))->getString();
4436 Str = Attr.getArgAsIdent(0)->Ident->getName();
4437 return llvm::StringSwitch<AttributedType::Kind>(Str)
4438 .Case("aapcs", AttributedType::attr_pcs)
4439 .Case("aapcs-vfp", AttributedType::attr_pcs_vfp);
4441 case AttributeList::AT_PnaclCall:
4442 return AttributedType::attr_pnaclcall;
4443 case AttributeList::AT_IntelOclBicc:
4444 return AttributedType::attr_inteloclbicc;
4445 case AttributeList::AT_MSABI:
4446 return AttributedType::attr_ms_abi;
4447 case AttributeList::AT_SysVABI:
4448 return AttributedType::attr_sysv_abi;
4450 llvm_unreachable("unexpected attribute kind!");
4453 /// Process an individual function attribute. Returns true to
4454 /// indicate that the attribute was handled, false if it wasn't.
4455 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4456 AttributeList &attr,
4458 Sema &S = state.getSema();
4460 FunctionTypeUnwrapper unwrapped(S, type);
4462 if (attr.getKind() == AttributeList::AT_NoReturn) {
4463 if (S.CheckNoReturnAttr(attr))
4466 // Delay if this is not a function type.
4467 if (!unwrapped.isFunctionType())
4470 // Otherwise we can process right away.
4471 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4472 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4476 // ns_returns_retained is not always a type attribute, but if we got
4477 // here, we're treating it as one right now.
4478 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4479 assert(S.getLangOpts().ObjCAutoRefCount &&
4480 "ns_returns_retained treated as type attribute in non-ARC");
4481 if (attr.getNumArgs()) return true;
4483 // Delay if this is not a function type.
4484 if (!unwrapped.isFunctionType())
4487 FunctionType::ExtInfo EI
4488 = unwrapped.get()->getExtInfo().withProducesResult(true);
4489 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4493 if (attr.getKind() == AttributeList::AT_Regparm) {
4495 if (S.CheckRegparmAttr(attr, value))
4498 // Delay if this is not a function type.
4499 if (!unwrapped.isFunctionType())
4502 // Diagnose regparm with fastcall.
4503 const FunctionType *fn = unwrapped.get();
4504 CallingConv CC = fn->getCallConv();
4505 if (CC == CC_X86FastCall) {
4506 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4507 << FunctionType::getNameForCallConv(CC)
4513 FunctionType::ExtInfo EI =
4514 unwrapped.get()->getExtInfo().withRegParm(value);
4515 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4519 // Delay if the type didn't work out to a function.
4520 if (!unwrapped.isFunctionType()) return false;
4522 // Otherwise, a calling convention.
4524 if (S.CheckCallingConvAttr(attr, CC))
4527 const FunctionType *fn = unwrapped.get();
4528 CallingConv CCOld = fn->getCallConv();
4529 AttributedType::Kind CCAttrKind = getCCTypeAttrKind(attr);
4532 // Error out on when there's already an attribute on the type
4533 // and the CCs don't match.
4534 const AttributedType *AT = S.getCallingConvAttributedType(type);
4535 if (AT && AT->getAttrKind() != CCAttrKind) {
4536 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4537 << FunctionType::getNameForCallConv(CC)
4538 << FunctionType::getNameForCallConv(CCOld);
4544 // Diagnose use of callee-cleanup calling convention on variadic functions.
4545 if (isCalleeCleanup(CC)) {
4546 const FunctionProtoType *FnP = dyn_cast<FunctionProtoType>(fn);
4547 if (FnP && FnP->isVariadic()) {
4548 unsigned DiagID = diag::err_cconv_varargs;
4549 // stdcall and fastcall are ignored with a warning for GCC and MS
4551 if (CC == CC_X86StdCall || CC == CC_X86FastCall)
4552 DiagID = diag::warn_cconv_varargs;
4554 S.Diag(attr.getLoc(), DiagID) << FunctionType::getNameForCallConv(CC);
4560 // Diagnose the use of X86 fastcall on unprototyped functions.
4561 if (CC == CC_X86FastCall) {
4562 if (isa<FunctionNoProtoType>(fn)) {
4563 S.Diag(attr.getLoc(), diag::err_cconv_knr)
4564 << FunctionType::getNameForCallConv(CC);
4569 // Also diagnose fastcall with regparm.
4570 if (fn->getHasRegParm()) {
4571 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4573 << FunctionType::getNameForCallConv(CC);
4579 // Modify the CC from the wrapped function type, wrap it all back, and then
4580 // wrap the whole thing in an AttributedType as written. The modified type
4581 // might have a different CC if we ignored the attribute.
4582 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4583 QualType Equivalent =
4584 unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4585 type = S.Context.getAttributedType(CCAttrKind, type, Equivalent);
4589 void Sema::adjustMemberFunctionCC(QualType &T, bool IsStatic) {
4590 const FunctionType *FT = T->castAs<FunctionType>();
4591 bool IsVariadic = (isa<FunctionProtoType>(FT) &&
4592 cast<FunctionProtoType>(FT)->isVariadic());
4593 CallingConv CC = FT->getCallConv();
4595 // Only adjust types with the default convention. For example, on Windows we
4596 // should adjust a __cdecl type to __thiscall for instance methods, and a
4597 // __thiscall type to __cdecl for static methods.
4598 CallingConv DefaultCC =
4599 Context.getDefaultCallingConvention(IsVariadic, IsStatic);
4600 if (CC != DefaultCC)
4603 // Check if there was an explicit attribute, but only look through parens.
4604 // The intent is to look for an attribute on the current declarator, but not
4605 // one that came from a typedef.
4606 QualType R = T.IgnoreParens();
4607 while (const AttributedType *AT = dyn_cast<AttributedType>(R)) {
4608 if (AT->isCallingConv())
4610 R = AT->getModifiedType().IgnoreParens();
4613 // FIXME: This loses sugar. This should probably be fixed with an implicit
4614 // AttributedType node that adjusts the convention.
4615 CC = Context.getDefaultCallingConvention(IsVariadic, !IsStatic);
4616 FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC));
4617 FunctionTypeUnwrapper Unwrapped(*this, T);
4618 T = Unwrapped.wrap(*this, FT);
4621 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4622 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4623 const AttributeList &Attr,
4625 // Check the attribute arguments.
4626 if (Attr.getNumArgs() != 1) {
4627 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4628 << Attr.getName() << 1;
4632 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4633 llvm::APSInt arg(32);
4634 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4635 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4636 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4637 << Attr.getName() << AANT_ArgumentIntegerConstant
4638 << sizeExpr->getSourceRange();
4642 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4644 case CLIA_read_only:
4645 case CLIA_write_only:
4646 case CLIA_read_write:
4647 // Implemented in a separate patch
4650 // Implemented in a separate patch
4651 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4652 << sizeExpr->getSourceRange();
4658 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4659 /// and float scalars, although arrays, pointers, and function return values are
4660 /// allowed in conjunction with this construct. Aggregates with this attribute
4661 /// are invalid, even if they are of the same size as a corresponding scalar.
4662 /// The raw attribute should contain precisely 1 argument, the vector size for
4663 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4664 /// this routine will return a new vector type.
4665 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4667 // Check the attribute arguments.
4668 if (Attr.getNumArgs() != 1) {
4669 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4670 << Attr.getName() << 1;
4674 Expr *sizeExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4675 llvm::APSInt vecSize(32);
4676 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4677 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4678 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4679 << Attr.getName() << AANT_ArgumentIntegerConstant
4680 << sizeExpr->getSourceRange();
4684 // The base type must be integer (not Boolean or enumeration) or float, and
4685 // can't already be a vector.
4686 if (!CurType->isBuiltinType() || CurType->isBooleanType() ||
4687 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) {
4688 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4692 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4693 // vecSize is specified in bytes - convert to bits.
4694 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4696 // the vector size needs to be an integral multiple of the type size.
4697 if (vectorSize % typeSize) {
4698 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4699 << sizeExpr->getSourceRange();
4703 if (VectorType::isVectorSizeTooLarge(vectorSize / typeSize)) {
4704 S.Diag(Attr.getLoc(), diag::err_attribute_size_too_large)
4705 << sizeExpr->getSourceRange();
4709 if (vectorSize == 0) {
4710 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4711 << sizeExpr->getSourceRange();
4716 // Success! Instantiate the vector type, the number of elements is > 0, and
4717 // not required to be a power of 2, unlike GCC.
4718 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4719 VectorType::GenericVector);
4722 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4724 static void HandleExtVectorTypeAttr(QualType &CurType,
4725 const AttributeList &Attr,
4727 // check the attribute arguments.
4728 if (Attr.getNumArgs() != 1) {
4729 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4730 << Attr.getName() << 1;
4736 // Special case where the argument is a template id.
4737 if (Attr.isArgIdent(0)) {
4739 SourceLocation TemplateKWLoc;
4741 id.setIdentifier(Attr.getArgAsIdent(0)->Ident, Attr.getLoc());
4743 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4745 if (Size.isInvalid())
4748 sizeExpr = Size.get();
4750 sizeExpr = Attr.getArgAsExpr(0);
4753 // Create the vector type.
4754 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4759 static bool isPermittedNeonBaseType(QualType &Ty,
4760 VectorType::VectorKind VecKind,
4762 const BuiltinType *BTy = Ty->getAs<BuiltinType>();
4766 if (VecKind == VectorType::NeonPolyVector) {
4768 // AArch64 polynomial vectors are unsigned and support poly64.
4769 return BTy->getKind() == BuiltinType::UChar ||
4770 BTy->getKind() == BuiltinType::UShort ||
4771 BTy->getKind() == BuiltinType::ULongLong;
4773 // AArch32 polynomial vector are signed.
4774 return BTy->getKind() == BuiltinType::SChar ||
4775 BTy->getKind() == BuiltinType::Short;
4779 // Non-polynomial vector types: the usual suspects are allowed, as well as
4780 // float64_t on AArch64.
4781 if (IsAArch64 && BTy->getKind() == BuiltinType::Double)
4784 return BTy->getKind() == BuiltinType::SChar ||
4785 BTy->getKind() == BuiltinType::UChar ||
4786 BTy->getKind() == BuiltinType::Short ||
4787 BTy->getKind() == BuiltinType::UShort ||
4788 BTy->getKind() == BuiltinType::Int ||
4789 BTy->getKind() == BuiltinType::UInt ||
4790 BTy->getKind() == BuiltinType::LongLong ||
4791 BTy->getKind() == BuiltinType::ULongLong ||
4792 BTy->getKind() == BuiltinType::Float ||
4793 BTy->getKind() == BuiltinType::Half;
4796 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4797 /// "neon_polyvector_type" attributes are used to create vector types that
4798 /// are mangled according to ARM's ABI. Otherwise, these types are identical
4799 /// to those created with the "vector_size" attribute. Unlike "vector_size"
4800 /// the argument to these Neon attributes is the number of vector elements,
4801 /// not the vector size in bytes. The vector width and element type must
4802 /// match one of the standard Neon vector types.
4803 static void HandleNeonVectorTypeAttr(QualType& CurType,
4804 const AttributeList &Attr, Sema &S,
4805 VectorType::VectorKind VecKind) {
4806 // Target must have NEON
4807 if (!S.Context.getTargetInfo().hasFeature("neon")) {
4808 S.Diag(Attr.getLoc(), diag::err_attribute_unsupported) << Attr.getName();
4812 // Check the attribute arguments.
4813 if (Attr.getNumArgs() != 1) {
4814 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments)
4815 << Attr.getName() << 1;
4819 // The number of elements must be an ICE.
4820 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArgAsExpr(0));
4821 llvm::APSInt numEltsInt(32);
4822 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4823 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4824 S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
4825 << Attr.getName() << AANT_ArgumentIntegerConstant
4826 << numEltsExpr->getSourceRange();
4830 // Only certain element types are supported for Neon vectors.
4831 llvm::Triple::ArchType Arch =
4832 S.Context.getTargetInfo().getTriple().getArch();
4833 if (!isPermittedNeonBaseType(CurType, VecKind,
4834 Arch == llvm::Triple::aarch64)) {
4835 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4840 // The total size of the vector must be 64 or 128 bits.
4841 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4842 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4843 unsigned vecSize = typeSize * numElts;
4844 if (vecSize != 64 && vecSize != 128) {
4845 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4850 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4853 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4854 TypeAttrLocation TAL, AttributeList *attrs) {
4855 // Scan through and apply attributes to this type where it makes sense. Some
4856 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4857 // type, but others can be present in the type specifiers even though they
4858 // apply to the decl. Here we apply type attributes and ignore the rest.
4860 AttributeList *next;
4862 AttributeList &attr = *attrs;
4863 next = attr.getNext();
4865 // Skip attributes that were marked to be invalid.
4866 if (attr.isInvalid())
4869 if (attr.isCXX11Attribute()) {
4870 // [[gnu::...]] attributes are treated as declaration attributes, so may
4871 // not appertain to a DeclaratorChunk, even if we handle them as type
4873 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4874 if (TAL == TAL_DeclChunk) {
4875 state.getSema().Diag(attr.getLoc(),
4876 diag::warn_cxx11_gnu_attribute_on_type)
4880 } else if (TAL != TAL_DeclChunk) {
4881 // Otherwise, only consider type processing for a C++11 attribute if
4882 // it's actually been applied to a type.
4887 // If this is an attribute we can handle, do so now,
4888 // otherwise, add it to the FnAttrs list for rechaining.
4889 switch (attr.getKind()) {
4891 // A C++11 attribute on a declarator chunk must appertain to a type.
4892 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4893 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4895 attr.setUsedAsTypeAttr();
4899 case AttributeList::UnknownAttribute:
4900 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4901 state.getSema().Diag(attr.getLoc(),
4902 diag::warn_unknown_attribute_ignored)
4906 case AttributeList::IgnoredAttribute:
4909 case AttributeList::AT_MayAlias:
4910 // FIXME: This attribute needs to actually be handled, but if we ignore
4911 // it it breaks large amounts of Linux software.
4912 attr.setUsedAsTypeAttr();
4914 case AttributeList::AT_AddressSpace:
4915 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4916 attr.setUsedAsTypeAttr();
4918 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4919 if (!handleObjCPointerTypeAttr(state, attr, type))
4920 distributeObjCPointerTypeAttr(state, attr, type);
4921 attr.setUsedAsTypeAttr();
4923 case AttributeList::AT_VectorSize:
4924 HandleVectorSizeAttr(type, attr, state.getSema());
4925 attr.setUsedAsTypeAttr();
4927 case AttributeList::AT_ExtVectorType:
4928 HandleExtVectorTypeAttr(type, attr, state.getSema());
4929 attr.setUsedAsTypeAttr();
4931 case AttributeList::AT_NeonVectorType:
4932 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4933 VectorType::NeonVector);
4934 attr.setUsedAsTypeAttr();
4936 case AttributeList::AT_NeonPolyVectorType:
4937 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4938 VectorType::NeonPolyVector);
4939 attr.setUsedAsTypeAttr();
4941 case AttributeList::AT_OpenCLImageAccess:
4942 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4943 attr.setUsedAsTypeAttr();
4946 case AttributeList::AT_Win64:
4947 attr.setUsedAsTypeAttr();
4949 MS_TYPE_ATTRS_CASELIST:
4950 if (!handleMSPointerTypeQualifierAttr(state, attr, type))
4951 attr.setUsedAsTypeAttr();
4954 case AttributeList::AT_NSReturnsRetained:
4955 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4957 // fallthrough into the function attrs
4959 FUNCTION_TYPE_ATTRS_CASELIST:
4960 attr.setUsedAsTypeAttr();
4962 // Never process function type attributes as part of the
4963 // declaration-specifiers.
4964 if (TAL == TAL_DeclSpec)
4965 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4967 // Otherwise, handle the possible delays.
4968 else if (!handleFunctionTypeAttr(state, attr, type))
4969 distributeFunctionTypeAttr(state, attr, type);
4972 } while ((attrs = next));
4975 /// \brief Ensure that the type of the given expression is complete.
4977 /// This routine checks whether the expression \p E has a complete type. If the
4978 /// expression refers to an instantiable construct, that instantiation is
4979 /// performed as needed to complete its type. Furthermore
4980 /// Sema::RequireCompleteType is called for the expression's type (or in the
4981 /// case of a reference type, the referred-to type).
4983 /// \param E The expression whose type is required to be complete.
4984 /// \param Diagnoser The object that will emit a diagnostic if the type is
4987 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4989 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4990 QualType T = E->getType();
4992 // Fast path the case where the type is already complete.
4993 if (!T->isIncompleteType())
4994 // FIXME: The definition might not be visible.
4997 // Incomplete array types may be completed by the initializer attached to
4998 // their definitions. For static data members of class templates and for
4999 // variable templates, we need to instantiate the definition to get this
5000 // initializer and complete the type.
5001 if (T->isIncompleteArrayType()) {
5002 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5003 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5004 if (isTemplateInstantiation(Var->getTemplateSpecializationKind())) {
5005 SourceLocation PointOfInstantiation = E->getExprLoc();
5007 if (MemberSpecializationInfo *MSInfo =
5008 Var->getMemberSpecializationInfo()) {
5009 // If we don't already have a point of instantiation, this is it.
5010 if (MSInfo->getPointOfInstantiation().isInvalid()) {
5011 MSInfo->setPointOfInstantiation(PointOfInstantiation);
5013 // This is a modification of an existing AST node. Notify
5015 if (ASTMutationListener *L = getASTMutationListener())
5016 L->StaticDataMemberInstantiated(Var);
5019 VarTemplateSpecializationDecl *VarSpec =
5020 cast<VarTemplateSpecializationDecl>(Var);
5021 if (VarSpec->getPointOfInstantiation().isInvalid())
5022 VarSpec->setPointOfInstantiation(PointOfInstantiation);
5025 InstantiateVariableDefinition(PointOfInstantiation, Var);
5027 // Update the type to the newly instantiated definition's type both
5028 // here and within the expression.
5029 if (VarDecl *Def = Var->getDefinition()) {
5036 // We still go on to try to complete the type independently, as it
5037 // may also require instantiations or diagnostics if it remains
5044 // FIXME: Are there other cases which require instantiating something other
5045 // than the type to complete the type of an expression?
5047 // Look through reference types and complete the referred type.
5048 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5049 T = Ref->getPointeeType();
5051 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
5055 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
5058 TypeDiagnoserDiag(unsigned DiagID)
5059 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
5061 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
5062 if (Suppressed) return;
5063 S.Diag(Loc, DiagID) << T;
5068 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
5069 TypeDiagnoserDiag Diagnoser(DiagID);
5070 return RequireCompleteExprType(E, Diagnoser);
5073 /// @brief Ensure that the type T is a complete type.
5075 /// This routine checks whether the type @p T is complete in any
5076 /// context where a complete type is required. If @p T is a complete
5077 /// type, returns false. If @p T is a class template specialization,
5078 /// this routine then attempts to perform class template
5079 /// instantiation. If instantiation fails, or if @p T is incomplete
5080 /// and cannot be completed, issues the diagnostic @p diag (giving it
5081 /// the type @p T) and returns true.
5083 /// @param Loc The location in the source that the incomplete type
5084 /// diagnostic should refer to.
5086 /// @param T The type that this routine is examining for completeness.
5088 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
5089 /// @c false otherwise.
5090 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5091 TypeDiagnoser &Diagnoser) {
5092 if (RequireCompleteTypeImpl(Loc, T, Diagnoser))
5094 if (const TagType *Tag = T->getAs<TagType>()) {
5095 if (!Tag->getDecl()->isCompleteDefinitionRequired()) {
5096 Tag->getDecl()->setCompleteDefinitionRequired();
5097 Consumer.HandleTagDeclRequiredDefinition(Tag->getDecl());
5103 /// \brief The implementation of RequireCompleteType
5104 bool Sema::RequireCompleteTypeImpl(SourceLocation Loc, QualType T,
5105 TypeDiagnoser &Diagnoser) {
5106 // FIXME: Add this assertion to make sure we always get instantiation points.
5107 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
5108 // FIXME: Add this assertion to help us flush out problems with
5109 // checking for dependent types and type-dependent expressions.
5111 // assert(!T->isDependentType() &&
5112 // "Can't ask whether a dependent type is complete");
5114 // If we have a complete type, we're done.
5116 if (!T->isIncompleteType(&Def)) {
5117 // If we know about the definition but it is not visible, complain.
5118 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(*this, Def)) {
5119 // Suppress this error outside of a SFINAE context if we've already
5120 // emitted the error once for this type. There's no usefulness in
5121 // repeating the diagnostic.
5122 // FIXME: Add a Fix-It that imports the corresponding module or includes
5124 Module *Owner = Def->getOwningModule();
5125 Diag(Loc, diag::err_module_private_definition)
5126 << T << Owner->getFullModuleName();
5127 Diag(Def->getLocation(), diag::note_previous_definition);
5129 if (!isSFINAEContext()) {
5130 // Recover by implicitly importing this module.
5131 createImplicitModuleImport(Loc, Owner);
5138 // FIXME: If there's an unimported definition of this type in a module (for
5139 // instance, because we forward declared it, then imported the definition),
5140 // import that definition now.
5141 // FIXME: What about other cases where an import extends a redeclaration
5142 // chain for a declaration that can be accessed through a mechanism other
5143 // than name lookup (eg, referenced in a template, or a variable whose type
5144 // could be completed by the module)?
5146 const TagType *Tag = T->getAs<TagType>();
5147 const ObjCInterfaceType *IFace = 0;
5150 // Avoid diagnosing invalid decls as incomplete.
5151 if (Tag->getDecl()->isInvalidDecl())
5154 // Give the external AST source a chance to complete the type.
5155 if (Tag->getDecl()->hasExternalLexicalStorage()) {
5156 Context.getExternalSource()->CompleteType(Tag->getDecl());
5157 if (!Tag->isIncompleteType())
5161 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
5162 // Avoid diagnosing invalid decls as incomplete.
5163 if (IFace->getDecl()->isInvalidDecl())
5166 // Give the external AST source a chance to complete the type.
5167 if (IFace->getDecl()->hasExternalLexicalStorage()) {
5168 Context.getExternalSource()->CompleteType(IFace->getDecl());
5169 if (!IFace->isIncompleteType())
5174 // If we have a class template specialization or a class member of a
5175 // class template specialization, or an array with known size of such,
5176 // try to instantiate it.
5177 QualType MaybeTemplate = T;
5178 while (const ConstantArrayType *Array
5179 = Context.getAsConstantArrayType(MaybeTemplate))
5180 MaybeTemplate = Array->getElementType();
5181 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
5182 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
5183 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
5184 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
5185 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
5186 TSK_ImplicitInstantiation,
5187 /*Complain=*/!Diagnoser.Suppressed);
5188 } else if (CXXRecordDecl *Rec
5189 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
5190 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
5191 if (!Rec->isBeingDefined() && Pattern) {
5192 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
5193 assert(MSI && "Missing member specialization information?");
5194 // This record was instantiated from a class within a template.
5195 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
5196 return InstantiateClass(Loc, Rec, Pattern,
5197 getTemplateInstantiationArgs(Rec),
5198 TSK_ImplicitInstantiation,
5199 /*Complain=*/!Diagnoser.Suppressed);
5204 if (Diagnoser.Suppressed)
5207 // We have an incomplete type. Produce a diagnostic.
5208 if (Ident___float128 &&
5209 T == Context.getTypeDeclType(Context.getFloat128StubType())) {
5210 Diag(Loc, diag::err_typecheck_decl_incomplete_type___float128);
5214 Diagnoser.diagnose(*this, Loc, T);
5216 // If the type was a forward declaration of a class/struct/union
5217 // type, produce a note.
5218 if (Tag && !Tag->getDecl()->isInvalidDecl())
5219 Diag(Tag->getDecl()->getLocation(),
5220 Tag->isBeingDefined() ? diag::note_type_being_defined
5221 : diag::note_forward_declaration)
5222 << QualType(Tag, 0);
5224 // If the Objective-C class was a forward declaration, produce a note.
5225 if (IFace && !IFace->getDecl()->isInvalidDecl())
5226 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
5228 // If we have external information that we can use to suggest a fix,
5231 ExternalSource->MaybeDiagnoseMissingCompleteType(Loc, T);
5236 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
5238 TypeDiagnoserDiag Diagnoser(DiagID);
5239 return RequireCompleteType(Loc, T, Diagnoser);
5242 /// \brief Get diagnostic %select index for tag kind for
5243 /// literal type diagnostic message.
5244 /// WARNING: Indexes apply to particular diagnostics only!
5246 /// \returns diagnostic %select index.
5247 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
5249 case TTK_Struct: return 0;
5250 case TTK_Interface: return 1;
5251 case TTK_Class: return 2;
5252 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
5256 /// @brief Ensure that the type T is a literal type.
5258 /// This routine checks whether the type @p T is a literal type. If @p T is an
5259 /// incomplete type, an attempt is made to complete it. If @p T is a literal
5260 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
5261 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
5262 /// it the type @p T), along with notes explaining why the type is not a
5263 /// literal type, and returns true.
5265 /// @param Loc The location in the source that the non-literal type
5266 /// diagnostic should refer to.
5268 /// @param T The type that this routine is examining for literalness.
5270 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
5272 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
5273 /// @c false otherwise.
5274 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
5275 TypeDiagnoser &Diagnoser) {
5276 assert(!T->isDependentType() && "type should not be dependent");
5278 QualType ElemType = Context.getBaseElementType(T);
5279 RequireCompleteType(Loc, ElemType, 0);
5281 if (T->isLiteralType(Context))
5284 if (Diagnoser.Suppressed)
5287 Diagnoser.diagnose(*this, Loc, T);
5289 if (T->isVariableArrayType())
5292 const RecordType *RT = ElemType->getAs<RecordType>();
5296 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
5298 // A partially-defined class type can't be a literal type, because a literal
5299 // class type must have a trivial destructor (which can't be checked until
5300 // the class definition is complete).
5301 if (!RD->isCompleteDefinition()) {
5302 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
5306 // If the class has virtual base classes, then it's not an aggregate, and
5307 // cannot have any constexpr constructors or a trivial default constructor,
5308 // so is non-literal. This is better to diagnose than the resulting absence
5309 // of constexpr constructors.
5310 if (RD->getNumVBases()) {
5311 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
5312 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
5313 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
5314 E = RD->vbases_end(); I != E; ++I)
5315 Diag(I->getLocStart(),
5316 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
5317 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
5318 !RD->hasTrivialDefaultConstructor()) {
5319 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
5320 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
5321 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
5322 E = RD->bases_end(); I != E; ++I) {
5323 if (!I->getType()->isLiteralType(Context)) {
5324 Diag(I->getLocStart(),
5325 diag::note_non_literal_base_class)
5326 << RD << I->getType() << I->getSourceRange();
5330 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
5331 E = RD->field_end(); I != E; ++I) {
5332 if (!I->getType()->isLiteralType(Context) ||
5333 I->getType().isVolatileQualified()) {
5334 Diag(I->getLocation(), diag::note_non_literal_field)
5335 << RD << *I << I->getType()
5336 << I->getType().isVolatileQualified();
5340 } else if (!RD->hasTrivialDestructor()) {
5341 // All fields and bases are of literal types, so have trivial destructors.
5342 // If this class's destructor is non-trivial it must be user-declared.
5343 CXXDestructorDecl *Dtor = RD->getDestructor();
5344 assert(Dtor && "class has literal fields and bases but no dtor?");
5348 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
5349 diag::note_non_literal_user_provided_dtor :
5350 diag::note_non_literal_nontrivial_dtor) << RD;
5351 if (!Dtor->isUserProvided())
5352 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
5358 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
5359 TypeDiagnoserDiag Diagnoser(DiagID);
5360 return RequireLiteralType(Loc, T, Diagnoser);
5363 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
5364 /// and qualified by the nested-name-specifier contained in SS.
5365 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
5366 const CXXScopeSpec &SS, QualType T) {
5369 NestedNameSpecifier *NNS;
5371 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
5373 if (Keyword == ETK_None)
5377 return Context.getElaboratedType(Keyword, NNS, T);
5380 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
5381 ExprResult ER = CheckPlaceholderExpr(E);
5382 if (ER.isInvalid()) return QualType();
5385 if (!E->isTypeDependent()) {
5386 QualType T = E->getType();
5387 if (const TagType *TT = T->getAs<TagType>())
5388 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
5390 return Context.getTypeOfExprType(E);
5393 /// getDecltypeForExpr - Given an expr, will return the decltype for
5394 /// that expression, according to the rules in C++11
5395 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
5396 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
5397 if (E->isTypeDependent())
5398 return S.Context.DependentTy;
5400 // C++11 [dcl.type.simple]p4:
5401 // The type denoted by decltype(e) is defined as follows:
5403 // - if e is an unparenthesized id-expression or an unparenthesized class
5404 // member access (5.2.5), decltype(e) is the type of the entity named
5405 // by e. If there is no such entity, or if e names a set of overloaded
5406 // functions, the program is ill-formed;
5408 // We apply the same rules for Objective-C ivar and property references.
5409 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5410 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5411 return VD->getType();
5412 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5413 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5414 return FD->getType();
5415 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5416 return IR->getDecl()->getType();
5417 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5418 if (PR->isExplicitProperty())
5419 return PR->getExplicitProperty()->getType();
5422 // C++11 [expr.lambda.prim]p18:
5423 // Every occurrence of decltype((x)) where x is a possibly
5424 // parenthesized id-expression that names an entity of automatic
5425 // storage duration is treated as if x were transformed into an
5426 // access to a corresponding data member of the closure type that
5427 // would have been declared if x were an odr-use of the denoted
5429 using namespace sema;
5430 if (S.getCurLambda()) {
5431 if (isa<ParenExpr>(E)) {
5432 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5433 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5434 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5436 return S.Context.getLValueReferenceType(T);
5443 // C++11 [dcl.type.simple]p4:
5445 QualType T = E->getType();
5446 switch (E->getValueKind()) {
5447 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5449 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5450 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5452 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5453 // - otherwise, decltype(e) is the type of e.
5454 case VK_RValue: break;
5460 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
5461 ExprResult ER = CheckPlaceholderExpr(E);
5462 if (ER.isInvalid()) return QualType();
5465 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5468 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5469 UnaryTransformType::UTTKind UKind,
5470 SourceLocation Loc) {
5472 case UnaryTransformType::EnumUnderlyingType:
5473 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5474 Diag(Loc, diag::err_only_enums_have_underlying_types);
5477 QualType Underlying = BaseType;
5478 if (!BaseType->isDependentType()) {
5479 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5480 assert(ED && "EnumType has no EnumDecl");
5481 DiagnoseUseOfDecl(ED, Loc);
5482 Underlying = ED->getIntegerType();
5484 assert(!Underlying.isNull());
5485 return Context.getUnaryTransformType(BaseType, Underlying,
5486 UnaryTransformType::EnumUnderlyingType);
5489 llvm_unreachable("unknown unary transform type");
5492 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5493 if (!T->isDependentType()) {
5494 // FIXME: It isn't entirely clear whether incomplete atomic types
5495 // are allowed or not; for simplicity, ban them for the moment.
5496 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5499 int DisallowedKind = -1;
5500 if (T->isArrayType())
5502 else if (T->isFunctionType())
5504 else if (T->isReferenceType())
5506 else if (T->isAtomicType())
5508 else if (T.hasQualifiers())
5510 else if (!T.isTriviallyCopyableType(Context))
5511 // Some other non-trivially-copyable type (probably a C++ class)
5514 if (DisallowedKind != -1) {
5515 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5519 // FIXME: Do we need any handling for ARC here?
5522 // Build the pointer type.
5523 return Context.getAtomicType(T);