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/ASTContext.h"
16 #include "clang/AST/ASTMutationListener.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/TypeLoc.h"
22 #include "clang/AST/TypeLocVisitor.h"
23 #include "clang/Basic/OpenCL.h"
24 #include "clang/Basic/PartialDiagnostic.h"
25 #include "clang/Basic/TargetInfo.h"
26 #include "clang/Lex/Preprocessor.h"
27 #include "clang/Parse/ParseDiagnostic.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "clang/Sema/DelayedDiagnostic.h"
30 #include "clang/Sema/Lookup.h"
31 #include "clang/Sema/ScopeInfo.h"
32 #include "clang/Sema/Template.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/Support/ErrorHandling.h"
36 using namespace clang;
38 /// isOmittedBlockReturnType - Return true if this declarator is missing a
39 /// return type because this is a omitted return type on a block literal.
40 static bool isOmittedBlockReturnType(const Declarator &D) {
41 if (D.getContext() != Declarator::BlockLiteralContext ||
42 D.getDeclSpec().hasTypeSpecifier())
45 if (D.getNumTypeObjects() == 0)
46 return true; // ^{ ... }
48 if (D.getNumTypeObjects() == 1 &&
49 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
50 return true; // ^(int X, float Y) { ... }
55 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
56 /// doesn't apply to the given type.
57 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
59 bool useExpansionLoc = false;
62 switch (attr.getKind()) {
63 case AttributeList::AT_ObjCGC:
64 diagID = diag::warn_pointer_attribute_wrong_type;
65 useExpansionLoc = true;
68 case AttributeList::AT_ObjCOwnership:
69 diagID = diag::warn_objc_object_attribute_wrong_type;
70 useExpansionLoc = true;
74 // Assume everything else was a function attribute.
75 diagID = diag::warn_function_attribute_wrong_type;
79 SourceLocation loc = attr.getLoc();
80 StringRef name = attr.getName()->getName();
82 // The GC attributes are usually written with macros; special-case them.
83 if (useExpansionLoc && loc.isMacroID() && attr.getParameterName()) {
84 if (attr.getParameterName()->isStr("strong")) {
85 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
86 } else if (attr.getParameterName()->isStr("weak")) {
87 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
91 S.Diag(loc, diagID) << name << type;
94 // objc_gc applies to Objective-C pointers or, otherwise, to the
95 // smallest available pointer type (i.e. 'void*' in 'void**').
96 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
97 case AttributeList::AT_ObjCGC: \
98 case AttributeList::AT_ObjCOwnership
100 // Function type attributes.
101 #define FUNCTION_TYPE_ATTRS_CASELIST \
102 case AttributeList::AT_NoReturn: \
103 case AttributeList::AT_CDecl: \
104 case AttributeList::AT_FastCall: \
105 case AttributeList::AT_StdCall: \
106 case AttributeList::AT_ThisCall: \
107 case AttributeList::AT_Pascal: \
108 case AttributeList::AT_MSABI: \
109 case AttributeList::AT_SysVABI: \
110 case AttributeList::AT_Regparm: \
111 case AttributeList::AT_Pcs: \
112 case AttributeList::AT_PnaclCall: \
113 case AttributeList::AT_IntelOclBicc \
116 /// An object which stores processing state for the entire
117 /// GetTypeForDeclarator process.
118 class TypeProcessingState {
121 /// The declarator being processed.
122 Declarator &declarator;
124 /// The index of the declarator chunk we're currently processing.
125 /// May be the total number of valid chunks, indicating the
129 /// Whether there are non-trivial modifications to the decl spec.
132 /// Whether we saved the attributes in the decl spec.
135 /// The original set of attributes on the DeclSpec.
136 SmallVector<AttributeList*, 2> savedAttrs;
138 /// A list of attributes to diagnose the uselessness of when the
139 /// processing is complete.
140 SmallVector<AttributeList*, 2> ignoredTypeAttrs;
143 TypeProcessingState(Sema &sema, Declarator &declarator)
144 : sema(sema), declarator(declarator),
145 chunkIndex(declarator.getNumTypeObjects()),
146 trivial(true), hasSavedAttrs(false) {}
148 Sema &getSema() const {
152 Declarator &getDeclarator() const {
156 bool isProcessingDeclSpec() const {
157 return chunkIndex == declarator.getNumTypeObjects();
160 unsigned getCurrentChunkIndex() const {
164 void setCurrentChunkIndex(unsigned idx) {
165 assert(idx <= declarator.getNumTypeObjects());
169 AttributeList *&getCurrentAttrListRef() const {
170 if (isProcessingDeclSpec())
171 return getMutableDeclSpec().getAttributes().getListRef();
172 return declarator.getTypeObject(chunkIndex).getAttrListRef();
175 /// Save the current set of attributes on the DeclSpec.
176 void saveDeclSpecAttrs() {
177 // Don't try to save them multiple times.
178 if (hasSavedAttrs) return;
180 DeclSpec &spec = getMutableDeclSpec();
181 for (AttributeList *attr = spec.getAttributes().getList(); attr;
182 attr = attr->getNext())
183 savedAttrs.push_back(attr);
184 trivial &= savedAttrs.empty();
185 hasSavedAttrs = true;
188 /// Record that we had nowhere to put the given type attribute.
189 /// We will diagnose such attributes later.
190 void addIgnoredTypeAttr(AttributeList &attr) {
191 ignoredTypeAttrs.push_back(&attr);
194 /// Diagnose all the ignored type attributes, given that the
195 /// declarator worked out to the given type.
196 void diagnoseIgnoredTypeAttrs(QualType type) const {
197 for (SmallVectorImpl<AttributeList*>::const_iterator
198 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
200 diagnoseBadTypeAttribute(getSema(), **i, type);
203 ~TypeProcessingState() {
206 restoreDeclSpecAttrs();
210 DeclSpec &getMutableDeclSpec() const {
211 return const_cast<DeclSpec&>(declarator.getDeclSpec());
214 void restoreDeclSpecAttrs() {
215 assert(hasSavedAttrs);
217 if (savedAttrs.empty()) {
218 getMutableDeclSpec().getAttributes().set(0);
222 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
223 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
224 savedAttrs[i]->setNext(savedAttrs[i+1]);
225 savedAttrs.back()->setNext(0);
229 /// Basically std::pair except that we really want to avoid an
230 /// implicit operator= for safety concerns. It's also a minor
231 /// link-time optimization for this to be a private type.
234 AttributeList &first;
236 /// The head of the list the attribute is currently in.
237 AttributeList *&second;
239 AttrAndList(AttributeList &attr, AttributeList *&head)
240 : first(attr), second(head) {}
245 template <> struct isPodLike<AttrAndList> {
246 static const bool value = true;
250 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
255 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
257 head = attr.getNext();
261 AttributeList *cur = head;
263 assert(cur && cur->getNext() && "ran out of attrs?");
264 if (cur->getNext() == &attr) {
265 cur->setNext(attr.getNext());
268 cur = cur->getNext();
272 static void moveAttrFromListToList(AttributeList &attr,
273 AttributeList *&fromList,
274 AttributeList *&toList) {
275 spliceAttrOutOfList(attr, fromList);
276 spliceAttrIntoList(attr, toList);
279 /// The location of a type attribute.
280 enum TypeAttrLocation {
281 /// The attribute is in the decl-specifier-seq.
283 /// The attribute is part of a DeclaratorChunk.
285 /// The attribute is immediately after the declaration's name.
289 static void processTypeAttrs(TypeProcessingState &state,
290 QualType &type, TypeAttrLocation TAL,
291 AttributeList *attrs);
293 static bool handleFunctionTypeAttr(TypeProcessingState &state,
297 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
298 AttributeList &attr, QualType &type);
300 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
301 AttributeList &attr, QualType &type);
303 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
304 AttributeList &attr, QualType &type) {
305 if (attr.getKind() == AttributeList::AT_ObjCGC)
306 return handleObjCGCTypeAttr(state, attr, type);
307 assert(attr.getKind() == AttributeList::AT_ObjCOwnership);
308 return handleObjCOwnershipTypeAttr(state, attr, type);
311 /// Given the index of a declarator chunk, check whether that chunk
312 /// directly specifies the return type of a function and, if so, find
313 /// an appropriate place for it.
315 /// \param i - a notional index which the search will start
316 /// immediately inside
317 static DeclaratorChunk *maybeMovePastReturnType(Declarator &declarator,
319 assert(i <= declarator.getNumTypeObjects());
321 DeclaratorChunk *result = 0;
323 // First, look inwards past parens for a function declarator.
324 for (; i != 0; --i) {
325 DeclaratorChunk &fnChunk = declarator.getTypeObject(i-1);
326 switch (fnChunk.Kind) {
327 case DeclaratorChunk::Paren:
330 // If we find anything except a function, bail out.
331 case DeclaratorChunk::Pointer:
332 case DeclaratorChunk::BlockPointer:
333 case DeclaratorChunk::Array:
334 case DeclaratorChunk::Reference:
335 case DeclaratorChunk::MemberPointer:
338 // If we do find a function declarator, scan inwards from that,
339 // looking for a block-pointer declarator.
340 case DeclaratorChunk::Function:
341 for (--i; i != 0; --i) {
342 DeclaratorChunk &blockChunk = declarator.getTypeObject(i-1);
343 switch (blockChunk.Kind) {
344 case DeclaratorChunk::Paren:
345 case DeclaratorChunk::Pointer:
346 case DeclaratorChunk::Array:
347 case DeclaratorChunk::Function:
348 case DeclaratorChunk::Reference:
349 case DeclaratorChunk::MemberPointer:
351 case DeclaratorChunk::BlockPointer:
352 result = &blockChunk;
355 llvm_unreachable("bad declarator chunk kind");
358 // If we run out of declarators doing that, we're done.
361 llvm_unreachable("bad declarator chunk kind");
363 // Okay, reconsider from our new point.
367 // Ran out of chunks, bail out.
371 /// Given that an objc_gc attribute was written somewhere on a
372 /// declaration *other* than on the declarator itself (for which, use
373 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
374 /// didn't apply in whatever position it was written in, try to move
375 /// it to a more appropriate position.
376 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
379 Declarator &declarator = state.getDeclarator();
381 // Move it to the outermost normal or block pointer declarator.
382 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
383 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
384 switch (chunk.Kind) {
385 case DeclaratorChunk::Pointer:
386 case DeclaratorChunk::BlockPointer: {
387 // But don't move an ARC ownership attribute to the return type
389 DeclaratorChunk *destChunk = 0;
390 if (state.isProcessingDeclSpec() &&
391 attr.getKind() == AttributeList::AT_ObjCOwnership)
392 destChunk = maybeMovePastReturnType(declarator, i - 1);
393 if (!destChunk) destChunk = &chunk;
395 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
396 destChunk->getAttrListRef());
400 case DeclaratorChunk::Paren:
401 case DeclaratorChunk::Array:
404 // We may be starting at the return type of a block.
405 case DeclaratorChunk::Function:
406 if (state.isProcessingDeclSpec() &&
407 attr.getKind() == AttributeList::AT_ObjCOwnership) {
408 if (DeclaratorChunk *dest = maybeMovePastReturnType(declarator, i)) {
409 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
410 dest->getAttrListRef());
416 // Don't walk through these.
417 case DeclaratorChunk::Reference:
418 case DeclaratorChunk::MemberPointer:
424 diagnoseBadTypeAttribute(state.getSema(), attr, type);
427 /// Distribute an objc_gc type attribute that was written on the
430 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
432 QualType &declSpecType) {
433 Declarator &declarator = state.getDeclarator();
435 // objc_gc goes on the innermost pointer to something that's not a
437 unsigned innermost = -1U;
438 bool considerDeclSpec = true;
439 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
440 DeclaratorChunk &chunk = declarator.getTypeObject(i);
441 switch (chunk.Kind) {
442 case DeclaratorChunk::Pointer:
443 case DeclaratorChunk::BlockPointer:
447 case DeclaratorChunk::Reference:
448 case DeclaratorChunk::MemberPointer:
449 case DeclaratorChunk::Paren:
450 case DeclaratorChunk::Array:
453 case DeclaratorChunk::Function:
454 considerDeclSpec = false;
460 // That might actually be the decl spec if we weren't blocked by
461 // anything in the declarator.
462 if (considerDeclSpec) {
463 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
464 // Splice the attribute into the decl spec. Prevents the
465 // attribute from being applied multiple times and gives
466 // the source-location-filler something to work with.
467 state.saveDeclSpecAttrs();
468 moveAttrFromListToList(attr, declarator.getAttrListRef(),
469 declarator.getMutableDeclSpec().getAttributes().getListRef());
474 // Otherwise, if we found an appropriate chunk, splice the attribute
476 if (innermost != -1U) {
477 moveAttrFromListToList(attr, declarator.getAttrListRef(),
478 declarator.getTypeObject(innermost).getAttrListRef());
482 // Otherwise, diagnose when we're done building the type.
483 spliceAttrOutOfList(attr, declarator.getAttrListRef());
484 state.addIgnoredTypeAttr(attr);
487 /// A function type attribute was written somewhere in a declaration
488 /// *other* than on the declarator itself or in the decl spec. Given
489 /// that it didn't apply in whatever position it was written in, try
490 /// to move it to a more appropriate position.
491 static void distributeFunctionTypeAttr(TypeProcessingState &state,
494 Declarator &declarator = state.getDeclarator();
496 // Try to push the attribute from the return type of a function to
497 // the function itself.
498 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
499 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
500 switch (chunk.Kind) {
501 case DeclaratorChunk::Function:
502 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
503 chunk.getAttrListRef());
506 case DeclaratorChunk::Paren:
507 case DeclaratorChunk::Pointer:
508 case DeclaratorChunk::BlockPointer:
509 case DeclaratorChunk::Array:
510 case DeclaratorChunk::Reference:
511 case DeclaratorChunk::MemberPointer:
516 diagnoseBadTypeAttribute(state.getSema(), attr, type);
519 /// Try to distribute a function type attribute to the innermost
520 /// function chunk or type. Returns true if the attribute was
521 /// distributed, false if no location was found.
523 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
525 AttributeList *&attrList,
526 QualType &declSpecType) {
527 Declarator &declarator = state.getDeclarator();
529 // Put it on the innermost function chunk, if there is one.
530 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
531 DeclaratorChunk &chunk = declarator.getTypeObject(i);
532 if (chunk.Kind != DeclaratorChunk::Function) continue;
534 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
538 if (handleFunctionTypeAttr(state, attr, declSpecType)) {
539 spliceAttrOutOfList(attr, attrList);
546 /// A function type attribute was written in the decl spec. Try to
547 /// apply it somewhere.
549 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
551 QualType &declSpecType) {
552 state.saveDeclSpecAttrs();
554 // C++11 attributes before the decl specifiers actually appertain to
555 // the declarators. Move them straight there. We don't support the
556 // 'put them wherever you like' semantics we allow for GNU attributes.
557 if (attr.isCXX11Attribute()) {
558 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
559 state.getDeclarator().getAttrListRef());
563 // Try to distribute to the innermost.
564 if (distributeFunctionTypeAttrToInnermost(state, attr,
565 state.getCurrentAttrListRef(),
569 // If that failed, diagnose the bad attribute when the declarator is
571 state.addIgnoredTypeAttr(attr);
574 /// A function type attribute was written on the declarator. Try to
575 /// apply it somewhere.
577 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
579 QualType &declSpecType) {
580 Declarator &declarator = state.getDeclarator();
582 // Try to distribute to the innermost.
583 if (distributeFunctionTypeAttrToInnermost(state, attr,
584 declarator.getAttrListRef(),
588 // If that failed, diagnose the bad attribute when the declarator is
590 spliceAttrOutOfList(attr, declarator.getAttrListRef());
591 state.addIgnoredTypeAttr(attr);
594 /// \brief Given that there are attributes written on the declarator
595 /// itself, try to distribute any type attributes to the appropriate
596 /// declarator chunk.
598 /// These are attributes like the following:
601 /// but not necessarily this:
603 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
604 QualType &declSpecType) {
605 // Collect all the type attributes from the declarator itself.
606 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
607 AttributeList *attr = state.getDeclarator().getAttributes();
610 next = attr->getNext();
612 // Do not distribute C++11 attributes. They have strict rules for what
613 // they appertain to.
614 if (attr->isCXX11Attribute())
617 switch (attr->getKind()) {
618 OBJC_POINTER_TYPE_ATTRS_CASELIST:
619 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
622 case AttributeList::AT_NSReturnsRetained:
623 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
627 FUNCTION_TYPE_ATTRS_CASELIST:
628 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
634 } while ((attr = next));
637 /// Add a synthetic '()' to a block-literal declarator if it is
638 /// required, given the return type.
639 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
640 QualType declSpecType) {
641 Declarator &declarator = state.getDeclarator();
643 // First, check whether the declarator would produce a function,
644 // i.e. whether the innermost semantic chunk is a function.
645 if (declarator.isFunctionDeclarator()) {
646 // If so, make that declarator a prototyped declarator.
647 declarator.getFunctionTypeInfo().hasPrototype = true;
651 // If there are any type objects, the type as written won't name a
652 // function, regardless of the decl spec type. This is because a
653 // block signature declarator is always an abstract-declarator, and
654 // abstract-declarators can't just be parentheses chunks. Therefore
655 // we need to build a function chunk unless there are no type
656 // objects and the decl spec type is a function.
657 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
660 // Note that there *are* cases with invalid declarators where
661 // declarators consist solely of parentheses. In general, these
662 // occur only in failed efforts to make function declarators, so
663 // faking up the function chunk is still the right thing to do.
665 // Otherwise, we need to fake up a function declarator.
666 SourceLocation loc = declarator.getLocStart();
668 // ...and *prepend* it to the declarator.
669 SourceLocation NoLoc;
670 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
672 /*IsAmbiguous=*/false,
676 /*EllipsisLoc=*/NoLoc,
679 /*RefQualifierIsLvalueRef=*/true,
680 /*RefQualifierLoc=*/NoLoc,
681 /*ConstQualifierLoc=*/NoLoc,
682 /*VolatileQualifierLoc=*/NoLoc,
683 /*MutableLoc=*/NoLoc,
687 /*ExceptionRanges=*/0,
690 loc, loc, declarator));
692 // For consistency, make sure the state still has us as processing
694 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
695 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
698 /// \brief Convert the specified declspec to the appropriate type
700 /// \param state Specifies the declarator containing the declaration specifier
701 /// to be converted, along with other associated processing state.
702 /// \returns The type described by the declaration specifiers. This function
703 /// never returns null.
704 static QualType ConvertDeclSpecToType(TypeProcessingState &state) {
705 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
708 Sema &S = state.getSema();
709 Declarator &declarator = state.getDeclarator();
710 const DeclSpec &DS = declarator.getDeclSpec();
711 SourceLocation DeclLoc = declarator.getIdentifierLoc();
712 if (DeclLoc.isInvalid())
713 DeclLoc = DS.getLocStart();
715 ASTContext &Context = S.Context;
718 switch (DS.getTypeSpecType()) {
719 case DeclSpec::TST_void:
720 Result = Context.VoidTy;
722 case DeclSpec::TST_char:
723 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
724 Result = Context.CharTy;
725 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
726 Result = Context.SignedCharTy;
728 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
729 "Unknown TSS value");
730 Result = Context.UnsignedCharTy;
733 case DeclSpec::TST_wchar:
734 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
735 Result = Context.WCharTy;
736 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
737 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
738 << DS.getSpecifierName(DS.getTypeSpecType());
739 Result = Context.getSignedWCharType();
741 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
742 "Unknown TSS value");
743 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
744 << DS.getSpecifierName(DS.getTypeSpecType());
745 Result = Context.getUnsignedWCharType();
748 case DeclSpec::TST_char16:
749 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
750 "Unknown TSS value");
751 Result = Context.Char16Ty;
753 case DeclSpec::TST_char32:
754 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
755 "Unknown TSS value");
756 Result = Context.Char32Ty;
758 case DeclSpec::TST_unspecified:
759 // "<proto1,proto2>" is an objc qualified ID with a missing id.
760 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
761 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
762 (ObjCProtocolDecl*const*)PQ,
763 DS.getNumProtocolQualifiers());
764 Result = Context.getObjCObjectPointerType(Result);
768 // If this is a missing declspec in a block literal return context, then it
769 // is inferred from the return statements inside the block.
770 // The declspec is always missing in a lambda expr context; it is either
771 // specified with a trailing return type or inferred.
772 if (declarator.getContext() == Declarator::LambdaExprContext ||
773 isOmittedBlockReturnType(declarator)) {
774 Result = Context.DependentTy;
778 // Unspecified typespec defaults to int in C90. However, the C90 grammar
779 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
780 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
781 // Note that the one exception to this is function definitions, which are
782 // allowed to be completely missing a declspec. This is handled in the
783 // parser already though by it pretending to have seen an 'int' in this
785 if (S.getLangOpts().ImplicitInt) {
786 // In C89 mode, we only warn if there is a completely missing declspec
787 // when one is not allowed.
789 S.Diag(DeclLoc, diag::ext_missing_declspec)
790 << DS.getSourceRange()
791 << FixItHint::CreateInsertion(DS.getLocStart(), "int");
793 } else if (!DS.hasTypeSpecifier()) {
794 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
795 // "At least one type specifier shall be given in the declaration
796 // specifiers in each declaration, and in the specifier-qualifier list in
797 // each struct declaration and type name."
798 if (S.getLangOpts().CPlusPlus) {
799 S.Diag(DeclLoc, diag::err_missing_type_specifier)
800 << DS.getSourceRange();
802 // When this occurs in C++ code, often something is very broken with the
803 // value being declared, poison it as invalid so we don't get chains of
805 declarator.setInvalidType(true);
807 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
808 << DS.getSourceRange();
813 case DeclSpec::TST_int: {
814 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
815 switch (DS.getTypeSpecWidth()) {
816 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
817 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
818 case DeclSpec::TSW_long: Result = Context.LongTy; break;
819 case DeclSpec::TSW_longlong:
820 Result = Context.LongLongTy;
822 // 'long long' is a C99 or C++11 feature.
823 if (!S.getLangOpts().C99) {
824 if (S.getLangOpts().CPlusPlus)
825 S.Diag(DS.getTypeSpecWidthLoc(),
826 S.getLangOpts().CPlusPlus11 ?
827 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
829 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
834 switch (DS.getTypeSpecWidth()) {
835 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
836 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
837 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
838 case DeclSpec::TSW_longlong:
839 Result = Context.UnsignedLongLongTy;
841 // 'long long' is a C99 or C++11 feature.
842 if (!S.getLangOpts().C99) {
843 if (S.getLangOpts().CPlusPlus)
844 S.Diag(DS.getTypeSpecWidthLoc(),
845 S.getLangOpts().CPlusPlus11 ?
846 diag::warn_cxx98_compat_longlong : diag::ext_cxx11_longlong);
848 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_c99_longlong);
855 case DeclSpec::TST_int128:
856 if (!S.PP.getTargetInfo().hasInt128Type())
857 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_int128_unsupported);
858 if (DS.getTypeSpecSign() == DeclSpec::TSS_unsigned)
859 Result = Context.UnsignedInt128Ty;
861 Result = Context.Int128Ty;
863 case DeclSpec::TST_half: Result = Context.HalfTy; break;
864 case DeclSpec::TST_float: Result = Context.FloatTy; break;
865 case DeclSpec::TST_double:
866 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
867 Result = Context.LongDoubleTy;
869 Result = Context.DoubleTy;
871 if (S.getLangOpts().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
872 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
873 declarator.setInvalidType(true);
876 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
877 case DeclSpec::TST_decimal32: // _Decimal32
878 case DeclSpec::TST_decimal64: // _Decimal64
879 case DeclSpec::TST_decimal128: // _Decimal128
880 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
881 Result = Context.IntTy;
882 declarator.setInvalidType(true);
884 case DeclSpec::TST_class:
885 case DeclSpec::TST_enum:
886 case DeclSpec::TST_union:
887 case DeclSpec::TST_struct:
888 case DeclSpec::TST_interface: {
889 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
891 // This can happen in C++ with ambiguous lookups.
892 Result = Context.IntTy;
893 declarator.setInvalidType(true);
897 // If the type is deprecated or unavailable, diagnose it.
898 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
900 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
901 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
903 // TypeQuals handled by caller.
904 Result = Context.getTypeDeclType(D);
906 // In both C and C++, make an ElaboratedType.
907 ElaboratedTypeKeyword Keyword
908 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
909 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
912 case DeclSpec::TST_typename: {
913 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
914 DS.getTypeSpecSign() == 0 &&
915 "Can't handle qualifiers on typedef names yet!");
916 Result = S.GetTypeFromParser(DS.getRepAsType());
918 declarator.setInvalidType(true);
919 else if (DeclSpec::ProtocolQualifierListTy PQ
920 = DS.getProtocolQualifiers()) {
921 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
922 // Silently drop any existing protocol qualifiers.
923 // TODO: determine whether that's the right thing to do.
924 if (ObjT->getNumProtocols())
925 Result = ObjT->getBaseType();
927 if (DS.getNumProtocolQualifiers())
928 Result = Context.getObjCObjectType(Result,
929 (ObjCProtocolDecl*const*) PQ,
930 DS.getNumProtocolQualifiers());
931 } else if (Result->isObjCIdType()) {
933 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
934 (ObjCProtocolDecl*const*) PQ,
935 DS.getNumProtocolQualifiers());
936 Result = Context.getObjCObjectPointerType(Result);
937 } else if (Result->isObjCClassType()) {
938 // Class<protocol-list>
939 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
940 (ObjCProtocolDecl*const*) PQ,
941 DS.getNumProtocolQualifiers());
942 Result = Context.getObjCObjectPointerType(Result);
944 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
945 << DS.getSourceRange();
946 declarator.setInvalidType(true);
950 // TypeQuals handled by caller.
953 case DeclSpec::TST_typeofType:
954 // FIXME: Preserve type source info.
955 Result = S.GetTypeFromParser(DS.getRepAsType());
956 assert(!Result.isNull() && "Didn't get a type for typeof?");
957 if (!Result->isDependentType())
958 if (const TagType *TT = Result->getAs<TagType>())
959 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
960 // TypeQuals handled by caller.
961 Result = Context.getTypeOfType(Result);
963 case DeclSpec::TST_typeofExpr: {
964 Expr *E = DS.getRepAsExpr();
965 assert(E && "Didn't get an expression for typeof?");
966 // TypeQuals handled by caller.
967 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
968 if (Result.isNull()) {
969 Result = Context.IntTy;
970 declarator.setInvalidType(true);
974 case DeclSpec::TST_decltype: {
975 Expr *E = DS.getRepAsExpr();
976 assert(E && "Didn't get an expression for decltype?");
977 // TypeQuals handled by caller.
978 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
979 if (Result.isNull()) {
980 Result = Context.IntTy;
981 declarator.setInvalidType(true);
985 case DeclSpec::TST_underlyingType:
986 Result = S.GetTypeFromParser(DS.getRepAsType());
987 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
988 Result = S.BuildUnaryTransformType(Result,
989 UnaryTransformType::EnumUnderlyingType,
990 DS.getTypeSpecTypeLoc());
991 if (Result.isNull()) {
992 Result = Context.IntTy;
993 declarator.setInvalidType(true);
997 case DeclSpec::TST_auto:
998 // TypeQuals handled by caller.
999 Result = Context.getAutoType(QualType(), /*decltype(auto)*/false);
1002 case DeclSpec::TST_decltype_auto:
1003 Result = Context.getAutoType(QualType(), /*decltype(auto)*/true);
1006 case DeclSpec::TST_unknown_anytype:
1007 Result = Context.UnknownAnyTy;
1010 case DeclSpec::TST_atomic:
1011 Result = S.GetTypeFromParser(DS.getRepAsType());
1012 assert(!Result.isNull() && "Didn't get a type for _Atomic?");
1013 Result = S.BuildAtomicType(Result, DS.getTypeSpecTypeLoc());
1014 if (Result.isNull()) {
1015 Result = Context.IntTy;
1016 declarator.setInvalidType(true);
1020 case DeclSpec::TST_image1d_t:
1021 Result = Context.OCLImage1dTy;
1024 case DeclSpec::TST_image1d_array_t:
1025 Result = Context.OCLImage1dArrayTy;
1028 case DeclSpec::TST_image1d_buffer_t:
1029 Result = Context.OCLImage1dBufferTy;
1032 case DeclSpec::TST_image2d_t:
1033 Result = Context.OCLImage2dTy;
1036 case DeclSpec::TST_image2d_array_t:
1037 Result = Context.OCLImage2dArrayTy;
1040 case DeclSpec::TST_image3d_t:
1041 Result = Context.OCLImage3dTy;
1044 case DeclSpec::TST_sampler_t:
1045 Result = Context.OCLSamplerTy;
1048 case DeclSpec::TST_event_t:
1049 Result = Context.OCLEventTy;
1052 case DeclSpec::TST_error:
1053 Result = Context.IntTy;
1054 declarator.setInvalidType(true);
1058 // Handle complex types.
1059 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
1060 if (S.getLangOpts().Freestanding)
1061 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
1062 Result = Context.getComplexType(Result);
1063 } else if (DS.isTypeAltiVecVector()) {
1064 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
1065 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
1066 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
1067 if (DS.isTypeAltiVecPixel())
1068 VecKind = VectorType::AltiVecPixel;
1069 else if (DS.isTypeAltiVecBool())
1070 VecKind = VectorType::AltiVecBool;
1071 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
1074 // FIXME: Imaginary.
1075 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
1076 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
1078 // Before we process any type attributes, synthesize a block literal
1079 // function declarator if necessary.
1080 if (declarator.getContext() == Declarator::BlockLiteralContext)
1081 maybeSynthesizeBlockSignature(state, Result);
1083 // Apply any type attributes from the decl spec. This may cause the
1084 // list of type attributes to be temporarily saved while the type
1085 // attributes are pushed around.
1086 if (AttributeList *attrs = DS.getAttributes().getList())
1087 processTypeAttrs(state, Result, TAL_DeclSpec, attrs);
1089 // Apply const/volatile/restrict qualifiers to T.
1090 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
1092 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
1093 // of a function type includes any type qualifiers, the behavior is
1095 if (Result->isFunctionType() && TypeQuals) {
1096 if (TypeQuals & DeclSpec::TQ_const)
1097 S.Diag(DS.getConstSpecLoc(), diag::warn_typecheck_function_qualifiers)
1098 << Result << DS.getSourceRange();
1099 else if (TypeQuals & DeclSpec::TQ_volatile)
1100 S.Diag(DS.getVolatileSpecLoc(), diag::warn_typecheck_function_qualifiers)
1101 << Result << DS.getSourceRange();
1103 assert((TypeQuals & (DeclSpec::TQ_restrict | DeclSpec::TQ_atomic)) &&
1104 "Has CVRA quals but not C, V, R, or A?");
1105 // No diagnostic; we'll diagnose 'restrict' or '_Atomic' applied to a
1106 // function type later, in BuildQualifiedType.
1111 // Cv-qualified references are ill-formed except when the
1112 // cv-qualifiers are introduced through the use of a typedef
1113 // (7.1.3) or of a template type argument (14.3), in which
1114 // case the cv-qualifiers are ignored.
1115 // FIXME: Shouldn't we be checking SCS_typedef here?
1116 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
1117 TypeQuals && Result->isReferenceType()) {
1118 TypeQuals &= ~DeclSpec::TQ_const;
1119 TypeQuals &= ~DeclSpec::TQ_volatile;
1120 TypeQuals &= ~DeclSpec::TQ_atomic;
1123 // C90 6.5.3 constraints: "The same type qualifier shall not appear more
1124 // than once in the same specifier-list or qualifier-list, either directly
1125 // or via one or more typedefs."
1126 if (!S.getLangOpts().C99 && !S.getLangOpts().CPlusPlus
1127 && TypeQuals & Result.getCVRQualifiers()) {
1128 if (TypeQuals & DeclSpec::TQ_const && Result.isConstQualified()) {
1129 S.Diag(DS.getConstSpecLoc(), diag::ext_duplicate_declspec)
1133 if (TypeQuals & DeclSpec::TQ_volatile && Result.isVolatileQualified()) {
1134 S.Diag(DS.getVolatileSpecLoc(), diag::ext_duplicate_declspec)
1138 // C90 doesn't have restrict nor _Atomic, so it doesn't force us to
1139 // produce a warning in this case.
1142 QualType Qualified = S.BuildQualifiedType(Result, DeclLoc, TypeQuals, &DS);
1144 // If adding qualifiers fails, just use the unqualified type.
1145 if (Qualified.isNull())
1146 declarator.setInvalidType(true);
1154 static std::string getPrintableNameForEntity(DeclarationName Entity) {
1156 return Entity.getAsString();
1161 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1162 Qualifiers Qs, const DeclSpec *DS) {
1163 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
1164 // object or incomplete types shall not be restrict-qualified."
1165 if (Qs.hasRestrict()) {
1166 unsigned DiagID = 0;
1169 if (T->isAnyPointerType() || T->isReferenceType() ||
1170 T->isMemberPointerType()) {
1172 if (T->isObjCObjectPointerType())
1174 else if (const MemberPointerType *PTy = T->getAs<MemberPointerType>())
1175 EltTy = PTy->getPointeeType();
1177 EltTy = T->getPointeeType();
1179 // If we have a pointer or reference, the pointee must have an object
1181 if (!EltTy->isIncompleteOrObjectType()) {
1182 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1185 } else if (!T->isDependentType()) {
1186 DiagID = diag::err_typecheck_invalid_restrict_not_pointer;
1191 Diag(DS ? DS->getRestrictSpecLoc() : Loc, DiagID) << ProblemTy;
1192 Qs.removeRestrict();
1196 return Context.getQualifiedType(T, Qs);
1199 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
1200 unsigned CVRA, const DeclSpec *DS) {
1201 // Convert from DeclSpec::TQ to Qualifiers::TQ by just dropping TQ_atomic.
1202 unsigned CVR = CVRA & ~DeclSpec::TQ_atomic;
1205 // If the same qualifier appears more than once in the same
1206 // specifier-qualifier-list, either directly or via one or more typedefs,
1207 // the behavior is the same as if it appeared only once.
1209 // It's not specified what happens when the _Atomic qualifier is applied to
1210 // a type specified with the _Atomic specifier, but we assume that this
1211 // should be treated as if the _Atomic qualifier appeared multiple times.
1212 if (CVRA & DeclSpec::TQ_atomic && !T->isAtomicType()) {
1214 // If other qualifiers appear along with the _Atomic qualifier in a
1215 // specifier-qualifier-list, the resulting type is the so-qualified
1218 // Don't need to worry about array types here, since _Atomic can't be
1219 // applied to such types.
1220 SplitQualType Split = T.getSplitUnqualifiedType();
1221 T = BuildAtomicType(QualType(Split.Ty, 0),
1222 DS ? DS->getAtomicSpecLoc() : Loc);
1225 Split.Quals.addCVRQualifiers(CVR);
1226 return BuildQualifiedType(T, Loc, Split.Quals);
1229 return BuildQualifiedType(T, Loc, Qualifiers::fromCVRMask(CVR), DS);
1232 /// \brief Build a paren type including \p T.
1233 QualType Sema::BuildParenType(QualType T) {
1234 return Context.getParenType(T);
1237 /// Given that we're building a pointer or reference to the given
1238 static QualType inferARCLifetimeForPointee(Sema &S, QualType type,
1241 // Bail out if retention is unrequired or already specified.
1242 if (!type->isObjCLifetimeType() ||
1243 type.getObjCLifetime() != Qualifiers::OCL_None)
1246 Qualifiers::ObjCLifetime implicitLifetime = Qualifiers::OCL_None;
1248 // If the object type is const-qualified, we can safely use
1249 // __unsafe_unretained. This is safe (because there are no read
1250 // barriers), and it'll be safe to coerce anything but __weak* to
1251 // the resulting type.
1252 if (type.isConstQualified()) {
1253 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1255 // Otherwise, check whether the static type does not require
1256 // retaining. This currently only triggers for Class (possibly
1257 // protocol-qualifed, and arrays thereof).
1258 } else if (type->isObjCARCImplicitlyUnretainedType()) {
1259 implicitLifetime = Qualifiers::OCL_ExplicitNone;
1261 // If we are in an unevaluated context, like sizeof, skip adding a
1263 } else if (S.isUnevaluatedContext()) {
1266 // If that failed, give an error and recover using __strong. __strong
1267 // is the option most likely to prevent spurious second-order diagnostics,
1268 // like when binding a reference to a field.
1270 // These types can show up in private ivars in system headers, so
1271 // we need this to not be an error in those cases. Instead we
1273 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1274 S.DelayedDiagnostics.add(
1275 sema::DelayedDiagnostic::makeForbiddenType(loc,
1276 diag::err_arc_indirect_no_ownership, type, isReference));
1278 S.Diag(loc, diag::err_arc_indirect_no_ownership) << type << isReference;
1280 implicitLifetime = Qualifiers::OCL_Strong;
1282 assert(implicitLifetime && "didn't infer any lifetime!");
1285 qs.addObjCLifetime(implicitLifetime);
1286 return S.Context.getQualifiedType(type, qs);
1289 /// \brief Build a pointer type.
1291 /// \param T The type to which we'll be building a pointer.
1293 /// \param Loc The location of the entity whose type involves this
1294 /// pointer type or, if there is no such entity, the location of the
1295 /// type that will have pointer type.
1297 /// \param Entity The name of the entity that involves the pointer
1300 /// \returns A suitable pointer type, if there are no
1301 /// errors. Otherwise, returns a NULL type.
1302 QualType Sema::BuildPointerType(QualType T,
1303 SourceLocation Loc, DeclarationName Entity) {
1304 if (T->isReferenceType()) {
1305 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1306 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1307 << getPrintableNameForEntity(Entity) << T;
1311 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1313 // In ARC, it is forbidden to build pointers to unqualified pointers.
1314 if (getLangOpts().ObjCAutoRefCount)
1315 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ false);
1317 // Build the pointer type.
1318 return Context.getPointerType(T);
1321 /// \brief Build a reference type.
1323 /// \param T The type to which we'll be building a reference.
1325 /// \param Loc The location of the entity whose type involves this
1326 /// reference type or, if there is no such entity, the location of the
1327 /// type that will have reference type.
1329 /// \param Entity The name of the entity that involves the reference
1332 /// \returns A suitable reference type, if there are no
1333 /// errors. Otherwise, returns a NULL type.
1334 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1336 DeclarationName Entity) {
1337 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1338 "Unresolved overloaded function type");
1340 // C++0x [dcl.ref]p6:
1341 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1342 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1343 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1344 // the type "lvalue reference to T", while an attempt to create the type
1345 // "rvalue reference to cv TR" creates the type TR.
1346 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1348 // C++ [dcl.ref]p4: There shall be no references to references.
1350 // According to C++ DR 106, references to references are only
1351 // diagnosed when they are written directly (e.g., "int & &"),
1352 // but not when they happen via a typedef:
1354 // typedef int& intref;
1355 // typedef intref& intref2;
1357 // Parser::ParseDeclaratorInternal diagnoses the case where
1358 // references are written directly; here, we handle the
1359 // collapsing of references-to-references as described in C++0x.
1360 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1363 // A declarator that specifies the type "reference to cv void"
1365 if (T->isVoidType()) {
1366 Diag(Loc, diag::err_reference_to_void);
1370 // In ARC, it is forbidden to build references to unqualified pointers.
1371 if (getLangOpts().ObjCAutoRefCount)
1372 T = inferARCLifetimeForPointee(*this, T, Loc, /*reference*/ true);
1374 // Handle restrict on references.
1376 return Context.getLValueReferenceType(T, SpelledAsLValue);
1377 return Context.getRValueReferenceType(T);
1380 /// Check whether the specified array size makes the array type a VLA. If so,
1381 /// return true, if not, return the size of the array in SizeVal.
1382 static bool isArraySizeVLA(Sema &S, Expr *ArraySize, llvm::APSInt &SizeVal) {
1383 // If the size is an ICE, it certainly isn't a VLA. If we're in a GNU mode
1384 // (like gnu99, but not c99) accept any evaluatable value as an extension.
1385 class VLADiagnoser : public Sema::VerifyICEDiagnoser {
1387 VLADiagnoser() : Sema::VerifyICEDiagnoser(true) {}
1389 virtual void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1392 virtual void diagnoseFold(Sema &S, SourceLocation Loc, SourceRange SR) {
1393 S.Diag(Loc, diag::ext_vla_folded_to_constant) << SR;
1397 return S.VerifyIntegerConstantExpression(ArraySize, &SizeVal, Diagnoser,
1398 S.LangOpts.GNUMode).isInvalid();
1402 /// \brief Build an array type.
1404 /// \param T The type of each element in the array.
1406 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1408 /// \param ArraySize Expression describing the size of the array.
1410 /// \param Brackets The range from the opening '[' to the closing ']'.
1412 /// \param Entity The name of the entity that involves the array
1415 /// \returns A suitable array type, if there are no errors. Otherwise,
1416 /// returns a NULL type.
1417 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1418 Expr *ArraySize, unsigned Quals,
1419 SourceRange Brackets, DeclarationName Entity) {
1421 SourceLocation Loc = Brackets.getBegin();
1422 if (getLangOpts().CPlusPlus) {
1423 // C++ [dcl.array]p1:
1424 // T is called the array element type; this type shall not be a reference
1425 // type, the (possibly cv-qualified) type void, a function type or an
1426 // abstract class type.
1428 // C++ [dcl.array]p3:
1429 // When several "array of" specifications are adjacent, [...] only the
1430 // first of the constant expressions that specify the bounds of the arrays
1433 // Note: function types are handled in the common path with C.
1434 if (T->isReferenceType()) {
1435 Diag(Loc, diag::err_illegal_decl_array_of_references)
1436 << getPrintableNameForEntity(Entity) << T;
1440 if (T->isVoidType() || T->isIncompleteArrayType()) {
1441 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1445 if (RequireNonAbstractType(Brackets.getBegin(), T,
1446 diag::err_array_of_abstract_type))
1450 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1451 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1452 if (RequireCompleteType(Loc, T,
1453 diag::err_illegal_decl_array_incomplete_type))
1457 if (T->isFunctionType()) {
1458 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1459 << getPrintableNameForEntity(Entity) << T;
1463 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1464 // If the element type is a struct or union that contains a variadic
1465 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1466 if (EltTy->getDecl()->hasFlexibleArrayMember())
1467 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1468 } else if (T->isObjCObjectType()) {
1469 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1473 // Do placeholder conversions on the array size expression.
1474 if (ArraySize && ArraySize->hasPlaceholderType()) {
1475 ExprResult Result = CheckPlaceholderExpr(ArraySize);
1476 if (Result.isInvalid()) return QualType();
1477 ArraySize = Result.take();
1480 // Do lvalue-to-rvalue conversions on the array size expression.
1481 if (ArraySize && !ArraySize->isRValue()) {
1482 ExprResult Result = DefaultLvalueConversion(ArraySize);
1483 if (Result.isInvalid())
1486 ArraySize = Result.take();
1489 // C99 6.7.5.2p1: The size expression shall have integer type.
1490 // C++11 allows contextual conversions to such types.
1491 if (!getLangOpts().CPlusPlus11 &&
1492 ArraySize && !ArraySize->isTypeDependent() &&
1493 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1494 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1495 << ArraySize->getType() << ArraySize->getSourceRange();
1499 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1501 if (ASM == ArrayType::Star)
1502 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1504 T = Context.getIncompleteArrayType(T, ASM, Quals);
1505 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1506 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1507 } else if ((!T->isDependentType() && !T->isIncompleteType() &&
1508 !T->isConstantSizeType()) ||
1509 isArraySizeVLA(*this, ArraySize, ConstVal)) {
1510 // Even in C++11, don't allow contextual conversions in the array bound
1512 if (getLangOpts().CPlusPlus11 &&
1513 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1514 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1515 << ArraySize->getType() << ArraySize->getSourceRange();
1519 // C99: an array with an element type that has a non-constant-size is a VLA.
1520 // C99: an array with a non-ICE size is a VLA. We accept any expression
1521 // that we can fold to a non-zero positive value as an extension.
1522 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1524 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1525 // have a value greater than zero.
1526 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1528 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1529 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1531 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1532 << ArraySize->getSourceRange();
1535 if (ConstVal == 0) {
1536 // GCC accepts zero sized static arrays. We allow them when
1537 // we're not in a SFINAE context.
1538 Diag(ArraySize->getLocStart(),
1539 isSFINAEContext()? diag::err_typecheck_zero_array_size
1540 : diag::ext_typecheck_zero_array_size)
1541 << ArraySize->getSourceRange();
1543 if (ASM == ArrayType::Static) {
1544 Diag(ArraySize->getLocStart(),
1545 diag::warn_typecheck_zero_static_array_size)
1546 << ArraySize->getSourceRange();
1547 ASM = ArrayType::Normal;
1549 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1550 !T->isIncompleteType()) {
1551 // Is the array too large?
1552 unsigned ActiveSizeBits
1553 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1554 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1555 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1556 << ConstVal.toString(10)
1557 << ArraySize->getSourceRange();
1560 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1563 // OpenCL v1.2 s6.9.d: variable length arrays are not supported.
1564 if (getLangOpts().OpenCL && T->isVariableArrayType()) {
1565 Diag(Loc, diag::err_opencl_vla);
1568 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1569 if (!getLangOpts().C99) {
1570 if (T->isVariableArrayType()) {
1571 // Prohibit the use of non-POD types in VLAs.
1572 // FIXME: C++1y allows this.
1573 QualType BaseT = Context.getBaseElementType(T);
1574 if (!T->isDependentType() &&
1575 !BaseT.isPODType(Context) &&
1576 !BaseT->isObjCLifetimeType()) {
1577 Diag(Loc, diag::err_vla_non_pod)
1581 // Prohibit the use of VLAs during template argument deduction.
1582 else if (isSFINAEContext()) {
1583 Diag(Loc, diag::err_vla_in_sfinae);
1586 // Just extwarn about VLAs.
1588 Diag(Loc, getLangOpts().CPlusPlus1y
1589 ? diag::warn_cxx11_compat_array_of_runtime_bound
1591 } else if (ASM != ArrayType::Normal || Quals != 0)
1593 getLangOpts().CPlusPlus? diag::err_c99_array_usage_cxx
1594 : diag::ext_c99_array_usage) << ASM;
1597 if (T->isVariableArrayType()) {
1598 // Warn about VLAs for -Wvla.
1599 Diag(Loc, diag::warn_vla_used);
1605 /// \brief Build an ext-vector type.
1607 /// Run the required checks for the extended vector type.
1608 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1609 SourceLocation AttrLoc) {
1610 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1611 // in conjunction with complex types (pointers, arrays, functions, etc.).
1612 if (!T->isDependentType() &&
1613 !T->isIntegerType() && !T->isRealFloatingType()) {
1614 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1618 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1619 llvm::APSInt vecSize(32);
1620 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1621 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1622 << "ext_vector_type" << ArraySize->getSourceRange();
1626 // unlike gcc's vector_size attribute, the size is specified as the
1627 // number of elements, not the number of bytes.
1628 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1630 if (vectorSize == 0) {
1631 Diag(AttrLoc, diag::err_attribute_zero_size)
1632 << ArraySize->getSourceRange();
1636 return Context.getExtVectorType(T, vectorSize);
1639 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1642 QualType Sema::BuildFunctionType(QualType T,
1643 llvm::MutableArrayRef<QualType> ParamTypes,
1644 SourceLocation Loc, DeclarationName Entity,
1645 const FunctionProtoType::ExtProtoInfo &EPI) {
1646 if (T->isArrayType() || T->isFunctionType()) {
1647 Diag(Loc, diag::err_func_returning_array_function)
1648 << T->isFunctionType() << T;
1652 // Functions cannot return half FP.
1653 if (T->isHalfType()) {
1654 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 1 <<
1655 FixItHint::CreateInsertion(Loc, "*");
1659 bool Invalid = false;
1660 for (unsigned Idx = 0, Cnt = ParamTypes.size(); Idx < Cnt; ++Idx) {
1661 // FIXME: Loc is too inprecise here, should use proper locations for args.
1662 QualType ParamType = Context.getAdjustedParameterType(ParamTypes[Idx]);
1663 if (ParamType->isVoidType()) {
1664 Diag(Loc, diag::err_param_with_void_type);
1666 } else if (ParamType->isHalfType()) {
1667 // Disallow half FP arguments.
1668 Diag(Loc, diag::err_parameters_retval_cannot_have_fp16_type) << 0 <<
1669 FixItHint::CreateInsertion(Loc, "*");
1673 ParamTypes[Idx] = ParamType;
1679 return Context.getFunctionType(T, ParamTypes, EPI);
1682 /// \brief Build a member pointer type \c T Class::*.
1684 /// \param T the type to which the member pointer refers.
1685 /// \param Class the class type into which the member pointer points.
1686 /// \param Loc the location where this type begins
1687 /// \param Entity the name of the entity that will have this member pointer type
1689 /// \returns a member pointer type, if successful, or a NULL type if there was
1691 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1693 DeclarationName Entity) {
1694 // Verify that we're not building a pointer to pointer to function with
1695 // exception specification.
1696 if (CheckDistantExceptionSpec(T)) {
1697 Diag(Loc, diag::err_distant_exception_spec);
1699 // FIXME: If we're doing this as part of template instantiation,
1700 // we should return immediately.
1702 // Build the type anyway, but use the canonical type so that the
1703 // exception specifiers are stripped off.
1704 T = Context.getCanonicalType(T);
1707 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1708 // with reference type, or "cv void."
1709 if (T->isReferenceType()) {
1710 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1711 << (Entity? Entity.getAsString() : "type name") << T;
1715 if (T->isVoidType()) {
1716 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1717 << (Entity? Entity.getAsString() : "type name");
1721 if (!Class->isDependentType() && !Class->isRecordType()) {
1722 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1726 // C++ allows the class type in a member pointer to be an incomplete type.
1727 // In the Microsoft ABI, the size of the member pointer can vary
1728 // according to the class type, which means that we really need a
1729 // complete type if possible, which means we need to instantiate templates.
1731 // If template instantiation fails or the type is just incomplete, we have to
1732 // add an extra slot to the member pointer. Yes, this does cause problems
1733 // when passing pointers between TUs that disagree about the size.
1734 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
1735 CXXRecordDecl *RD = Class->getAsCXXRecordDecl();
1736 if (RD && !RD->hasAttr<MSInheritanceAttr>()) {
1737 // Lock in the inheritance model on the first use of a member pointer.
1738 // Otherwise we may disagree about the size at different points in the TU.
1739 // FIXME: MSVC picks a model on the first use that needs to know the size,
1740 // rather than on the first mention of the type, e.g. typedefs.
1741 if (RequireCompleteType(Loc, Class, 0) && !RD->isBeingDefined()) {
1742 // We know it doesn't have an attribute and it's incomplete, so use the
1743 // unspecified inheritance model. If we're in the record body, we can
1744 // figure out the inheritance model.
1745 for (CXXRecordDecl::redecl_iterator I = RD->redecls_begin(),
1746 E = RD->redecls_end(); I != E; ++I) {
1747 I->addAttr(::new (Context) UnspecifiedInheritanceAttr(
1748 RD->getSourceRange(), Context));
1754 return Context.getMemberPointerType(T, Class.getTypePtr());
1757 /// \brief Build a block pointer type.
1759 /// \param T The type to which we'll be building a block pointer.
1761 /// \param Loc The source location, used for diagnostics.
1763 /// \param Entity The name of the entity that involves the block pointer
1766 /// \returns A suitable block pointer type, if there are no
1767 /// errors. Otherwise, returns a NULL type.
1768 QualType Sema::BuildBlockPointerType(QualType T,
1770 DeclarationName Entity) {
1771 if (!T->isFunctionType()) {
1772 Diag(Loc, diag::err_nonfunction_block_type);
1776 return Context.getBlockPointerType(T);
1779 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1780 QualType QT = Ty.get();
1782 if (TInfo) *TInfo = 0;
1786 TypeSourceInfo *DI = 0;
1787 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1788 QT = LIT->getType();
1789 DI = LIT->getTypeSourceInfo();
1792 if (TInfo) *TInfo = DI;
1796 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
1797 Qualifiers::ObjCLifetime ownership,
1798 unsigned chunkIndex);
1800 /// Given that this is the declaration of a parameter under ARC,
1801 /// attempt to infer attributes and such for pointer-to-whatever
1803 static void inferARCWriteback(TypeProcessingState &state,
1804 QualType &declSpecType) {
1805 Sema &S = state.getSema();
1806 Declarator &declarator = state.getDeclarator();
1808 // TODO: should we care about decl qualifiers?
1810 // Check whether the declarator has the expected form. We walk
1811 // from the inside out in order to make the block logic work.
1812 unsigned outermostPointerIndex = 0;
1813 bool isBlockPointer = false;
1814 unsigned numPointers = 0;
1815 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
1816 unsigned chunkIndex = i;
1817 DeclaratorChunk &chunk = declarator.getTypeObject(chunkIndex);
1818 switch (chunk.Kind) {
1819 case DeclaratorChunk::Paren:
1823 case DeclaratorChunk::Reference:
1824 case DeclaratorChunk::Pointer:
1825 // Count the number of pointers. Treat references
1826 // interchangeably as pointers; if they're mis-ordered, normal
1827 // type building will discover that.
1828 outermostPointerIndex = chunkIndex;
1832 case DeclaratorChunk::BlockPointer:
1833 // If we have a pointer to block pointer, that's an acceptable
1834 // indirect reference; anything else is not an application of
1836 if (numPointers != 1) return;
1838 outermostPointerIndex = chunkIndex;
1839 isBlockPointer = true;
1841 // We don't care about pointer structure in return values here.
1844 case DeclaratorChunk::Array: // suppress if written (id[])?
1845 case DeclaratorChunk::Function:
1846 case DeclaratorChunk::MemberPointer:
1852 // If we have *one* pointer, then we want to throw the qualifier on
1853 // the declaration-specifiers, which means that it needs to be a
1854 // retainable object type.
1855 if (numPointers == 1) {
1856 // If it's not a retainable object type, the rule doesn't apply.
1857 if (!declSpecType->isObjCRetainableType()) return;
1859 // If it already has lifetime, don't do anything.
1860 if (declSpecType.getObjCLifetime()) return;
1862 // Otherwise, modify the type in-place.
1865 if (declSpecType->isObjCARCImplicitlyUnretainedType())
1866 qs.addObjCLifetime(Qualifiers::OCL_ExplicitNone);
1868 qs.addObjCLifetime(Qualifiers::OCL_Autoreleasing);
1869 declSpecType = S.Context.getQualifiedType(declSpecType, qs);
1871 // If we have *two* pointers, then we want to throw the qualifier on
1872 // the outermost pointer.
1873 } else if (numPointers == 2) {
1874 // If we don't have a block pointer, we need to check whether the
1875 // declaration-specifiers gave us something that will turn into a
1876 // retainable object pointer after we slap the first pointer on it.
1877 if (!isBlockPointer && !declSpecType->isObjCObjectType())
1880 // Look for an explicit lifetime attribute there.
1881 DeclaratorChunk &chunk = declarator.getTypeObject(outermostPointerIndex);
1882 if (chunk.Kind != DeclaratorChunk::Pointer &&
1883 chunk.Kind != DeclaratorChunk::BlockPointer)
1885 for (const AttributeList *attr = chunk.getAttrs(); attr;
1886 attr = attr->getNext())
1887 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
1890 transferARCOwnershipToDeclaratorChunk(state, Qualifiers::OCL_Autoreleasing,
1891 outermostPointerIndex);
1893 // Any other number of pointers/references does not trigger the rule.
1896 // TODO: mark whether we did this inference?
1899 static void diagnoseIgnoredQualifiers(
1900 Sema &S, unsigned Quals,
1901 SourceLocation FallbackLoc,
1902 SourceLocation ConstQualLoc = SourceLocation(),
1903 SourceLocation VolatileQualLoc = SourceLocation(),
1904 SourceLocation RestrictQualLoc = SourceLocation(),
1905 SourceLocation AtomicQualLoc = SourceLocation()) {
1909 const SourceManager &SM = S.getSourceManager();
1915 } const QualKinds[4] = {
1916 { DeclSpec::TQ_const, "const", ConstQualLoc },
1917 { DeclSpec::TQ_volatile, "volatile", VolatileQualLoc },
1918 { DeclSpec::TQ_restrict, "restrict", RestrictQualLoc },
1919 { DeclSpec::TQ_atomic, "_Atomic", AtomicQualLoc }
1922 llvm::SmallString<32> QualStr;
1923 unsigned NumQuals = 0;
1925 FixItHint FixIts[4];
1927 // Build a string naming the redundant qualifiers.
1928 for (unsigned I = 0; I != 4; ++I) {
1929 if (Quals & QualKinds[I].Mask) {
1930 if (!QualStr.empty()) QualStr += ' ';
1931 QualStr += QualKinds[I].Name;
1933 // If we have a location for the qualifier, offer a fixit.
1934 SourceLocation QualLoc = QualKinds[I].Loc;
1935 if (!QualLoc.isInvalid()) {
1936 FixIts[NumQuals] = FixItHint::CreateRemoval(QualLoc);
1937 if (Loc.isInvalid() || SM.isBeforeInTranslationUnit(QualLoc, Loc))
1945 S.Diag(Loc.isInvalid() ? FallbackLoc : Loc, diag::warn_qual_return_type)
1946 << QualStr << NumQuals << FixIts[0] << FixIts[1] << FixIts[2] << FixIts[3];
1949 // Diagnose pointless type qualifiers on the return type of a function.
1950 static void diagnoseIgnoredFunctionQualifiers(Sema &S, QualType RetTy,
1952 unsigned FunctionChunkIndex) {
1953 if (D.getTypeObject(FunctionChunkIndex).Fun.hasTrailingReturnType()) {
1954 // FIXME: TypeSourceInfo doesn't preserve location information for
1956 diagnoseIgnoredQualifiers(S, RetTy.getLocalCVRQualifiers(),
1957 D.getIdentifierLoc());
1961 for (unsigned OuterChunkIndex = FunctionChunkIndex + 1,
1962 End = D.getNumTypeObjects();
1963 OuterChunkIndex != End; ++OuterChunkIndex) {
1964 DeclaratorChunk &OuterChunk = D.getTypeObject(OuterChunkIndex);
1965 switch (OuterChunk.Kind) {
1966 case DeclaratorChunk::Paren:
1969 case DeclaratorChunk::Pointer: {
1970 DeclaratorChunk::PointerTypeInfo &PTI = OuterChunk.Ptr;
1971 diagnoseIgnoredQualifiers(
1974 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
1975 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
1976 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
1977 SourceLocation::getFromRawEncoding(PTI.AtomicQualLoc));
1981 case DeclaratorChunk::Function:
1982 case DeclaratorChunk::BlockPointer:
1983 case DeclaratorChunk::Reference:
1984 case DeclaratorChunk::Array:
1985 case DeclaratorChunk::MemberPointer:
1986 // FIXME: We can't currently provide an accurate source location and a
1987 // fix-it hint for these.
1988 unsigned AtomicQual = RetTy->isAtomicType() ? DeclSpec::TQ_atomic : 0;
1989 diagnoseIgnoredQualifiers(S, RetTy.getCVRQualifiers() | AtomicQual,
1990 D.getIdentifierLoc());
1994 llvm_unreachable("unknown declarator chunk kind");
1997 // If the qualifiers come from a conversion function type, don't diagnose
1998 // them -- they're not necessarily redundant, since such a conversion
1999 // operator can be explicitly called as "x.operator const int()".
2000 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2003 // Just parens all the way out to the decl specifiers. Diagnose any qualifiers
2004 // which are present there.
2005 diagnoseIgnoredQualifiers(S, D.getDeclSpec().getTypeQualifiers(),
2006 D.getIdentifierLoc(),
2007 D.getDeclSpec().getConstSpecLoc(),
2008 D.getDeclSpec().getVolatileSpecLoc(),
2009 D.getDeclSpec().getRestrictSpecLoc(),
2010 D.getDeclSpec().getAtomicSpecLoc());
2013 static QualType GetDeclSpecTypeForDeclarator(TypeProcessingState &state,
2014 TypeSourceInfo *&ReturnTypeInfo) {
2015 Sema &SemaRef = state.getSema();
2016 Declarator &D = state.getDeclarator();
2020 // The TagDecl owned by the DeclSpec.
2021 TagDecl *OwnedTagDecl = 0;
2023 bool ContainsPlaceholderType = false;
2025 switch (D.getName().getKind()) {
2026 case UnqualifiedId::IK_ImplicitSelfParam:
2027 case UnqualifiedId::IK_OperatorFunctionId:
2028 case UnqualifiedId::IK_Identifier:
2029 case UnqualifiedId::IK_LiteralOperatorId:
2030 case UnqualifiedId::IK_TemplateId:
2031 T = ConvertDeclSpecToType(state);
2032 ContainsPlaceholderType = D.getDeclSpec().containsPlaceholderType();
2034 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
2035 OwnedTagDecl = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2036 // Owned declaration is embedded in declarator.
2037 OwnedTagDecl->setEmbeddedInDeclarator(true);
2041 case UnqualifiedId::IK_ConstructorName:
2042 case UnqualifiedId::IK_ConstructorTemplateId:
2043 case UnqualifiedId::IK_DestructorName:
2044 // Constructors and destructors don't have return types. Use
2046 T = SemaRef.Context.VoidTy;
2047 if (AttributeList *attrs = D.getDeclSpec().getAttributes().getList())
2048 processTypeAttrs(state, T, TAL_DeclSpec, attrs);
2051 case UnqualifiedId::IK_ConversionFunctionId:
2052 // The result type of a conversion function is the type that it
2054 T = SemaRef.GetTypeFromParser(D.getName().ConversionFunctionId,
2056 ContainsPlaceholderType = T->getContainedAutoType();
2060 if (D.getAttributes())
2061 distributeTypeAttrsFromDeclarator(state, T);
2063 // C++11 [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
2064 // In C++11, a function declarator using 'auto' must have a trailing return
2065 // type (this is checked later) and we can skip this. In other languages
2066 // using auto, we need to check regardless.
2067 if (ContainsPlaceholderType &&
2068 (!SemaRef.getLangOpts().CPlusPlus11 || !D.isFunctionDeclarator())) {
2071 switch (D.getContext()) {
2072 case Declarator::KNRTypeListContext:
2073 llvm_unreachable("K&R type lists aren't allowed in C++");
2074 case Declarator::LambdaExprContext:
2075 llvm_unreachable("Can't specify a type specifier in lambda grammar");
2076 case Declarator::ObjCParameterContext:
2077 case Declarator::ObjCResultContext:
2078 case Declarator::PrototypeContext:
2079 Error = 0; // Function prototype
2081 case Declarator::MemberContext:
2082 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
2084 switch (cast<TagDecl>(SemaRef.CurContext)->getTagKind()) {
2085 case TTK_Enum: llvm_unreachable("unhandled tag kind");
2086 case TTK_Struct: Error = 1; /* Struct member */ break;
2087 case TTK_Union: Error = 2; /* Union member */ break;
2088 case TTK_Class: Error = 3; /* Class member */ break;
2089 case TTK_Interface: Error = 4; /* Interface member */ break;
2092 case Declarator::CXXCatchContext:
2093 case Declarator::ObjCCatchContext:
2094 Error = 5; // Exception declaration
2096 case Declarator::TemplateParamContext:
2097 Error = 6; // Template parameter
2099 case Declarator::BlockLiteralContext:
2100 Error = 7; // Block literal
2102 case Declarator::TemplateTypeArgContext:
2103 Error = 8; // Template type argument
2105 case Declarator::AliasDeclContext:
2106 case Declarator::AliasTemplateContext:
2107 Error = 10; // Type alias
2109 case Declarator::TrailingReturnContext:
2110 if (!SemaRef.getLangOpts().CPlusPlus1y)
2111 Error = 11; // Function return type
2113 case Declarator::ConversionIdContext:
2114 if (!SemaRef.getLangOpts().CPlusPlus1y)
2115 Error = 12; // conversion-type-id
2117 case Declarator::TypeNameContext:
2118 Error = 13; // Generic
2120 case Declarator::FileContext:
2121 case Declarator::BlockContext:
2122 case Declarator::ForContext:
2123 case Declarator::ConditionContext:
2124 case Declarator::CXXNewContext:
2128 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
2131 // In Objective-C it is an error to use 'auto' on a function declarator.
2132 if (D.isFunctionDeclarator())
2135 // C++11 [dcl.spec.auto]p2: 'auto' is always fine if the declarator
2136 // contains a trailing return type. That is only legal at the outermost
2137 // level. Check all declarator chunks (outermost first) anyway, to give
2138 // better diagnostics.
2139 if (SemaRef.getLangOpts().CPlusPlus11 && Error != -1) {
2140 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2141 unsigned chunkIndex = e - i - 1;
2142 state.setCurrentChunkIndex(chunkIndex);
2143 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2144 if (DeclType.Kind == DeclaratorChunk::Function) {
2145 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2146 if (FTI.hasTrailingReturnType()) {
2154 SourceRange AutoRange = D.getDeclSpec().getTypeSpecTypeLoc();
2155 if (D.getName().getKind() == UnqualifiedId::IK_ConversionFunctionId)
2156 AutoRange = D.getName().getSourceRange();
2159 SemaRef.Diag(AutoRange.getBegin(), diag::err_auto_not_allowed)
2160 << Error << AutoRange;
2161 T = SemaRef.Context.IntTy;
2162 D.setInvalidType(true);
2164 SemaRef.Diag(AutoRange.getBegin(),
2165 diag::warn_cxx98_compat_auto_type_specifier)
2169 if (SemaRef.getLangOpts().CPlusPlus &&
2170 OwnedTagDecl && OwnedTagDecl->isCompleteDefinition()) {
2171 // Check the contexts where C++ forbids the declaration of a new class
2172 // or enumeration in a type-specifier-seq.
2173 switch (D.getContext()) {
2174 case Declarator::TrailingReturnContext:
2175 // Class and enumeration definitions are syntactically not allowed in
2176 // trailing return types.
2177 llvm_unreachable("parser should not have allowed this");
2179 case Declarator::FileContext:
2180 case Declarator::MemberContext:
2181 case Declarator::BlockContext:
2182 case Declarator::ForContext:
2183 case Declarator::BlockLiteralContext:
2184 case Declarator::LambdaExprContext:
2185 // C++11 [dcl.type]p3:
2186 // A type-specifier-seq shall not define a class or enumeration unless
2187 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2188 // the declaration of a template-declaration.
2189 case Declarator::AliasDeclContext:
2191 case Declarator::AliasTemplateContext:
2192 SemaRef.Diag(OwnedTagDecl->getLocation(),
2193 diag::err_type_defined_in_alias_template)
2194 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2195 D.setInvalidType(true);
2197 case Declarator::TypeNameContext:
2198 case Declarator::ConversionIdContext:
2199 case Declarator::TemplateParamContext:
2200 case Declarator::CXXNewContext:
2201 case Declarator::CXXCatchContext:
2202 case Declarator::ObjCCatchContext:
2203 case Declarator::TemplateTypeArgContext:
2204 SemaRef.Diag(OwnedTagDecl->getLocation(),
2205 diag::err_type_defined_in_type_specifier)
2206 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2207 D.setInvalidType(true);
2209 case Declarator::PrototypeContext:
2210 case Declarator::ObjCParameterContext:
2211 case Declarator::ObjCResultContext:
2212 case Declarator::KNRTypeListContext:
2214 // Types shall not be defined in return or parameter types.
2215 SemaRef.Diag(OwnedTagDecl->getLocation(),
2216 diag::err_type_defined_in_param_type)
2217 << SemaRef.Context.getTypeDeclType(OwnedTagDecl);
2218 D.setInvalidType(true);
2220 case Declarator::ConditionContext:
2222 // The type-specifier-seq shall not contain typedef and shall not declare
2223 // a new class or enumeration.
2224 SemaRef.Diag(OwnedTagDecl->getLocation(),
2225 diag::err_type_defined_in_condition);
2226 D.setInvalidType(true);
2234 static std::string getFunctionQualifiersAsString(const FunctionProtoType *FnTy){
2236 Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2238 switch (FnTy->getRefQualifier()) {
2258 /// Check that the function type T, which has a cv-qualifier or a ref-qualifier,
2259 /// can be contained within the declarator chunk DeclType, and produce an
2260 /// appropriate diagnostic if not.
2261 static void checkQualifiedFunction(Sema &S, QualType T,
2262 DeclaratorChunk &DeclType) {
2263 // C++98 [dcl.fct]p4 / C++11 [dcl.fct]p6: a function type with a
2264 // cv-qualifier or a ref-qualifier can only appear at the topmost level
2267 switch (DeclType.Kind) {
2268 case DeclaratorChunk::Paren:
2269 case DeclaratorChunk::MemberPointer:
2270 // These cases are permitted.
2272 case DeclaratorChunk::Array:
2273 case DeclaratorChunk::Function:
2274 // These cases don't allow function types at all; no need to diagnose the
2275 // qualifiers separately.
2277 case DeclaratorChunk::BlockPointer:
2280 case DeclaratorChunk::Pointer:
2283 case DeclaratorChunk::Reference:
2288 assert(DiagKind != -1);
2289 S.Diag(DeclType.Loc, diag::err_compound_qualified_function_type)
2290 << DiagKind << isa<FunctionType>(T.IgnoreParens()) << T
2291 << getFunctionQualifiersAsString(T->castAs<FunctionProtoType>());
2294 /// Produce an approprioate diagnostic for an ambiguity between a function
2295 /// declarator and a C++ direct-initializer.
2296 static void warnAboutAmbiguousFunction(Sema &S, Declarator &D,
2297 DeclaratorChunk &DeclType, QualType RT) {
2298 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2299 assert(FTI.isAmbiguous && "no direct-initializer / function ambiguity");
2301 // If the return type is void there is no ambiguity.
2302 if (RT->isVoidType())
2305 // An initializer for a non-class type can have at most one argument.
2306 if (!RT->isRecordType() && FTI.NumArgs > 1)
2309 // An initializer for a reference must have exactly one argument.
2310 if (RT->isReferenceType() && FTI.NumArgs != 1)
2313 // Only warn if this declarator is declaring a function at block scope, and
2314 // doesn't have a storage class (such as 'extern') specified.
2315 if (!D.isFunctionDeclarator() ||
2316 D.getFunctionDefinitionKind() != FDK_Declaration ||
2317 !S.CurContext->isFunctionOrMethod() ||
2318 D.getDeclSpec().getStorageClassSpec()
2319 != DeclSpec::SCS_unspecified)
2322 // Inside a condition, a direct initializer is not permitted. We allow one to
2323 // be parsed in order to give better diagnostics in condition parsing.
2324 if (D.getContext() == Declarator::ConditionContext)
2327 SourceRange ParenRange(DeclType.Loc, DeclType.EndLoc);
2329 S.Diag(DeclType.Loc,
2330 FTI.NumArgs ? diag::warn_parens_disambiguated_as_function_declaration
2331 : diag::warn_empty_parens_are_function_decl)
2334 // If the declaration looks like:
2337 // and name lookup finds a function named 'f', then the ',' was
2338 // probably intended to be a ';'.
2339 if (!D.isFirstDeclarator() && D.getIdentifier()) {
2340 FullSourceLoc Comma(D.getCommaLoc(), S.SourceMgr);
2341 FullSourceLoc Name(D.getIdentifierLoc(), S.SourceMgr);
2342 if (Comma.getFileID() != Name.getFileID() ||
2343 Comma.getSpellingLineNumber() != Name.getSpellingLineNumber()) {
2344 LookupResult Result(S, D.getIdentifier(), SourceLocation(),
2345 Sema::LookupOrdinaryName);
2346 if (S.LookupName(Result, S.getCurScope()))
2347 S.Diag(D.getCommaLoc(), diag::note_empty_parens_function_call)
2348 << FixItHint::CreateReplacement(D.getCommaLoc(), ";")
2349 << D.getIdentifier();
2353 if (FTI.NumArgs > 0) {
2354 // For a declaration with parameters, eg. "T var(T());", suggest adding parens
2355 // around the first parameter to turn the declaration into a variable
2357 SourceRange Range = FTI.ArgInfo[0].Param->getSourceRange();
2358 SourceLocation B = Range.getBegin();
2359 SourceLocation E = S.PP.getLocForEndOfToken(Range.getEnd());
2360 // FIXME: Maybe we should suggest adding braces instead of parens
2361 // in C++11 for classes that don't have an initializer_list constructor.
2362 S.Diag(B, diag::note_additional_parens_for_variable_declaration)
2363 << FixItHint::CreateInsertion(B, "(")
2364 << FixItHint::CreateInsertion(E, ")");
2366 // For a declaration without parameters, eg. "T var();", suggest replacing the
2367 // parens with an initializer to turn the declaration into a variable
2369 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
2371 // Empty parens mean value-initialization, and no parens mean
2372 // default initialization. These are equivalent if the default
2373 // constructor is user-provided or if zero-initialization is a
2375 if (RD && RD->hasDefinition() &&
2376 (RD->isEmpty() || RD->hasUserProvidedDefaultConstructor()))
2377 S.Diag(DeclType.Loc, diag::note_empty_parens_default_ctor)
2378 << FixItHint::CreateRemoval(ParenRange);
2380 std::string Init = S.getFixItZeroInitializerForType(RT);
2381 if (Init.empty() && S.LangOpts.CPlusPlus11)
2384 S.Diag(DeclType.Loc, diag::note_empty_parens_zero_initialize)
2385 << FixItHint::CreateReplacement(ParenRange, Init);
2390 static TypeSourceInfo *GetFullTypeForDeclarator(TypeProcessingState &state,
2391 QualType declSpecType,
2392 TypeSourceInfo *TInfo) {
2394 QualType T = declSpecType;
2395 Declarator &D = state.getDeclarator();
2396 Sema &S = state.getSema();
2397 ASTContext &Context = S.Context;
2398 const LangOptions &LangOpts = S.getLangOpts();
2400 // The name we're declaring, if any.
2401 DeclarationName Name;
2402 if (D.getIdentifier())
2403 Name = D.getIdentifier();
2405 // Does this declaration declare a typedef-name?
2406 bool IsTypedefName =
2407 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
2408 D.getContext() == Declarator::AliasDeclContext ||
2409 D.getContext() == Declarator::AliasTemplateContext;
2411 // Does T refer to a function type with a cv-qualifier or a ref-qualifier?
2412 bool IsQualifiedFunction = T->isFunctionProtoType() &&
2413 (T->castAs<FunctionProtoType>()->getTypeQuals() != 0 ||
2414 T->castAs<FunctionProtoType>()->getRefQualifier() != RQ_None);
2416 // If T is 'decltype(auto)', the only declarators we can have are parens
2417 // and at most one function declarator if this is a function declaration.
2418 if (const AutoType *AT = T->getAs<AutoType>()) {
2419 if (AT->isDecltypeAuto()) {
2420 for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
2421 unsigned Index = E - I - 1;
2422 DeclaratorChunk &DeclChunk = D.getTypeObject(Index);
2423 unsigned DiagId = diag::err_decltype_auto_compound_type;
2424 unsigned DiagKind = 0;
2425 switch (DeclChunk.Kind) {
2426 case DeclaratorChunk::Paren:
2428 case DeclaratorChunk::Function: {
2430 if (D.isFunctionDeclarationContext() &&
2431 D.isFunctionDeclarator(FnIndex) && FnIndex == Index)
2433 DiagId = diag::err_decltype_auto_function_declarator_not_declaration;
2436 case DeclaratorChunk::Pointer:
2437 case DeclaratorChunk::BlockPointer:
2438 case DeclaratorChunk::MemberPointer:
2441 case DeclaratorChunk::Reference:
2444 case DeclaratorChunk::Array:
2449 S.Diag(DeclChunk.Loc, DiagId) << DiagKind;
2450 D.setInvalidType(true);
2456 // Walk the DeclTypeInfo, building the recursive type as we go.
2457 // DeclTypeInfos are ordered from the identifier out, which is
2458 // opposite of what we want :).
2459 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2460 unsigned chunkIndex = e - i - 1;
2461 state.setCurrentChunkIndex(chunkIndex);
2462 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
2463 if (IsQualifiedFunction) {
2464 checkQualifiedFunction(S, T, DeclType);
2465 IsQualifiedFunction = DeclType.Kind == DeclaratorChunk::Paren;
2467 switch (DeclType.Kind) {
2468 case DeclaratorChunk::Paren:
2469 T = S.BuildParenType(T);
2471 case DeclaratorChunk::BlockPointer:
2472 // If blocks are disabled, emit an error.
2473 if (!LangOpts.Blocks)
2474 S.Diag(DeclType.Loc, diag::err_blocks_disable);
2476 T = S.BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
2477 if (DeclType.Cls.TypeQuals)
2478 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
2480 case DeclaratorChunk::Pointer:
2481 // Verify that we're not building a pointer to pointer to function with
2482 // exception specification.
2483 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2484 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2485 D.setInvalidType(true);
2486 // Build the type anyway.
2488 if (LangOpts.ObjC1 && T->getAs<ObjCObjectType>()) {
2489 T = Context.getObjCObjectPointerType(T);
2490 if (DeclType.Ptr.TypeQuals)
2491 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2494 T = S.BuildPointerType(T, DeclType.Loc, Name);
2495 if (DeclType.Ptr.TypeQuals)
2496 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
2499 case DeclaratorChunk::Reference: {
2500 // Verify that we're not building a reference to pointer to function with
2501 // exception specification.
2502 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2503 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2504 D.setInvalidType(true);
2505 // Build the type anyway.
2507 T = S.BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
2510 if (DeclType.Ref.HasRestrict)
2511 T = S.BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
2514 case DeclaratorChunk::Array: {
2515 // Verify that we're not building an array of pointers to function with
2516 // exception specification.
2517 if (LangOpts.CPlusPlus && S.CheckDistantExceptionSpec(T)) {
2518 S.Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
2519 D.setInvalidType(true);
2520 // Build the type anyway.
2522 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
2523 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
2524 ArrayType::ArraySizeModifier ASM;
2526 ASM = ArrayType::Star;
2527 else if (ATI.hasStatic)
2528 ASM = ArrayType::Static;
2530 ASM = ArrayType::Normal;
2531 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
2532 // FIXME: This check isn't quite right: it allows star in prototypes
2533 // for function definitions, and disallows some edge cases detailed
2534 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
2535 S.Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
2536 ASM = ArrayType::Normal;
2537 D.setInvalidType(true);
2540 // C99 6.7.5.2p1: The optional type qualifiers and the keyword static
2541 // shall appear only in a declaration of a function parameter with an
2543 if (ASM == ArrayType::Static || ATI.TypeQuals) {
2544 if (!(D.isPrototypeContext() ||
2545 D.getContext() == Declarator::KNRTypeListContext)) {
2546 S.Diag(DeclType.Loc, diag::err_array_static_outside_prototype) <<
2547 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2548 // Remove the 'static' and the type qualifiers.
2549 if (ASM == ArrayType::Static)
2550 ASM = ArrayType::Normal;
2552 D.setInvalidType(true);
2555 // C99 6.7.5.2p1: ... and then only in the outermost array type
2557 unsigned x = chunkIndex;
2559 // Walk outwards along the declarator chunks.
2561 const DeclaratorChunk &DC = D.getTypeObject(x);
2563 case DeclaratorChunk::Paren:
2565 case DeclaratorChunk::Array:
2566 case DeclaratorChunk::Pointer:
2567 case DeclaratorChunk::Reference:
2568 case DeclaratorChunk::MemberPointer:
2569 S.Diag(DeclType.Loc, diag::err_array_static_not_outermost) <<
2570 (ASM == ArrayType::Static ? "'static'" : "type qualifier");
2571 if (ASM == ArrayType::Static)
2572 ASM = ArrayType::Normal;
2574 D.setInvalidType(true);
2576 case DeclaratorChunk::Function:
2577 case DeclaratorChunk::BlockPointer:
2578 // These are invalid anyway, so just ignore.
2584 if (const AutoType *AT = T->getContainedAutoType()) {
2585 // We've already diagnosed this for decltype(auto).
2586 if (!AT->isDecltypeAuto())
2587 S.Diag(DeclType.Loc, diag::err_illegal_decl_array_of_auto)
2588 << getPrintableNameForEntity(Name) << T;
2593 T = S.BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals,
2594 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
2597 case DeclaratorChunk::Function: {
2598 // If the function declarator has a prototype (i.e. it is not () and
2599 // does not have a K&R-style identifier list), then the arguments are part
2600 // of the type, otherwise the argument list is ().
2601 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
2602 IsQualifiedFunction = FTI.TypeQuals || FTI.hasRefQualifier();
2604 // Check for auto functions and trailing return type and adjust the
2605 // return type accordingly.
2606 if (!D.isInvalidType()) {
2607 // trailing-return-type is only required if we're declaring a function,
2608 // and not, for instance, a pointer to a function.
2609 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
2610 !FTI.hasTrailingReturnType() && chunkIndex == 0 &&
2611 !S.getLangOpts().CPlusPlus1y) {
2612 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2613 diag::err_auto_missing_trailing_return);
2615 D.setInvalidType(true);
2616 } else if (FTI.hasTrailingReturnType()) {
2617 // T must be exactly 'auto' at this point. See CWG issue 681.
2618 if (isa<ParenType>(T)) {
2619 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2620 diag::err_trailing_return_in_parens)
2621 << T << D.getDeclSpec().getSourceRange();
2622 D.setInvalidType(true);
2623 } else if (D.getContext() != Declarator::LambdaExprContext &&
2624 (T.hasQualifiers() || !isa<AutoType>(T) ||
2625 cast<AutoType>(T)->isDecltypeAuto())) {
2626 S.Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
2627 diag::err_trailing_return_without_auto)
2628 << T << D.getDeclSpec().getSourceRange();
2629 D.setInvalidType(true);
2631 T = S.GetTypeFromParser(FTI.getTrailingReturnType(), &TInfo);
2633 // An error occurred parsing the trailing return type.
2635 D.setInvalidType(true);
2640 // C99 6.7.5.3p1: The return type may not be a function or array type.
2641 // For conversion functions, we'll diagnose this particular error later.
2642 if ((T->isArrayType() || T->isFunctionType()) &&
2643 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
2644 unsigned diagID = diag::err_func_returning_array_function;
2645 // Last processing chunk in block context means this function chunk
2646 // represents the block.
2647 if (chunkIndex == 0 &&
2648 D.getContext() == Declarator::BlockLiteralContext)
2649 diagID = diag::err_block_returning_array_function;
2650 S.Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
2652 D.setInvalidType(true);
2655 // Do not allow returning half FP value.
2656 // FIXME: This really should be in BuildFunctionType.
2657 if (T->isHalfType()) {
2658 if (S.getLangOpts().OpenCL) {
2659 if (!S.getOpenCLOptions().cl_khr_fp16) {
2660 S.Diag(D.getIdentifierLoc(), diag::err_opencl_half_return) << T;
2661 D.setInvalidType(true);
2664 S.Diag(D.getIdentifierLoc(),
2665 diag::err_parameters_retval_cannot_have_fp16_type) << 1;
2666 D.setInvalidType(true);
2670 // cv-qualifiers on return types are pointless except when the type is a
2671 // class type in C++.
2672 if ((T.getCVRQualifiers() || T->isAtomicType()) &&
2673 !(S.getLangOpts().CPlusPlus &&
2674 (T->isDependentType() || T->isRecordType())))
2675 diagnoseIgnoredFunctionQualifiers(S, T, D, chunkIndex);
2677 // Objective-C ARC ownership qualifiers are ignored on the function
2678 // return type (by type canonicalization). Complain if this attribute
2679 // was written here.
2680 if (T.getQualifiers().hasObjCLifetime()) {
2681 SourceLocation AttrLoc;
2682 if (chunkIndex + 1 < D.getNumTypeObjects()) {
2683 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
2684 for (const AttributeList *Attr = ReturnTypeChunk.getAttrs();
2685 Attr; Attr = Attr->getNext()) {
2686 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2687 AttrLoc = Attr->getLoc();
2692 if (AttrLoc.isInvalid()) {
2693 for (const AttributeList *Attr
2694 = D.getDeclSpec().getAttributes().getList();
2695 Attr; Attr = Attr->getNext()) {
2696 if (Attr->getKind() == AttributeList::AT_ObjCOwnership) {
2697 AttrLoc = Attr->getLoc();
2703 if (AttrLoc.isValid()) {
2704 // The ownership attributes are almost always written via
2706 // __strong/__weak/__autoreleasing/__unsafe_unretained.
2707 if (AttrLoc.isMacroID())
2708 AttrLoc = S.SourceMgr.getImmediateExpansionRange(AttrLoc).first;
2710 S.Diag(AttrLoc, diag::warn_arc_lifetime_result_type)
2711 << T.getQualifiers().getObjCLifetime();
2715 if (LangOpts.CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
2717 // Types shall not be defined in return or parameter types.
2718 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
2719 if (Tag->isCompleteDefinition())
2720 S.Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
2721 << Context.getTypeDeclType(Tag);
2724 // Exception specs are not allowed in typedefs. Complain, but add it
2726 if (IsTypedefName && FTI.getExceptionSpecType())
2727 S.Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
2728 << (D.getContext() == Declarator::AliasDeclContext ||
2729 D.getContext() == Declarator::AliasTemplateContext);
2731 // If we see "T var();" or "T var(T());" at block scope, it is probably
2732 // an attempt to initialize a variable, not a function declaration.
2733 if (FTI.isAmbiguous)
2734 warnAboutAmbiguousFunction(S, D, DeclType, T);
2736 if (!FTI.NumArgs && !FTI.isVariadic && !LangOpts.CPlusPlus) {
2737 // Simple void foo(), where the incoming T is the result type.
2738 T = Context.getFunctionNoProtoType(T);
2740 // We allow a zero-parameter variadic function in C if the
2741 // function is marked with the "overloadable" attribute. Scan
2742 // for this attribute now.
2743 if (!FTI.NumArgs && FTI.isVariadic && !LangOpts.CPlusPlus) {
2744 bool Overloadable = false;
2745 for (const AttributeList *Attrs = D.getAttributes();
2746 Attrs; Attrs = Attrs->getNext()) {
2747 if (Attrs->getKind() == AttributeList::AT_Overloadable) {
2748 Overloadable = true;
2754 S.Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
2757 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
2758 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
2760 S.Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
2761 D.setInvalidType(true);
2762 // Recover by creating a K&R-style function type.
2763 T = Context.getFunctionNoProtoType(T);
2767 FunctionProtoType::ExtProtoInfo EPI;
2768 EPI.Variadic = FTI.isVariadic;
2769 EPI.HasTrailingReturn = FTI.hasTrailingReturnType();
2770 EPI.TypeQuals = FTI.TypeQuals;
2771 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
2772 : FTI.RefQualifierIsLValueRef? RQ_LValue
2775 // Otherwise, we have a function with an argument list that is
2776 // potentially variadic.
2777 SmallVector<QualType, 16> ArgTys;
2778 ArgTys.reserve(FTI.NumArgs);
2780 SmallVector<bool, 16> ConsumedArguments;
2781 ConsumedArguments.reserve(FTI.NumArgs);
2782 bool HasAnyConsumedArguments = false;
2784 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
2785 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2786 QualType ArgTy = Param->getType();
2787 assert(!ArgTy.isNull() && "Couldn't parse type?");
2789 // Adjust the parameter type.
2790 assert((ArgTy == Context.getAdjustedParameterType(ArgTy)) &&
2791 "Unadjusted type?");
2793 // Look for 'void'. void is allowed only as a single argument to a
2794 // function with no other parameters (C99 6.7.5.3p10). We record
2795 // int(void) as a FunctionProtoType with an empty argument list.
2796 if (ArgTy->isVoidType()) {
2797 // If this is something like 'float(int, void)', reject it. 'void'
2798 // is an incomplete type (C99 6.2.5p19) and function decls cannot
2799 // have arguments of incomplete type.
2800 if (FTI.NumArgs != 1 || FTI.isVariadic) {
2801 S.Diag(DeclType.Loc, diag::err_void_only_param);
2802 ArgTy = Context.IntTy;
2803 Param->setType(ArgTy);
2804 } else if (FTI.ArgInfo[i].Ident) {
2805 // Reject, but continue to parse 'int(void abc)'.
2806 S.Diag(FTI.ArgInfo[i].IdentLoc,
2807 diag::err_param_with_void_type);
2808 ArgTy = Context.IntTy;
2809 Param->setType(ArgTy);
2811 // Reject, but continue to parse 'float(const void)'.
2812 if (ArgTy.hasQualifiers())
2813 S.Diag(DeclType.Loc, diag::err_void_param_qualified);
2815 // Do not add 'void' to the ArgTys list.
2818 } else if (ArgTy->isHalfType()) {
2819 // Disallow half FP arguments.
2820 // FIXME: This really should be in BuildFunctionType.
2821 if (S.getLangOpts().OpenCL) {
2822 if (!S.getOpenCLOptions().cl_khr_fp16) {
2823 S.Diag(Param->getLocation(),
2824 diag::err_opencl_half_argument) << ArgTy;
2826 Param->setInvalidDecl();
2829 S.Diag(Param->getLocation(),
2830 diag::err_parameters_retval_cannot_have_fp16_type) << 0;
2833 } else if (!FTI.hasPrototype) {
2834 if (ArgTy->isPromotableIntegerType()) {
2835 ArgTy = Context.getPromotedIntegerType(ArgTy);
2836 Param->setKNRPromoted(true);
2837 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
2838 if (BTy->getKind() == BuiltinType::Float) {
2839 ArgTy = Context.DoubleTy;
2840 Param->setKNRPromoted(true);
2845 if (LangOpts.ObjCAutoRefCount) {
2846 bool Consumed = Param->hasAttr<NSConsumedAttr>();
2847 ConsumedArguments.push_back(Consumed);
2848 HasAnyConsumedArguments |= Consumed;
2851 ArgTys.push_back(ArgTy);
2854 if (HasAnyConsumedArguments)
2855 EPI.ConsumedArguments = ConsumedArguments.data();
2857 SmallVector<QualType, 4> Exceptions;
2858 SmallVector<ParsedType, 2> DynamicExceptions;
2859 SmallVector<SourceRange, 2> DynamicExceptionRanges;
2860 Expr *NoexceptExpr = 0;
2862 if (FTI.getExceptionSpecType() == EST_Dynamic) {
2863 // FIXME: It's rather inefficient to have to split into two vectors
2865 unsigned N = FTI.NumExceptions;
2866 DynamicExceptions.reserve(N);
2867 DynamicExceptionRanges.reserve(N);
2868 for (unsigned I = 0; I != N; ++I) {
2869 DynamicExceptions.push_back(FTI.Exceptions[I].Ty);
2870 DynamicExceptionRanges.push_back(FTI.Exceptions[I].Range);
2872 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
2873 NoexceptExpr = FTI.NoexceptExpr;
2876 S.checkExceptionSpecification(FTI.getExceptionSpecType(),
2878 DynamicExceptionRanges,
2883 T = Context.getFunctionType(T, ArgTys, EPI);
2888 case DeclaratorChunk::MemberPointer:
2889 // The scope spec must refer to a class, or be dependent.
2890 CXXScopeSpec &SS = DeclType.Mem.Scope();
2892 if (SS.isInvalid()) {
2893 // Avoid emitting extra errors if we already errored on the scope.
2894 D.setInvalidType(true);
2895 } else if (S.isDependentScopeSpecifier(SS) ||
2896 dyn_cast_or_null<CXXRecordDecl>(S.computeDeclContext(SS))) {
2897 NestedNameSpecifier *NNS
2898 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2899 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2900 switch (NNS->getKind()) {
2901 case NestedNameSpecifier::Identifier:
2902 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2903 NNS->getAsIdentifier());
2906 case NestedNameSpecifier::Namespace:
2907 case NestedNameSpecifier::NamespaceAlias:
2908 case NestedNameSpecifier::Global:
2909 llvm_unreachable("Nested-name-specifier must name a type");
2911 case NestedNameSpecifier::TypeSpec:
2912 case NestedNameSpecifier::TypeSpecWithTemplate:
2913 ClsType = QualType(NNS->getAsType(), 0);
2914 // Note: if the NNS has a prefix and ClsType is a nondependent
2915 // TemplateSpecializationType, then the NNS prefix is NOT included
2916 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2917 // NOTE: in particular, no wrap occurs if ClsType already is an
2918 // Elaborated, DependentName, or DependentTemplateSpecialization.
2919 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2920 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2924 S.Diag(DeclType.Mem.Scope().getBeginLoc(),
2925 diag::err_illegal_decl_mempointer_in_nonclass)
2926 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2927 << DeclType.Mem.Scope().getRange();
2928 D.setInvalidType(true);
2931 if (!ClsType.isNull())
2932 T = S.BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2935 D.setInvalidType(true);
2936 } else if (DeclType.Mem.TypeQuals) {
2937 T = S.BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2943 D.setInvalidType(true);
2947 // See if there are any attributes on this declarator chunk.
2948 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2949 processTypeAttrs(state, T, TAL_DeclChunk, attrs);
2952 if (LangOpts.CPlusPlus && T->isFunctionType()) {
2953 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2954 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2957 // A cv-qualifier-seq shall only be part of the function type
2958 // for a nonstatic member function, the function type to which a pointer
2959 // to member refers, or the top-level function type of a function typedef
2962 // Core issue 547 also allows cv-qualifiers on function types that are
2963 // top-level template type arguments.
2965 if (!D.getCXXScopeSpec().isSet()) {
2966 FreeFunction = ((D.getContext() != Declarator::MemberContext &&
2967 D.getContext() != Declarator::LambdaExprContext) ||
2968 D.getDeclSpec().isFriendSpecified());
2970 DeclContext *DC = S.computeDeclContext(D.getCXXScopeSpec());
2971 FreeFunction = (DC && !DC->isRecord());
2974 // C++11 [dcl.fct]p6 (w/DR1417):
2975 // An attempt to specify a function type with a cv-qualifier-seq or a
2976 // ref-qualifier (including by typedef-name) is ill-formed unless it is:
2977 // - the function type for a non-static member function,
2978 // - the function type to which a pointer to member refers,
2979 // - the top-level function type of a function typedef declaration or
2980 // alias-declaration,
2981 // - the type-id in the default argument of a type-parameter, or
2982 // - the type-id of a template-argument for a type-parameter
2983 if (IsQualifiedFunction &&
2985 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_static) &&
2987 D.getContext() != Declarator::TemplateTypeArgContext) {
2988 SourceLocation Loc = D.getLocStart();
2989 SourceRange RemovalRange;
2991 if (D.isFunctionDeclarator(I)) {
2992 SmallVector<SourceLocation, 4> RemovalLocs;
2993 const DeclaratorChunk &Chunk = D.getTypeObject(I);
2994 assert(Chunk.Kind == DeclaratorChunk::Function);
2995 if (Chunk.Fun.hasRefQualifier())
2996 RemovalLocs.push_back(Chunk.Fun.getRefQualifierLoc());
2997 if (Chunk.Fun.TypeQuals & Qualifiers::Const)
2998 RemovalLocs.push_back(Chunk.Fun.getConstQualifierLoc());
2999 if (Chunk.Fun.TypeQuals & Qualifiers::Volatile)
3000 RemovalLocs.push_back(Chunk.Fun.getVolatileQualifierLoc());
3001 // FIXME: We do not track the location of the __restrict qualifier.
3002 //if (Chunk.Fun.TypeQuals & Qualifiers::Restrict)
3003 // RemovalLocs.push_back(Chunk.Fun.getRestrictQualifierLoc());
3004 if (!RemovalLocs.empty()) {
3005 std::sort(RemovalLocs.begin(), RemovalLocs.end(),
3006 BeforeThanCompare<SourceLocation>(S.getSourceManager()));
3007 RemovalRange = SourceRange(RemovalLocs.front(), RemovalLocs.back());
3008 Loc = RemovalLocs.front();
3012 S.Diag(Loc, diag::err_invalid_qualified_function_type)
3013 << FreeFunction << D.isFunctionDeclarator() << T
3014 << getFunctionQualifiersAsString(FnTy)
3015 << FixItHint::CreateRemoval(RemovalRange);
3017 // Strip the cv-qualifiers and ref-qualifiers from the type.
3018 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
3020 EPI.RefQualifier = RQ_None;
3022 T = Context.getFunctionType(FnTy->getResultType(),
3023 ArrayRef<QualType>(FnTy->arg_type_begin(),
3024 FnTy->getNumArgs()),
3026 // Rebuild any parens around the identifier in the function type.
3027 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3028 if (D.getTypeObject(i).Kind != DeclaratorChunk::Paren)
3030 T = S.BuildParenType(T);
3035 // Apply any undistributed attributes from the declarator.
3037 if (AttributeList *attrs = D.getAttributes())
3038 processTypeAttrs(state, T, TAL_DeclName, attrs);
3040 // Diagnose any ignored type attributes.
3041 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
3043 // C++0x [dcl.constexpr]p9:
3044 // A constexpr specifier used in an object declaration declares the object
3046 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
3050 // If there was an ellipsis in the declarator, the declaration declares a
3051 // parameter pack whose type may be a pack expansion type.
3052 if (D.hasEllipsis() && !T.isNull()) {
3053 // C++0x [dcl.fct]p13:
3054 // A declarator-id or abstract-declarator containing an ellipsis shall
3055 // only be used in a parameter-declaration. Such a parameter-declaration
3056 // is a parameter pack (14.5.3). [...]
3057 switch (D.getContext()) {
3058 case Declarator::PrototypeContext:
3059 // C++0x [dcl.fct]p13:
3060 // [...] When it is part of a parameter-declaration-clause, the
3061 // parameter pack is a function parameter pack (14.5.3). The type T
3062 // of the declarator-id of the function parameter pack shall contain
3063 // a template parameter pack; each template parameter pack in T is
3064 // expanded by the function parameter pack.
3066 // We represent function parameter packs as function parameters whose
3067 // type is a pack expansion.
3068 if (!T->containsUnexpandedParameterPack()) {
3069 S.Diag(D.getEllipsisLoc(),
3070 diag::err_function_parameter_pack_without_parameter_packs)
3071 << T << D.getSourceRange();
3072 D.setEllipsisLoc(SourceLocation());
3074 T = Context.getPackExpansionType(T, None);
3078 case Declarator::TemplateParamContext:
3079 // C++0x [temp.param]p15:
3080 // If a template-parameter is a [...] is a parameter-declaration that
3081 // declares a parameter pack (8.3.5), then the template-parameter is a
3082 // template parameter pack (14.5.3).
3084 // Note: core issue 778 clarifies that, if there are any unexpanded
3085 // parameter packs in the type of the non-type template parameter, then
3086 // it expands those parameter packs.
3087 if (T->containsUnexpandedParameterPack())
3088 T = Context.getPackExpansionType(T, None);
3090 S.Diag(D.getEllipsisLoc(),
3091 LangOpts.CPlusPlus11
3092 ? diag::warn_cxx98_compat_variadic_templates
3093 : diag::ext_variadic_templates);
3096 case Declarator::FileContext:
3097 case Declarator::KNRTypeListContext:
3098 case Declarator::ObjCParameterContext: // FIXME: special diagnostic here?
3099 case Declarator::ObjCResultContext: // FIXME: special diagnostic here?
3100 case Declarator::TypeNameContext:
3101 case Declarator::CXXNewContext:
3102 case Declarator::AliasDeclContext:
3103 case Declarator::AliasTemplateContext:
3104 case Declarator::MemberContext:
3105 case Declarator::BlockContext:
3106 case Declarator::ForContext:
3107 case Declarator::ConditionContext:
3108 case Declarator::CXXCatchContext:
3109 case Declarator::ObjCCatchContext:
3110 case Declarator::BlockLiteralContext:
3111 case Declarator::LambdaExprContext:
3112 case Declarator::ConversionIdContext:
3113 case Declarator::TrailingReturnContext:
3114 case Declarator::TemplateTypeArgContext:
3115 // FIXME: We may want to allow parameter packs in block-literal contexts
3117 S.Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
3118 D.setEllipsisLoc(SourceLocation());
3124 return Context.getNullTypeSourceInfo();
3125 else if (D.isInvalidType())
3126 return Context.getTrivialTypeSourceInfo(T);
3128 return S.GetTypeSourceInfoForDeclarator(D, T, TInfo);
3131 /// GetTypeForDeclarator - Convert the type for the specified
3132 /// declarator to Type instances.
3134 /// The result of this call will never be null, but the associated
3135 /// type may be a null type if there's an unrecoverable error.
3136 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S) {
3137 // Determine the type of the declarator. Not all forms of declarator
3140 TypeProcessingState state(*this, D);
3142 TypeSourceInfo *ReturnTypeInfo = 0;
3143 QualType T = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3145 return Context.getNullTypeSourceInfo();
3147 if (D.isPrototypeContext() && getLangOpts().ObjCAutoRefCount)
3148 inferARCWriteback(state, T);
3150 return GetFullTypeForDeclarator(state, T, ReturnTypeInfo);
3153 static void transferARCOwnershipToDeclSpec(Sema &S,
3154 QualType &declSpecTy,
3155 Qualifiers::ObjCLifetime ownership) {
3156 if (declSpecTy->isObjCRetainableType() &&
3157 declSpecTy.getObjCLifetime() == Qualifiers::OCL_None) {
3159 qs.addObjCLifetime(ownership);
3160 declSpecTy = S.Context.getQualifiedType(declSpecTy, qs);
3164 static void transferARCOwnershipToDeclaratorChunk(TypeProcessingState &state,
3165 Qualifiers::ObjCLifetime ownership,
3166 unsigned chunkIndex) {
3167 Sema &S = state.getSema();
3168 Declarator &D = state.getDeclarator();
3170 // Look for an explicit lifetime attribute.
3171 DeclaratorChunk &chunk = D.getTypeObject(chunkIndex);
3172 for (const AttributeList *attr = chunk.getAttrs(); attr;
3173 attr = attr->getNext())
3174 if (attr->getKind() == AttributeList::AT_ObjCOwnership)
3177 const char *attrStr = 0;
3178 switch (ownership) {
3179 case Qualifiers::OCL_None: llvm_unreachable("no ownership!");
3180 case Qualifiers::OCL_ExplicitNone: attrStr = "none"; break;
3181 case Qualifiers::OCL_Strong: attrStr = "strong"; break;
3182 case Qualifiers::OCL_Weak: attrStr = "weak"; break;
3183 case Qualifiers::OCL_Autoreleasing: attrStr = "autoreleasing"; break;
3186 // If there wasn't one, add one (with an invalid source location
3187 // so that we don't make an AttributedType for it).
3188 AttributeList *attr = D.getAttributePool()
3189 .create(&S.Context.Idents.get("objc_ownership"), SourceLocation(),
3190 /*scope*/ 0, SourceLocation(),
3191 &S.Context.Idents.get(attrStr), SourceLocation(),
3192 /*args*/ 0, 0, AttributeList::AS_GNU);
3193 spliceAttrIntoList(*attr, chunk.getAttrListRef());
3195 // TODO: mark whether we did this inference?
3198 /// \brief Used for transferring ownership in casts resulting in l-values.
3199 static void transferARCOwnership(TypeProcessingState &state,
3200 QualType &declSpecTy,
3201 Qualifiers::ObjCLifetime ownership) {
3202 Sema &S = state.getSema();
3203 Declarator &D = state.getDeclarator();
3206 bool hasIndirection = false;
3207 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3208 DeclaratorChunk &chunk = D.getTypeObject(i);
3209 switch (chunk.Kind) {
3210 case DeclaratorChunk::Paren:
3214 case DeclaratorChunk::Array:
3215 case DeclaratorChunk::Reference:
3216 case DeclaratorChunk::Pointer:
3218 hasIndirection = true;
3222 case DeclaratorChunk::BlockPointer:
3224 transferARCOwnershipToDeclaratorChunk(state, ownership, i);
3227 case DeclaratorChunk::Function:
3228 case DeclaratorChunk::MemberPointer:
3236 DeclaratorChunk &chunk = D.getTypeObject(inner);
3237 if (chunk.Kind == DeclaratorChunk::Pointer) {
3238 if (declSpecTy->isObjCRetainableType())
3239 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3240 if (declSpecTy->isObjCObjectType() && hasIndirection)
3241 return transferARCOwnershipToDeclaratorChunk(state, ownership, inner);
3243 assert(chunk.Kind == DeclaratorChunk::Array ||
3244 chunk.Kind == DeclaratorChunk::Reference);
3245 return transferARCOwnershipToDeclSpec(S, declSpecTy, ownership);
3249 TypeSourceInfo *Sema::GetTypeForDeclaratorCast(Declarator &D, QualType FromTy) {
3250 TypeProcessingState state(*this, D);
3252 TypeSourceInfo *ReturnTypeInfo = 0;
3253 QualType declSpecTy = GetDeclSpecTypeForDeclarator(state, ReturnTypeInfo);
3254 if (declSpecTy.isNull())
3255 return Context.getNullTypeSourceInfo();
3257 if (getLangOpts().ObjCAutoRefCount) {
3258 Qualifiers::ObjCLifetime ownership = Context.getInnerObjCOwnership(FromTy);
3259 if (ownership != Qualifiers::OCL_None)
3260 transferARCOwnership(state, declSpecTy, ownership);
3263 return GetFullTypeForDeclarator(state, declSpecTy, ReturnTypeInfo);
3266 /// Map an AttributedType::Kind to an AttributeList::Kind.
3267 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
3269 case AttributedType::attr_address_space:
3270 return AttributeList::AT_AddressSpace;
3271 case AttributedType::attr_regparm:
3272 return AttributeList::AT_Regparm;
3273 case AttributedType::attr_vector_size:
3274 return AttributeList::AT_VectorSize;
3275 case AttributedType::attr_neon_vector_type:
3276 return AttributeList::AT_NeonVectorType;
3277 case AttributedType::attr_neon_polyvector_type:
3278 return AttributeList::AT_NeonPolyVectorType;
3279 case AttributedType::attr_objc_gc:
3280 return AttributeList::AT_ObjCGC;
3281 case AttributedType::attr_objc_ownership:
3282 return AttributeList::AT_ObjCOwnership;
3283 case AttributedType::attr_noreturn:
3284 return AttributeList::AT_NoReturn;
3285 case AttributedType::attr_cdecl:
3286 return AttributeList::AT_CDecl;
3287 case AttributedType::attr_fastcall:
3288 return AttributeList::AT_FastCall;
3289 case AttributedType::attr_stdcall:
3290 return AttributeList::AT_StdCall;
3291 case AttributedType::attr_thiscall:
3292 return AttributeList::AT_ThisCall;
3293 case AttributedType::attr_pascal:
3294 return AttributeList::AT_Pascal;
3295 case AttributedType::attr_pcs:
3296 return AttributeList::AT_Pcs;
3297 case AttributedType::attr_pnaclcall:
3298 return AttributeList::AT_PnaclCall;
3299 case AttributedType::attr_inteloclbicc:
3300 return AttributeList::AT_IntelOclBicc;
3301 case AttributedType::attr_ms_abi:
3302 return AttributeList::AT_MSABI;
3303 case AttributedType::attr_sysv_abi:
3304 return AttributeList::AT_SysVABI;
3306 llvm_unreachable("unexpected attribute kind!");
3309 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
3310 const AttributeList *attrs) {
3311 AttributedType::Kind kind = TL.getAttrKind();
3313 assert(attrs && "no type attributes in the expected location!");
3314 AttributeList::Kind parsedKind = getAttrListKind(kind);
3315 while (attrs->getKind() != parsedKind) {
3316 attrs = attrs->getNext();
3317 assert(attrs && "no matching attribute in expected location!");
3320 TL.setAttrNameLoc(attrs->getLoc());
3321 if (TL.hasAttrExprOperand())
3322 TL.setAttrExprOperand(attrs->getArg(0));
3323 else if (TL.hasAttrEnumOperand())
3324 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
3326 // FIXME: preserve this information to here.
3327 if (TL.hasAttrOperand())
3328 TL.setAttrOperandParensRange(SourceRange());
3332 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
3333 ASTContext &Context;
3337 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
3338 : Context(Context), DS(DS) {}
3340 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3341 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
3342 Visit(TL.getModifiedLoc());
3344 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3345 Visit(TL.getUnqualifiedLoc());
3347 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
3348 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3350 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
3351 TL.setNameLoc(DS.getTypeSpecTypeLoc());
3352 // FIXME. We should have DS.getTypeSpecTypeEndLoc(). But, it requires
3353 // addition field. What we have is good enough for dispay of location
3354 // of 'fixit' on interface name.
3355 TL.setNameEndLoc(DS.getLocEnd());
3357 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
3358 // Handle the base type, which might not have been written explicitly.
3359 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
3360 TL.setHasBaseTypeAsWritten(false);
3361 TL.getBaseLoc().initialize(Context, SourceLocation());
3363 TL.setHasBaseTypeAsWritten(true);
3364 Visit(TL.getBaseLoc());
3367 // Protocol qualifiers.
3368 if (DS.getProtocolQualifiers()) {
3369 assert(TL.getNumProtocols() > 0);
3370 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
3371 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
3372 TL.setRAngleLoc(DS.getSourceRange().getEnd());
3373 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
3374 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
3376 assert(TL.getNumProtocols() == 0);
3377 TL.setLAngleLoc(SourceLocation());
3378 TL.setRAngleLoc(SourceLocation());
3381 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3382 TL.setStarLoc(SourceLocation());
3383 Visit(TL.getPointeeLoc());
3385 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
3386 TypeSourceInfo *TInfo = 0;
3387 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3389 // If we got no declarator info from previous Sema routines,
3390 // just fill with the typespec loc.
3392 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
3396 TypeLoc OldTL = TInfo->getTypeLoc();
3397 if (TInfo->getType()->getAs<ElaboratedType>()) {
3398 ElaboratedTypeLoc ElabTL = OldTL.castAs<ElaboratedTypeLoc>();
3399 TemplateSpecializationTypeLoc NamedTL = ElabTL.getNamedTypeLoc()
3400 .castAs<TemplateSpecializationTypeLoc>();
3404 TL.copy(OldTL.castAs<TemplateSpecializationTypeLoc>());
3406 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
3407 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
3408 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3409 TL.setParensRange(DS.getTypeofParensRange());
3411 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
3412 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
3413 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
3414 TL.setParensRange(DS.getTypeofParensRange());
3415 assert(DS.getRepAsType());
3416 TypeSourceInfo *TInfo = 0;
3417 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3418 TL.setUnderlyingTInfo(TInfo);
3420 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
3421 // FIXME: This holds only because we only have one unary transform.
3422 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
3423 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3424 TL.setParensRange(DS.getTypeofParensRange());
3425 assert(DS.getRepAsType());
3426 TypeSourceInfo *TInfo = 0;
3427 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3428 TL.setUnderlyingTInfo(TInfo);
3430 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
3431 // By default, use the source location of the type specifier.
3432 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
3433 if (TL.needsExtraLocalData()) {
3434 // Set info for the written builtin specifiers.
3435 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
3436 // Try to have a meaningful source location.
3437 if (TL.getWrittenSignSpec() != TSS_unspecified)
3438 // Sign spec loc overrides the others (e.g., 'unsigned long').
3439 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
3440 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
3441 // Width spec loc overrides type spec loc (e.g., 'short int').
3442 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
3445 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
3446 ElaboratedTypeKeyword Keyword
3447 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
3448 if (DS.getTypeSpecType() == TST_typename) {
3449 TypeSourceInfo *TInfo = 0;
3450 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3452 TL.copy(TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>());
3456 TL.setElaboratedKeywordLoc(Keyword != ETK_None
3457 ? DS.getTypeSpecTypeLoc()
3458 : SourceLocation());
3459 const CXXScopeSpec& SS = DS.getTypeSpecScope();
3460 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3461 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
3463 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
3464 assert(DS.getTypeSpecType() == TST_typename);
3465 TypeSourceInfo *TInfo = 0;
3466 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3468 TL.copy(TInfo->getTypeLoc().castAs<DependentNameTypeLoc>());
3470 void VisitDependentTemplateSpecializationTypeLoc(
3471 DependentTemplateSpecializationTypeLoc TL) {
3472 assert(DS.getTypeSpecType() == TST_typename);
3473 TypeSourceInfo *TInfo = 0;
3474 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3477 TInfo->getTypeLoc().castAs<DependentTemplateSpecializationTypeLoc>());
3479 void VisitTagTypeLoc(TagTypeLoc TL) {
3480 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
3482 void VisitAtomicTypeLoc(AtomicTypeLoc TL) {
3483 // An AtomicTypeLoc can come from either an _Atomic(...) type specifier
3484 // or an _Atomic qualifier.
3485 if (DS.getTypeSpecType() == DeclSpec::TST_atomic) {
3486 TL.setKWLoc(DS.getTypeSpecTypeLoc());
3487 TL.setParensRange(DS.getTypeofParensRange());
3489 TypeSourceInfo *TInfo = 0;
3490 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
3492 TL.getValueLoc().initializeFullCopy(TInfo->getTypeLoc());
3494 TL.setKWLoc(DS.getAtomicSpecLoc());
3495 // No parens, to indicate this was spelled as an _Atomic qualifier.
3496 TL.setParensRange(SourceRange());
3497 Visit(TL.getValueLoc());
3501 void VisitTypeLoc(TypeLoc TL) {
3502 // FIXME: add other typespec types and change this to an assert.
3503 TL.initialize(Context, DS.getTypeSpecTypeLoc());
3507 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
3508 ASTContext &Context;
3509 const DeclaratorChunk &Chunk;
3512 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
3513 : Context(Context), Chunk(Chunk) {}
3515 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
3516 llvm_unreachable("qualified type locs not expected here!");
3519 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
3520 fillAttributedTypeLoc(TL, Chunk.getAttrs());
3522 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
3523 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
3524 TL.setCaretLoc(Chunk.Loc);
3526 void VisitPointerTypeLoc(PointerTypeLoc TL) {
3527 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3528 TL.setStarLoc(Chunk.Loc);
3530 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
3531 assert(Chunk.Kind == DeclaratorChunk::Pointer);
3532 TL.setStarLoc(Chunk.Loc);
3534 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
3535 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
3536 const CXXScopeSpec& SS = Chunk.Mem.Scope();
3537 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
3539 const Type* ClsTy = TL.getClass();
3540 QualType ClsQT = QualType(ClsTy, 0);
3541 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
3542 // Now copy source location info into the type loc component.
3543 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
3544 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
3545 case NestedNameSpecifier::Identifier:
3546 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
3548 DependentNameTypeLoc DNTLoc = ClsTL.castAs<DependentNameTypeLoc>();
3549 DNTLoc.setElaboratedKeywordLoc(SourceLocation());
3550 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
3551 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
3555 case NestedNameSpecifier::TypeSpec:
3556 case NestedNameSpecifier::TypeSpecWithTemplate:
3557 if (isa<ElaboratedType>(ClsTy)) {
3558 ElaboratedTypeLoc ETLoc = ClsTL.castAs<ElaboratedTypeLoc>();
3559 ETLoc.setElaboratedKeywordLoc(SourceLocation());
3560 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
3561 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
3562 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
3564 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
3568 case NestedNameSpecifier::Namespace:
3569 case NestedNameSpecifier::NamespaceAlias:
3570 case NestedNameSpecifier::Global:
3571 llvm_unreachable("Nested-name-specifier must name a type");
3574 // Finally fill in MemberPointerLocInfo fields.
3575 TL.setStarLoc(Chunk.Loc);
3576 TL.setClassTInfo(ClsTInfo);
3578 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
3579 assert(Chunk.Kind == DeclaratorChunk::Reference);
3580 // 'Amp' is misleading: this might have been originally
3581 /// spelled with AmpAmp.
3582 TL.setAmpLoc(Chunk.Loc);
3584 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
3585 assert(Chunk.Kind == DeclaratorChunk::Reference);
3586 assert(!Chunk.Ref.LValueRef);
3587 TL.setAmpAmpLoc(Chunk.Loc);
3589 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
3590 assert(Chunk.Kind == DeclaratorChunk::Array);
3591 TL.setLBracketLoc(Chunk.Loc);
3592 TL.setRBracketLoc(Chunk.EndLoc);
3593 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
3595 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
3596 assert(Chunk.Kind == DeclaratorChunk::Function);
3597 TL.setLocalRangeBegin(Chunk.Loc);
3598 TL.setLocalRangeEnd(Chunk.EndLoc);
3600 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
3601 TL.setLParenLoc(FTI.getLParenLoc());
3602 TL.setRParenLoc(FTI.getRParenLoc());
3603 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
3604 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
3605 TL.setArg(tpi++, Param);
3607 // FIXME: exception specs
3609 void VisitParenTypeLoc(ParenTypeLoc TL) {
3610 assert(Chunk.Kind == DeclaratorChunk::Paren);
3611 TL.setLParenLoc(Chunk.Loc);
3612 TL.setRParenLoc(Chunk.EndLoc);
3615 void VisitTypeLoc(TypeLoc TL) {
3616 llvm_unreachable("unsupported TypeLoc kind in declarator!");
3621 static void fillAtomicQualLoc(AtomicTypeLoc ATL, const DeclaratorChunk &Chunk) {
3623 switch (Chunk.Kind) {
3624 case DeclaratorChunk::Function:
3625 case DeclaratorChunk::Array:
3626 case DeclaratorChunk::Paren:
3627 llvm_unreachable("cannot be _Atomic qualified");
3629 case DeclaratorChunk::Pointer:
3630 Loc = SourceLocation::getFromRawEncoding(Chunk.Ptr.AtomicQualLoc);
3633 case DeclaratorChunk::BlockPointer:
3634 case DeclaratorChunk::Reference:
3635 case DeclaratorChunk::MemberPointer:
3636 // FIXME: Provide a source location for the _Atomic keyword.
3641 ATL.setParensRange(SourceRange());
3644 /// \brief Create and instantiate a TypeSourceInfo with type source information.
3646 /// \param T QualType referring to the type as written in source code.
3648 /// \param ReturnTypeInfo For declarators whose return type does not show
3649 /// up in the normal place in the declaration specifiers (such as a C++
3650 /// conversion function), this pointer will refer to a type source information
3651 /// for that return type.
3653 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
3654 TypeSourceInfo *ReturnTypeInfo) {
3655 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
3656 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
3658 // Handle parameter packs whose type is a pack expansion.
3659 if (isa<PackExpansionType>(T)) {
3660 CurrTL.castAs<PackExpansionTypeLoc>().setEllipsisLoc(D.getEllipsisLoc());
3661 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3664 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
3665 // An AtomicTypeLoc might be produced by an atomic qualifier in this
3666 // declarator chunk.
3667 if (AtomicTypeLoc ATL = CurrTL.getAs<AtomicTypeLoc>()) {
3668 fillAtomicQualLoc(ATL, D.getTypeObject(i));
3669 CurrTL = ATL.getValueLoc().getUnqualifiedLoc();
3672 while (AttributedTypeLoc TL = CurrTL.getAs<AttributedTypeLoc>()) {
3673 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
3674 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
3677 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
3678 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
3681 // If we have different source information for the return type, use
3682 // that. This really only applies to C++ conversion functions.
3683 if (ReturnTypeInfo) {
3684 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
3685 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
3686 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
3688 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
3694 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
3695 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
3696 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
3697 // and Sema during declaration parsing. Try deallocating/caching them when
3698 // it's appropriate, instead of allocating them and keeping them around.
3699 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
3701 new (LocT) LocInfoType(T, TInfo);
3702 assert(LocT->getTypeClass() != T->getTypeClass() &&
3703 "LocInfoType's TypeClass conflicts with an existing Type class");
3704 return ParsedType::make(QualType(LocT, 0));
3707 void LocInfoType::getAsStringInternal(std::string &Str,
3708 const PrintingPolicy &Policy) const {
3709 llvm_unreachable("LocInfoType leaked into the type system; an opaque TypeTy*"
3710 " was used directly instead of getting the QualType through"
3711 " GetTypeFromParser");
3714 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
3715 // C99 6.7.6: Type names have no identifier. This is already validated by
3717 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
3719 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3720 QualType T = TInfo->getType();
3721 if (D.isInvalidType())
3724 // Make sure there are no unused decl attributes on the declarator.
3725 // We don't want to do this for ObjC parameters because we're going
3726 // to apply them to the actual parameter declaration.
3727 // Likewise, we don't want to do this for alias declarations, because
3728 // we are actually going to build a declaration from this eventually.
3729 if (D.getContext() != Declarator::ObjCParameterContext &&
3730 D.getContext() != Declarator::AliasDeclContext &&
3731 D.getContext() != Declarator::AliasTemplateContext)
3732 checkUnusedDeclAttributes(D);
3734 if (getLangOpts().CPlusPlus) {
3735 // Check that there are no default arguments (C++ only).
3736 CheckExtraCXXDefaultArguments(D);
3739 return CreateParsedType(T, TInfo);
3742 ParsedType Sema::ActOnObjCInstanceType(SourceLocation Loc) {
3743 QualType T = Context.getObjCInstanceType();
3744 TypeSourceInfo *TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
3745 return CreateParsedType(T, TInfo);
3749 //===----------------------------------------------------------------------===//
3750 // Type Attribute Processing
3751 //===----------------------------------------------------------------------===//
3753 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
3754 /// specified type. The attribute contains 1 argument, the id of the address
3755 /// space for the type.
3756 static void HandleAddressSpaceTypeAttribute(QualType &Type,
3757 const AttributeList &Attr, Sema &S){
3759 // If this type is already address space qualified, reject it.
3760 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "No type shall be qualified by
3761 // qualifiers for two or more different address spaces."
3762 if (Type.getAddressSpace()) {
3763 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
3768 // ISO/IEC TR 18037 S5.3 (amending C99 6.7.3): "A function type shall not be
3769 // qualified by an address-space qualifier."
3770 if (Type->isFunctionType()) {
3771 S.Diag(Attr.getLoc(), diag::err_attribute_address_function_type);
3776 // Check the attribute arguments.
3777 if (Attr.getNumArgs() != 1) {
3778 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3782 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
3783 llvm::APSInt addrSpace(32);
3784 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
3785 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
3786 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
3787 << ASArgExpr->getSourceRange();
3793 if (addrSpace.isSigned()) {
3794 if (addrSpace.isNegative()) {
3795 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
3796 << ASArgExpr->getSourceRange();
3800 addrSpace.setIsSigned(false);
3802 llvm::APSInt max(addrSpace.getBitWidth());
3803 max = Qualifiers::MaxAddressSpace;
3804 if (addrSpace > max) {
3805 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
3806 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
3811 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
3812 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
3815 /// Does this type have a "direct" ownership qualifier? That is,
3816 /// is it written like "__strong id", as opposed to something like
3817 /// "typeof(foo)", where that happens to be strong?
3818 static bool hasDirectOwnershipQualifier(QualType type) {
3819 // Fast path: no qualifier at all.
3820 assert(type.getQualifiers().hasObjCLifetime());
3824 if (const AttributedType *attr = dyn_cast<AttributedType>(type)) {
3825 if (attr->getAttrKind() == AttributedType::attr_objc_ownership)
3828 type = attr->getModifiedType();
3830 // X *__strong (...)
3831 } else if (const ParenType *paren = dyn_cast<ParenType>(type)) {
3832 type = paren->getInnerType();
3834 // That's it for things we want to complain about. In particular,
3835 // we do not want to look through typedefs, typeof(expr),
3836 // typeof(type), or any other way that the type is somehow
3845 /// handleObjCOwnershipTypeAttr - Process an objc_ownership
3846 /// attribute on the specified type.
3848 /// Returns 'true' if the attribute was handled.
3849 static bool handleObjCOwnershipTypeAttr(TypeProcessingState &state,
3850 AttributeList &attr,
3852 bool NonObjCPointer = false;
3854 if (!type->isDependentType() && !type->isUndeducedType()) {
3855 if (const PointerType *ptr = type->getAs<PointerType>()) {
3856 QualType pointee = ptr->getPointeeType();
3857 if (pointee->isObjCRetainableType() || pointee->isPointerType())
3859 // It is important not to lose the source info that there was an attribute
3860 // applied to non-objc pointer. We will create an attributed type but
3861 // its type will be the same as the original type.
3862 NonObjCPointer = true;
3863 } else if (!type->isObjCRetainableType()) {
3867 // Don't accept an ownership attribute in the declspec if it would
3868 // just be the return type of a block pointer.
3869 if (state.isProcessingDeclSpec()) {
3870 Declarator &D = state.getDeclarator();
3871 if (maybeMovePastReturnType(D, D.getNumTypeObjects()))
3876 Sema &S = state.getSema();
3877 SourceLocation AttrLoc = attr.getLoc();
3878 if (AttrLoc.isMacroID())
3879 AttrLoc = S.getSourceManager().getImmediateExpansionRange(AttrLoc).first;
3881 if (!attr.getParameterName()) {
3882 S.Diag(AttrLoc, diag::err_attribute_argument_n_not_string)
3883 << "objc_ownership" << 1;
3888 // Consume lifetime attributes without further comment outside of
3890 if (!S.getLangOpts().ObjCAutoRefCount)
3893 Qualifiers::ObjCLifetime lifetime;
3894 if (attr.getParameterName()->isStr("none"))
3895 lifetime = Qualifiers::OCL_ExplicitNone;
3896 else if (attr.getParameterName()->isStr("strong"))
3897 lifetime = Qualifiers::OCL_Strong;
3898 else if (attr.getParameterName()->isStr("weak"))
3899 lifetime = Qualifiers::OCL_Weak;
3900 else if (attr.getParameterName()->isStr("autoreleasing"))
3901 lifetime = Qualifiers::OCL_Autoreleasing;
3903 S.Diag(AttrLoc, diag::warn_attribute_type_not_supported)
3904 << "objc_ownership" << attr.getParameterName();
3909 SplitQualType underlyingType = type.split();
3911 // Check for redundant/conflicting ownership qualifiers.
3912 if (Qualifiers::ObjCLifetime previousLifetime
3913 = type.getQualifiers().getObjCLifetime()) {
3914 // If it's written directly, that's an error.
3915 if (hasDirectOwnershipQualifier(type)) {
3916 S.Diag(AttrLoc, diag::err_attr_objc_ownership_redundant)
3921 // Otherwise, if the qualifiers actually conflict, pull sugar off
3922 // until we reach a type that is directly qualified.
3923 if (previousLifetime != lifetime) {
3924 // This should always terminate: the canonical type is
3925 // qualified, so some bit of sugar must be hiding it.
3926 while (!underlyingType.Quals.hasObjCLifetime()) {
3927 underlyingType = underlyingType.getSingleStepDesugaredType();
3929 underlyingType.Quals.removeObjCLifetime();
3933 underlyingType.Quals.addObjCLifetime(lifetime);
3935 if (NonObjCPointer) {
3936 StringRef name = attr.getName()->getName();
3938 case Qualifiers::OCL_None:
3939 case Qualifiers::OCL_ExplicitNone:
3941 case Qualifiers::OCL_Strong: name = "__strong"; break;
3942 case Qualifiers::OCL_Weak: name = "__weak"; break;
3943 case Qualifiers::OCL_Autoreleasing: name = "__autoreleasing"; break;
3945 S.Diag(AttrLoc, diag::warn_objc_object_attribute_wrong_type)
3949 QualType origType = type;
3950 if (!NonObjCPointer)
3951 type = S.Context.getQualifiedType(underlyingType);
3953 // If we have a valid source location for the attribute, use an
3954 // AttributedType instead.
3955 if (AttrLoc.isValid())
3956 type = S.Context.getAttributedType(AttributedType::attr_objc_ownership,
3959 // Forbid __weak if the runtime doesn't support it.
3960 if (lifetime == Qualifiers::OCL_Weak &&
3961 !S.getLangOpts().ObjCARCWeak && !NonObjCPointer) {
3963 // Actually, delay this until we know what we're parsing.
3964 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
3965 S.DelayedDiagnostics.add(
3966 sema::DelayedDiagnostic::makeForbiddenType(
3967 S.getSourceManager().getExpansionLoc(AttrLoc),
3968 diag::err_arc_weak_no_runtime, type, /*ignored*/ 0));
3970 S.Diag(AttrLoc, diag::err_arc_weak_no_runtime);
3977 // Forbid __weak for class objects marked as
3978 // objc_arc_weak_reference_unavailable
3979 if (lifetime == Qualifiers::OCL_Weak) {
3980 if (const ObjCObjectPointerType *ObjT =
3981 type->getAs<ObjCObjectPointerType>()) {
3982 if (ObjCInterfaceDecl *Class = ObjT->getInterfaceDecl()) {
3983 if (Class->isArcWeakrefUnavailable()) {
3984 S.Diag(AttrLoc, diag::err_arc_unsupported_weak_class);
3985 S.Diag(ObjT->getInterfaceDecl()->getLocation(),
3986 diag::note_class_declared);
3995 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
3996 /// attribute on the specified type. Returns true to indicate that
3997 /// the attribute was handled, false to indicate that the type does
3998 /// not permit the attribute.
3999 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
4000 AttributeList &attr,
4002 Sema &S = state.getSema();
4004 // Delay if this isn't some kind of pointer.
4005 if (!type->isPointerType() &&
4006 !type->isObjCObjectPointerType() &&
4007 !type->isBlockPointerType())
4010 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
4011 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
4016 // Check the attribute arguments.
4017 if (!attr.getParameterName()) {
4018 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
4023 Qualifiers::GC GCAttr;
4024 if (attr.getNumArgs() != 0) {
4025 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4029 if (attr.getParameterName()->isStr("weak"))
4030 GCAttr = Qualifiers::Weak;
4031 else if (attr.getParameterName()->isStr("strong"))
4032 GCAttr = Qualifiers::Strong;
4034 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
4035 << "objc_gc" << attr.getParameterName();
4040 QualType origType = type;
4041 type = S.Context.getObjCGCQualType(origType, GCAttr);
4043 // Make an attributed type to preserve the source information.
4044 if (attr.getLoc().isValid())
4045 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
4052 /// A helper class to unwrap a type down to a function for the
4053 /// purposes of applying attributes there.
4056 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
4057 /// if (unwrapped.isFunctionType()) {
4058 /// const FunctionType *fn = unwrapped.get();
4059 /// // change fn somehow
4060 /// T = unwrapped.wrap(fn);
4062 struct FunctionTypeUnwrapper {
4073 const FunctionType *Fn;
4074 SmallVector<unsigned char /*WrapKind*/, 8> Stack;
4076 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
4078 const Type *Ty = T.getTypePtr();
4079 if (isa<FunctionType>(Ty)) {
4080 Fn = cast<FunctionType>(Ty);
4082 } else if (isa<ParenType>(Ty)) {
4083 T = cast<ParenType>(Ty)->getInnerType();
4084 Stack.push_back(Parens);
4085 } else if (isa<PointerType>(Ty)) {
4086 T = cast<PointerType>(Ty)->getPointeeType();
4087 Stack.push_back(Pointer);
4088 } else if (isa<BlockPointerType>(Ty)) {
4089 T = cast<BlockPointerType>(Ty)->getPointeeType();
4090 Stack.push_back(BlockPointer);
4091 } else if (isa<MemberPointerType>(Ty)) {
4092 T = cast<MemberPointerType>(Ty)->getPointeeType();
4093 Stack.push_back(MemberPointer);
4094 } else if (isa<ReferenceType>(Ty)) {
4095 T = cast<ReferenceType>(Ty)->getPointeeType();
4096 Stack.push_back(Reference);
4098 const Type *DTy = Ty->getUnqualifiedDesugaredType();
4104 T = QualType(DTy, 0);
4105 Stack.push_back(Desugar);
4110 bool isFunctionType() const { return (Fn != 0); }
4111 const FunctionType *get() const { return Fn; }
4113 QualType wrap(Sema &S, const FunctionType *New) {
4114 // If T wasn't modified from the unwrapped type, do nothing.
4115 if (New == get()) return Original;
4118 return wrap(S.Context, Original, 0);
4122 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
4123 if (I == Stack.size())
4124 return C.getQualifiedType(Fn, Old.getQualifiers());
4126 // Build up the inner type, applying the qualifiers from the old
4127 // type to the new type.
4128 SplitQualType SplitOld = Old.split();
4130 // As a special case, tail-recurse if there are no qualifiers.
4131 if (SplitOld.Quals.empty())
4132 return wrap(C, SplitOld.Ty, I);
4133 return C.getQualifiedType(wrap(C, SplitOld.Ty, I), SplitOld.Quals);
4136 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
4137 if (I == Stack.size()) return QualType(Fn, 0);
4139 switch (static_cast<WrapKind>(Stack[I++])) {
4141 // This is the point at which we potentially lose source
4143 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
4146 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
4147 return C.getParenType(New);
4151 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
4152 return C.getPointerType(New);
4155 case BlockPointer: {
4156 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
4157 return C.getBlockPointerType(New);
4160 case MemberPointer: {
4161 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
4162 QualType New = wrap(C, OldMPT->getPointeeType(), I);
4163 return C.getMemberPointerType(New, OldMPT->getClass());
4167 const ReferenceType *OldRef = cast<ReferenceType>(Old);
4168 QualType New = wrap(C, OldRef->getPointeeType(), I);
4169 if (isa<LValueReferenceType>(OldRef))
4170 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
4172 return C.getRValueReferenceType(New);
4176 llvm_unreachable("unknown wrapping kind");
4181 /// Process an individual function attribute. Returns true to
4182 /// indicate that the attribute was handled, false if it wasn't.
4183 static bool handleFunctionTypeAttr(TypeProcessingState &state,
4184 AttributeList &attr,
4186 Sema &S = state.getSema();
4188 FunctionTypeUnwrapper unwrapped(S, type);
4190 if (attr.getKind() == AttributeList::AT_NoReturn) {
4191 if (S.CheckNoReturnAttr(attr))
4194 // Delay if this is not a function type.
4195 if (!unwrapped.isFunctionType())
4198 // Otherwise we can process right away.
4199 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
4200 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4204 // ns_returns_retained is not always a type attribute, but if we got
4205 // here, we're treating it as one right now.
4206 if (attr.getKind() == AttributeList::AT_NSReturnsRetained) {
4207 assert(S.getLangOpts().ObjCAutoRefCount &&
4208 "ns_returns_retained treated as type attribute in non-ARC");
4209 if (attr.getNumArgs()) return true;
4211 // Delay if this is not a function type.
4212 if (!unwrapped.isFunctionType())
4215 FunctionType::ExtInfo EI
4216 = unwrapped.get()->getExtInfo().withProducesResult(true);
4217 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4221 if (attr.getKind() == AttributeList::AT_Regparm) {
4223 if (S.CheckRegparmAttr(attr, value))
4226 // Delay if this is not a function type.
4227 if (!unwrapped.isFunctionType())
4230 // Diagnose regparm with fastcall.
4231 const FunctionType *fn = unwrapped.get();
4232 CallingConv CC = fn->getCallConv();
4233 if (CC == CC_X86FastCall) {
4234 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4235 << FunctionType::getNameForCallConv(CC)
4241 FunctionType::ExtInfo EI =
4242 unwrapped.get()->getExtInfo().withRegParm(value);
4243 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4247 // Delay if the type didn't work out to a function.
4248 if (!unwrapped.isFunctionType()) return false;
4250 // Otherwise, a calling convention.
4252 if (S.CheckCallingConvAttr(attr, CC))
4255 const FunctionType *fn = unwrapped.get();
4256 CallingConv CCOld = fn->getCallConv();
4257 if (S.Context.getCanonicalCallConv(CC) ==
4258 S.Context.getCanonicalCallConv(CCOld)) {
4259 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
4260 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4264 if (CCOld != (S.LangOpts.MRTD ? CC_X86StdCall : CC_Default)) {
4265 // Should we diagnose reapplications of the same convention?
4266 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4267 << FunctionType::getNameForCallConv(CC)
4268 << FunctionType::getNameForCallConv(CCOld);
4273 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
4274 if (CC == CC_X86FastCall) {
4275 if (isa<FunctionNoProtoType>(fn)) {
4276 S.Diag(attr.getLoc(), diag::err_cconv_knr)
4277 << FunctionType::getNameForCallConv(CC);
4282 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
4283 if (FnP->isVariadic()) {
4284 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
4285 << FunctionType::getNameForCallConv(CC);
4290 // Also diagnose fastcall with regparm.
4291 if (fn->getHasRegParm()) {
4292 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
4294 << FunctionType::getNameForCallConv(CC);
4300 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
4301 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
4305 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
4306 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
4307 const AttributeList &Attr,
4309 // Check the attribute arguments.
4310 if (Attr.getNumArgs() != 1) {
4311 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4315 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4316 llvm::APSInt arg(32);
4317 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4318 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
4319 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4320 << "opencl_image_access" << sizeExpr->getSourceRange();
4324 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
4326 case CLIA_read_only:
4327 case CLIA_write_only:
4328 case CLIA_read_write:
4329 // Implemented in a separate patch
4332 // Implemented in a separate patch
4333 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4334 << sizeExpr->getSourceRange();
4340 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
4341 /// and float scalars, although arrays, pointers, and function return values are
4342 /// allowed in conjunction with this construct. Aggregates with this attribute
4343 /// are invalid, even if they are of the same size as a corresponding scalar.
4344 /// The raw attribute should contain precisely 1 argument, the vector size for
4345 /// the variable, measured in bytes. If curType and rawAttr are well formed,
4346 /// this routine will return a new vector type.
4347 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
4349 // Check the attribute arguments.
4350 if (Attr.getNumArgs() != 1) {
4351 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4355 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
4356 llvm::APSInt vecSize(32);
4357 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
4358 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
4359 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4360 << "vector_size" << sizeExpr->getSourceRange();
4364 // the base type must be integer or float, and can't already be a vector.
4365 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
4366 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
4370 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4371 // vecSize is specified in bytes - convert to bits.
4372 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
4374 // the vector size needs to be an integral multiple of the type size.
4375 if (vectorSize % typeSize) {
4376 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
4377 << sizeExpr->getSourceRange();
4381 if (vectorSize == 0) {
4382 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
4383 << sizeExpr->getSourceRange();
4388 // Success! Instantiate the vector type, the number of elements is > 0, and
4389 // not required to be a power of 2, unlike GCC.
4390 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
4391 VectorType::GenericVector);
4394 /// \brief Process the OpenCL-like ext_vector_type attribute when it occurs on
4396 static void HandleExtVectorTypeAttr(QualType &CurType,
4397 const AttributeList &Attr,
4401 // Special case where the argument is a template id.
4402 if (Attr.getParameterName()) {
4404 SourceLocation TemplateKWLoc;
4406 id.setIdentifier(Attr.getParameterName(), Attr.getLoc());
4408 ExprResult Size = S.ActOnIdExpression(S.getCurScope(), SS, TemplateKWLoc,
4410 if (Size.isInvalid())
4413 sizeExpr = Size.get();
4415 // check the attribute arguments.
4416 if (Attr.getNumArgs() != 1) {
4417 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4420 sizeExpr = Attr.getArg(0);
4423 // Create the vector type.
4424 QualType T = S.BuildExtVectorType(CurType, sizeExpr, Attr.getLoc());
4429 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
4430 /// "neon_polyvector_type" attributes are used to create vector types that
4431 /// are mangled according to ARM's ABI. Otherwise, these types are identical
4432 /// to those created with the "vector_size" attribute. Unlike "vector_size"
4433 /// the argument to these Neon attributes is the number of vector elements,
4434 /// not the vector size in bytes. The vector width and element type must
4435 /// match one of the standard Neon vector types.
4436 static void HandleNeonVectorTypeAttr(QualType& CurType,
4437 const AttributeList &Attr, Sema &S,
4438 VectorType::VectorKind VecKind,
4439 const char *AttrName) {
4440 // Check the attribute arguments.
4441 if (Attr.getNumArgs() != 1) {
4442 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
4446 // The number of elements must be an ICE.
4447 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
4448 llvm::APSInt numEltsInt(32);
4449 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
4450 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
4451 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
4452 << AttrName << numEltsExpr->getSourceRange();
4456 // Only certain element types are supported for Neon vectors.
4457 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
4459 (VecKind == VectorType::NeonPolyVector &&
4460 BTy->getKind() != BuiltinType::SChar &&
4461 BTy->getKind() != BuiltinType::Short) ||
4462 (BTy->getKind() != BuiltinType::SChar &&
4463 BTy->getKind() != BuiltinType::UChar &&
4464 BTy->getKind() != BuiltinType::Short &&
4465 BTy->getKind() != BuiltinType::UShort &&
4466 BTy->getKind() != BuiltinType::Int &&
4467 BTy->getKind() != BuiltinType::UInt &&
4468 BTy->getKind() != BuiltinType::LongLong &&
4469 BTy->getKind() != BuiltinType::ULongLong &&
4470 BTy->getKind() != BuiltinType::Float)) {
4471 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
4475 // The total size of the vector must be 64 or 128 bits.
4476 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
4477 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
4478 unsigned vecSize = typeSize * numElts;
4479 if (vecSize != 64 && vecSize != 128) {
4480 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
4485 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
4488 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
4489 TypeAttrLocation TAL, AttributeList *attrs) {
4490 // Scan through and apply attributes to this type where it makes sense. Some
4491 // attributes (such as __address_space__, __vector_size__, etc) apply to the
4492 // type, but others can be present in the type specifiers even though they
4493 // apply to the decl. Here we apply type attributes and ignore the rest.
4495 AttributeList *next;
4497 AttributeList &attr = *attrs;
4498 next = attr.getNext();
4500 // Skip attributes that were marked to be invalid.
4501 if (attr.isInvalid())
4504 if (attr.isCXX11Attribute()) {
4505 // [[gnu::...]] attributes are treated as declaration attributes, so may
4506 // not appertain to a DeclaratorChunk, even if we handle them as type
4508 if (attr.getScopeName() && attr.getScopeName()->isStr("gnu")) {
4509 if (TAL == TAL_DeclChunk) {
4510 state.getSema().Diag(attr.getLoc(),
4511 diag::warn_cxx11_gnu_attribute_on_type)
4515 } else if (TAL != TAL_DeclChunk) {
4516 // Otherwise, only consider type processing for a C++11 attribute if
4517 // it's actually been applied to a type.
4522 // If this is an attribute we can handle, do so now,
4523 // otherwise, add it to the FnAttrs list for rechaining.
4524 switch (attr.getKind()) {
4526 // A C++11 attribute on a declarator chunk must appertain to a type.
4527 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk) {
4528 state.getSema().Diag(attr.getLoc(), diag::err_attribute_not_type_attr)
4530 attr.setUsedAsTypeAttr();
4534 case AttributeList::UnknownAttribute:
4535 if (attr.isCXX11Attribute() && TAL == TAL_DeclChunk)
4536 state.getSema().Diag(attr.getLoc(),
4537 diag::warn_unknown_attribute_ignored)
4541 case AttributeList::IgnoredAttribute:
4544 case AttributeList::AT_MayAlias:
4545 // FIXME: This attribute needs to actually be handled, but if we ignore
4546 // it it breaks large amounts of Linux software.
4547 attr.setUsedAsTypeAttr();
4549 case AttributeList::AT_AddressSpace:
4550 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
4551 attr.setUsedAsTypeAttr();
4553 OBJC_POINTER_TYPE_ATTRS_CASELIST:
4554 if (!handleObjCPointerTypeAttr(state, attr, type))
4555 distributeObjCPointerTypeAttr(state, attr, type);
4556 attr.setUsedAsTypeAttr();
4558 case AttributeList::AT_VectorSize:
4559 HandleVectorSizeAttr(type, attr, state.getSema());
4560 attr.setUsedAsTypeAttr();
4562 case AttributeList::AT_ExtVectorType:
4563 HandleExtVectorTypeAttr(type, attr, state.getSema());
4564 attr.setUsedAsTypeAttr();
4566 case AttributeList::AT_NeonVectorType:
4567 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4568 VectorType::NeonVector, "neon_vector_type");
4569 attr.setUsedAsTypeAttr();
4571 case AttributeList::AT_NeonPolyVectorType:
4572 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
4573 VectorType::NeonPolyVector,
4574 "neon_polyvector_type");
4575 attr.setUsedAsTypeAttr();
4577 case AttributeList::AT_OpenCLImageAccess:
4578 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
4579 attr.setUsedAsTypeAttr();
4582 case AttributeList::AT_Win64:
4583 case AttributeList::AT_Ptr32:
4584 case AttributeList::AT_Ptr64:
4585 // FIXME: Don't ignore these. We have partial handling for them as
4586 // declaration attributes in SemaDeclAttr.cpp; that should be moved here.
4587 attr.setUsedAsTypeAttr();
4590 case AttributeList::AT_NSReturnsRetained:
4591 if (!state.getSema().getLangOpts().ObjCAutoRefCount)
4593 // fallthrough into the function attrs
4595 FUNCTION_TYPE_ATTRS_CASELIST:
4596 attr.setUsedAsTypeAttr();
4598 // Never process function type attributes as part of the
4599 // declaration-specifiers.
4600 if (TAL == TAL_DeclSpec)
4601 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
4603 // Otherwise, handle the possible delays.
4604 else if (!handleFunctionTypeAttr(state, attr, type))
4605 distributeFunctionTypeAttr(state, attr, type);
4608 } while ((attrs = next));
4611 /// \brief Ensure that the type of the given expression is complete.
4613 /// This routine checks whether the expression \p E has a complete type. If the
4614 /// expression refers to an instantiable construct, that instantiation is
4615 /// performed as needed to complete its type. Furthermore
4616 /// Sema::RequireCompleteType is called for the expression's type (or in the
4617 /// case of a reference type, the referred-to type).
4619 /// \param E The expression whose type is required to be complete.
4620 /// \param Diagnoser The object that will emit a diagnostic if the type is
4623 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
4625 bool Sema::RequireCompleteExprType(Expr *E, TypeDiagnoser &Diagnoser){
4626 QualType T = E->getType();
4628 // Fast path the case where the type is already complete.
4629 if (!T->isIncompleteType())
4632 // Incomplete array types may be completed by the initializer attached to
4633 // their definitions. For static data members of class templates we need to
4634 // instantiate the definition to get this initializer and complete the type.
4635 if (T->isIncompleteArrayType()) {
4636 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
4637 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
4638 if (Var->isStaticDataMember() &&
4639 Var->getInstantiatedFromStaticDataMember()) {
4641 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
4642 assert(MSInfo && "Missing member specialization information?");
4643 if (MSInfo->getTemplateSpecializationKind()
4644 != TSK_ExplicitSpecialization) {
4645 // If we don't already have a point of instantiation, this is it.
4646 if (MSInfo->getPointOfInstantiation().isInvalid()) {
4647 MSInfo->setPointOfInstantiation(E->getLocStart());
4649 // This is a modification of an existing AST node. Notify
4651 if (ASTMutationListener *L = getASTMutationListener())
4652 L->StaticDataMemberInstantiated(Var);
4655 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
4657 // Update the type to the newly instantiated definition's type both
4658 // here and within the expression.
4659 if (VarDecl *Def = Var->getDefinition()) {
4667 // We still go on to try to complete the type independently, as it
4668 // may also require instantiations or diagnostics if it remains
4675 // FIXME: Are there other cases which require instantiating something other
4676 // than the type to complete the type of an expression?
4678 // Look through reference types and complete the referred type.
4679 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4680 T = Ref->getPointeeType();
4682 return RequireCompleteType(E->getExprLoc(), T, Diagnoser);
4686 struct TypeDiagnoserDiag : Sema::TypeDiagnoser {
4689 TypeDiagnoserDiag(unsigned DiagID)
4690 : Sema::TypeDiagnoser(DiagID == 0), DiagID(DiagID) {}
4692 virtual void diagnose(Sema &S, SourceLocation Loc, QualType T) {
4693 if (Suppressed) return;
4694 S.Diag(Loc, DiagID) << T;
4699 bool Sema::RequireCompleteExprType(Expr *E, unsigned DiagID) {
4700 TypeDiagnoserDiag Diagnoser(DiagID);
4701 return RequireCompleteExprType(E, Diagnoser);
4704 /// @brief Ensure that the type T is a complete type.
4706 /// This routine checks whether the type @p T is complete in any
4707 /// context where a complete type is required. If @p T is a complete
4708 /// type, returns false. If @p T is a class template specialization,
4709 /// this routine then attempts to perform class template
4710 /// instantiation. If instantiation fails, or if @p T is incomplete
4711 /// and cannot be completed, issues the diagnostic @p diag (giving it
4712 /// the type @p T) and returns true.
4714 /// @param Loc The location in the source that the incomplete type
4715 /// diagnostic should refer to.
4717 /// @param T The type that this routine is examining for completeness.
4719 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
4720 /// @c false otherwise.
4721 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4722 TypeDiagnoser &Diagnoser) {
4723 // FIXME: Add this assertion to make sure we always get instantiation points.
4724 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
4725 // FIXME: Add this assertion to help us flush out problems with
4726 // checking for dependent types and type-dependent expressions.
4728 // assert(!T->isDependentType() &&
4729 // "Can't ask whether a dependent type is complete");
4731 // If we have a complete type, we're done.
4733 if (!T->isIncompleteType(&Def)) {
4734 // If we know about the definition but it is not visible, complain.
4735 if (!Diagnoser.Suppressed && Def && !LookupResult::isVisible(Def)) {
4736 // Suppress this error outside of a SFINAE context if we've already
4737 // emitted the error once for this type. There's no usefulness in
4738 // repeating the diagnostic.
4739 // FIXME: Add a Fix-It that imports the corresponding module or includes
4741 Module *Owner = Def->getOwningModule();
4742 Diag(Loc, diag::err_module_private_definition)
4743 << T << Owner->getFullModuleName();
4744 Diag(Def->getLocation(), diag::note_previous_definition);
4746 if (!isSFINAEContext()) {
4747 // Recover by implicitly importing this module.
4748 createImplicitModuleImport(Loc, Owner);
4755 const TagType *Tag = T->getAs<TagType>();
4756 const ObjCInterfaceType *IFace = 0;
4759 // Avoid diagnosing invalid decls as incomplete.
4760 if (Tag->getDecl()->isInvalidDecl())
4763 // Give the external AST source a chance to complete the type.
4764 if (Tag->getDecl()->hasExternalLexicalStorage()) {
4765 Context.getExternalSource()->CompleteType(Tag->getDecl());
4766 if (!Tag->isIncompleteType())
4770 else if ((IFace = T->getAs<ObjCInterfaceType>())) {
4771 // Avoid diagnosing invalid decls as incomplete.
4772 if (IFace->getDecl()->isInvalidDecl())
4775 // Give the external AST source a chance to complete the type.
4776 if (IFace->getDecl()->hasExternalLexicalStorage()) {
4777 Context.getExternalSource()->CompleteType(IFace->getDecl());
4778 if (!IFace->isIncompleteType())
4783 // If we have a class template specialization or a class member of a
4784 // class template specialization, or an array with known size of such,
4785 // try to instantiate it.
4786 QualType MaybeTemplate = T;
4787 while (const ConstantArrayType *Array
4788 = Context.getAsConstantArrayType(MaybeTemplate))
4789 MaybeTemplate = Array->getElementType();
4790 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
4791 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
4792 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
4793 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
4794 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
4795 TSK_ImplicitInstantiation,
4796 /*Complain=*/!Diagnoser.Suppressed);
4797 } else if (CXXRecordDecl *Rec
4798 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
4799 CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass();
4800 if (!Rec->isBeingDefined() && Pattern) {
4801 MemberSpecializationInfo *MSI = Rec->getMemberSpecializationInfo();
4802 assert(MSI && "Missing member specialization information?");
4803 // This record was instantiated from a class within a template.
4804 if (MSI->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
4805 return InstantiateClass(Loc, Rec, Pattern,
4806 getTemplateInstantiationArgs(Rec),
4807 TSK_ImplicitInstantiation,
4808 /*Complain=*/!Diagnoser.Suppressed);
4813 if (Diagnoser.Suppressed)
4816 // We have an incomplete type. Produce a diagnostic.
4817 Diagnoser.diagnose(*this, Loc, T);
4819 // If the type was a forward declaration of a class/struct/union
4820 // type, produce a note.
4821 if (Tag && !Tag->getDecl()->isInvalidDecl())
4822 Diag(Tag->getDecl()->getLocation(),
4823 Tag->isBeingDefined() ? diag::note_type_being_defined
4824 : diag::note_forward_declaration)
4825 << QualType(Tag, 0);
4827 // If the Objective-C class was a forward declaration, produce a note.
4828 if (IFace && !IFace->getDecl()->isInvalidDecl())
4829 Diag(IFace->getDecl()->getLocation(), diag::note_forward_class);
4834 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
4836 TypeDiagnoserDiag Diagnoser(DiagID);
4837 return RequireCompleteType(Loc, T, Diagnoser);
4840 /// \brief Get diagnostic %select index for tag kind for
4841 /// literal type diagnostic message.
4842 /// WARNING: Indexes apply to particular diagnostics only!
4844 /// \returns diagnostic %select index.
4845 static unsigned getLiteralDiagFromTagKind(TagTypeKind Tag) {
4847 case TTK_Struct: return 0;
4848 case TTK_Interface: return 1;
4849 case TTK_Class: return 2;
4850 default: llvm_unreachable("Invalid tag kind for literal type diagnostic!");
4854 /// @brief Ensure that the type T is a literal type.
4856 /// This routine checks whether the type @p T is a literal type. If @p T is an
4857 /// incomplete type, an attempt is made to complete it. If @p T is a literal
4858 /// type, or @p AllowIncompleteType is true and @p T is an incomplete type,
4859 /// returns false. Otherwise, this routine issues the diagnostic @p PD (giving
4860 /// it the type @p T), along with notes explaining why the type is not a
4861 /// literal type, and returns true.
4863 /// @param Loc The location in the source that the non-literal type
4864 /// diagnostic should refer to.
4866 /// @param T The type that this routine is examining for literalness.
4868 /// @param Diagnoser Emits a diagnostic if T is not a literal type.
4870 /// @returns @c true if @p T is not a literal type and a diagnostic was emitted,
4871 /// @c false otherwise.
4872 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T,
4873 TypeDiagnoser &Diagnoser) {
4874 assert(!T->isDependentType() && "type should not be dependent");
4876 QualType ElemType = Context.getBaseElementType(T);
4877 RequireCompleteType(Loc, ElemType, 0);
4879 if (T->isLiteralType(Context))
4882 if (Diagnoser.Suppressed)
4885 Diagnoser.diagnose(*this, Loc, T);
4887 if (T->isVariableArrayType())
4890 const RecordType *RT = ElemType->getAs<RecordType>();
4894 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
4896 // A partially-defined class type can't be a literal type, because a literal
4897 // class type must have a trivial destructor (which can't be checked until
4898 // the class definition is complete).
4899 if (!RD->isCompleteDefinition()) {
4900 RequireCompleteType(Loc, ElemType, diag::note_non_literal_incomplete, T);
4904 // If the class has virtual base classes, then it's not an aggregate, and
4905 // cannot have any constexpr constructors or a trivial default constructor,
4906 // so is non-literal. This is better to diagnose than the resulting absence
4907 // of constexpr constructors.
4908 if (RD->getNumVBases()) {
4909 Diag(RD->getLocation(), diag::note_non_literal_virtual_base)
4910 << getLiteralDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
4911 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
4912 E = RD->vbases_end(); I != E; ++I)
4913 Diag(I->getLocStart(),
4914 diag::note_constexpr_virtual_base_here) << I->getSourceRange();
4915 } else if (!RD->isAggregate() && !RD->hasConstexprNonCopyMoveConstructor() &&
4916 !RD->hasTrivialDefaultConstructor()) {
4917 Diag(RD->getLocation(), diag::note_non_literal_no_constexpr_ctors) << RD;
4918 } else if (RD->hasNonLiteralTypeFieldsOrBases()) {
4919 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
4920 E = RD->bases_end(); I != E; ++I) {
4921 if (!I->getType()->isLiteralType(Context)) {
4922 Diag(I->getLocStart(),
4923 diag::note_non_literal_base_class)
4924 << RD << I->getType() << I->getSourceRange();
4928 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
4929 E = RD->field_end(); I != E; ++I) {
4930 if (!I->getType()->isLiteralType(Context) ||
4931 I->getType().isVolatileQualified()) {
4932 Diag(I->getLocation(), diag::note_non_literal_field)
4933 << RD << *I << I->getType()
4934 << I->getType().isVolatileQualified();
4938 } else if (!RD->hasTrivialDestructor()) {
4939 // All fields and bases are of literal types, so have trivial destructors.
4940 // If this class's destructor is non-trivial it must be user-declared.
4941 CXXDestructorDecl *Dtor = RD->getDestructor();
4942 assert(Dtor && "class has literal fields and bases but no dtor?");
4946 Diag(Dtor->getLocation(), Dtor->isUserProvided() ?
4947 diag::note_non_literal_user_provided_dtor :
4948 diag::note_non_literal_nontrivial_dtor) << RD;
4949 if (!Dtor->isUserProvided())
4950 SpecialMemberIsTrivial(Dtor, CXXDestructor, /*Diagnose*/true);
4956 bool Sema::RequireLiteralType(SourceLocation Loc, QualType T, unsigned DiagID) {
4957 TypeDiagnoserDiag Diagnoser(DiagID);
4958 return RequireLiteralType(Loc, T, Diagnoser);
4961 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
4962 /// and qualified by the nested-name-specifier contained in SS.
4963 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
4964 const CXXScopeSpec &SS, QualType T) {
4967 NestedNameSpecifier *NNS;
4969 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
4971 if (Keyword == ETK_None)
4975 return Context.getElaboratedType(Keyword, NNS, T);
4978 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
4979 ExprResult ER = CheckPlaceholderExpr(E);
4980 if (ER.isInvalid()) return QualType();
4983 if (!E->isTypeDependent()) {
4984 QualType T = E->getType();
4985 if (const TagType *TT = T->getAs<TagType>())
4986 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
4988 return Context.getTypeOfExprType(E);
4991 /// getDecltypeForExpr - Given an expr, will return the decltype for
4992 /// that expression, according to the rules in C++11
4993 /// [dcl.type.simple]p4 and C++11 [expr.lambda.prim]p18.
4994 static QualType getDecltypeForExpr(Sema &S, Expr *E) {
4995 if (E->isTypeDependent())
4996 return S.Context.DependentTy;
4998 // C++11 [dcl.type.simple]p4:
4999 // The type denoted by decltype(e) is defined as follows:
5001 // - if e is an unparenthesized id-expression or an unparenthesized class
5002 // member access (5.2.5), decltype(e) is the type of the entity named
5003 // by e. If there is no such entity, or if e names a set of overloaded
5004 // functions, the program is ill-formed;
5006 // We apply the same rules for Objective-C ivar and property references.
5007 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
5008 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl()))
5009 return VD->getType();
5010 } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
5011 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
5012 return FD->getType();
5013 } else if (const ObjCIvarRefExpr *IR = dyn_cast<ObjCIvarRefExpr>(E)) {
5014 return IR->getDecl()->getType();
5015 } else if (const ObjCPropertyRefExpr *PR = dyn_cast<ObjCPropertyRefExpr>(E)) {
5016 if (PR->isExplicitProperty())
5017 return PR->getExplicitProperty()->getType();
5020 // C++11 [expr.lambda.prim]p18:
5021 // Every occurrence of decltype((x)) where x is a possibly
5022 // parenthesized id-expression that names an entity of automatic
5023 // storage duration is treated as if x were transformed into an
5024 // access to a corresponding data member of the closure type that
5025 // would have been declared if x were an odr-use of the denoted
5027 using namespace sema;
5028 if (S.getCurLambda()) {
5029 if (isa<ParenExpr>(E)) {
5030 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
5031 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
5032 QualType T = S.getCapturedDeclRefType(Var, DRE->getLocation());
5034 return S.Context.getLValueReferenceType(T);
5041 // C++11 [dcl.type.simple]p4:
5043 QualType T = E->getType();
5044 switch (E->getValueKind()) {
5045 // - otherwise, if e is an xvalue, decltype(e) is T&&, where T is the
5047 case VK_XValue: T = S.Context.getRValueReferenceType(T); break;
5048 // - otherwise, if e is an lvalue, decltype(e) is T&, where T is the
5050 case VK_LValue: T = S.Context.getLValueReferenceType(T); break;
5051 // - otherwise, decltype(e) is the type of e.
5052 case VK_RValue: break;
5058 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
5059 ExprResult ER = CheckPlaceholderExpr(E);
5060 if (ER.isInvalid()) return QualType();
5063 return Context.getDecltypeType(E, getDecltypeForExpr(*this, E));
5066 QualType Sema::BuildUnaryTransformType(QualType BaseType,
5067 UnaryTransformType::UTTKind UKind,
5068 SourceLocation Loc) {
5070 case UnaryTransformType::EnumUnderlyingType:
5071 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
5072 Diag(Loc, diag::err_only_enums_have_underlying_types);
5075 QualType Underlying = BaseType;
5076 if (!BaseType->isDependentType()) {
5077 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
5078 assert(ED && "EnumType has no EnumDecl");
5079 DiagnoseUseOfDecl(ED, Loc);
5080 Underlying = ED->getIntegerType();
5082 assert(!Underlying.isNull());
5083 return Context.getUnaryTransformType(BaseType, Underlying,
5084 UnaryTransformType::EnumUnderlyingType);
5087 llvm_unreachable("unknown unary transform type");
5090 QualType Sema::BuildAtomicType(QualType T, SourceLocation Loc) {
5091 if (!T->isDependentType()) {
5092 // FIXME: It isn't entirely clear whether incomplete atomic types
5093 // are allowed or not; for simplicity, ban them for the moment.
5094 if (RequireCompleteType(Loc, T, diag::err_atomic_specifier_bad_type, 0))
5097 int DisallowedKind = -1;
5098 if (T->isArrayType())
5100 else if (T->isFunctionType())
5102 else if (T->isReferenceType())
5104 else if (T->isAtomicType())
5106 else if (T.hasQualifiers())
5108 else if (!T.isTriviallyCopyableType(Context))
5109 // Some other non-trivially-copyable type (probably a C++ class)
5112 if (DisallowedKind != -1) {
5113 Diag(Loc, diag::err_atomic_specifier_bad_type) << DisallowedKind << T;
5117 // FIXME: Do we need any handling for ARC here?
5120 // Build the pointer type.
5121 return Context.getAtomicType(T);