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/Sema/Template.h"
16 #include "clang/Basic/OpenCL.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/CXXInheritance.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/TypeLoc.h"
23 #include "clang/AST/TypeLocVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Basic/PartialDiagnostic.h"
26 #include "clang/Basic/TargetInfo.h"
27 #include "clang/Lex/Preprocessor.h"
28 #include "clang/Sema/DeclSpec.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/Support/ErrorHandling.h"
31 using namespace clang;
33 /// \brief Perform adjustment on the parameter type of a function.
35 /// This routine adjusts the given parameter type @p T to the actual
36 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
37 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
38 QualType Sema::adjustParameterType(QualType T) {
40 // A declaration of a parameter as "array of type" shall be
41 // adjusted to "qualified pointer to type", where the type
42 // qualifiers (if any) are those specified within the [ and ] of
43 // the array type derivation.
45 return Context.getArrayDecayedType(T);
48 // A declaration of a parameter as "function returning type"
49 // shall be adjusted to "pointer to function returning type", as
51 if (T->isFunctionType())
52 return Context.getPointerType(T);
59 /// isOmittedBlockReturnType - Return true if this declarator is missing a
60 /// return type because this is a omitted return type on a block literal.
61 static bool isOmittedBlockReturnType(const Declarator &D) {
62 if (D.getContext() != Declarator::BlockLiteralContext ||
63 D.getDeclSpec().hasTypeSpecifier())
66 if (D.getNumTypeObjects() == 0)
67 return true; // ^{ ... }
69 if (D.getNumTypeObjects() == 1 &&
70 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
71 return true; // ^(int X, float Y) { ... }
76 /// diagnoseBadTypeAttribute - Diagnoses a type attribute which
77 /// doesn't apply to the given type.
78 static void diagnoseBadTypeAttribute(Sema &S, const AttributeList &attr,
80 bool useInstantiationLoc = false;
83 switch (attr.getKind()) {
84 case AttributeList::AT_objc_gc:
85 diagID = diag::warn_pointer_attribute_wrong_type;
86 useInstantiationLoc = true;
90 // Assume everything else was a function attribute.
91 diagID = diag::warn_function_attribute_wrong_type;
95 SourceLocation loc = attr.getLoc();
96 llvm::StringRef name = attr.getName()->getName();
98 // The GC attributes are usually written with macros; special-case them.
99 if (useInstantiationLoc && loc.isMacroID() && attr.getParameterName()) {
100 if (attr.getParameterName()->isStr("strong")) {
101 if (S.findMacroSpelling(loc, "__strong")) name = "__strong";
102 } else if (attr.getParameterName()->isStr("weak")) {
103 if (S.findMacroSpelling(loc, "__weak")) name = "__weak";
107 S.Diag(loc, diagID) << name << type;
110 // objc_gc applies to Objective-C pointers or, otherwise, to the
111 // smallest available pointer type (i.e. 'void*' in 'void**').
112 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
113 case AttributeList::AT_objc_gc
115 // Function type attributes.
116 #define FUNCTION_TYPE_ATTRS_CASELIST \
117 case AttributeList::AT_noreturn: \
118 case AttributeList::AT_cdecl: \
119 case AttributeList::AT_fastcall: \
120 case AttributeList::AT_stdcall: \
121 case AttributeList::AT_thiscall: \
122 case AttributeList::AT_pascal: \
123 case AttributeList::AT_regparm: \
124 case AttributeList::AT_pcs \
127 /// An object which stores processing state for the entire
128 /// GetTypeForDeclarator process.
129 class TypeProcessingState {
132 /// The declarator being processed.
133 Declarator &declarator;
135 /// The index of the declarator chunk we're currently processing.
136 /// May be the total number of valid chunks, indicating the
140 /// Whether there are non-trivial modifications to the decl spec.
143 /// Whether we saved the attributes in the decl spec.
146 /// The original set of attributes on the DeclSpec.
147 llvm::SmallVector<AttributeList*, 2> savedAttrs;
149 /// A list of attributes to diagnose the uselessness of when the
150 /// processing is complete.
151 llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs;
154 TypeProcessingState(Sema &sema, Declarator &declarator)
155 : sema(sema), declarator(declarator),
156 chunkIndex(declarator.getNumTypeObjects()),
157 trivial(true), hasSavedAttrs(false) {}
159 Sema &getSema() const {
163 Declarator &getDeclarator() const {
167 unsigned getCurrentChunkIndex() const {
171 void setCurrentChunkIndex(unsigned idx) {
172 assert(idx <= declarator.getNumTypeObjects());
176 AttributeList *&getCurrentAttrListRef() const {
177 assert(chunkIndex <= declarator.getNumTypeObjects());
178 if (chunkIndex == declarator.getNumTypeObjects())
179 return getMutableDeclSpec().getAttributes().getListRef();
180 return declarator.getTypeObject(chunkIndex).getAttrListRef();
183 /// Save the current set of attributes on the DeclSpec.
184 void saveDeclSpecAttrs() {
185 // Don't try to save them multiple times.
186 if (hasSavedAttrs) return;
188 DeclSpec &spec = getMutableDeclSpec();
189 for (AttributeList *attr = spec.getAttributes().getList(); attr;
190 attr = attr->getNext())
191 savedAttrs.push_back(attr);
192 trivial &= savedAttrs.empty();
193 hasSavedAttrs = true;
196 /// Record that we had nowhere to put the given type attribute.
197 /// We will diagnose such attributes later.
198 void addIgnoredTypeAttr(AttributeList &attr) {
199 ignoredTypeAttrs.push_back(&attr);
202 /// Diagnose all the ignored type attributes, given that the
203 /// declarator worked out to the given type.
204 void diagnoseIgnoredTypeAttrs(QualType type) const {
205 for (llvm::SmallVectorImpl<AttributeList*>::const_iterator
206 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
208 diagnoseBadTypeAttribute(getSema(), **i, type);
211 ~TypeProcessingState() {
214 restoreDeclSpecAttrs();
218 DeclSpec &getMutableDeclSpec() const {
219 return const_cast<DeclSpec&>(declarator.getDeclSpec());
222 void restoreDeclSpecAttrs() {
223 assert(hasSavedAttrs);
225 if (savedAttrs.empty()) {
226 getMutableDeclSpec().getAttributes().set(0);
230 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
231 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
232 savedAttrs[i]->setNext(savedAttrs[i+1]);
233 savedAttrs.back()->setNext(0);
237 /// Basically std::pair except that we really want to avoid an
238 /// implicit operator= for safety concerns. It's also a minor
239 /// link-time optimization for this to be a private type.
242 AttributeList &first;
244 /// The head of the list the attribute is currently in.
245 AttributeList *&second;
247 AttrAndList(AttributeList &attr, AttributeList *&head)
248 : first(attr), second(head) {}
253 template <> struct isPodLike<AttrAndList> {
254 static const bool value = true;
258 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
263 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
265 head = attr.getNext();
269 AttributeList *cur = head;
271 assert(cur && cur->getNext() && "ran out of attrs?");
272 if (cur->getNext() == &attr) {
273 cur->setNext(attr.getNext());
276 cur = cur->getNext();
280 static void moveAttrFromListToList(AttributeList &attr,
281 AttributeList *&fromList,
282 AttributeList *&toList) {
283 spliceAttrOutOfList(attr, fromList);
284 spliceAttrIntoList(attr, toList);
287 static void processTypeAttrs(TypeProcessingState &state,
288 QualType &type, bool isDeclSpec,
289 AttributeList *attrs);
291 static bool handleFunctionTypeAttr(TypeProcessingState &state,
295 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
296 AttributeList &attr, QualType &type);
298 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
299 AttributeList &attr, QualType &type) {
300 // Right now, we have exactly one of these attributes: objc_gc.
301 assert(attr.getKind() == AttributeList::AT_objc_gc);
302 return handleObjCGCTypeAttr(state, attr, type);
305 /// Given that an objc_gc attribute was written somewhere on a
306 /// declaration *other* than on the declarator itself (for which, use
307 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
308 /// didn't apply in whatever position it was written in, try to move
309 /// it to a more appropriate position.
310 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
313 Declarator &declarator = state.getDeclarator();
314 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
315 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
316 switch (chunk.Kind) {
317 case DeclaratorChunk::Pointer:
318 case DeclaratorChunk::BlockPointer:
319 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
320 chunk.getAttrListRef());
323 case DeclaratorChunk::Paren:
324 case DeclaratorChunk::Array:
327 // Don't walk through these.
328 case DeclaratorChunk::Reference:
329 case DeclaratorChunk::Function:
330 case DeclaratorChunk::MemberPointer:
336 diagnoseBadTypeAttribute(state.getSema(), attr, type);
339 /// Distribute an objc_gc type attribute that was written on the
342 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
344 QualType &declSpecType) {
345 Declarator &declarator = state.getDeclarator();
347 // objc_gc goes on the innermost pointer to something that's not a
349 unsigned innermost = -1U;
350 bool considerDeclSpec = true;
351 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
352 DeclaratorChunk &chunk = declarator.getTypeObject(i);
353 switch (chunk.Kind) {
354 case DeclaratorChunk::Pointer:
355 case DeclaratorChunk::BlockPointer:
359 case DeclaratorChunk::Reference:
360 case DeclaratorChunk::MemberPointer:
361 case DeclaratorChunk::Paren:
362 case DeclaratorChunk::Array:
365 case DeclaratorChunk::Function:
366 considerDeclSpec = false;
372 // That might actually be the decl spec if we weren't blocked by
373 // anything in the declarator.
374 if (considerDeclSpec) {
375 if (handleObjCPointerTypeAttr(state, attr, declSpecType)) {
376 // Splice the attribute into the decl spec. Prevents the
377 // attribute from being applied multiple times and gives
378 // the source-location-filler something to work with.
379 state.saveDeclSpecAttrs();
380 moveAttrFromListToList(attr, declarator.getAttrListRef(),
381 declarator.getMutableDeclSpec().getAttributes().getListRef());
386 // Otherwise, if we found an appropriate chunk, splice the attribute
388 if (innermost != -1U) {
389 moveAttrFromListToList(attr, declarator.getAttrListRef(),
390 declarator.getTypeObject(innermost).getAttrListRef());
394 // Otherwise, diagnose when we're done building the type.
395 spliceAttrOutOfList(attr, declarator.getAttrListRef());
396 state.addIgnoredTypeAttr(attr);
399 /// A function type attribute was written somewhere in a declaration
400 /// *other* than on the declarator itself or in the decl spec. Given
401 /// that it didn't apply in whatever position it was written in, try
402 /// to move it to a more appropriate position.
403 static void distributeFunctionTypeAttr(TypeProcessingState &state,
406 Declarator &declarator = state.getDeclarator();
408 // Try to push the attribute from the return type of a function to
409 // the function itself.
410 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
411 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
412 switch (chunk.Kind) {
413 case DeclaratorChunk::Function:
414 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
415 chunk.getAttrListRef());
418 case DeclaratorChunk::Paren:
419 case DeclaratorChunk::Pointer:
420 case DeclaratorChunk::BlockPointer:
421 case DeclaratorChunk::Array:
422 case DeclaratorChunk::Reference:
423 case DeclaratorChunk::MemberPointer:
428 diagnoseBadTypeAttribute(state.getSema(), attr, type);
431 /// Try to distribute a function type attribute to the innermost
432 /// function chunk or type. Returns true if the attribute was
433 /// distributed, false if no location was found.
435 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
437 AttributeList *&attrList,
438 QualType &declSpecType) {
439 Declarator &declarator = state.getDeclarator();
441 // Put it on the innermost function chunk, if there is one.
442 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
443 DeclaratorChunk &chunk = declarator.getTypeObject(i);
444 if (chunk.Kind != DeclaratorChunk::Function) continue;
446 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
450 return handleFunctionTypeAttr(state, attr, declSpecType);
453 /// A function type attribute was written in the decl spec. Try to
454 /// apply it somewhere.
456 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
458 QualType &declSpecType) {
459 state.saveDeclSpecAttrs();
461 // Try to distribute to the innermost.
462 if (distributeFunctionTypeAttrToInnermost(state, attr,
463 state.getCurrentAttrListRef(),
467 // If that failed, diagnose the bad attribute when the declarator is
469 state.addIgnoredTypeAttr(attr);
472 /// A function type attribute was written on the declarator. Try to
473 /// apply it somewhere.
475 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
477 QualType &declSpecType) {
478 Declarator &declarator = state.getDeclarator();
480 // Try to distribute to the innermost.
481 if (distributeFunctionTypeAttrToInnermost(state, attr,
482 declarator.getAttrListRef(),
486 // If that failed, diagnose the bad attribute when the declarator is
488 spliceAttrOutOfList(attr, declarator.getAttrListRef());
489 state.addIgnoredTypeAttr(attr);
492 /// \brief Given that there are attributes written on the declarator
493 /// itself, try to distribute any type attributes to the appropriate
494 /// declarator chunk.
496 /// These are attributes like the following:
499 /// but not necessarily this:
501 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
502 QualType &declSpecType) {
503 // Collect all the type attributes from the declarator itself.
504 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
505 AttributeList *attr = state.getDeclarator().getAttributes();
508 next = attr->getNext();
510 switch (attr->getKind()) {
511 OBJC_POINTER_TYPE_ATTRS_CASELIST:
512 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
515 FUNCTION_TYPE_ATTRS_CASELIST:
516 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
522 } while ((attr = next));
525 /// Add a synthetic '()' to a block-literal declarator if it is
526 /// required, given the return type.
527 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
528 QualType declSpecType) {
529 Declarator &declarator = state.getDeclarator();
531 // First, check whether the declarator would produce a function,
532 // i.e. whether the innermost semantic chunk is a function.
533 if (declarator.isFunctionDeclarator()) {
534 // If so, make that declarator a prototyped declarator.
535 declarator.getFunctionTypeInfo().hasPrototype = true;
539 // If there are any type objects, the type as written won't name a
540 // function, regardless of the decl spec type. This is because a
541 // block signature declarator is always an abstract-declarator, and
542 // abstract-declarators can't just be parentheses chunks. Therefore
543 // we need to build a function chunk unless there are no type
544 // objects and the decl spec type is a function.
545 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
548 // Note that there *are* cases with invalid declarators where
549 // declarators consist solely of parentheses. In general, these
550 // occur only in failed efforts to make function declarators, so
551 // faking up the function chunk is still the right thing to do.
553 // Otherwise, we need to fake up a function declarator.
554 SourceLocation loc = declarator.getSourceRange().getBegin();
556 // ...and *prepend* it to the declarator.
557 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
559 /*variadic*/ false, SourceLocation(),
562 /*ref-qualifier*/true, SourceLocation(),
563 /*EH*/ EST_None, SourceLocation(), 0, 0, 0, 0,
567 // For consistency, make sure the state still has us as processing
569 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
570 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
573 /// \brief Convert the specified declspec to the appropriate type
575 /// \param D the declarator containing the declaration specifier.
576 /// \returns The type described by the declaration specifiers. This function
577 /// never returns null.
578 static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) {
579 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
582 Declarator &declarator = state.getDeclarator();
583 const DeclSpec &DS = declarator.getDeclSpec();
584 SourceLocation DeclLoc = declarator.getIdentifierLoc();
585 if (DeclLoc.isInvalid())
586 DeclLoc = DS.getSourceRange().getBegin();
588 ASTContext &Context = S.Context;
591 switch (DS.getTypeSpecType()) {
592 case DeclSpec::TST_void:
593 Result = Context.VoidTy;
595 case DeclSpec::TST_char:
596 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
597 Result = Context.CharTy;
598 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
599 Result = Context.SignedCharTy;
601 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
602 "Unknown TSS value");
603 Result = Context.UnsignedCharTy;
606 case DeclSpec::TST_wchar:
607 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
608 Result = Context.WCharTy;
609 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
610 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
611 << DS.getSpecifierName(DS.getTypeSpecType());
612 Result = Context.getSignedWCharType();
614 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
615 "Unknown TSS value");
616 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
617 << DS.getSpecifierName(DS.getTypeSpecType());
618 Result = Context.getUnsignedWCharType();
621 case DeclSpec::TST_char16:
622 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
623 "Unknown TSS value");
624 Result = Context.Char16Ty;
626 case DeclSpec::TST_char32:
627 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
628 "Unknown TSS value");
629 Result = Context.Char32Ty;
631 case DeclSpec::TST_unspecified:
632 // "<proto1,proto2>" is an objc qualified ID with a missing id.
633 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
634 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
635 (ObjCProtocolDecl**)PQ,
636 DS.getNumProtocolQualifiers());
637 Result = Context.getObjCObjectPointerType(Result);
641 // If this is a missing declspec in a block literal return context, then it
642 // is inferred from the return statements inside the block.
643 if (isOmittedBlockReturnType(declarator)) {
644 Result = Context.DependentTy;
648 // Unspecified typespec defaults to int in C90. However, the C90 grammar
649 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
650 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
651 // Note that the one exception to this is function definitions, which are
652 // allowed to be completely missing a declspec. This is handled in the
653 // parser already though by it pretending to have seen an 'int' in this
655 if (S.getLangOptions().ImplicitInt) {
656 // In C89 mode, we only warn if there is a completely missing declspec
657 // when one is not allowed.
659 S.Diag(DeclLoc, diag::ext_missing_declspec)
660 << DS.getSourceRange()
661 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
663 } else if (!DS.hasTypeSpecifier()) {
664 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
665 // "At least one type specifier shall be given in the declaration
666 // specifiers in each declaration, and in the specifier-qualifier list in
667 // each struct declaration and type name."
668 // FIXME: Does Microsoft really have the implicit int extension in C++?
669 if (S.getLangOptions().CPlusPlus &&
670 !S.getLangOptions().Microsoft) {
671 S.Diag(DeclLoc, diag::err_missing_type_specifier)
672 << DS.getSourceRange();
674 // When this occurs in C++ code, often something is very broken with the
675 // value being declared, poison it as invalid so we don't get chains of
677 declarator.setInvalidType(true);
679 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
680 << DS.getSourceRange();
685 case DeclSpec::TST_int: {
686 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
687 switch (DS.getTypeSpecWidth()) {
688 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
689 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
690 case DeclSpec::TSW_long: Result = Context.LongTy; break;
691 case DeclSpec::TSW_longlong:
692 Result = Context.LongLongTy;
694 // long long is a C99 feature.
695 if (!S.getLangOptions().C99 &&
696 !S.getLangOptions().CPlusPlus0x)
697 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
701 switch (DS.getTypeSpecWidth()) {
702 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
703 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
704 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
705 case DeclSpec::TSW_longlong:
706 Result = Context.UnsignedLongLongTy;
708 // long long is a C99 feature.
709 if (!S.getLangOptions().C99 &&
710 !S.getLangOptions().CPlusPlus0x)
711 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
717 case DeclSpec::TST_float: Result = Context.FloatTy; break;
718 case DeclSpec::TST_double:
719 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
720 Result = Context.LongDoubleTy;
722 Result = Context.DoubleTy;
724 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
725 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
726 declarator.setInvalidType(true);
729 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
730 case DeclSpec::TST_decimal32: // _Decimal32
731 case DeclSpec::TST_decimal64: // _Decimal64
732 case DeclSpec::TST_decimal128: // _Decimal128
733 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
734 Result = Context.IntTy;
735 declarator.setInvalidType(true);
737 case DeclSpec::TST_class:
738 case DeclSpec::TST_enum:
739 case DeclSpec::TST_union:
740 case DeclSpec::TST_struct: {
741 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
743 // This can happen in C++ with ambiguous lookups.
744 Result = Context.IntTy;
745 declarator.setInvalidType(true);
749 // If the type is deprecated or unavailable, diagnose it.
750 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeNameLoc());
752 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
753 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
755 // TypeQuals handled by caller.
756 Result = Context.getTypeDeclType(D);
758 // In both C and C++, make an ElaboratedType.
759 ElaboratedTypeKeyword Keyword
760 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
761 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
763 if (D->isInvalidDecl())
764 declarator.setInvalidType(true);
767 case DeclSpec::TST_typename: {
768 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
769 DS.getTypeSpecSign() == 0 &&
770 "Can't handle qualifiers on typedef names yet!");
771 Result = S.GetTypeFromParser(DS.getRepAsType());
773 declarator.setInvalidType(true);
774 else if (DeclSpec::ProtocolQualifierListTy PQ
775 = DS.getProtocolQualifiers()) {
776 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
777 // Silently drop any existing protocol qualifiers.
778 // TODO: determine whether that's the right thing to do.
779 if (ObjT->getNumProtocols())
780 Result = ObjT->getBaseType();
782 if (DS.getNumProtocolQualifiers())
783 Result = Context.getObjCObjectType(Result,
784 (ObjCProtocolDecl**) PQ,
785 DS.getNumProtocolQualifiers());
786 } else if (Result->isObjCIdType()) {
788 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
789 (ObjCProtocolDecl**) PQ,
790 DS.getNumProtocolQualifiers());
791 Result = Context.getObjCObjectPointerType(Result);
792 } else if (Result->isObjCClassType()) {
793 // Class<protocol-list>
794 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
795 (ObjCProtocolDecl**) PQ,
796 DS.getNumProtocolQualifiers());
797 Result = Context.getObjCObjectPointerType(Result);
799 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
800 << DS.getSourceRange();
801 declarator.setInvalidType(true);
805 // TypeQuals handled by caller.
808 case DeclSpec::TST_typeofType:
809 // FIXME: Preserve type source info.
810 Result = S.GetTypeFromParser(DS.getRepAsType());
811 assert(!Result.isNull() && "Didn't get a type for typeof?");
812 if (!Result->isDependentType())
813 if (const TagType *TT = Result->getAs<TagType>())
814 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
815 // TypeQuals handled by caller.
816 Result = Context.getTypeOfType(Result);
818 case DeclSpec::TST_typeofExpr: {
819 Expr *E = DS.getRepAsExpr();
820 assert(E && "Didn't get an expression for typeof?");
821 // TypeQuals handled by caller.
822 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
823 if (Result.isNull()) {
824 Result = Context.IntTy;
825 declarator.setInvalidType(true);
829 case DeclSpec::TST_decltype: {
830 Expr *E = DS.getRepAsExpr();
831 assert(E && "Didn't get an expression for decltype?");
832 // TypeQuals handled by caller.
833 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
834 if (Result.isNull()) {
835 Result = Context.IntTy;
836 declarator.setInvalidType(true);
840 case DeclSpec::TST_underlyingType:
841 Result = S.GetTypeFromParser(DS.getRepAsType());
842 assert(!Result.isNull() && "Didn't get a type for __underlying_type?");
843 Result = S.BuildUnaryTransformType(Result,
844 UnaryTransformType::EnumUnderlyingType,
845 DS.getTypeSpecTypeLoc());
846 if (Result.isNull()) {
847 Result = Context.IntTy;
848 declarator.setInvalidType(true);
852 case DeclSpec::TST_auto: {
853 // TypeQuals handled by caller.
854 Result = Context.getAutoType(QualType());
858 case DeclSpec::TST_unknown_anytype:
859 Result = Context.UnknownAnyTy;
862 case DeclSpec::TST_error:
863 Result = Context.IntTy;
864 declarator.setInvalidType(true);
868 // Handle complex types.
869 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
870 if (S.getLangOptions().Freestanding)
871 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
872 Result = Context.getComplexType(Result);
873 } else if (DS.isTypeAltiVecVector()) {
874 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
875 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
876 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
877 if (DS.isTypeAltiVecPixel())
878 VecKind = VectorType::AltiVecPixel;
879 else if (DS.isTypeAltiVecBool())
880 VecKind = VectorType::AltiVecBool;
881 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
885 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
886 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
888 // Before we process any type attributes, synthesize a block literal
889 // function declarator if necessary.
890 if (declarator.getContext() == Declarator::BlockLiteralContext)
891 maybeSynthesizeBlockSignature(state, Result);
893 // Apply any type attributes from the decl spec. This may cause the
894 // list of type attributes to be temporarily saved while the type
895 // attributes are pushed around.
896 if (AttributeList *attrs = DS.getAttributes().getList())
897 processTypeAttrs(state, Result, true, attrs);
899 // Apply const/volatile/restrict qualifiers to T.
900 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
902 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
903 // or incomplete types shall not be restrict-qualified." C++ also allows
904 // restrict-qualified references.
905 if (TypeQuals & DeclSpec::TQ_restrict) {
906 if (Result->isAnyPointerType() || Result->isReferenceType()) {
908 if (Result->isObjCObjectPointerType())
911 EltTy = Result->isPointerType() ?
912 Result->getAs<PointerType>()->getPointeeType() :
913 Result->getAs<ReferenceType>()->getPointeeType();
915 // If we have a pointer or reference, the pointee must have an object
917 if (!EltTy->isIncompleteOrObjectType()) {
918 S.Diag(DS.getRestrictSpecLoc(),
919 diag::err_typecheck_invalid_restrict_invalid_pointee)
920 << EltTy << DS.getSourceRange();
921 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
924 S.Diag(DS.getRestrictSpecLoc(),
925 diag::err_typecheck_invalid_restrict_not_pointer)
926 << Result << DS.getSourceRange();
927 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
931 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
932 // of a function type includes any type qualifiers, the behavior is
934 if (Result->isFunctionType() && TypeQuals) {
935 // Get some location to point at, either the C or V location.
937 if (TypeQuals & DeclSpec::TQ_const)
938 Loc = DS.getConstSpecLoc();
939 else if (TypeQuals & DeclSpec::TQ_volatile)
940 Loc = DS.getVolatileSpecLoc();
942 assert((TypeQuals & DeclSpec::TQ_restrict) &&
943 "Has CVR quals but not C, V, or R?");
944 Loc = DS.getRestrictSpecLoc();
946 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
947 << Result << DS.getSourceRange();
951 // Cv-qualified references are ill-formed except when the
952 // cv-qualifiers are introduced through the use of a typedef
953 // (7.1.3) or of a template type argument (14.3), in which
954 // case the cv-qualifiers are ignored.
955 // FIXME: Shouldn't we be checking SCS_typedef here?
956 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
957 TypeQuals && Result->isReferenceType()) {
958 TypeQuals &= ~DeclSpec::TQ_const;
959 TypeQuals &= ~DeclSpec::TQ_volatile;
962 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
963 Result = Context.getQualifiedType(Result, Quals);
969 static std::string getPrintableNameForEntity(DeclarationName Entity) {
971 return Entity.getAsString();
976 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
978 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
979 // object or incomplete types shall not be restrict-qualified."
980 if (Qs.hasRestrict()) {
984 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
985 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
986 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
987 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
988 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
990 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
991 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
992 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
993 ProblemTy = T->getAs<PointerType>()->getPointeeType();
995 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
996 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
997 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
998 ProblemTy = T->getAs<PointerType>()->getPointeeType();
1000 } else if (!Ty->isDependentType()) {
1001 // FIXME: this deserves a proper diagnostic
1002 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
1007 Diag(Loc, DiagID) << ProblemTy;
1008 Qs.removeRestrict();
1012 return Context.getQualifiedType(T, Qs);
1015 /// \brief Build a paren type including \p T.
1016 QualType Sema::BuildParenType(QualType T) {
1017 return Context.getParenType(T);
1020 /// \brief Build a pointer type.
1022 /// \param T The type to which we'll be building a pointer.
1024 /// \param Loc The location of the entity whose type involves this
1025 /// pointer type or, if there is no such entity, the location of the
1026 /// type that will have pointer type.
1028 /// \param Entity The name of the entity that involves the pointer
1031 /// \returns A suitable pointer type, if there are no
1032 /// errors. Otherwise, returns a NULL type.
1033 QualType Sema::BuildPointerType(QualType T,
1034 SourceLocation Loc, DeclarationName Entity) {
1035 if (T->isReferenceType()) {
1036 // C++ 8.3.2p4: There shall be no ... pointers to references ...
1037 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
1038 << getPrintableNameForEntity(Entity) << T;
1042 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
1044 // Build the pointer type.
1045 return Context.getPointerType(T);
1048 /// \brief Build a reference type.
1050 /// \param T The type to which we'll be building a reference.
1052 /// \param Loc The location of the entity whose type involves this
1053 /// reference type or, if there is no such entity, the location of the
1054 /// type that will have reference type.
1056 /// \param Entity The name of the entity that involves the reference
1059 /// \returns A suitable reference type, if there are no
1060 /// errors. Otherwise, returns a NULL type.
1061 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
1063 DeclarationName Entity) {
1064 assert(Context.getCanonicalType(T) != Context.OverloadTy &&
1065 "Unresolved overloaded function type");
1067 // C++0x [dcl.ref]p6:
1068 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1069 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1070 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1071 // the type "lvalue reference to T", while an attempt to create the type
1072 // "rvalue reference to cv TR" creates the type TR.
1073 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1075 // C++ [dcl.ref]p4: There shall be no references to references.
1077 // According to C++ DR 106, references to references are only
1078 // diagnosed when they are written directly (e.g., "int & &"),
1079 // but not when they happen via a typedef:
1081 // typedef int& intref;
1082 // typedef intref& intref2;
1084 // Parser::ParseDeclaratorInternal diagnoses the case where
1085 // references are written directly; here, we handle the
1086 // collapsing of references-to-references as described in C++0x.
1087 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1090 // A declarator that specifies the type "reference to cv void"
1092 if (T->isVoidType()) {
1093 Diag(Loc, diag::err_reference_to_void);
1097 // Handle restrict on references.
1099 return Context.getLValueReferenceType(T, SpelledAsLValue);
1100 return Context.getRValueReferenceType(T);
1103 /// \brief Build an array type.
1105 /// \param T The type of each element in the array.
1107 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1109 /// \param ArraySize Expression describing the size of the array.
1111 /// \param Loc The location of the entity whose type involves this
1112 /// array type or, if there is no such entity, the location of the
1113 /// type that will have array type.
1115 /// \param Entity The name of the entity that involves the array
1118 /// \returns A suitable array type, if there are no errors. Otherwise,
1119 /// returns a NULL type.
1120 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1121 Expr *ArraySize, unsigned Quals,
1122 SourceRange Brackets, DeclarationName Entity) {
1124 SourceLocation Loc = Brackets.getBegin();
1125 if (getLangOptions().CPlusPlus) {
1126 // C++ [dcl.array]p1:
1127 // T is called the array element type; this type shall not be a reference
1128 // type, the (possibly cv-qualified) type void, a function type or an
1129 // abstract class type.
1131 // Note: function types are handled in the common path with C.
1132 if (T->isReferenceType()) {
1133 Diag(Loc, diag::err_illegal_decl_array_of_references)
1134 << getPrintableNameForEntity(Entity) << T;
1138 if (T->isVoidType()) {
1139 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1143 if (RequireNonAbstractType(Brackets.getBegin(), T,
1144 diag::err_array_of_abstract_type))
1148 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1149 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1150 if (RequireCompleteType(Loc, T,
1151 diag::err_illegal_decl_array_incomplete_type))
1155 if (T->isFunctionType()) {
1156 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1157 << getPrintableNameForEntity(Entity) << T;
1161 if (T->getContainedAutoType()) {
1162 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1163 << getPrintableNameForEntity(Entity) << T;
1167 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1168 // If the element type is a struct or union that contains a variadic
1169 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1170 if (EltTy->getDecl()->hasFlexibleArrayMember())
1171 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1172 } else if (T->isObjCObjectType()) {
1173 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1177 // Do lvalue-to-rvalue conversions on the array size expression.
1178 if (ArraySize && !ArraySize->isRValue()) {
1179 ExprResult Result = DefaultLvalueConversion(ArraySize);
1180 if (Result.isInvalid())
1183 ArraySize = Result.take();
1186 // C99 6.7.5.2p1: The size expression shall have integer type.
1187 // TODO: in theory, if we were insane, we could allow contextual
1188 // conversions to integer type here.
1189 if (ArraySize && !ArraySize->isTypeDependent() &&
1190 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1191 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1192 << ArraySize->getType() << ArraySize->getSourceRange();
1195 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1197 if (ASM == ArrayType::Star)
1198 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1200 T = Context.getIncompleteArrayType(T, ASM, Quals);
1201 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1202 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1203 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
1204 (!T->isDependentType() && !T->isIncompleteType() &&
1205 !T->isConstantSizeType())) {
1206 // Per C99, a variable array is an array with either a non-constant
1207 // size or an element type that has a non-constant-size
1208 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1210 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1211 // have a value greater than zero.
1212 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1214 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1215 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1217 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1218 << ArraySize->getSourceRange();
1221 if (ConstVal == 0) {
1222 // GCC accepts zero sized static arrays. We allow them when
1223 // we're not in a SFINAE context.
1224 Diag(ArraySize->getLocStart(),
1225 isSFINAEContext()? diag::err_typecheck_zero_array_size
1226 : diag::ext_typecheck_zero_array_size)
1227 << ArraySize->getSourceRange();
1228 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1229 !T->isIncompleteType()) {
1230 // Is the array too large?
1231 unsigned ActiveSizeBits
1232 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1233 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1234 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1235 << ConstVal.toString(10)
1236 << ArraySize->getSourceRange();
1239 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1241 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1242 if (!getLangOptions().C99) {
1243 if (T->isVariableArrayType()) {
1244 // Prohibit the use of non-POD types in VLAs.
1245 if (!T->isDependentType() &&
1246 !Context.getBaseElementType(T)->isPODType()) {
1247 Diag(Loc, diag::err_vla_non_pod)
1248 << Context.getBaseElementType(T);
1251 // Prohibit the use of VLAs during template argument deduction.
1252 else if (isSFINAEContext()) {
1253 Diag(Loc, diag::err_vla_in_sfinae);
1256 // Just extwarn about VLAs.
1258 Diag(Loc, diag::ext_vla);
1259 } else if (ASM != ArrayType::Normal || Quals != 0)
1261 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1262 : diag::ext_c99_array_usage);
1268 /// \brief Build an ext-vector type.
1270 /// Run the required checks for the extended vector type.
1271 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1272 SourceLocation AttrLoc) {
1273 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1274 // in conjunction with complex types (pointers, arrays, functions, etc.).
1275 if (!T->isDependentType() &&
1276 !T->isIntegerType() && !T->isRealFloatingType()) {
1277 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1281 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1282 llvm::APSInt vecSize(32);
1283 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1284 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1285 << "ext_vector_type" << ArraySize->getSourceRange();
1289 // unlike gcc's vector_size attribute, the size is specified as the
1290 // number of elements, not the number of bytes.
1291 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1293 if (vectorSize == 0) {
1294 Diag(AttrLoc, diag::err_attribute_zero_size)
1295 << ArraySize->getSourceRange();
1299 if (!T->isDependentType())
1300 return Context.getExtVectorType(T, vectorSize);
1303 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1306 /// \brief Build a function type.
1308 /// This routine checks the function type according to C++ rules and
1309 /// under the assumption that the result type and parameter types have
1310 /// just been instantiated from a template. It therefore duplicates
1311 /// some of the behavior of GetTypeForDeclarator, but in a much
1312 /// simpler form that is only suitable for this narrow use case.
1314 /// \param T The return type of the function.
1316 /// \param ParamTypes The parameter types of the function. This array
1317 /// will be modified to account for adjustments to the types of the
1318 /// function parameters.
1320 /// \param NumParamTypes The number of parameter types in ParamTypes.
1322 /// \param Variadic Whether this is a variadic function type.
1324 /// \param Quals The cvr-qualifiers to be applied to the function type.
1326 /// \param Loc The location of the entity whose type involves this
1327 /// function type or, if there is no such entity, the location of the
1328 /// type that will have function type.
1330 /// \param Entity The name of the entity that involves the function
1333 /// \returns A suitable function type, if there are no
1334 /// errors. Otherwise, returns a NULL type.
1335 QualType Sema::BuildFunctionType(QualType T,
1336 QualType *ParamTypes,
1337 unsigned NumParamTypes,
1338 bool Variadic, unsigned Quals,
1339 RefQualifierKind RefQualifier,
1340 SourceLocation Loc, DeclarationName Entity,
1341 FunctionType::ExtInfo Info) {
1342 if (T->isArrayType() || T->isFunctionType()) {
1343 Diag(Loc, diag::err_func_returning_array_function)
1344 << T->isFunctionType() << T;
1348 bool Invalid = false;
1349 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1350 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
1351 if (ParamType->isVoidType()) {
1352 Diag(Loc, diag::err_param_with_void_type);
1356 ParamTypes[Idx] = ParamType;
1362 FunctionProtoType::ExtProtoInfo EPI;
1363 EPI.Variadic = Variadic;
1364 EPI.TypeQuals = Quals;
1365 EPI.RefQualifier = RefQualifier;
1368 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1371 /// \brief Build a member pointer type \c T Class::*.
1373 /// \param T the type to which the member pointer refers.
1374 /// \param Class the class type into which the member pointer points.
1375 /// \param CVR Qualifiers applied to the member pointer type
1376 /// \param Loc the location where this type begins
1377 /// \param Entity the name of the entity that will have this member pointer type
1379 /// \returns a member pointer type, if successful, or a NULL type if there was
1381 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1383 DeclarationName Entity) {
1384 // Verify that we're not building a pointer to pointer to function with
1385 // exception specification.
1386 if (CheckDistantExceptionSpec(T)) {
1387 Diag(Loc, diag::err_distant_exception_spec);
1389 // FIXME: If we're doing this as part of template instantiation,
1390 // we should return immediately.
1392 // Build the type anyway, but use the canonical type so that the
1393 // exception specifiers are stripped off.
1394 T = Context.getCanonicalType(T);
1397 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1398 // with reference type, or "cv void."
1399 if (T->isReferenceType()) {
1400 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1401 << (Entity? Entity.getAsString() : "type name") << T;
1405 if (T->isVoidType()) {
1406 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1407 << (Entity? Entity.getAsString() : "type name");
1411 if (!Class->isDependentType() && !Class->isRecordType()) {
1412 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1416 // In the Microsoft ABI, the class is allowed to be an incomplete
1417 // type. In such cases, the compiler makes a worst-case assumption.
1418 // We make no such assumption right now, so emit an error if the
1419 // class isn't a complete type.
1420 if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
1421 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1424 return Context.getMemberPointerType(T, Class.getTypePtr());
1427 /// \brief Build a block pointer type.
1429 /// \param T The type to which we'll be building a block pointer.
1431 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1433 /// \param Loc The location of the entity whose type involves this
1434 /// block pointer type or, if there is no such entity, the location of the
1435 /// type that will have block pointer type.
1437 /// \param Entity The name of the entity that involves the block pointer
1440 /// \returns A suitable block pointer type, if there are no
1441 /// errors. Otherwise, returns a NULL type.
1442 QualType Sema::BuildBlockPointerType(QualType T,
1444 DeclarationName Entity) {
1445 if (!T->isFunctionType()) {
1446 Diag(Loc, diag::err_nonfunction_block_type);
1450 return Context.getBlockPointerType(T);
1453 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1454 QualType QT = Ty.get();
1456 if (TInfo) *TInfo = 0;
1460 TypeSourceInfo *DI = 0;
1461 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1462 QT = LIT->getType();
1463 DI = LIT->getTypeSourceInfo();
1466 if (TInfo) *TInfo = DI;
1470 static void DiagnoseIgnoredQualifiers(unsigned Quals,
1471 SourceLocation ConstQualLoc,
1472 SourceLocation VolatileQualLoc,
1473 SourceLocation RestrictQualLoc,
1475 std::string QualStr;
1476 unsigned NumQuals = 0;
1479 FixItHint ConstFixIt;
1480 FixItHint VolatileFixIt;
1481 FixItHint RestrictFixIt;
1483 const SourceManager &SM = S.getSourceManager();
1485 // FIXME: The locations here are set kind of arbitrarily. It'd be nicer to
1486 // find a range and grow it to encompass all the qualifiers, regardless of
1487 // the order in which they textually appear.
1488 if (Quals & Qualifiers::Const) {
1489 ConstFixIt = FixItHint::CreateRemoval(ConstQualLoc);
1492 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(ConstQualLoc, Loc))
1495 if (Quals & Qualifiers::Volatile) {
1496 VolatileFixIt = FixItHint::CreateRemoval(VolatileQualLoc);
1497 QualStr += (NumQuals == 0 ? "volatile" : " volatile");
1499 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(VolatileQualLoc, Loc))
1500 Loc = VolatileQualLoc;
1502 if (Quals & Qualifiers::Restrict) {
1503 RestrictFixIt = FixItHint::CreateRemoval(RestrictQualLoc);
1504 QualStr += (NumQuals == 0 ? "restrict" : " restrict");
1506 if (!Loc.isValid() || SM.isBeforeInTranslationUnit(RestrictQualLoc, Loc))
1507 Loc = RestrictQualLoc;
1510 assert(NumQuals > 0 && "No known qualifiers?");
1512 S.Diag(Loc, diag::warn_qual_return_type)
1513 << QualStr << NumQuals << ConstFixIt << VolatileFixIt << RestrictFixIt;
1516 /// GetTypeForDeclarator - Convert the type for the specified
1517 /// declarator to Type instances.
1519 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
1520 /// owns the declaration of a type (e.g., the definition of a struct
1521 /// type), then *OwnedDecl will receive the owned declaration.
1523 /// The result of this call will never be null, but the associated
1524 /// type may be a null type if there's an unrecoverable error.
1525 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
1526 TagDecl **OwnedDecl,
1527 bool AutoAllowedInTypeName) {
1528 // Determine the type of the declarator. Not all forms of declarator
1531 TypeSourceInfo *ReturnTypeInfo = 0;
1533 TypeProcessingState state(*this, D);
1535 // In C++0x, deallocation functions (normal and array operator delete)
1536 // are implicitly noexcept.
1537 bool ImplicitlyNoexcept = false;
1539 switch (D.getName().getKind()) {
1540 case UnqualifiedId::IK_OperatorFunctionId:
1541 if (getLangOptions().CPlusPlus0x) {
1542 OverloadedOperatorKind OO = D.getName().OperatorFunctionId.Operator;
1543 if (OO == OO_Delete || OO == OO_Array_Delete)
1544 ImplicitlyNoexcept = true;
1546 // Intentional fall-through.
1547 case UnqualifiedId::IK_Identifier:
1548 case UnqualifiedId::IK_LiteralOperatorId:
1549 case UnqualifiedId::IK_TemplateId:
1550 T = ConvertDeclSpecToType(*this, state);
1552 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1553 TagDecl* Owned = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1554 // Owned declaration is embedded in declarator.
1555 Owned->setEmbeddedInDeclarator(true);
1556 if (OwnedDecl) *OwnedDecl = Owned;
1560 case UnqualifiedId::IK_ConstructorName:
1561 case UnqualifiedId::IK_ConstructorTemplateId:
1562 case UnqualifiedId::IK_DestructorName:
1563 // Constructors and destructors don't have return types. Use
1568 case UnqualifiedId::IK_ConversionFunctionId:
1569 // The result type of a conversion function is the type that it
1571 T = GetTypeFromParser(D.getName().ConversionFunctionId,
1576 if (D.getAttributes())
1577 distributeTypeAttrsFromDeclarator(state, T);
1579 // C++0x [dcl.spec.auto]p5: reject 'auto' if it is not in an allowed context.
1580 // In C++0x, a function declarator using 'auto' must have a trailing return
1581 // type (this is checked later) and we can skip this. In other languages
1582 // using auto, we need to check regardless.
1583 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1584 (!getLangOptions().CPlusPlus0x || !D.isFunctionDeclarator())) {
1587 switch (D.getContext()) {
1588 case Declarator::KNRTypeListContext:
1589 assert(0 && "K&R type lists aren't allowed in C++");
1591 case Declarator::ObjCPrototypeContext:
1592 case Declarator::PrototypeContext:
1593 Error = 0; // Function prototype
1595 case Declarator::MemberContext:
1596 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)
1598 switch (cast<TagDecl>(CurContext)->getTagKind()) {
1599 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1600 case TTK_Struct: Error = 1; /* Struct member */ break;
1601 case TTK_Union: Error = 2; /* Union member */ break;
1602 case TTK_Class: Error = 3; /* Class member */ break;
1605 case Declarator::CXXCatchContext:
1606 Error = 4; // Exception declaration
1608 case Declarator::TemplateParamContext:
1609 Error = 5; // Template parameter
1611 case Declarator::BlockLiteralContext:
1612 Error = 6; // Block literal
1614 case Declarator::TemplateTypeArgContext:
1615 Error = 7; // Template type argument
1617 case Declarator::AliasDeclContext:
1618 case Declarator::AliasTemplateContext:
1619 Error = 9; // Type alias
1621 case Declarator::TypeNameContext:
1622 if (!AutoAllowedInTypeName)
1623 Error = 11; // Generic
1625 case Declarator::FileContext:
1626 case Declarator::BlockContext:
1627 case Declarator::ForContext:
1628 case Declarator::ConditionContext:
1632 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1635 // In Objective-C it is an error to use 'auto' on a function declarator.
1636 if (D.isFunctionDeclarator())
1639 // C++0x [dcl.spec.auto]p2: 'auto' is always fine if the declarator
1640 // contains a trailing return type. That is only legal at the outermost
1641 // level. Check all declarator chunks (outermost first) anyway, to give
1642 // better diagnostics.
1643 if (getLangOptions().CPlusPlus0x && Error != -1) {
1644 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1645 unsigned chunkIndex = e - i - 1;
1646 state.setCurrentChunkIndex(chunkIndex);
1647 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1648 if (DeclType.Kind == DeclaratorChunk::Function) {
1649 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1650 if (FTI.TrailingReturnType) {
1659 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1662 D.setInvalidType(true);
1667 return Context.getNullTypeSourceInfo();
1669 // The name we're declaring, if any.
1670 DeclarationName Name;
1671 if (D.getIdentifier())
1672 Name = D.getIdentifier();
1674 // Does this declaration declare a typedef-name?
1675 bool IsTypedefName =
1676 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef ||
1677 D.getContext() == Declarator::AliasDeclContext ||
1678 D.getContext() == Declarator::AliasTemplateContext;
1680 // Walk the DeclTypeInfo, building the recursive type as we go.
1681 // DeclTypeInfos are ordered from the identifier out, which is
1682 // opposite of what we want :).
1683 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1684 unsigned chunkIndex = e - i - 1;
1685 state.setCurrentChunkIndex(chunkIndex);
1686 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1687 switch (DeclType.Kind) {
1688 default: assert(0 && "Unknown decltype!");
1689 case DeclaratorChunk::Paren:
1690 T = BuildParenType(T);
1692 case DeclaratorChunk::BlockPointer:
1693 // If blocks are disabled, emit an error.
1694 if (!LangOpts.Blocks)
1695 Diag(DeclType.Loc, diag::err_blocks_disable);
1697 T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1698 if (DeclType.Cls.TypeQuals)
1699 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1701 case DeclaratorChunk::Pointer:
1702 // Verify that we're not building a pointer to pointer to function with
1703 // exception specification.
1704 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1705 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1706 D.setInvalidType(true);
1707 // Build the type anyway.
1709 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1710 T = Context.getObjCObjectPointerType(T);
1711 if (DeclType.Ptr.TypeQuals)
1712 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1715 T = BuildPointerType(T, DeclType.Loc, Name);
1716 if (DeclType.Ptr.TypeQuals)
1717 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1720 case DeclaratorChunk::Reference: {
1721 // Verify that we're not building a reference to pointer to function with
1722 // exception specification.
1723 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1724 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1725 D.setInvalidType(true);
1726 // Build the type anyway.
1728 T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1731 if (DeclType.Ref.HasRestrict)
1732 T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1735 case DeclaratorChunk::Array: {
1736 // Verify that we're not building an array of pointers to function with
1737 // exception specification.
1738 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1739 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1740 D.setInvalidType(true);
1741 // Build the type anyway.
1743 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1744 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1745 ArrayType::ArraySizeModifier ASM;
1747 ASM = ArrayType::Star;
1748 else if (ATI.hasStatic)
1749 ASM = ArrayType::Static;
1751 ASM = ArrayType::Normal;
1752 if (ASM == ArrayType::Star && !D.isPrototypeContext()) {
1753 // FIXME: This check isn't quite right: it allows star in prototypes
1754 // for function definitions, and disallows some edge cases detailed
1755 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1756 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1757 ASM = ArrayType::Normal;
1758 D.setInvalidType(true);
1760 T = BuildArrayType(T, ASM, ArraySize,
1761 Qualifiers::fromCVRMask(ATI.TypeQuals),
1762 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1765 case DeclaratorChunk::Function: {
1766 // If the function declarator has a prototype (i.e. it is not () and
1767 // does not have a K&R-style identifier list), then the arguments are part
1768 // of the type, otherwise the argument list is ().
1769 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1771 // Check for auto functions and trailing return type and adjust the
1772 // return type accordingly.
1773 if (!D.isInvalidType()) {
1774 // trailing-return-type is only required if we're declaring a function,
1775 // and not, for instance, a pointer to a function.
1776 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1777 !FTI.TrailingReturnType && chunkIndex == 0) {
1778 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1779 diag::err_auto_missing_trailing_return);
1781 D.setInvalidType(true);
1782 } else if (FTI.TrailingReturnType) {
1783 // T must be exactly 'auto' at this point. See CWG issue 681.
1784 if (isa<ParenType>(T)) {
1785 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1786 diag::err_trailing_return_in_parens)
1787 << T << D.getDeclSpec().getSourceRange();
1788 D.setInvalidType(true);
1789 } else if (T.hasQualifiers() || !isa<AutoType>(T)) {
1790 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1791 diag::err_trailing_return_without_auto)
1792 << T << D.getDeclSpec().getSourceRange();
1793 D.setInvalidType(true);
1796 T = GetTypeFromParser(
1797 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
1802 // C99 6.7.5.3p1: The return type may not be a function or array type.
1803 // For conversion functions, we'll diagnose this particular error later.
1804 if ((T->isArrayType() || T->isFunctionType()) &&
1805 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1806 unsigned diagID = diag::err_func_returning_array_function;
1807 // Last processing chunk in block context means this function chunk
1808 // represents the block.
1809 if (chunkIndex == 0 &&
1810 D.getContext() == Declarator::BlockLiteralContext)
1811 diagID = diag::err_block_returning_array_function;
1812 Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
1814 D.setInvalidType(true);
1817 // cv-qualifiers on return types are pointless except when the type is a
1818 // class type in C++.
1819 if (isa<PointerType>(T) && T.getLocalCVRQualifiers() &&
1820 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId) &&
1821 (!getLangOptions().CPlusPlus || !T->isDependentType())) {
1822 assert(chunkIndex + 1 < e && "No DeclaratorChunk for the return type?");
1823 DeclaratorChunk ReturnTypeChunk = D.getTypeObject(chunkIndex + 1);
1824 assert(ReturnTypeChunk.Kind == DeclaratorChunk::Pointer);
1826 DeclaratorChunk::PointerTypeInfo &PTI = ReturnTypeChunk.Ptr;
1828 DiagnoseIgnoredQualifiers(PTI.TypeQuals,
1829 SourceLocation::getFromRawEncoding(PTI.ConstQualLoc),
1830 SourceLocation::getFromRawEncoding(PTI.VolatileQualLoc),
1831 SourceLocation::getFromRawEncoding(PTI.RestrictQualLoc),
1834 } else if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
1835 (!getLangOptions().CPlusPlus ||
1836 (!T->isDependentType() && !T->isRecordType()))) {
1838 DiagnoseIgnoredQualifiers(D.getDeclSpec().getTypeQualifiers(),
1839 D.getDeclSpec().getConstSpecLoc(),
1840 D.getDeclSpec().getVolatileSpecLoc(),
1841 D.getDeclSpec().getRestrictSpecLoc(),
1845 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1847 // Types shall not be defined in return or parameter types.
1848 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1849 if (Tag->isDefinition())
1850 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1851 << Context.getTypeDeclType(Tag);
1854 // Exception specs are not allowed in typedefs. Complain, but add it
1856 if (IsTypedefName && FTI.getExceptionSpecType())
1857 Diag(FTI.getExceptionSpecLoc(), diag::err_exception_spec_in_typedef)
1858 << (D.getContext() == Declarator::AliasDeclContext ||
1859 D.getContext() == Declarator::AliasTemplateContext);
1861 if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
1862 // Simple void foo(), where the incoming T is the result type.
1863 T = Context.getFunctionNoProtoType(T);
1865 // We allow a zero-parameter variadic function in C if the
1866 // function is marked with the "overloadable" attribute. Scan
1867 // for this attribute now.
1868 if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
1869 bool Overloadable = false;
1870 for (const AttributeList *Attrs = D.getAttributes();
1871 Attrs; Attrs = Attrs->getNext()) {
1872 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1873 Overloadable = true;
1879 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1882 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
1883 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
1885 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1886 D.setInvalidType(true);
1890 FunctionProtoType::ExtProtoInfo EPI;
1891 EPI.Variadic = FTI.isVariadic;
1892 EPI.TypeQuals = FTI.TypeQuals;
1893 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
1894 : FTI.RefQualifierIsLValueRef? RQ_LValue
1897 // Otherwise, we have a function with an argument list that is
1898 // potentially variadic.
1899 llvm::SmallVector<QualType, 16> ArgTys;
1900 ArgTys.reserve(FTI.NumArgs);
1902 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1903 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
1904 QualType ArgTy = Param->getType();
1905 assert(!ArgTy.isNull() && "Couldn't parse type?");
1907 // Adjust the parameter type.
1908 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1910 // Look for 'void'. void is allowed only as a single argument to a
1911 // function with no other parameters (C99 6.7.5.3p10). We record
1912 // int(void) as a FunctionProtoType with an empty argument list.
1913 if (ArgTy->isVoidType()) {
1914 // If this is something like 'float(int, void)', reject it. 'void'
1915 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1916 // have arguments of incomplete type.
1917 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1918 Diag(DeclType.Loc, diag::err_void_only_param);
1919 ArgTy = Context.IntTy;
1920 Param->setType(ArgTy);
1921 } else if (FTI.ArgInfo[i].Ident) {
1922 // Reject, but continue to parse 'int(void abc)'.
1923 Diag(FTI.ArgInfo[i].IdentLoc,
1924 diag::err_param_with_void_type);
1925 ArgTy = Context.IntTy;
1926 Param->setType(ArgTy);
1928 // Reject, but continue to parse 'float(const void)'.
1929 if (ArgTy.hasQualifiers())
1930 Diag(DeclType.Loc, diag::err_void_param_qualified);
1932 // Do not add 'void' to the ArgTys list.
1935 } else if (!FTI.hasPrototype) {
1936 if (ArgTy->isPromotableIntegerType()) {
1937 ArgTy = Context.getPromotedIntegerType(ArgTy);
1938 Param->setKNRPromoted(true);
1939 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1940 if (BTy->getKind() == BuiltinType::Float) {
1941 ArgTy = Context.DoubleTy;
1942 Param->setKNRPromoted(true);
1947 ArgTys.push_back(ArgTy);
1950 llvm::SmallVector<QualType, 4> Exceptions;
1951 EPI.ExceptionSpecType = FTI.getExceptionSpecType();
1952 if (FTI.getExceptionSpecType() == EST_Dynamic) {
1953 Exceptions.reserve(FTI.NumExceptions);
1954 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1955 // FIXME: Preserve type source info.
1956 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1957 // Check that the type is valid for an exception spec, and
1959 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1960 Exceptions.push_back(ET);
1962 EPI.NumExceptions = Exceptions.size();
1963 EPI.Exceptions = Exceptions.data();
1964 } else if (FTI.getExceptionSpecType() == EST_ComputedNoexcept) {
1965 // If an error occurred, there's no expression here.
1966 if (Expr *NoexceptExpr = FTI.NoexceptExpr) {
1967 assert((NoexceptExpr->isTypeDependent() ||
1968 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
1970 "Parser should have made sure that the expression is boolean");
1971 SourceLocation ErrLoc;
1973 if (!NoexceptExpr->isValueDependent() &&
1974 !NoexceptExpr->isIntegerConstantExpr(Dummy, Context, &ErrLoc,
1975 /*evaluated*/false))
1976 Diag(ErrLoc, diag::err_noexcept_needs_constant_expression)
1977 << NoexceptExpr->getSourceRange();
1979 EPI.NoexceptExpr = NoexceptExpr;
1981 } else if (FTI.getExceptionSpecType() == EST_None &&
1982 ImplicitlyNoexcept && chunkIndex == 0) {
1983 // Only the outermost chunk is marked noexcept, of course.
1984 EPI.ExceptionSpecType = EST_BasicNoexcept;
1987 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
1992 case DeclaratorChunk::MemberPointer:
1993 // The scope spec must refer to a class, or be dependent.
1994 CXXScopeSpec &SS = DeclType.Mem.Scope();
1996 if (SS.isInvalid()) {
1997 // Avoid emitting extra errors if we already errored on the scope.
1998 D.setInvalidType(true);
1999 } else if (isDependentScopeSpecifier(SS) ||
2000 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) {
2001 NestedNameSpecifier *NNS
2002 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
2003 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
2004 switch (NNS->getKind()) {
2005 case NestedNameSpecifier::Identifier:
2006 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
2007 NNS->getAsIdentifier());
2010 case NestedNameSpecifier::Namespace:
2011 case NestedNameSpecifier::NamespaceAlias:
2012 case NestedNameSpecifier::Global:
2013 llvm_unreachable("Nested-name-specifier must name a type");
2016 case NestedNameSpecifier::TypeSpec:
2017 case NestedNameSpecifier::TypeSpecWithTemplate:
2018 ClsType = QualType(NNS->getAsType(), 0);
2019 // Note: if the NNS has a prefix and ClsType is a nondependent
2020 // TemplateSpecializationType, then the NNS prefix is NOT included
2021 // in ClsType; hence we wrap ClsType into an ElaboratedType.
2022 // NOTE: in particular, no wrap occurs if ClsType already is an
2023 // Elaborated, DependentName, or DependentTemplateSpecialization.
2024 if (NNSPrefix && isa<TemplateSpecializationType>(NNS->getAsType()))
2025 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
2029 Diag(DeclType.Mem.Scope().getBeginLoc(),
2030 diag::err_illegal_decl_mempointer_in_nonclass)
2031 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
2032 << DeclType.Mem.Scope().getRange();
2033 D.setInvalidType(true);
2036 if (!ClsType.isNull())
2037 T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
2040 D.setInvalidType(true);
2041 } else if (DeclType.Mem.TypeQuals) {
2042 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
2048 D.setInvalidType(true);
2052 // See if there are any attributes on this declarator chunk.
2053 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
2054 processTypeAttrs(state, T, false, attrs);
2057 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
2058 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
2059 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
2062 // A cv-qualifier-seq shall only be part of the function type
2063 // for a nonstatic member function, the function type to which a pointer
2064 // to member refers, or the top-level function type of a function typedef
2067 // Core issue 547 also allows cv-qualifiers on function types that are
2068 // top-level template type arguments.
2070 if (!D.getCXXScopeSpec().isSet()) {
2071 FreeFunction = (D.getContext() != Declarator::MemberContext ||
2072 D.getDeclSpec().isFriendSpecified());
2074 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec());
2075 FreeFunction = (DC && !DC->isRecord());
2078 // C++0x [dcl.fct]p6:
2079 // A ref-qualifier shall only be part of the function type for a
2080 // non-static member function, the function type to which a pointer to
2081 // member refers, or the top-level function type of a function typedef
2083 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
2084 !(D.getContext() == Declarator::TemplateTypeArgContext &&
2085 !D.isFunctionDeclarator()) && !IsTypedefName &&
2087 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
2088 if (D.getContext() == Declarator::TemplateTypeArgContext) {
2089 // Accept qualified function types as template type arguments as a GNU
2090 // extension. This is also the subject of C++ core issue 547.
2092 if (FnTy->getTypeQuals() != 0)
2093 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
2095 switch (FnTy->getRefQualifier()) {
2112 Diag(D.getIdentifierLoc(),
2113 diag::ext_qualified_function_type_template_arg)
2116 if (FnTy->getTypeQuals() != 0) {
2117 if (D.isFunctionDeclarator())
2118 Diag(D.getIdentifierLoc(),
2119 diag::err_invalid_qualified_function_type);
2121 Diag(D.getIdentifierLoc(),
2122 diag::err_invalid_qualified_typedef_function_type_use)
2126 if (FnTy->getRefQualifier()) {
2127 if (D.isFunctionDeclarator()) {
2128 SourceLocation Loc = D.getIdentifierLoc();
2129 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
2130 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
2131 if (Chunk.Kind == DeclaratorChunk::Function &&
2132 Chunk.Fun.hasRefQualifier()) {
2133 Loc = Chunk.Fun.getRefQualifierLoc();
2138 Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
2139 << (FnTy->getRefQualifier() == RQ_LValue)
2140 << FixItHint::CreateRemoval(Loc);
2142 Diag(D.getIdentifierLoc(),
2143 diag::err_invalid_ref_qualifier_typedef_function_type_use)
2145 << (FnTy->getRefQualifier() == RQ_LValue);
2149 // Strip the cv-qualifiers and ref-qualifiers from the type.
2150 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
2152 EPI.RefQualifier = RQ_None;
2154 T = Context.getFunctionType(FnTy->getResultType(),
2155 FnTy->arg_type_begin(),
2156 FnTy->getNumArgs(), EPI);
2161 // Apply any undistributed attributes from the declarator.
2163 if (AttributeList *attrs = D.getAttributes())
2164 processTypeAttrs(state, T, false, attrs);
2166 // Diagnose any ignored type attributes.
2167 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
2169 // C++0x [dcl.constexpr]p9:
2170 // A constexpr specifier used in an object declaration declares the object
2172 if (D.getDeclSpec().isConstexprSpecified() && T->isObjectType()) {
2176 // If there was an ellipsis in the declarator, the declaration declares a
2177 // parameter pack whose type may be a pack expansion type.
2178 if (D.hasEllipsis() && !T.isNull()) {
2179 // C++0x [dcl.fct]p13:
2180 // A declarator-id or abstract-declarator containing an ellipsis shall
2181 // only be used in a parameter-declaration. Such a parameter-declaration
2182 // is a parameter pack (14.5.3). [...]
2183 switch (D.getContext()) {
2184 case Declarator::PrototypeContext:
2185 // C++0x [dcl.fct]p13:
2186 // [...] When it is part of a parameter-declaration-clause, the
2187 // parameter pack is a function parameter pack (14.5.3). The type T
2188 // of the declarator-id of the function parameter pack shall contain
2189 // a template parameter pack; each template parameter pack in T is
2190 // expanded by the function parameter pack.
2192 // We represent function parameter packs as function parameters whose
2193 // type is a pack expansion.
2194 if (!T->containsUnexpandedParameterPack()) {
2195 Diag(D.getEllipsisLoc(),
2196 diag::err_function_parameter_pack_without_parameter_packs)
2197 << T << D.getSourceRange();
2198 D.setEllipsisLoc(SourceLocation());
2200 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2204 case Declarator::TemplateParamContext:
2205 // C++0x [temp.param]p15:
2206 // If a template-parameter is a [...] is a parameter-declaration that
2207 // declares a parameter pack (8.3.5), then the template-parameter is a
2208 // template parameter pack (14.5.3).
2210 // Note: core issue 778 clarifies that, if there are any unexpanded
2211 // parameter packs in the type of the non-type template parameter, then
2212 // it expands those parameter packs.
2213 if (T->containsUnexpandedParameterPack())
2214 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2215 else if (!getLangOptions().CPlusPlus0x)
2216 Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
2219 case Declarator::FileContext:
2220 case Declarator::KNRTypeListContext:
2221 case Declarator::ObjCPrototypeContext: // FIXME: special diagnostic here?
2222 case Declarator::TypeNameContext:
2223 case Declarator::AliasDeclContext:
2224 case Declarator::AliasTemplateContext:
2225 case Declarator::MemberContext:
2226 case Declarator::BlockContext:
2227 case Declarator::ForContext:
2228 case Declarator::ConditionContext:
2229 case Declarator::CXXCatchContext:
2230 case Declarator::BlockLiteralContext:
2231 case Declarator::TemplateTypeArgContext:
2232 // FIXME: We may want to allow parameter packs in block-literal contexts
2234 Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2235 D.setEllipsisLoc(SourceLocation());
2241 return Context.getNullTypeSourceInfo();
2242 else if (D.isInvalidType())
2243 return Context.getTrivialTypeSourceInfo(T);
2244 return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
2247 /// Map an AttributedType::Kind to an AttributeList::Kind.
2248 static AttributeList::Kind getAttrListKind(AttributedType::Kind kind) {
2250 case AttributedType::attr_address_space:
2251 return AttributeList::AT_address_space;
2252 case AttributedType::attr_regparm:
2253 return AttributeList::AT_regparm;
2254 case AttributedType::attr_vector_size:
2255 return AttributeList::AT_vector_size;
2256 case AttributedType::attr_neon_vector_type:
2257 return AttributeList::AT_neon_vector_type;
2258 case AttributedType::attr_neon_polyvector_type:
2259 return AttributeList::AT_neon_polyvector_type;
2260 case AttributedType::attr_objc_gc:
2261 return AttributeList::AT_objc_gc;
2262 case AttributedType::attr_noreturn:
2263 return AttributeList::AT_noreturn;
2264 case AttributedType::attr_cdecl:
2265 return AttributeList::AT_cdecl;
2266 case AttributedType::attr_fastcall:
2267 return AttributeList::AT_fastcall;
2268 case AttributedType::attr_stdcall:
2269 return AttributeList::AT_stdcall;
2270 case AttributedType::attr_thiscall:
2271 return AttributeList::AT_thiscall;
2272 case AttributedType::attr_pascal:
2273 return AttributeList::AT_pascal;
2274 case AttributedType::attr_pcs:
2275 return AttributeList::AT_pcs;
2277 llvm_unreachable("unexpected attribute kind!");
2278 return AttributeList::Kind();
2281 static void fillAttributedTypeLoc(AttributedTypeLoc TL,
2282 const AttributeList *attrs) {
2283 AttributedType::Kind kind = TL.getAttrKind();
2285 assert(attrs && "no type attributes in the expected location!");
2286 AttributeList::Kind parsedKind = getAttrListKind(kind);
2287 while (attrs->getKind() != parsedKind) {
2288 attrs = attrs->getNext();
2289 assert(attrs && "no matching attribute in expected location!");
2292 TL.setAttrNameLoc(attrs->getLoc());
2293 if (TL.hasAttrExprOperand())
2294 TL.setAttrExprOperand(attrs->getArg(0));
2295 else if (TL.hasAttrEnumOperand())
2296 TL.setAttrEnumOperandLoc(attrs->getParameterLoc());
2298 // FIXME: preserve this information to here.
2299 if (TL.hasAttrOperand())
2300 TL.setAttrOperandParensRange(SourceRange());
2304 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2305 ASTContext &Context;
2309 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2310 : Context(Context), DS(DS) {}
2312 void VisitAttributedTypeLoc(AttributedTypeLoc TL) {
2313 fillAttributedTypeLoc(TL, DS.getAttributes().getList());
2314 Visit(TL.getModifiedLoc());
2316 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2317 Visit(TL.getUnqualifiedLoc());
2319 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2320 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2322 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2323 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2325 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2326 // Handle the base type, which might not have been written explicitly.
2327 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2328 TL.setHasBaseTypeAsWritten(false);
2329 TL.getBaseLoc().initialize(Context, SourceLocation());
2331 TL.setHasBaseTypeAsWritten(true);
2332 Visit(TL.getBaseLoc());
2335 // Protocol qualifiers.
2336 if (DS.getProtocolQualifiers()) {
2337 assert(TL.getNumProtocols() > 0);
2338 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2339 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2340 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2341 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2342 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2344 assert(TL.getNumProtocols() == 0);
2345 TL.setLAngleLoc(SourceLocation());
2346 TL.setRAngleLoc(SourceLocation());
2349 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2350 TL.setStarLoc(SourceLocation());
2351 Visit(TL.getPointeeLoc());
2353 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2354 TypeSourceInfo *TInfo = 0;
2355 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2357 // If we got no declarator info from previous Sema routines,
2358 // just fill with the typespec loc.
2360 TL.initialize(Context, DS.getTypeSpecTypeNameLoc());
2364 TypeLoc OldTL = TInfo->getTypeLoc();
2365 if (TInfo->getType()->getAs<ElaboratedType>()) {
2366 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2367 TemplateSpecializationTypeLoc NamedTL =
2368 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2372 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2374 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2375 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2376 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2377 TL.setParensRange(DS.getTypeofParensRange());
2379 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2380 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2381 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2382 TL.setParensRange(DS.getTypeofParensRange());
2383 assert(DS.getRepAsType());
2384 TypeSourceInfo *TInfo = 0;
2385 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2386 TL.setUnderlyingTInfo(TInfo);
2388 void VisitUnaryTransformTypeLoc(UnaryTransformTypeLoc TL) {
2389 // FIXME: This holds only because we only have one unary transform.
2390 assert(DS.getTypeSpecType() == DeclSpec::TST_underlyingType);
2391 TL.setKWLoc(DS.getTypeSpecTypeLoc());
2392 TL.setParensRange(DS.getTypeofParensRange());
2393 assert(DS.getRepAsType());
2394 TypeSourceInfo *TInfo = 0;
2395 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2396 TL.setUnderlyingTInfo(TInfo);
2398 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2399 // By default, use the source location of the type specifier.
2400 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2401 if (TL.needsExtraLocalData()) {
2402 // Set info for the written builtin specifiers.
2403 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2404 // Try to have a meaningful source location.
2405 if (TL.getWrittenSignSpec() != TSS_unspecified)
2406 // Sign spec loc overrides the others (e.g., 'unsigned long').
2407 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2408 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2409 // Width spec loc overrides type spec loc (e.g., 'short int').
2410 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2413 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2414 ElaboratedTypeKeyword Keyword
2415 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2416 if (DS.getTypeSpecType() == TST_typename) {
2417 TypeSourceInfo *TInfo = 0;
2418 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2420 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2424 TL.setKeywordLoc(Keyword != ETK_None
2425 ? DS.getTypeSpecTypeLoc()
2426 : SourceLocation());
2427 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2428 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2429 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2431 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2432 ElaboratedTypeKeyword Keyword
2433 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2434 if (DS.getTypeSpecType() == TST_typename) {
2435 TypeSourceInfo *TInfo = 0;
2436 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2438 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2442 TL.setKeywordLoc(Keyword != ETK_None
2443 ? DS.getTypeSpecTypeLoc()
2444 : SourceLocation());
2445 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2446 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2447 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2449 void VisitDependentTemplateSpecializationTypeLoc(
2450 DependentTemplateSpecializationTypeLoc TL) {
2451 ElaboratedTypeKeyword Keyword
2452 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2453 if (Keyword == ETK_Typename) {
2454 TypeSourceInfo *TInfo = 0;
2455 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2457 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2458 TInfo->getTypeLoc()));
2462 TL.initializeLocal(Context, SourceLocation());
2463 TL.setKeywordLoc(Keyword != ETK_None
2464 ? DS.getTypeSpecTypeLoc()
2465 : SourceLocation());
2466 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2467 TL.setQualifierLoc(SS.getWithLocInContext(Context));
2468 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2470 void VisitTagTypeLoc(TagTypeLoc TL) {
2471 TL.setNameLoc(DS.getTypeSpecTypeNameLoc());
2474 void VisitTypeLoc(TypeLoc TL) {
2475 // FIXME: add other typespec types and change this to an assert.
2476 TL.initialize(Context, DS.getTypeSpecTypeLoc());
2480 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2481 ASTContext &Context;
2482 const DeclaratorChunk &Chunk;
2485 DeclaratorLocFiller(ASTContext &Context, const DeclaratorChunk &Chunk)
2486 : Context(Context), Chunk(Chunk) {}
2488 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2489 llvm_unreachable("qualified type locs not expected here!");
2492 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2493 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2494 TL.setCaretLoc(Chunk.Loc);
2496 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2497 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2498 TL.setStarLoc(Chunk.Loc);
2500 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2501 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2502 TL.setStarLoc(Chunk.Loc);
2504 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2505 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2506 const CXXScopeSpec& SS = Chunk.Mem.Scope();
2507 NestedNameSpecifierLoc NNSLoc = SS.getWithLocInContext(Context);
2509 const Type* ClsTy = TL.getClass();
2510 QualType ClsQT = QualType(ClsTy, 0);
2511 TypeSourceInfo *ClsTInfo = Context.CreateTypeSourceInfo(ClsQT, 0);
2512 // Now copy source location info into the type loc component.
2513 TypeLoc ClsTL = ClsTInfo->getTypeLoc();
2514 switch (NNSLoc.getNestedNameSpecifier()->getKind()) {
2515 case NestedNameSpecifier::Identifier:
2516 assert(isa<DependentNameType>(ClsTy) && "Unexpected TypeLoc");
2518 DependentNameTypeLoc DNTLoc = cast<DependentNameTypeLoc>(ClsTL);
2519 DNTLoc.setKeywordLoc(SourceLocation());
2520 DNTLoc.setQualifierLoc(NNSLoc.getPrefix());
2521 DNTLoc.setNameLoc(NNSLoc.getLocalBeginLoc());
2525 case NestedNameSpecifier::TypeSpec:
2526 case NestedNameSpecifier::TypeSpecWithTemplate:
2527 if (isa<ElaboratedType>(ClsTy)) {
2528 ElaboratedTypeLoc ETLoc = *cast<ElaboratedTypeLoc>(&ClsTL);
2529 ETLoc.setKeywordLoc(SourceLocation());
2530 ETLoc.setQualifierLoc(NNSLoc.getPrefix());
2531 TypeLoc NamedTL = ETLoc.getNamedTypeLoc();
2532 NamedTL.initializeFullCopy(NNSLoc.getTypeLoc());
2534 ClsTL.initializeFullCopy(NNSLoc.getTypeLoc());
2538 case NestedNameSpecifier::Namespace:
2539 case NestedNameSpecifier::NamespaceAlias:
2540 case NestedNameSpecifier::Global:
2541 llvm_unreachable("Nested-name-specifier must name a type");
2545 // Finally fill in MemberPointerLocInfo fields.
2546 TL.setStarLoc(Chunk.Loc);
2547 TL.setClassTInfo(ClsTInfo);
2549 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2550 assert(Chunk.Kind == DeclaratorChunk::Reference);
2551 // 'Amp' is misleading: this might have been originally
2552 /// spelled with AmpAmp.
2553 TL.setAmpLoc(Chunk.Loc);
2555 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2556 assert(Chunk.Kind == DeclaratorChunk::Reference);
2557 assert(!Chunk.Ref.LValueRef);
2558 TL.setAmpAmpLoc(Chunk.Loc);
2560 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2561 assert(Chunk.Kind == DeclaratorChunk::Array);
2562 TL.setLBracketLoc(Chunk.Loc);
2563 TL.setRBracketLoc(Chunk.EndLoc);
2564 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2566 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2567 assert(Chunk.Kind == DeclaratorChunk::Function);
2568 TL.setLocalRangeBegin(Chunk.Loc);
2569 TL.setLocalRangeEnd(Chunk.EndLoc);
2570 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
2572 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
2573 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
2574 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2575 TL.setArg(tpi++, Param);
2577 // FIXME: exception specs
2579 void VisitParenTypeLoc(ParenTypeLoc TL) {
2580 assert(Chunk.Kind == DeclaratorChunk::Paren);
2581 TL.setLParenLoc(Chunk.Loc);
2582 TL.setRParenLoc(Chunk.EndLoc);
2585 void VisitTypeLoc(TypeLoc TL) {
2586 llvm_unreachable("unsupported TypeLoc kind in declarator!");
2591 /// \brief Create and instantiate a TypeSourceInfo with type source information.
2593 /// \param T QualType referring to the type as written in source code.
2595 /// \param ReturnTypeInfo For declarators whose return type does not show
2596 /// up in the normal place in the declaration specifiers (such as a C++
2597 /// conversion function), this pointer will refer to a type source information
2598 /// for that return type.
2600 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2601 TypeSourceInfo *ReturnTypeInfo) {
2602 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2603 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
2605 // Handle parameter packs whose type is a pack expansion.
2606 if (isa<PackExpansionType>(T)) {
2607 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2608 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2611 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2612 while (isa<AttributedTypeLoc>(CurrTL)) {
2613 AttributedTypeLoc TL = cast<AttributedTypeLoc>(CurrTL);
2614 fillAttributedTypeLoc(TL, D.getTypeObject(i).getAttrs());
2615 CurrTL = TL.getNextTypeLoc().getUnqualifiedLoc();
2618 DeclaratorLocFiller(Context, D.getTypeObject(i)).Visit(CurrTL);
2619 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2622 // If we have different source information for the return type, use
2623 // that. This really only applies to C++ conversion functions.
2624 if (ReturnTypeInfo) {
2625 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
2626 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
2627 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
2629 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
2635 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
2636 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
2637 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
2638 // and Sema during declaration parsing. Try deallocating/caching them when
2639 // it's appropriate, instead of allocating them and keeping them around.
2640 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
2642 new (LocT) LocInfoType(T, TInfo);
2643 assert(LocT->getTypeClass() != T->getTypeClass() &&
2644 "LocInfoType's TypeClass conflicts with an existing Type class");
2645 return ParsedType::make(QualType(LocT, 0));
2648 void LocInfoType::getAsStringInternal(std::string &Str,
2649 const PrintingPolicy &Policy) const {
2650 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
2651 " was used directly instead of getting the QualType through"
2652 " GetTypeFromParser");
2655 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
2656 // C99 6.7.6: Type names have no identifier. This is already validated by
2658 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
2660 TagDecl *OwnedTag = 0;
2661 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
2662 QualType T = TInfo->getType();
2663 if (D.isInvalidType())
2666 if (getLangOptions().CPlusPlus) {
2667 // Check that there are no default arguments (C++ only).
2668 CheckExtraCXXDefaultArguments(D);
2670 // C++0x [dcl.type]p3:
2671 // A type-specifier-seq shall not define a class or enumeration unless
2672 // it appears in the type-id of an alias-declaration (7.1.3) that is not
2673 // the declaration of a template-declaration.
2674 if (OwnedTag && OwnedTag->isDefinition()) {
2675 if (D.getContext() == Declarator::AliasTemplateContext)
2676 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_alias_template)
2677 << Context.getTypeDeclType(OwnedTag);
2678 else if (D.getContext() != Declarator::AliasDeclContext)
2679 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
2680 << Context.getTypeDeclType(OwnedTag);
2684 return CreateParsedType(T, TInfo);
2689 //===----------------------------------------------------------------------===//
2690 // Type Attribute Processing
2691 //===----------------------------------------------------------------------===//
2693 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
2694 /// specified type. The attribute contains 1 argument, the id of the address
2695 /// space for the type.
2696 static void HandleAddressSpaceTypeAttribute(QualType &Type,
2697 const AttributeList &Attr, Sema &S){
2699 // If this type is already address space qualified, reject it.
2700 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
2701 // for two or more different address spaces."
2702 if (Type.getAddressSpace()) {
2703 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
2708 // Check the attribute arguments.
2709 if (Attr.getNumArgs() != 1) {
2710 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2714 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
2715 llvm::APSInt addrSpace(32);
2716 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
2717 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
2718 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
2719 << ASArgExpr->getSourceRange();
2725 if (addrSpace.isSigned()) {
2726 if (addrSpace.isNegative()) {
2727 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
2728 << ASArgExpr->getSourceRange();
2732 addrSpace.setIsSigned(false);
2734 llvm::APSInt max(addrSpace.getBitWidth());
2735 max = Qualifiers::MaxAddressSpace;
2736 if (addrSpace > max) {
2737 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
2738 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
2743 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
2744 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
2747 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
2748 /// attribute on the specified type. Returns true to indicate that
2749 /// the attribute was handled, false to indicate that the type does
2750 /// not permit the attribute.
2751 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
2752 AttributeList &attr,
2754 Sema &S = state.getSema();
2756 // Delay if this isn't some kind of pointer.
2757 if (!type->isPointerType() &&
2758 !type->isObjCObjectPointerType() &&
2759 !type->isBlockPointerType())
2762 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
2763 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
2768 // Check the attribute arguments.
2769 if (!attr.getParameterName()) {
2770 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2775 Qualifiers::GC GCAttr;
2776 if (attr.getNumArgs() != 0) {
2777 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2781 if (attr.getParameterName()->isStr("weak"))
2782 GCAttr = Qualifiers::Weak;
2783 else if (attr.getParameterName()->isStr("strong"))
2784 GCAttr = Qualifiers::Strong;
2786 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
2787 << "objc_gc" << attr.getParameterName();
2792 QualType origType = type;
2793 type = S.Context.getObjCGCQualType(origType, GCAttr);
2795 // Make an attributed type to preserve the source information.
2796 if (attr.getLoc().isValid())
2797 type = S.Context.getAttributedType(AttributedType::attr_objc_gc,
2804 /// A helper class to unwrap a type down to a function for the
2805 /// purposes of applying attributes there.
2808 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
2809 /// if (unwrapped.isFunctionType()) {
2810 /// const FunctionType *fn = unwrapped.get();
2811 /// // change fn somehow
2812 /// T = unwrapped.wrap(fn);
2814 struct FunctionTypeUnwrapper {
2825 const FunctionType *Fn;
2826 llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack;
2828 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
2830 const Type *Ty = T.getTypePtr();
2831 if (isa<FunctionType>(Ty)) {
2832 Fn = cast<FunctionType>(Ty);
2834 } else if (isa<ParenType>(Ty)) {
2835 T = cast<ParenType>(Ty)->getInnerType();
2836 Stack.push_back(Parens);
2837 } else if (isa<PointerType>(Ty)) {
2838 T = cast<PointerType>(Ty)->getPointeeType();
2839 Stack.push_back(Pointer);
2840 } else if (isa<BlockPointerType>(Ty)) {
2841 T = cast<BlockPointerType>(Ty)->getPointeeType();
2842 Stack.push_back(BlockPointer);
2843 } else if (isa<MemberPointerType>(Ty)) {
2844 T = cast<MemberPointerType>(Ty)->getPointeeType();
2845 Stack.push_back(MemberPointer);
2846 } else if (isa<ReferenceType>(Ty)) {
2847 T = cast<ReferenceType>(Ty)->getPointeeType();
2848 Stack.push_back(Reference);
2850 const Type *DTy = Ty->getUnqualifiedDesugaredType();
2856 T = QualType(DTy, 0);
2857 Stack.push_back(Desugar);
2862 bool isFunctionType() const { return (Fn != 0); }
2863 const FunctionType *get() const { return Fn; }
2865 QualType wrap(Sema &S, const FunctionType *New) {
2866 // If T wasn't modified from the unwrapped type, do nothing.
2867 if (New == get()) return Original;
2870 return wrap(S.Context, Original, 0);
2874 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
2875 if (I == Stack.size())
2876 return C.getQualifiedType(Fn, Old.getQualifiers());
2878 // Build up the inner type, applying the qualifiers from the old
2879 // type to the new type.
2880 SplitQualType SplitOld = Old.split();
2882 // As a special case, tail-recurse if there are no qualifiers.
2883 if (SplitOld.second.empty())
2884 return wrap(C, SplitOld.first, I);
2885 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
2888 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
2889 if (I == Stack.size()) return QualType(Fn, 0);
2891 switch (static_cast<WrapKind>(Stack[I++])) {
2893 // This is the point at which we potentially lose source
2895 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
2898 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
2899 return C.getParenType(New);
2903 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
2904 return C.getPointerType(New);
2907 case BlockPointer: {
2908 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
2909 return C.getBlockPointerType(New);
2912 case MemberPointer: {
2913 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
2914 QualType New = wrap(C, OldMPT->getPointeeType(), I);
2915 return C.getMemberPointerType(New, OldMPT->getClass());
2919 const ReferenceType *OldRef = cast<ReferenceType>(Old);
2920 QualType New = wrap(C, OldRef->getPointeeType(), I);
2921 if (isa<LValueReferenceType>(OldRef))
2922 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
2924 return C.getRValueReferenceType(New);
2928 llvm_unreachable("unknown wrapping kind");
2934 /// Process an individual function attribute. Returns true to
2935 /// indicate that the attribute was handled, false if it wasn't.
2936 static bool handleFunctionTypeAttr(TypeProcessingState &state,
2937 AttributeList &attr,
2939 Sema &S = state.getSema();
2941 FunctionTypeUnwrapper unwrapped(S, type);
2943 if (attr.getKind() == AttributeList::AT_noreturn) {
2944 if (S.CheckNoReturnAttr(attr))
2947 // Delay if this is not a function type.
2948 if (!unwrapped.isFunctionType())
2951 // Otherwise we can process right away.
2952 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
2953 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2957 if (attr.getKind() == AttributeList::AT_regparm) {
2959 if (S.CheckRegparmAttr(attr, value))
2962 // Delay if this is not a function type.
2963 if (!unwrapped.isFunctionType())
2966 // Diagnose regparm with fastcall.
2967 const FunctionType *fn = unwrapped.get();
2968 CallingConv CC = fn->getCallConv();
2969 if (CC == CC_X86FastCall) {
2970 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2971 << FunctionType::getNameForCallConv(CC)
2977 FunctionType::ExtInfo EI =
2978 unwrapped.get()->getExtInfo().withRegParm(value);
2979 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2983 // Otherwise, a calling convention.
2985 if (S.CheckCallingConvAttr(attr, CC))
2988 // Delay if the type didn't work out to a function.
2989 if (!unwrapped.isFunctionType()) return false;
2991 const FunctionType *fn = unwrapped.get();
2992 CallingConv CCOld = fn->getCallConv();
2993 if (S.Context.getCanonicalCallConv(CC) ==
2994 S.Context.getCanonicalCallConv(CCOld)) {
2995 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
2996 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3000 if (CCOld != CC_Default) {
3001 // Should we diagnose reapplications of the same convention?
3002 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3003 << FunctionType::getNameForCallConv(CC)
3004 << FunctionType::getNameForCallConv(CCOld);
3009 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
3010 if (CC == CC_X86FastCall) {
3011 if (isa<FunctionNoProtoType>(fn)) {
3012 S.Diag(attr.getLoc(), diag::err_cconv_knr)
3013 << FunctionType::getNameForCallConv(CC);
3018 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
3019 if (FnP->isVariadic()) {
3020 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
3021 << FunctionType::getNameForCallConv(CC);
3026 // Also diagnose fastcall with regparm.
3027 if (fn->getHasRegParm()) {
3028 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
3030 << FunctionType::getNameForCallConv(CC);
3036 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
3037 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
3041 /// Handle OpenCL image access qualifiers: read_only, write_only, read_write
3042 static void HandleOpenCLImageAccessAttribute(QualType& CurType,
3043 const AttributeList &Attr,
3045 // Check the attribute arguments.
3046 if (Attr.getNumArgs() != 1) {
3047 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3051 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3052 llvm::APSInt arg(32);
3053 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3054 !sizeExpr->isIntegerConstantExpr(arg, S.Context)) {
3055 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3056 << "opencl_image_access" << sizeExpr->getSourceRange();
3060 unsigned iarg = static_cast<unsigned>(arg.getZExtValue());
3062 case CLIA_read_only:
3063 case CLIA_write_only:
3064 case CLIA_read_write:
3065 // Implemented in a separate patch
3068 // Implemented in a separate patch
3069 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3070 << sizeExpr->getSourceRange();
3076 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
3077 /// and float scalars, although arrays, pointers, and function return values are
3078 /// allowed in conjunction with this construct. Aggregates with this attribute
3079 /// are invalid, even if they are of the same size as a corresponding scalar.
3080 /// The raw attribute should contain precisely 1 argument, the vector size for
3081 /// the variable, measured in bytes. If curType and rawAttr are well formed,
3082 /// this routine will return a new vector type.
3083 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
3085 // Check the attribute arguments.
3086 if (Attr.getNumArgs() != 1) {
3087 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3091 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
3092 llvm::APSInt vecSize(32);
3093 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
3094 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
3095 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3096 << "vector_size" << sizeExpr->getSourceRange();
3100 // the base type must be integer or float, and can't already be a vector.
3101 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
3102 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
3106 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3107 // vecSize is specified in bytes - convert to bits.
3108 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
3110 // the vector size needs to be an integral multiple of the type size.
3111 if (vectorSize % typeSize) {
3112 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
3113 << sizeExpr->getSourceRange();
3117 if (vectorSize == 0) {
3118 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
3119 << sizeExpr->getSourceRange();
3124 // Success! Instantiate the vector type, the number of elements is > 0, and
3125 // not required to be a power of 2, unlike GCC.
3126 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
3127 VectorType::GenericVector);
3130 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
3131 /// "neon_polyvector_type" attributes are used to create vector types that
3132 /// are mangled according to ARM's ABI. Otherwise, these types are identical
3133 /// to those created with the "vector_size" attribute. Unlike "vector_size"
3134 /// the argument to these Neon attributes is the number of vector elements,
3135 /// not the vector size in bytes. The vector width and element type must
3136 /// match one of the standard Neon vector types.
3137 static void HandleNeonVectorTypeAttr(QualType& CurType,
3138 const AttributeList &Attr, Sema &S,
3139 VectorType::VectorKind VecKind,
3140 const char *AttrName) {
3141 // Check the attribute arguments.
3142 if (Attr.getNumArgs() != 1) {
3143 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
3147 // The number of elements must be an ICE.
3148 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
3149 llvm::APSInt numEltsInt(32);
3150 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
3151 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
3152 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
3153 << AttrName << numEltsExpr->getSourceRange();
3157 // Only certain element types are supported for Neon vectors.
3158 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
3160 (VecKind == VectorType::NeonPolyVector &&
3161 BTy->getKind() != BuiltinType::SChar &&
3162 BTy->getKind() != BuiltinType::Short) ||
3163 (BTy->getKind() != BuiltinType::SChar &&
3164 BTy->getKind() != BuiltinType::UChar &&
3165 BTy->getKind() != BuiltinType::Short &&
3166 BTy->getKind() != BuiltinType::UShort &&
3167 BTy->getKind() != BuiltinType::Int &&
3168 BTy->getKind() != BuiltinType::UInt &&
3169 BTy->getKind() != BuiltinType::LongLong &&
3170 BTy->getKind() != BuiltinType::ULongLong &&
3171 BTy->getKind() != BuiltinType::Float)) {
3172 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
3176 // The total size of the vector must be 64 or 128 bits.
3177 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
3178 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
3179 unsigned vecSize = typeSize * numElts;
3180 if (vecSize != 64 && vecSize != 128) {
3181 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
3186 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
3189 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
3190 bool isDeclSpec, AttributeList *attrs) {
3191 // Scan through and apply attributes to this type where it makes sense. Some
3192 // attributes (such as __address_space__, __vector_size__, etc) apply to the
3193 // type, but others can be present in the type specifiers even though they
3194 // apply to the decl. Here we apply type attributes and ignore the rest.
3196 AttributeList *next;
3198 AttributeList &attr = *attrs;
3199 next = attr.getNext();
3201 // Skip attributes that were marked to be invalid.
3202 if (attr.isInvalid())
3205 // If this is an attribute we can handle, do so now,
3206 // otherwise, add it to the FnAttrs list for rechaining.
3207 switch (attr.getKind()) {
3210 case AttributeList::AT_address_space:
3211 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
3213 OBJC_POINTER_TYPE_ATTRS_CASELIST:
3214 if (!handleObjCPointerTypeAttr(state, attr, type))
3215 distributeObjCPointerTypeAttr(state, attr, type);
3217 case AttributeList::AT_vector_size:
3218 HandleVectorSizeAttr(type, attr, state.getSema());
3220 case AttributeList::AT_neon_vector_type:
3221 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3222 VectorType::NeonVector, "neon_vector_type");
3224 case AttributeList::AT_neon_polyvector_type:
3225 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
3226 VectorType::NeonPolyVector,
3227 "neon_polyvector_type");
3230 case AttributeList::AT_opencl_image_access:
3231 HandleOpenCLImageAccessAttribute(type, attr, state.getSema());
3234 FUNCTION_TYPE_ATTRS_CASELIST:
3235 // Never process function type attributes as part of the
3236 // declaration-specifiers.
3238 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
3240 // Otherwise, handle the possible delays.
3241 else if (!handleFunctionTypeAttr(state, attr, type))
3242 distributeFunctionTypeAttr(state, attr, type);
3245 } while ((attrs = next));
3248 /// \brief Ensure that the type of the given expression is complete.
3250 /// This routine checks whether the expression \p E has a complete type. If the
3251 /// expression refers to an instantiable construct, that instantiation is
3252 /// performed as needed to complete its type. Furthermore
3253 /// Sema::RequireCompleteType is called for the expression's type (or in the
3254 /// case of a reference type, the referred-to type).
3256 /// \param E The expression whose type is required to be complete.
3257 /// \param PD The partial diagnostic that will be printed out if the type cannot
3260 /// \returns \c true if the type of \p E is incomplete and diagnosed, \c false
3262 bool Sema::RequireCompleteExprType(Expr *E, const PartialDiagnostic &PD,
3263 std::pair<SourceLocation,
3264 PartialDiagnostic> Note) {
3265 QualType T = E->getType();
3267 // Fast path the case where the type is already complete.
3268 if (!T->isIncompleteType())
3271 // Incomplete array types may be completed by the initializer attached to
3272 // their definitions. For static data members of class templates we need to
3273 // instantiate the definition to get this initializer and complete the type.
3274 if (T->isIncompleteArrayType()) {
3275 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParens())) {
3276 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl())) {
3277 if (Var->isStaticDataMember() &&
3278 Var->getInstantiatedFromStaticDataMember()) {
3280 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3281 assert(MSInfo && "Missing member specialization information?");
3282 if (MSInfo->getTemplateSpecializationKind()
3283 != TSK_ExplicitSpecialization) {
3284 // If we don't already have a point of instantiation, this is it.
3285 if (MSInfo->getPointOfInstantiation().isInvalid()) {
3286 MSInfo->setPointOfInstantiation(E->getLocStart());
3288 // This is a modification of an existing AST node. Notify
3290 if (ASTMutationListener *L = getASTMutationListener())
3291 L->StaticDataMemberInstantiated(Var);
3294 InstantiateStaticDataMemberDefinition(E->getExprLoc(), Var);
3296 // Update the type to the newly instantiated definition's type both
3297 // here and within the expression.
3298 if (VarDecl *Def = Var->getDefinition()) {
3306 // We still go on to try to complete the type independently, as it
3307 // may also require instantiations or diagnostics if it remains
3314 // FIXME: Are there other cases which require instantiating something other
3315 // than the type to complete the type of an expression?
3317 // Look through reference types and complete the referred type.
3318 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
3319 T = Ref->getPointeeType();
3321 return RequireCompleteType(E->getExprLoc(), T, PD, Note);
3324 /// @brief Ensure that the type T is a complete type.
3326 /// This routine checks whether the type @p T is complete in any
3327 /// context where a complete type is required. If @p T is a complete
3328 /// type, returns false. If @p T is a class template specialization,
3329 /// this routine then attempts to perform class template
3330 /// instantiation. If instantiation fails, or if @p T is incomplete
3331 /// and cannot be completed, issues the diagnostic @p diag (giving it
3332 /// the type @p T) and returns true.
3334 /// @param Loc The location in the source that the incomplete type
3335 /// diagnostic should refer to.
3337 /// @param T The type that this routine is examining for completeness.
3339 /// @param PD The partial diagnostic that will be printed out if T is not a
3342 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
3343 /// @c false otherwise.
3344 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3345 const PartialDiagnostic &PD,
3346 std::pair<SourceLocation,
3347 PartialDiagnostic> Note) {
3348 unsigned diag = PD.getDiagID();
3350 // FIXME: Add this assertion to make sure we always get instantiation points.
3351 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
3352 // FIXME: Add this assertion to help us flush out problems with
3353 // checking for dependent types and type-dependent expressions.
3355 // assert(!T->isDependentType() &&
3356 // "Can't ask whether a dependent type is complete");
3358 // If we have a complete type, we're done.
3359 if (!T->isIncompleteType())
3362 // If we have a class template specialization or a class member of a
3363 // class template specialization, or an array with known size of such,
3364 // try to instantiate it.
3365 QualType MaybeTemplate = T;
3366 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
3367 MaybeTemplate = Array->getElementType();
3368 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
3369 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
3370 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
3371 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
3372 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
3373 TSK_ImplicitInstantiation,
3374 /*Complain=*/diag != 0);
3375 } else if (CXXRecordDecl *Rec
3376 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
3377 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
3378 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
3379 assert(MSInfo && "Missing member specialization information?");
3380 // This record was instantiated from a class within a template.
3381 if (MSInfo->getTemplateSpecializationKind()
3382 != TSK_ExplicitSpecialization)
3383 return InstantiateClass(Loc, Rec, Pattern,
3384 getTemplateInstantiationArgs(Rec),
3385 TSK_ImplicitInstantiation,
3386 /*Complain=*/diag != 0);
3394 const TagType *Tag = T->getAs<TagType>();
3396 // Avoid diagnosing invalid decls as incomplete.
3397 if (Tag && Tag->getDecl()->isInvalidDecl())
3400 // Give the external AST source a chance to complete the type.
3401 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
3402 Context.getExternalSource()->CompleteType(Tag->getDecl());
3403 if (!Tag->isIncompleteType())
3407 // We have an incomplete type. Produce a diagnostic.
3410 // If we have a note, produce it.
3411 if (!Note.first.isInvalid())
3412 Diag(Note.first, Note.second);
3414 // If the type was a forward declaration of a class/struct/union
3415 // type, produce a note.
3416 if (Tag && !Tag->getDecl()->isInvalidDecl())
3417 Diag(Tag->getDecl()->getLocation(),
3418 Tag->isBeingDefined() ? diag::note_type_being_defined
3419 : diag::note_forward_declaration)
3420 << QualType(Tag, 0);
3425 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3426 const PartialDiagnostic &PD) {
3427 return RequireCompleteType(Loc, T, PD,
3428 std::make_pair(SourceLocation(), PDiag(0)));
3431 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
3433 return RequireCompleteType(Loc, T, PDiag(DiagID),
3434 std::make_pair(SourceLocation(), PDiag(0)));
3437 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3438 /// and qualified by the nested-name-specifier contained in SS.
3439 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3440 const CXXScopeSpec &SS, QualType T) {
3443 NestedNameSpecifier *NNS;
3445 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3447 if (Keyword == ETK_None)
3451 return Context.getElaboratedType(Keyword, NNS, T);
3454 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
3455 ExprResult ER = CheckPlaceholderExpr(E);
3456 if (ER.isInvalid()) return QualType();
3459 if (!E->isTypeDependent()) {
3460 QualType T = E->getType();
3461 if (const TagType *TT = T->getAs<TagType>())
3462 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
3464 return Context.getTypeOfExprType(E);
3467 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
3468 ExprResult ER = CheckPlaceholderExpr(E);
3469 if (ER.isInvalid()) return QualType();
3472 return Context.getDecltypeType(E);
3475 QualType Sema::BuildUnaryTransformType(QualType BaseType,
3476 UnaryTransformType::UTTKind UKind,
3477 SourceLocation Loc) {
3479 case UnaryTransformType::EnumUnderlyingType:
3480 if (!BaseType->isDependentType() && !BaseType->isEnumeralType()) {
3481 Diag(Loc, diag::err_only_enums_have_underlying_types);
3484 QualType Underlying = BaseType;
3485 if (!BaseType->isDependentType()) {
3486 EnumDecl *ED = BaseType->getAs<EnumType>()->getDecl();
3487 assert(ED && "EnumType has no EnumDecl");
3488 DiagnoseUseOfDecl(ED, Loc);
3489 Underlying = ED->getIntegerType();
3491 assert(!Underlying.isNull());
3492 return Context.getUnaryTransformType(BaseType, Underlying,
3493 UnaryTransformType::EnumUnderlyingType);
3496 llvm_unreachable("unknown unary transform type");