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/AST/ASTContext.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/TypeLoc.h"
21 #include "clang/AST/TypeLocVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/Basic/PartialDiagnostic.h"
24 #include "clang/Basic/TargetInfo.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "llvm/ADT/SmallPtrSet.h"
27 #include "llvm/Support/ErrorHandling.h"
28 using namespace clang;
30 /// \brief Perform adjustment on the parameter type of a function.
32 /// This routine adjusts the given parameter type @p T to the actual
33 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
34 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
35 QualType Sema::adjustParameterType(QualType T) {
37 // A declaration of a parameter as "array of type" shall be
38 // adjusted to "qualified pointer to type", where the type
39 // qualifiers (if any) are those specified within the [ and ] of
40 // the array type derivation.
42 return Context.getArrayDecayedType(T);
45 // A declaration of a parameter as "function returning type"
46 // shall be adjusted to "pointer to function returning type", as
48 if (T->isFunctionType())
49 return Context.getPointerType(T);
56 /// isOmittedBlockReturnType - Return true if this declarator is missing a
57 /// return type because this is a omitted return type on a block literal.
58 static bool isOmittedBlockReturnType(const Declarator &D) {
59 if (D.getContext() != Declarator::BlockLiteralContext ||
60 D.getDeclSpec().hasTypeSpecifier())
63 if (D.getNumTypeObjects() == 0)
64 return true; // ^{ ... }
66 if (D.getNumTypeObjects() == 1 &&
67 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
68 return true; // ^(int X, float Y) { ... }
73 // objc_gc applies to Objective-C pointers or, otherwise, to the
74 // smallest available pointer type (i.e. 'void*' in 'void**').
75 #define OBJC_POINTER_TYPE_ATTRS_CASELIST \
76 case AttributeList::AT_objc_gc
78 // Function type attributes.
79 #define FUNCTION_TYPE_ATTRS_CASELIST \
80 case AttributeList::AT_noreturn: \
81 case AttributeList::AT_cdecl: \
82 case AttributeList::AT_fastcall: \
83 case AttributeList::AT_stdcall: \
84 case AttributeList::AT_thiscall: \
85 case AttributeList::AT_pascal: \
86 case AttributeList::AT_regparm
89 /// An object which stores processing state for the entire
90 /// GetTypeForDeclarator process.
91 class TypeProcessingState {
94 /// The declarator being processed.
95 Declarator &declarator;
97 /// The index of the declarator chunk we're currently processing.
98 /// May be the total number of valid chunks, indicating the
102 /// Whether there are non-trivial modifications to the decl spec.
105 /// The original set of attributes on the DeclSpec.
106 llvm::SmallVector<AttributeList*, 2> savedAttrs;
108 /// A list of attributes to diagnose the uselessness of when the
109 /// processing is complete.
110 llvm::SmallVector<AttributeList*, 2> ignoredTypeAttrs;
113 TypeProcessingState(Sema &sema, Declarator &declarator)
114 : sema(sema), declarator(declarator),
115 chunkIndex(declarator.getNumTypeObjects()),
118 Sema &getSema() const {
122 Declarator &getDeclarator() const {
126 unsigned getCurrentChunkIndex() const {
130 void setCurrentChunkIndex(unsigned idx) {
131 assert(idx <= declarator.getNumTypeObjects());
135 AttributeList *&getCurrentAttrListRef() const {
136 assert(chunkIndex <= declarator.getNumTypeObjects());
137 if (chunkIndex == declarator.getNumTypeObjects())
138 return getMutableDeclSpec().getAttributes().getListRef();
139 return declarator.getTypeObject(chunkIndex).getAttrListRef();
142 /// Save the current set of attributes on the DeclSpec.
143 void saveDeclSpecAttrs() {
144 // Don't try to save them multiple times.
145 if (!savedAttrs.empty()) return;
147 DeclSpec &spec = getMutableDeclSpec();
148 for (AttributeList *attr = spec.getAttributes().getList(); attr;
149 attr = attr->getNext())
150 savedAttrs.push_back(attr);
151 trivial &= savedAttrs.empty();
154 /// Record that we had nowhere to put the given type attribute.
155 /// We will diagnose such attributes later.
156 void addIgnoredTypeAttr(AttributeList &attr) {
157 ignoredTypeAttrs.push_back(&attr);
160 /// Diagnose all the ignored type attributes, given that the
161 /// declarator worked out to the given type.
162 void diagnoseIgnoredTypeAttrs(QualType type) const {
163 for (llvm::SmallVectorImpl<AttributeList*>::const_iterator
164 i = ignoredTypeAttrs.begin(), e = ignoredTypeAttrs.end();
166 AttributeList &attr = **i;
167 getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type)
168 << attr.getName() << type;
172 ~TypeProcessingState() {
175 restoreDeclSpecAttrs();
179 DeclSpec &getMutableDeclSpec() const {
180 return const_cast<DeclSpec&>(declarator.getDeclSpec());
183 void restoreDeclSpecAttrs() {
184 assert(!savedAttrs.empty());
185 getMutableDeclSpec().getAttributes().set(savedAttrs[0]);
186 for (unsigned i = 0, e = savedAttrs.size() - 1; i != e; ++i)
187 savedAttrs[i]->setNext(savedAttrs[i+1]);
188 savedAttrs.back()->setNext(0);
192 /// Basically std::pair except that we really want to avoid an
193 /// implicit operator= for safety concerns. It's also a minor
194 /// link-time optimization for this to be a private type.
197 AttributeList &first;
199 /// The head of the list the attribute is currently in.
200 AttributeList *&second;
202 AttrAndList(AttributeList &attr, AttributeList *&head)
203 : first(attr), second(head) {}
208 template <> struct isPodLike<AttrAndList> {
209 static const bool value = true;
213 static void spliceAttrIntoList(AttributeList &attr, AttributeList *&head) {
218 static void spliceAttrOutOfList(AttributeList &attr, AttributeList *&head) {
220 head = attr.getNext();
224 AttributeList *cur = head;
226 assert(cur && cur->getNext() && "ran out of attrs?");
227 if (cur->getNext() == &attr) {
228 cur->setNext(attr.getNext());
231 cur = cur->getNext();
235 static void moveAttrFromListToList(AttributeList &attr,
236 AttributeList *&fromList,
237 AttributeList *&toList) {
238 spliceAttrOutOfList(attr, fromList);
239 spliceAttrIntoList(attr, toList);
242 static void processTypeAttrs(TypeProcessingState &state,
243 QualType &type, bool isDeclSpec,
244 AttributeList *attrs);
246 static bool handleFunctionTypeAttr(TypeProcessingState &state,
250 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
251 AttributeList &attr, QualType &type);
253 static bool handleObjCPointerTypeAttr(TypeProcessingState &state,
254 AttributeList &attr, QualType &type) {
255 // Right now, we have exactly one of these attributes: objc_gc.
256 assert(attr.getKind() == AttributeList::AT_objc_gc);
257 return handleObjCGCTypeAttr(state, attr, type);
260 /// Given that an objc_gc attribute was written somewhere on a
261 /// declaration *other* than on the declarator itself (for which, use
262 /// distributeObjCPointerTypeAttrFromDeclarator), and given that it
263 /// didn't apply in whatever position it was written in, try to move
264 /// it to a more appropriate position.
265 static void distributeObjCPointerTypeAttr(TypeProcessingState &state,
268 Declarator &declarator = state.getDeclarator();
269 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
270 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
271 switch (chunk.Kind) {
272 case DeclaratorChunk::Pointer:
273 case DeclaratorChunk::BlockPointer:
274 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
275 chunk.getAttrListRef());
278 case DeclaratorChunk::Paren:
279 case DeclaratorChunk::Array:
282 // Don't walk through these.
283 case DeclaratorChunk::Reference:
284 case DeclaratorChunk::Function:
285 case DeclaratorChunk::MemberPointer:
291 state.getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type)
292 << attr.getName() << type;
295 /// Distribute an objc_gc type attribute that was written on the
298 distributeObjCPointerTypeAttrFromDeclarator(TypeProcessingState &state,
300 QualType &declSpecType) {
301 Declarator &declarator = state.getDeclarator();
303 // objc_gc goes on the innermost pointer to something that's not a
305 unsigned innermost = -1U;
306 bool considerDeclSpec = true;
307 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
308 DeclaratorChunk &chunk = declarator.getTypeObject(i);
309 switch (chunk.Kind) {
310 case DeclaratorChunk::Pointer:
311 case DeclaratorChunk::BlockPointer:
315 case DeclaratorChunk::Reference:
316 case DeclaratorChunk::MemberPointer:
317 case DeclaratorChunk::Paren:
318 case DeclaratorChunk::Array:
321 case DeclaratorChunk::Function:
322 considerDeclSpec = false;
328 // That might actually be the decl spec if we weren't blocked by
329 // anything in the declarator.
330 if (considerDeclSpec) {
331 if (handleObjCPointerTypeAttr(state, attr, declSpecType))
335 // Otherwise, if we found an appropriate chunk, splice the attribute
337 if (innermost != -1U) {
338 moveAttrFromListToList(attr, declarator.getAttrListRef(),
339 declarator.getTypeObject(innermost).getAttrListRef());
343 // Otherwise, diagnose when we're done building the type.
344 spliceAttrOutOfList(attr, declarator.getAttrListRef());
345 state.addIgnoredTypeAttr(attr);
348 /// A function type attribute was written somewhere in a declaration
349 /// *other* than on the declarator itself or in the decl spec. Given
350 /// that it didn't apply in whatever position it was written in, try
351 /// to move it to a more appropriate position.
352 static void distributeFunctionTypeAttr(TypeProcessingState &state,
355 Declarator &declarator = state.getDeclarator();
357 // Try to push the attribute from the return type of a function to
358 // the function itself.
359 for (unsigned i = state.getCurrentChunkIndex(); i != 0; --i) {
360 DeclaratorChunk &chunk = declarator.getTypeObject(i-1);
361 switch (chunk.Kind) {
362 case DeclaratorChunk::Function:
363 moveAttrFromListToList(attr, state.getCurrentAttrListRef(),
364 chunk.getAttrListRef());
367 case DeclaratorChunk::Paren:
368 case DeclaratorChunk::Pointer:
369 case DeclaratorChunk::BlockPointer:
370 case DeclaratorChunk::Array:
371 case DeclaratorChunk::Reference:
372 case DeclaratorChunk::MemberPointer:
377 state.getSema().Diag(attr.getLoc(), diag::warn_function_attribute_wrong_type)
378 << attr.getName() << type;
381 /// Try to distribute a function type attribute to the innermost
382 /// function chunk or type. Returns true if the attribute was
383 /// distributed, false if no location was found.
385 distributeFunctionTypeAttrToInnermost(TypeProcessingState &state,
387 AttributeList *&attrList,
388 QualType &declSpecType) {
389 Declarator &declarator = state.getDeclarator();
391 // Put it on the innermost function chunk, if there is one.
392 for (unsigned i = 0, e = declarator.getNumTypeObjects(); i != e; ++i) {
393 DeclaratorChunk &chunk = declarator.getTypeObject(i);
394 if (chunk.Kind != DeclaratorChunk::Function) continue;
396 moveAttrFromListToList(attr, attrList, chunk.getAttrListRef());
400 return handleFunctionTypeAttr(state, attr, declSpecType);
403 /// A function type attribute was written in the decl spec. Try to
404 /// apply it somewhere.
406 distributeFunctionTypeAttrFromDeclSpec(TypeProcessingState &state,
408 QualType &declSpecType) {
409 state.saveDeclSpecAttrs();
411 // Try to distribute to the innermost.
412 if (distributeFunctionTypeAttrToInnermost(state, attr,
413 state.getCurrentAttrListRef(),
417 // If that failed, diagnose the bad attribute when the declarator is
419 state.addIgnoredTypeAttr(attr);
422 /// A function type attribute was written on the declarator. Try to
423 /// apply it somewhere.
425 distributeFunctionTypeAttrFromDeclarator(TypeProcessingState &state,
427 QualType &declSpecType) {
428 Declarator &declarator = state.getDeclarator();
430 // Try to distribute to the innermost.
431 if (distributeFunctionTypeAttrToInnermost(state, attr,
432 declarator.getAttrListRef(),
436 // If that failed, diagnose the bad attribute when the declarator is
438 spliceAttrOutOfList(attr, declarator.getAttrListRef());
439 state.addIgnoredTypeAttr(attr);
442 /// \brief Given that there are attributes written on the declarator
443 /// itself, try to distribute any type attributes to the appropriate
444 /// declarator chunk.
446 /// These are attributes like the following:
449 /// but not necessarily this:
451 static void distributeTypeAttrsFromDeclarator(TypeProcessingState &state,
452 QualType &declSpecType) {
453 // Collect all the type attributes from the declarator itself.
454 assert(state.getDeclarator().getAttributes() && "declarator has no attrs!");
455 AttributeList *attr = state.getDeclarator().getAttributes();
458 next = attr->getNext();
460 switch (attr->getKind()) {
461 OBJC_POINTER_TYPE_ATTRS_CASELIST:
462 distributeObjCPointerTypeAttrFromDeclarator(state, *attr, declSpecType);
465 FUNCTION_TYPE_ATTRS_CASELIST:
466 distributeFunctionTypeAttrFromDeclarator(state, *attr, declSpecType);
472 } while ((attr = next));
475 /// Add a synthetic '()' to a block-literal declarator if it is
476 /// required, given the return type.
477 static void maybeSynthesizeBlockSignature(TypeProcessingState &state,
478 QualType declSpecType) {
479 Declarator &declarator = state.getDeclarator();
481 // First, check whether the declarator would produce a function,
482 // i.e. whether the innermost semantic chunk is a function.
483 if (declarator.isFunctionDeclarator()) {
484 // If so, make that declarator a prototyped declarator.
485 declarator.getFunctionTypeInfo().hasPrototype = true;
489 // If there are any type objects, the type as written won't name a
490 // function, regardless of the decl spec type. This is because a
491 // block signature declarator is always an abstract-declarator, and
492 // abstract-declarators can't just be parentheses chunks. Therefore
493 // we need to build a function chunk unless there are no type
494 // objects and the decl spec type is a function.
495 if (!declarator.getNumTypeObjects() && declSpecType->isFunctionType())
498 // Note that there *are* cases with invalid declarators where
499 // declarators consist solely of parentheses. In general, these
500 // occur only in failed efforts to make function declarators, so
501 // faking up the function chunk is still the right thing to do.
503 // Otherwise, we need to fake up a function declarator.
504 SourceLocation loc = declarator.getSourceRange().getBegin();
506 // ...and *prepend* it to the declarator.
507 declarator.AddInnermostTypeInfo(DeclaratorChunk::getFunction(
510 /*variadic*/ false, SourceLocation(),
513 /*ref-qualifier*/true, SourceLocation(),
514 /*EH*/ false, SourceLocation(), false, 0, 0, 0,
518 // For consistency, make sure the state still has us as processing
520 assert(state.getCurrentChunkIndex() == declarator.getNumTypeObjects() - 1);
521 state.setCurrentChunkIndex(declarator.getNumTypeObjects());
524 /// \brief Convert the specified declspec to the appropriate type
526 /// \param D the declarator containing the declaration specifier.
527 /// \returns The type described by the declaration specifiers. This function
528 /// never returns null.
529 static QualType ConvertDeclSpecToType(Sema &S, TypeProcessingState &state) {
530 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
533 Declarator &declarator = state.getDeclarator();
534 const DeclSpec &DS = declarator.getDeclSpec();
535 SourceLocation DeclLoc = declarator.getIdentifierLoc();
536 if (DeclLoc.isInvalid())
537 DeclLoc = DS.getSourceRange().getBegin();
539 ASTContext &Context = S.Context;
542 switch (DS.getTypeSpecType()) {
543 case DeclSpec::TST_void:
544 Result = Context.VoidTy;
546 case DeclSpec::TST_char:
547 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
548 Result = Context.CharTy;
549 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
550 Result = Context.SignedCharTy;
552 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
553 "Unknown TSS value");
554 Result = Context.UnsignedCharTy;
557 case DeclSpec::TST_wchar:
558 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
559 Result = Context.WCharTy;
560 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
561 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
562 << DS.getSpecifierName(DS.getTypeSpecType());
563 Result = Context.getSignedWCharType();
565 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
566 "Unknown TSS value");
567 S.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
568 << DS.getSpecifierName(DS.getTypeSpecType());
569 Result = Context.getUnsignedWCharType();
572 case DeclSpec::TST_char16:
573 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
574 "Unknown TSS value");
575 Result = Context.Char16Ty;
577 case DeclSpec::TST_char32:
578 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
579 "Unknown TSS value");
580 Result = Context.Char32Ty;
582 case DeclSpec::TST_unspecified:
583 // "<proto1,proto2>" is an objc qualified ID with a missing id.
584 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
585 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
586 (ObjCProtocolDecl**)PQ,
587 DS.getNumProtocolQualifiers());
588 Result = Context.getObjCObjectPointerType(Result);
592 // If this is a missing declspec in a block literal return context, then it
593 // is inferred from the return statements inside the block.
594 if (isOmittedBlockReturnType(declarator)) {
595 Result = Context.DependentTy;
599 // Unspecified typespec defaults to int in C90. However, the C90 grammar
600 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
601 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
602 // Note that the one exception to this is function definitions, which are
603 // allowed to be completely missing a declspec. This is handled in the
604 // parser already though by it pretending to have seen an 'int' in this
606 if (S.getLangOptions().ImplicitInt) {
607 // In C89 mode, we only warn if there is a completely missing declspec
608 // when one is not allowed.
610 S.Diag(DeclLoc, diag::ext_missing_declspec)
611 << DS.getSourceRange()
612 << FixItHint::CreateInsertion(DS.getSourceRange().getBegin(), "int");
614 } else if (!DS.hasTypeSpecifier()) {
615 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
616 // "At least one type specifier shall be given in the declaration
617 // specifiers in each declaration, and in the specifier-qualifier list in
618 // each struct declaration and type name."
619 // FIXME: Does Microsoft really have the implicit int extension in C++?
620 if (S.getLangOptions().CPlusPlus &&
621 !S.getLangOptions().Microsoft) {
622 S.Diag(DeclLoc, diag::err_missing_type_specifier)
623 << DS.getSourceRange();
625 // When this occurs in C++ code, often something is very broken with the
626 // value being declared, poison it as invalid so we don't get chains of
628 declarator.setInvalidType(true);
630 S.Diag(DeclLoc, diag::ext_missing_type_specifier)
631 << DS.getSourceRange();
636 case DeclSpec::TST_int: {
637 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
638 switch (DS.getTypeSpecWidth()) {
639 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
640 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
641 case DeclSpec::TSW_long: Result = Context.LongTy; break;
642 case DeclSpec::TSW_longlong:
643 Result = Context.LongLongTy;
645 // long long is a C99 feature.
646 if (!S.getLangOptions().C99 &&
647 !S.getLangOptions().CPlusPlus0x)
648 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
652 switch (DS.getTypeSpecWidth()) {
653 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
654 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
655 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
656 case DeclSpec::TSW_longlong:
657 Result = Context.UnsignedLongLongTy;
659 // long long is a C99 feature.
660 if (!S.getLangOptions().C99 &&
661 !S.getLangOptions().CPlusPlus0x)
662 S.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
668 case DeclSpec::TST_float: Result = Context.FloatTy; break;
669 case DeclSpec::TST_double:
670 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
671 Result = Context.LongDoubleTy;
673 Result = Context.DoubleTy;
675 if (S.getLangOptions().OpenCL && !S.getOpenCLOptions().cl_khr_fp64) {
676 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_double_requires_fp64);
677 declarator.setInvalidType(true);
680 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
681 case DeclSpec::TST_decimal32: // _Decimal32
682 case DeclSpec::TST_decimal64: // _Decimal64
683 case DeclSpec::TST_decimal128: // _Decimal128
684 S.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
685 Result = Context.IntTy;
686 declarator.setInvalidType(true);
688 case DeclSpec::TST_class:
689 case DeclSpec::TST_enum:
690 case DeclSpec::TST_union:
691 case DeclSpec::TST_struct: {
692 TypeDecl *D = dyn_cast_or_null<TypeDecl>(DS.getRepAsDecl());
694 // This can happen in C++ with ambiguous lookups.
695 Result = Context.IntTy;
696 declarator.setInvalidType(true);
700 // If the type is deprecated or unavailable, diagnose it.
701 S.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
703 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
704 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
706 // TypeQuals handled by caller.
707 Result = Context.getTypeDeclType(D);
709 // In C++, make an ElaboratedType.
710 if (S.getLangOptions().CPlusPlus) {
711 ElaboratedTypeKeyword Keyword
712 = ElaboratedType::getKeywordForTypeSpec(DS.getTypeSpecType());
713 Result = S.getElaboratedType(Keyword, DS.getTypeSpecScope(), Result);
715 if (D->isInvalidDecl())
716 declarator.setInvalidType(true);
719 case DeclSpec::TST_typename: {
720 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
721 DS.getTypeSpecSign() == 0 &&
722 "Can't handle qualifiers on typedef names yet!");
723 Result = S.GetTypeFromParser(DS.getRepAsType());
725 declarator.setInvalidType(true);
726 else if (DeclSpec::ProtocolQualifierListTy PQ
727 = DS.getProtocolQualifiers()) {
728 if (const ObjCObjectType *ObjT = Result->getAs<ObjCObjectType>()) {
729 // Silently drop any existing protocol qualifiers.
730 // TODO: determine whether that's the right thing to do.
731 if (ObjT->getNumProtocols())
732 Result = ObjT->getBaseType();
734 if (DS.getNumProtocolQualifiers())
735 Result = Context.getObjCObjectType(Result,
736 (ObjCProtocolDecl**) PQ,
737 DS.getNumProtocolQualifiers());
738 } else if (Result->isObjCIdType()) {
740 Result = Context.getObjCObjectType(Context.ObjCBuiltinIdTy,
741 (ObjCProtocolDecl**) PQ,
742 DS.getNumProtocolQualifiers());
743 Result = Context.getObjCObjectPointerType(Result);
744 } else if (Result->isObjCClassType()) {
745 // Class<protocol-list>
746 Result = Context.getObjCObjectType(Context.ObjCBuiltinClassTy,
747 (ObjCProtocolDecl**) PQ,
748 DS.getNumProtocolQualifiers());
749 Result = Context.getObjCObjectPointerType(Result);
751 S.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
752 << DS.getSourceRange();
753 declarator.setInvalidType(true);
757 // TypeQuals handled by caller.
760 case DeclSpec::TST_typeofType:
761 // FIXME: Preserve type source info.
762 Result = S.GetTypeFromParser(DS.getRepAsType());
763 assert(!Result.isNull() && "Didn't get a type for typeof?");
764 if (!Result->isDependentType())
765 if (const TagType *TT = Result->getAs<TagType>())
766 S.DiagnoseUseOfDecl(TT->getDecl(), DS.getTypeSpecTypeLoc());
767 // TypeQuals handled by caller.
768 Result = Context.getTypeOfType(Result);
770 case DeclSpec::TST_typeofExpr: {
771 Expr *E = DS.getRepAsExpr();
772 assert(E && "Didn't get an expression for typeof?");
773 // TypeQuals handled by caller.
774 Result = S.BuildTypeofExprType(E, DS.getTypeSpecTypeLoc());
775 if (Result.isNull()) {
776 Result = Context.IntTy;
777 declarator.setInvalidType(true);
781 case DeclSpec::TST_decltype: {
782 Expr *E = DS.getRepAsExpr();
783 assert(E && "Didn't get an expression for decltype?");
784 // TypeQuals handled by caller.
785 Result = S.BuildDecltypeType(E, DS.getTypeSpecTypeLoc());
786 if (Result.isNull()) {
787 Result = Context.IntTy;
788 declarator.setInvalidType(true);
792 case DeclSpec::TST_auto: {
793 // TypeQuals handled by caller.
794 Result = Context.getAutoType(QualType());
798 case DeclSpec::TST_error:
799 Result = Context.IntTy;
800 declarator.setInvalidType(true);
804 // Handle complex types.
805 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
806 if (S.getLangOptions().Freestanding)
807 S.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
808 Result = Context.getComplexType(Result);
809 } else if (DS.isTypeAltiVecVector()) {
810 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result));
811 assert(typeSize > 0 && "type size for vector must be greater than 0 bits");
812 VectorType::VectorKind VecKind = VectorType::AltiVecVector;
813 if (DS.isTypeAltiVecPixel())
814 VecKind = VectorType::AltiVecPixel;
815 else if (DS.isTypeAltiVecBool())
816 VecKind = VectorType::AltiVecBool;
817 Result = Context.getVectorType(Result, 128/typeSize, VecKind);
821 if (DS.getTypeSpecComplex() == DeclSpec::TSC_imaginary)
822 S.Diag(DS.getTypeSpecComplexLoc(), diag::err_imaginary_not_supported);
824 // Before we process any type attributes, synthesize a block literal
825 // function declarator if necessary.
826 if (declarator.getContext() == Declarator::BlockLiteralContext)
827 maybeSynthesizeBlockSignature(state, Result);
829 // Apply any type attributes from the decl spec. This may cause the
830 // list of type attributes to be temporarily saved while the type
831 // attributes are pushed around.
832 if (AttributeList *attrs = DS.getAttributes().getList())
833 processTypeAttrs(state, Result, true, attrs);
835 // Apply const/volatile/restrict qualifiers to T.
836 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
838 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
839 // or incomplete types shall not be restrict-qualified." C++ also allows
840 // restrict-qualified references.
841 if (TypeQuals & DeclSpec::TQ_restrict) {
842 if (Result->isAnyPointerType() || Result->isReferenceType()) {
844 if (Result->isObjCObjectPointerType())
847 EltTy = Result->isPointerType() ?
848 Result->getAs<PointerType>()->getPointeeType() :
849 Result->getAs<ReferenceType>()->getPointeeType();
851 // If we have a pointer or reference, the pointee must have an object
853 if (!EltTy->isIncompleteOrObjectType()) {
854 S.Diag(DS.getRestrictSpecLoc(),
855 diag::err_typecheck_invalid_restrict_invalid_pointee)
856 << EltTy << DS.getSourceRange();
857 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
860 S.Diag(DS.getRestrictSpecLoc(),
861 diag::err_typecheck_invalid_restrict_not_pointer)
862 << Result << DS.getSourceRange();
863 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
867 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
868 // of a function type includes any type qualifiers, the behavior is
870 if (Result->isFunctionType() && TypeQuals) {
871 // Get some location to point at, either the C or V location.
873 if (TypeQuals & DeclSpec::TQ_const)
874 Loc = DS.getConstSpecLoc();
875 else if (TypeQuals & DeclSpec::TQ_volatile)
876 Loc = DS.getVolatileSpecLoc();
878 assert((TypeQuals & DeclSpec::TQ_restrict) &&
879 "Has CVR quals but not C, V, or R?");
880 Loc = DS.getRestrictSpecLoc();
882 S.Diag(Loc, diag::warn_typecheck_function_qualifiers)
883 << Result << DS.getSourceRange();
887 // Cv-qualified references are ill-formed except when the
888 // cv-qualifiers are introduced through the use of a typedef
889 // (7.1.3) or of a template type argument (14.3), in which
890 // case the cv-qualifiers are ignored.
891 // FIXME: Shouldn't we be checking SCS_typedef here?
892 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
893 TypeQuals && Result->isReferenceType()) {
894 TypeQuals &= ~DeclSpec::TQ_const;
895 TypeQuals &= ~DeclSpec::TQ_volatile;
898 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
899 Result = Context.getQualifiedType(Result, Quals);
905 static std::string getPrintableNameForEntity(DeclarationName Entity) {
907 return Entity.getAsString();
912 QualType Sema::BuildQualifiedType(QualType T, SourceLocation Loc,
914 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
915 // object or incomplete types shall not be restrict-qualified."
916 if (Qs.hasRestrict()) {
920 const Type *Ty = T->getCanonicalTypeInternal().getTypePtr();
921 if (const ReferenceType *RTy = dyn_cast<ReferenceType>(Ty)) {
922 if (!RTy->getPointeeType()->isIncompleteOrObjectType()) {
923 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
924 ProblemTy = T->getAs<ReferenceType>()->getPointeeType();
926 } else if (const PointerType *PTy = dyn_cast<PointerType>(Ty)) {
927 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
928 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
929 ProblemTy = T->getAs<PointerType>()->getPointeeType();
931 } else if (const MemberPointerType *PTy = dyn_cast<MemberPointerType>(Ty)) {
932 if (!PTy->getPointeeType()->isIncompleteOrObjectType()) {
933 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
934 ProblemTy = T->getAs<PointerType>()->getPointeeType();
936 } else if (!Ty->isDependentType()) {
937 // FIXME: this deserves a proper diagnostic
938 DiagID = diag::err_typecheck_invalid_restrict_invalid_pointee;
943 Diag(Loc, DiagID) << ProblemTy;
948 return Context.getQualifiedType(T, Qs);
951 /// \brief Build a paren type including \p T.
952 QualType Sema::BuildParenType(QualType T) {
953 return Context.getParenType(T);
956 /// \brief Build a pointer type.
958 /// \param T The type to which we'll be building a pointer.
960 /// \param Loc The location of the entity whose type involves this
961 /// pointer type or, if there is no such entity, the location of the
962 /// type that will have pointer type.
964 /// \param Entity The name of the entity that involves the pointer
967 /// \returns A suitable pointer type, if there are no
968 /// errors. Otherwise, returns a NULL type.
969 QualType Sema::BuildPointerType(QualType T,
970 SourceLocation Loc, DeclarationName Entity) {
971 if (T->isReferenceType()) {
972 // C++ 8.3.2p4: There shall be no ... pointers to references ...
973 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
974 << getPrintableNameForEntity(Entity) << T;
978 assert(!T->isObjCObjectType() && "Should build ObjCObjectPointerType");
980 // Build the pointer type.
981 return Context.getPointerType(T);
984 /// \brief Build a reference type.
986 /// \param T The type to which we'll be building a reference.
988 /// \param Loc The location of the entity whose type involves this
989 /// reference type or, if there is no such entity, the location of the
990 /// type that will have reference type.
992 /// \param Entity The name of the entity that involves the reference
995 /// \returns A suitable reference type, if there are no
996 /// errors. Otherwise, returns a NULL type.
997 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
999 DeclarationName Entity) {
1000 // C++0x [dcl.ref]p6:
1001 // If a typedef (7.1.3), a type template-parameter (14.3.1), or a
1002 // decltype-specifier (7.1.6.2) denotes a type TR that is a reference to a
1003 // type T, an attempt to create the type "lvalue reference to cv TR" creates
1004 // the type "lvalue reference to T", while an attempt to create the type
1005 // "rvalue reference to cv TR" creates the type TR.
1006 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
1008 // C++ [dcl.ref]p4: There shall be no references to references.
1010 // According to C++ DR 106, references to references are only
1011 // diagnosed when they are written directly (e.g., "int & &"),
1012 // but not when they happen via a typedef:
1014 // typedef int& intref;
1015 // typedef intref& intref2;
1017 // Parser::ParseDeclaratorInternal diagnoses the case where
1018 // references are written directly; here, we handle the
1019 // collapsing of references-to-references as described in C++0x.
1020 // DR 106 and 540 introduce reference-collapsing into C++98/03.
1023 // A declarator that specifies the type "reference to cv void"
1025 if (T->isVoidType()) {
1026 Diag(Loc, diag::err_reference_to_void);
1030 // Handle restrict on references.
1032 return Context.getLValueReferenceType(T, SpelledAsLValue);
1033 return Context.getRValueReferenceType(T);
1036 /// \brief Build an array type.
1038 /// \param T The type of each element in the array.
1040 /// \param ASM C99 array size modifier (e.g., '*', 'static').
1042 /// \param ArraySize Expression describing the size of the array.
1044 /// \param Loc The location of the entity whose type involves this
1045 /// array type or, if there is no such entity, the location of the
1046 /// type that will have array type.
1048 /// \param Entity The name of the entity that involves the array
1051 /// \returns A suitable array type, if there are no errors. Otherwise,
1052 /// returns a NULL type.
1053 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
1054 Expr *ArraySize, unsigned Quals,
1055 SourceRange Brackets, DeclarationName Entity) {
1057 SourceLocation Loc = Brackets.getBegin();
1058 if (getLangOptions().CPlusPlus) {
1059 // C++ [dcl.array]p1:
1060 // T is called the array element type; this type shall not be a reference
1061 // type, the (possibly cv-qualified) type void, a function type or an
1062 // abstract class type.
1064 // Note: function types are handled in the common path with C.
1065 if (T->isReferenceType()) {
1066 Diag(Loc, diag::err_illegal_decl_array_of_references)
1067 << getPrintableNameForEntity(Entity) << T;
1071 if (T->isVoidType()) {
1072 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
1076 if (RequireNonAbstractType(Brackets.getBegin(), T,
1077 diag::err_array_of_abstract_type))
1081 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
1082 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
1083 if (RequireCompleteType(Loc, T,
1084 diag::err_illegal_decl_array_incomplete_type))
1088 if (T->isFunctionType()) {
1089 Diag(Loc, diag::err_illegal_decl_array_of_functions)
1090 << getPrintableNameForEntity(Entity) << T;
1094 if (T->getContainedAutoType()) {
1095 Diag(Loc, diag::err_illegal_decl_array_of_auto)
1096 << getPrintableNameForEntity(Entity) << T;
1100 if (const RecordType *EltTy = T->getAs<RecordType>()) {
1101 // If the element type is a struct or union that contains a variadic
1102 // array, accept it as a GNU extension: C99 6.7.2.1p2.
1103 if (EltTy->getDecl()->hasFlexibleArrayMember())
1104 Diag(Loc, diag::ext_flexible_array_in_array) << T;
1105 } else if (T->isObjCObjectType()) {
1106 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
1110 // Do lvalue-to-rvalue conversions on the array size expression.
1111 if (ArraySize && !ArraySize->isRValue())
1112 DefaultLvalueConversion(ArraySize);
1114 // C99 6.7.5.2p1: The size expression shall have integer type.
1115 // TODO: in theory, if we were insane, we could allow contextual
1116 // conversions to integer type here.
1117 if (ArraySize && !ArraySize->isTypeDependent() &&
1118 !ArraySize->getType()->isIntegralOrUnscopedEnumerationType()) {
1119 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
1120 << ArraySize->getType() << ArraySize->getSourceRange();
1123 llvm::APSInt ConstVal(Context.getTypeSize(Context.getSizeType()));
1125 if (ASM == ArrayType::Star)
1126 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
1128 T = Context.getIncompleteArrayType(T, ASM, Quals);
1129 } else if (ArraySize->isTypeDependent() || ArraySize->isValueDependent()) {
1130 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
1131 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
1132 (!T->isDependentType() && !T->isIncompleteType() &&
1133 !T->isConstantSizeType())) {
1134 // Per C99, a variable array is an array with either a non-constant
1135 // size or an element type that has a non-constant-size
1136 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
1138 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
1139 // have a value greater than zero.
1140 if (ConstVal.isSigned() && ConstVal.isNegative()) {
1142 Diag(ArraySize->getLocStart(), diag::err_decl_negative_array_size)
1143 << getPrintableNameForEntity(Entity) << ArraySize->getSourceRange();
1145 Diag(ArraySize->getLocStart(), diag::err_typecheck_negative_array_size)
1146 << ArraySize->getSourceRange();
1149 if (ConstVal == 0) {
1150 // GCC accepts zero sized static arrays. We allow them when
1151 // we're not in a SFINAE context.
1152 Diag(ArraySize->getLocStart(),
1153 isSFINAEContext()? diag::err_typecheck_zero_array_size
1154 : diag::ext_typecheck_zero_array_size)
1155 << ArraySize->getSourceRange();
1156 } else if (!T->isDependentType() && !T->isVariablyModifiedType() &&
1157 !T->isIncompleteType()) {
1158 // Is the array too large?
1159 unsigned ActiveSizeBits
1160 = ConstantArrayType::getNumAddressingBits(Context, T, ConstVal);
1161 if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context))
1162 Diag(ArraySize->getLocStart(), diag::err_array_too_large)
1163 << ConstVal.toString(10)
1164 << ArraySize->getSourceRange();
1167 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
1169 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
1170 if (!getLangOptions().C99) {
1171 if (T->isVariableArrayType()) {
1172 // Prohibit the use of non-POD types in VLAs.
1173 if (!T->isDependentType() &&
1174 !Context.getBaseElementType(T)->isPODType()) {
1175 Diag(Loc, diag::err_vla_non_pod)
1176 << Context.getBaseElementType(T);
1179 // Prohibit the use of VLAs during template argument deduction.
1180 else if (isSFINAEContext()) {
1181 Diag(Loc, diag::err_vla_in_sfinae);
1184 // Just extwarn about VLAs.
1186 Diag(Loc, diag::ext_vla);
1187 } else if (ASM != ArrayType::Normal || Quals != 0)
1189 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
1190 : diag::ext_c99_array_usage);
1196 /// \brief Build an ext-vector type.
1198 /// Run the required checks for the extended vector type.
1199 QualType Sema::BuildExtVectorType(QualType T, Expr *ArraySize,
1200 SourceLocation AttrLoc) {
1201 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
1202 // in conjunction with complex types (pointers, arrays, functions, etc.).
1203 if (!T->isDependentType() &&
1204 !T->isIntegerType() && !T->isRealFloatingType()) {
1205 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
1209 if (!ArraySize->isTypeDependent() && !ArraySize->isValueDependent()) {
1210 llvm::APSInt vecSize(32);
1211 if (!ArraySize->isIntegerConstantExpr(vecSize, Context)) {
1212 Diag(AttrLoc, diag::err_attribute_argument_not_int)
1213 << "ext_vector_type" << ArraySize->getSourceRange();
1217 // unlike gcc's vector_size attribute, the size is specified as the
1218 // number of elements, not the number of bytes.
1219 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
1221 if (vectorSize == 0) {
1222 Diag(AttrLoc, diag::err_attribute_zero_size)
1223 << ArraySize->getSourceRange();
1227 if (!T->isDependentType())
1228 return Context.getExtVectorType(T, vectorSize);
1231 return Context.getDependentSizedExtVectorType(T, ArraySize, AttrLoc);
1234 /// \brief Build a function type.
1236 /// This routine checks the function type according to C++ rules and
1237 /// under the assumption that the result type and parameter types have
1238 /// just been instantiated from a template. It therefore duplicates
1239 /// some of the behavior of GetTypeForDeclarator, but in a much
1240 /// simpler form that is only suitable for this narrow use case.
1242 /// \param T The return type of the function.
1244 /// \param ParamTypes The parameter types of the function. This array
1245 /// will be modified to account for adjustments to the types of the
1246 /// function parameters.
1248 /// \param NumParamTypes The number of parameter types in ParamTypes.
1250 /// \param Variadic Whether this is a variadic function type.
1252 /// \param Quals The cvr-qualifiers to be applied to the function type.
1254 /// \param Loc The location of the entity whose type involves this
1255 /// function type or, if there is no such entity, the location of the
1256 /// type that will have function type.
1258 /// \param Entity The name of the entity that involves the function
1261 /// \returns A suitable function type, if there are no
1262 /// errors. Otherwise, returns a NULL type.
1263 QualType Sema::BuildFunctionType(QualType T,
1264 QualType *ParamTypes,
1265 unsigned NumParamTypes,
1266 bool Variadic, unsigned Quals,
1267 RefQualifierKind RefQualifier,
1268 SourceLocation Loc, DeclarationName Entity,
1269 FunctionType::ExtInfo Info) {
1270 if (T->isArrayType() || T->isFunctionType()) {
1271 Diag(Loc, diag::err_func_returning_array_function)
1272 << T->isFunctionType() << T;
1276 bool Invalid = false;
1277 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
1278 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
1279 if (ParamType->isVoidType()) {
1280 Diag(Loc, diag::err_param_with_void_type);
1284 ParamTypes[Idx] = ParamType;
1290 FunctionProtoType::ExtProtoInfo EPI;
1291 EPI.Variadic = Variadic;
1292 EPI.TypeQuals = Quals;
1293 EPI.RefQualifier = RefQualifier;
1296 return Context.getFunctionType(T, ParamTypes, NumParamTypes, EPI);
1299 /// \brief Build a member pointer type \c T Class::*.
1301 /// \param T the type to which the member pointer refers.
1302 /// \param Class the class type into which the member pointer points.
1303 /// \param CVR Qualifiers applied to the member pointer type
1304 /// \param Loc the location where this type begins
1305 /// \param Entity the name of the entity that will have this member pointer type
1307 /// \returns a member pointer type, if successful, or a NULL type if there was
1309 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
1311 DeclarationName Entity) {
1312 // Verify that we're not building a pointer to pointer to function with
1313 // exception specification.
1314 if (CheckDistantExceptionSpec(T)) {
1315 Diag(Loc, diag::err_distant_exception_spec);
1317 // FIXME: If we're doing this as part of template instantiation,
1318 // we should return immediately.
1320 // Build the type anyway, but use the canonical type so that the
1321 // exception specifiers are stripped off.
1322 T = Context.getCanonicalType(T);
1325 // C++ 8.3.3p3: A pointer to member shall not point to ... a member
1326 // with reference type, or "cv void."
1327 if (T->isReferenceType()) {
1328 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
1329 << (Entity? Entity.getAsString() : "type name") << T;
1333 if (T->isVoidType()) {
1334 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
1335 << (Entity? Entity.getAsString() : "type name");
1339 if (!Class->isDependentType() && !Class->isRecordType()) {
1340 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
1344 // In the Microsoft ABI, the class is allowed to be an incomplete
1345 // type. In such cases, the compiler makes a worst-case assumption.
1346 // We make no such assumption right now, so emit an error if the
1347 // class isn't a complete type.
1348 if (Context.Target.getCXXABI() == CXXABI_Microsoft &&
1349 RequireCompleteType(Loc, Class, diag::err_incomplete_type))
1352 return Context.getMemberPointerType(T, Class.getTypePtr());
1355 /// \brief Build a block pointer type.
1357 /// \param T The type to which we'll be building a block pointer.
1359 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
1361 /// \param Loc The location of the entity whose type involves this
1362 /// block pointer type or, if there is no such entity, the location of the
1363 /// type that will have block pointer type.
1365 /// \param Entity The name of the entity that involves the block pointer
1368 /// \returns A suitable block pointer type, if there are no
1369 /// errors. Otherwise, returns a NULL type.
1370 QualType Sema::BuildBlockPointerType(QualType T,
1372 DeclarationName Entity) {
1373 if (!T->isFunctionType()) {
1374 Diag(Loc, diag::err_nonfunction_block_type);
1378 return Context.getBlockPointerType(T);
1381 QualType Sema::GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo) {
1382 QualType QT = Ty.get();
1384 if (TInfo) *TInfo = 0;
1388 TypeSourceInfo *DI = 0;
1389 if (const LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
1390 QT = LIT->getType();
1391 DI = LIT->getTypeSourceInfo();
1394 if (TInfo) *TInfo = DI;
1398 /// GetTypeForDeclarator - Convert the type for the specified
1399 /// declarator to Type instances.
1401 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
1402 /// owns the declaration of a type (e.g., the definition of a struct
1403 /// type), then *OwnedDecl will receive the owned declaration.
1405 /// The result of this call will never be null, but the associated
1406 /// type may be a null type if there's an unrecoverable error.
1407 TypeSourceInfo *Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
1408 TagDecl **OwnedDecl,
1409 bool AutoAllowedInTypeName) {
1410 // Determine the type of the declarator. Not all forms of declarator
1413 TypeSourceInfo *ReturnTypeInfo = 0;
1415 TypeProcessingState state(*this, D);
1417 switch (D.getName().getKind()) {
1418 case UnqualifiedId::IK_Identifier:
1419 case UnqualifiedId::IK_OperatorFunctionId:
1420 case UnqualifiedId::IK_LiteralOperatorId:
1421 case UnqualifiedId::IK_TemplateId:
1422 T = ConvertDeclSpecToType(*this, state);
1424 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) {
1425 TagDecl* Owned = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1426 // Owned is embedded if it was defined here, or if it is the
1427 // very first (i.e., canonical) declaration of this tag type.
1428 Owned->setEmbeddedInDeclarator(Owned->isDefinition() ||
1429 Owned->isCanonicalDecl());
1430 if (OwnedDecl) *OwnedDecl = Owned;
1434 case UnqualifiedId::IK_ConstructorName:
1435 case UnqualifiedId::IK_ConstructorTemplateId:
1436 case UnqualifiedId::IK_DestructorName:
1437 // Constructors and destructors don't have return types. Use
1442 case UnqualifiedId::IK_ConversionFunctionId:
1443 // The result type of a conversion function is the type that it
1445 T = GetTypeFromParser(D.getName().ConversionFunctionId,
1450 if (D.getAttributes())
1451 distributeTypeAttrsFromDeclarator(state, T);
1453 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1454 !D.isFunctionDeclarator()) {
1457 switch (D.getContext()) {
1458 case Declarator::KNRTypeListContext:
1459 assert(0 && "K&R type lists aren't allowed in C++");
1461 case Declarator::PrototypeContext:
1462 Error = 0; // Function prototype
1464 case Declarator::MemberContext:
1465 switch (cast<TagDecl>(CurContext)->getTagKind()) {
1466 case TTK_Enum: assert(0 && "unhandled tag kind"); break;
1467 case TTK_Struct: Error = 1; /* Struct member */ break;
1468 case TTK_Union: Error = 2; /* Union member */ break;
1469 case TTK_Class: Error = 3; /* Class member */ break;
1472 case Declarator::CXXCatchContext:
1473 Error = 4; // Exception declaration
1475 case Declarator::TemplateParamContext:
1476 Error = 5; // Template parameter
1478 case Declarator::BlockLiteralContext:
1479 Error = 6; // Block literal
1481 case Declarator::TemplateTypeArgContext:
1482 Error = 7; // Template type argument
1484 case Declarator::TypeNameContext:
1485 if (!AutoAllowedInTypeName)
1486 Error = 8; // Generic
1488 case Declarator::FileContext:
1489 case Declarator::BlockContext:
1490 case Declarator::ForContext:
1491 case Declarator::ConditionContext:
1496 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
1499 D.setInvalidType(true);
1504 return Context.getNullTypeSourceInfo();
1506 // The name we're declaring, if any.
1507 DeclarationName Name;
1508 if (D.getIdentifier())
1509 Name = D.getIdentifier();
1511 // Walk the DeclTypeInfo, building the recursive type as we go.
1512 // DeclTypeInfos are ordered from the identifier out, which is
1513 // opposite of what we want :).
1514 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1515 unsigned chunkIndex = e - i - 1;
1516 state.setCurrentChunkIndex(chunkIndex);
1517 DeclaratorChunk &DeclType = D.getTypeObject(chunkIndex);
1518 switch (DeclType.Kind) {
1519 default: assert(0 && "Unknown decltype!");
1520 case DeclaratorChunk::Paren:
1521 T = BuildParenType(T);
1523 case DeclaratorChunk::BlockPointer:
1524 // If blocks are disabled, emit an error.
1525 if (!LangOpts.Blocks)
1526 Diag(DeclType.Loc, diag::err_blocks_disable);
1528 T = BuildBlockPointerType(T, D.getIdentifierLoc(), Name);
1529 if (DeclType.Cls.TypeQuals)
1530 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Cls.TypeQuals);
1532 case DeclaratorChunk::Pointer:
1533 // Verify that we're not building a pointer to pointer to function with
1534 // exception specification.
1535 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1536 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1537 D.setInvalidType(true);
1538 // Build the type anyway.
1540 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) {
1541 T = Context.getObjCObjectPointerType(T);
1542 if (DeclType.Ptr.TypeQuals)
1543 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1546 T = BuildPointerType(T, DeclType.Loc, Name);
1547 if (DeclType.Ptr.TypeQuals)
1548 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Ptr.TypeQuals);
1551 case DeclaratorChunk::Reference: {
1552 // Verify that we're not building a reference to pointer to function with
1553 // exception specification.
1554 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1555 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1556 D.setInvalidType(true);
1557 // Build the type anyway.
1559 T = BuildReferenceType(T, DeclType.Ref.LValueRef, DeclType.Loc, Name);
1562 if (DeclType.Ref.HasRestrict)
1563 T = BuildQualifiedType(T, DeclType.Loc, Qualifiers::Restrict);
1566 case DeclaratorChunk::Array: {
1567 // Verify that we're not building an array of pointers to function with
1568 // exception specification.
1569 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1570 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1571 D.setInvalidType(true);
1572 // Build the type anyway.
1574 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1575 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1576 ArrayType::ArraySizeModifier ASM;
1578 ASM = ArrayType::Star;
1579 else if (ATI.hasStatic)
1580 ASM = ArrayType::Static;
1582 ASM = ArrayType::Normal;
1583 if (ASM == ArrayType::Star &&
1584 D.getContext() != Declarator::PrototypeContext) {
1585 // FIXME: This check isn't quite right: it allows star in prototypes
1586 // for function definitions, and disallows some edge cases detailed
1587 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1588 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1589 ASM = ArrayType::Normal;
1590 D.setInvalidType(true);
1592 T = BuildArrayType(T, ASM, ArraySize,
1593 Qualifiers::fromCVRMask(ATI.TypeQuals),
1594 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1597 case DeclaratorChunk::Function: {
1598 // If the function declarator has a prototype (i.e. it is not () and
1599 // does not have a K&R-style identifier list), then the arguments are part
1600 // of the type, otherwise the argument list is ().
1601 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1603 // C99 6.7.5.3p1: The return type may not be a function or array type.
1604 // For conversion functions, we'll diagnose this particular error later.
1605 if ((T->isArrayType() || T->isFunctionType()) &&
1606 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) {
1607 unsigned diagID = diag::err_func_returning_array_function;
1608 // Last processing chunk in block context means this function chunk
1609 // represents the block.
1610 if (chunkIndex == 0 &&
1611 D.getContext() == Declarator::BlockLiteralContext)
1612 diagID = diag::err_block_returning_array_function;
1613 Diag(DeclType.Loc, diagID) << T->isFunctionType() << T;
1615 D.setInvalidType(true);
1618 // Check for auto functions and trailing return type and adjust the
1619 // return type accordingly.
1620 if (!D.isInvalidType()) {
1621 // trailing-return-type is only required if we're declaring a function,
1622 // and not, for instance, a pointer to a function.
1623 if (D.getDeclSpec().getTypeSpecType() == DeclSpec::TST_auto &&
1624 !FTI.TrailingReturnType && chunkIndex == 0) {
1625 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1626 diag::err_auto_missing_trailing_return);
1628 D.setInvalidType(true);
1629 } else if (FTI.TrailingReturnType) {
1630 if (T.hasQualifiers() || !isa<AutoType>(T)) {
1631 // T must be exactly 'auto' at this point. See CWG issue 681.
1632 Diag(D.getDeclSpec().getTypeSpecTypeLoc(),
1633 diag::err_trailing_return_without_auto)
1634 << T << D.getDeclSpec().getSourceRange();
1635 D.setInvalidType(true);
1638 T = GetTypeFromParser(
1639 ParsedType::getFromOpaquePtr(FTI.TrailingReturnType),
1644 // cv-qualifiers on return types are pointless except when the type is a
1645 // class type in C++.
1646 if (T.getCVRQualifiers() && D.getDeclSpec().getTypeQualifiers() &&
1647 (!getLangOptions().CPlusPlus ||
1648 (!T->isDependentType() && !T->isRecordType()))) {
1649 unsigned Quals = D.getDeclSpec().getTypeQualifiers();
1650 std::string QualStr;
1651 unsigned NumQuals = 0;
1653 if (Quals & Qualifiers::Const) {
1654 Loc = D.getDeclSpec().getConstSpecLoc();
1658 if (Quals & Qualifiers::Volatile) {
1659 if (NumQuals == 0) {
1660 Loc = D.getDeclSpec().getVolatileSpecLoc();
1661 QualStr = "volatile";
1663 QualStr += " volatile";
1666 if (Quals & Qualifiers::Restrict) {
1667 if (NumQuals == 0) {
1668 Loc = D.getDeclSpec().getRestrictSpecLoc();
1669 QualStr = "restrict";
1671 QualStr += " restrict";
1674 assert(NumQuals > 0 && "No known qualifiers?");
1676 SemaDiagnosticBuilder DB = Diag(Loc, diag::warn_qual_return_type);
1677 DB << QualStr << NumQuals;
1678 if (Quals & Qualifiers::Const)
1679 DB << FixItHint::CreateRemoval(D.getDeclSpec().getConstSpecLoc());
1680 if (Quals & Qualifiers::Volatile)
1681 DB << FixItHint::CreateRemoval(D.getDeclSpec().getVolatileSpecLoc());
1682 if (Quals & Qualifiers::Restrict)
1683 DB << FixItHint::CreateRemoval(D.getDeclSpec().getRestrictSpecLoc());
1686 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1688 // Types shall not be defined in return or parameter types.
1689 TagDecl *Tag = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
1690 if (Tag->isDefinition())
1691 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1692 << Context.getTypeDeclType(Tag);
1695 // Exception specs are not allowed in typedefs. Complain, but add it
1697 if (FTI.hasExceptionSpec &&
1698 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1699 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1701 if (!FTI.NumArgs && !FTI.isVariadic && !getLangOptions().CPlusPlus) {
1702 // Simple void foo(), where the incoming T is the result type.
1703 T = Context.getFunctionNoProtoType(T);
1705 // We allow a zero-parameter variadic function in C if the
1706 // function is marked with the "overloadable" attribute. Scan
1707 // for this attribute now.
1708 if (!FTI.NumArgs && FTI.isVariadic && !getLangOptions().CPlusPlus) {
1709 bool Overloadable = false;
1710 for (const AttributeList *Attrs = D.getAttributes();
1711 Attrs; Attrs = Attrs->getNext()) {
1712 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1713 Overloadable = true;
1719 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1722 if (FTI.NumArgs && FTI.ArgInfo[0].Param == 0) {
1723 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function
1725 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1726 D.setInvalidType(true);
1730 FunctionProtoType::ExtProtoInfo EPI;
1731 EPI.Variadic = FTI.isVariadic;
1732 EPI.TypeQuals = FTI.TypeQuals;
1733 EPI.RefQualifier = !FTI.hasRefQualifier()? RQ_None
1734 : FTI.RefQualifierIsLValueRef? RQ_LValue
1737 // Otherwise, we have a function with an argument list that is
1738 // potentially variadic.
1739 llvm::SmallVector<QualType, 16> ArgTys;
1740 ArgTys.reserve(FTI.NumArgs);
1742 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1743 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
1744 QualType ArgTy = Param->getType();
1745 assert(!ArgTy.isNull() && "Couldn't parse type?");
1747 // Adjust the parameter type.
1748 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1750 // Look for 'void'. void is allowed only as a single argument to a
1751 // function with no other parameters (C99 6.7.5.3p10). We record
1752 // int(void) as a FunctionProtoType with an empty argument list.
1753 if (ArgTy->isVoidType()) {
1754 // If this is something like 'float(int, void)', reject it. 'void'
1755 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1756 // have arguments of incomplete type.
1757 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1758 Diag(DeclType.Loc, diag::err_void_only_param);
1759 ArgTy = Context.IntTy;
1760 Param->setType(ArgTy);
1761 } else if (FTI.ArgInfo[i].Ident) {
1762 // Reject, but continue to parse 'int(void abc)'.
1763 Diag(FTI.ArgInfo[i].IdentLoc,
1764 diag::err_param_with_void_type);
1765 ArgTy = Context.IntTy;
1766 Param->setType(ArgTy);
1768 // Reject, but continue to parse 'float(const void)'.
1769 if (ArgTy.hasQualifiers())
1770 Diag(DeclType.Loc, diag::err_void_param_qualified);
1772 // Do not add 'void' to the ArgTys list.
1775 } else if (!FTI.hasPrototype) {
1776 if (ArgTy->isPromotableIntegerType()) {
1777 ArgTy = Context.getPromotedIntegerType(ArgTy);
1778 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1779 if (BTy->getKind() == BuiltinType::Float)
1780 ArgTy = Context.DoubleTy;
1784 ArgTys.push_back(ArgTy);
1787 llvm::SmallVector<QualType, 4> Exceptions;
1788 if (FTI.hasExceptionSpec) {
1789 EPI.HasExceptionSpec = FTI.hasExceptionSpec;
1790 EPI.HasAnyExceptionSpec = FTI.hasAnyExceptionSpec;
1791 Exceptions.reserve(FTI.NumExceptions);
1792 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1793 // FIXME: Preserve type source info.
1794 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1795 // Check that the type is valid for an exception spec, and
1797 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1798 Exceptions.push_back(ET);
1800 EPI.NumExceptions = Exceptions.size();
1801 EPI.Exceptions = Exceptions.data();
1804 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), EPI);
1809 case DeclaratorChunk::MemberPointer:
1810 // The scope spec must refer to a class, or be dependent.
1811 CXXScopeSpec &SS = DeclType.Mem.Scope();
1813 if (SS.isInvalid()) {
1814 // Avoid emitting extra errors if we already errored on the scope.
1815 D.setInvalidType(true);
1816 } else if (isDependentScopeSpecifier(SS) ||
1817 dyn_cast_or_null<CXXRecordDecl>(computeDeclContext(SS))) {
1818 NestedNameSpecifier *NNS
1819 = static_cast<NestedNameSpecifier*>(SS.getScopeRep());
1820 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1821 switch (NNS->getKind()) {
1822 case NestedNameSpecifier::Identifier:
1823 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix,
1824 NNS->getAsIdentifier());
1827 case NestedNameSpecifier::Namespace:
1828 case NestedNameSpecifier::Global:
1829 llvm_unreachable("Nested-name-specifier must name a type");
1832 case NestedNameSpecifier::TypeSpec:
1833 case NestedNameSpecifier::TypeSpecWithTemplate:
1834 ClsType = QualType(NNS->getAsType(), 0);
1835 // Note: if NNS is dependent, then its prefix (if any) is already
1836 // included in ClsType; this does not hold if the NNS is
1837 // nondependent: in this case (if there is indeed a prefix)
1838 // ClsType needs to be wrapped into an elaborated type.
1839 if (NNSPrefix && !NNS->isDependent())
1840 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType);
1844 Diag(DeclType.Mem.Scope().getBeginLoc(),
1845 diag::err_illegal_decl_mempointer_in_nonclass)
1846 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1847 << DeclType.Mem.Scope().getRange();
1848 D.setInvalidType(true);
1851 if (!ClsType.isNull())
1852 T = BuildMemberPointerType(T, ClsType, DeclType.Loc, D.getIdentifier());
1855 D.setInvalidType(true);
1856 } else if (DeclType.Mem.TypeQuals) {
1857 T = BuildQualifiedType(T, DeclType.Loc, DeclType.Mem.TypeQuals);
1863 D.setInvalidType(true);
1867 // See if there are any attributes on this declarator chunk.
1868 if (AttributeList *attrs = const_cast<AttributeList*>(DeclType.getAttrs()))
1869 processTypeAttrs(state, T, false, attrs);
1872 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1873 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1874 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1877 // A cv-qualifier-seq shall only be part of the function type
1878 // for a nonstatic member function, the function type to which a pointer
1879 // to member refers, or the top-level function type of a function typedef
1882 // Core issue 547 also allows cv-qualifiers on function types that are
1883 // top-level template type arguments.
1885 if (!D.getCXXScopeSpec().isSet()) {
1886 FreeFunction = (D.getContext() != Declarator::MemberContext ||
1887 D.getDeclSpec().isFriendSpecified());
1889 DeclContext *DC = computeDeclContext(D.getCXXScopeSpec());
1890 FreeFunction = (DC && !DC->isRecord());
1893 // C++0x [dcl.fct]p6:
1894 // A ref-qualifier shall only be part of the function type for a
1895 // non-static member function, the function type to which a pointer to
1896 // member refers, or the top-level function type of a function typedef
1898 if ((FnTy->getTypeQuals() != 0 || FnTy->getRefQualifier()) &&
1899 !(D.getContext() == Declarator::TemplateTypeArgContext &&
1900 !D.isFunctionDeclarator()) &&
1901 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1903 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1904 if (D.getContext() == Declarator::TemplateTypeArgContext) {
1905 // Accept qualified function types as template type arguments as a GNU
1906 // extension. This is also the subject of C++ core issue 547.
1908 if (FnTy->getTypeQuals() != 0)
1909 Quals = Qualifiers::fromCVRMask(FnTy->getTypeQuals()).getAsString();
1911 switch (FnTy->getRefQualifier()) {
1928 Diag(D.getIdentifierLoc(),
1929 diag::ext_qualified_function_type_template_arg)
1932 if (FnTy->getTypeQuals() != 0) {
1933 if (D.isFunctionDeclarator())
1934 Diag(D.getIdentifierLoc(),
1935 diag::err_invalid_qualified_function_type);
1937 Diag(D.getIdentifierLoc(),
1938 diag::err_invalid_qualified_typedef_function_type_use)
1942 if (FnTy->getRefQualifier()) {
1943 if (D.isFunctionDeclarator()) {
1944 SourceLocation Loc = D.getIdentifierLoc();
1945 for (unsigned I = 0, N = D.getNumTypeObjects(); I != N; ++I) {
1946 const DeclaratorChunk &Chunk = D.getTypeObject(N-I-1);
1947 if (Chunk.Kind == DeclaratorChunk::Function &&
1948 Chunk.Fun.hasRefQualifier()) {
1949 Loc = Chunk.Fun.getRefQualifierLoc();
1954 Diag(Loc, diag::err_invalid_ref_qualifier_function_type)
1955 << (FnTy->getRefQualifier() == RQ_LValue)
1956 << FixItHint::CreateRemoval(Loc);
1958 Diag(D.getIdentifierLoc(),
1959 diag::err_invalid_ref_qualifier_typedef_function_type_use)
1961 << (FnTy->getRefQualifier() == RQ_LValue);
1965 // Strip the cv-qualifiers and ref-qualifiers from the type.
1966 FunctionProtoType::ExtProtoInfo EPI = FnTy->getExtProtoInfo();
1968 EPI.RefQualifier = RQ_None;
1970 T = Context.getFunctionType(FnTy->getResultType(),
1971 FnTy->arg_type_begin(),
1972 FnTy->getNumArgs(), EPI);
1977 // Apply any undistributed attributes from the declarator.
1979 if (AttributeList *attrs = D.getAttributes())
1980 processTypeAttrs(state, T, false, attrs);
1982 // Diagnose any ignored type attributes.
1983 if (!T.isNull()) state.diagnoseIgnoredTypeAttrs(T);
1985 // If there's a constexpr specifier, treat it as a top-level const.
1986 if (D.getDeclSpec().isConstexprSpecified()) {
1990 // If there was an ellipsis in the declarator, the declaration declares a
1991 // parameter pack whose type may be a pack expansion type.
1992 if (D.hasEllipsis() && !T.isNull()) {
1993 // C++0x [dcl.fct]p13:
1994 // A declarator-id or abstract-declarator containing an ellipsis shall
1995 // only be used in a parameter-declaration. Such a parameter-declaration
1996 // is a parameter pack (14.5.3). [...]
1997 switch (D.getContext()) {
1998 case Declarator::PrototypeContext:
1999 // C++0x [dcl.fct]p13:
2000 // [...] When it is part of a parameter-declaration-clause, the
2001 // parameter pack is a function parameter pack (14.5.3). The type T
2002 // of the declarator-id of the function parameter pack shall contain
2003 // a template parameter pack; each template parameter pack in T is
2004 // expanded by the function parameter pack.
2006 // We represent function parameter packs as function parameters whose
2007 // type is a pack expansion.
2008 if (!T->containsUnexpandedParameterPack()) {
2009 Diag(D.getEllipsisLoc(),
2010 diag::err_function_parameter_pack_without_parameter_packs)
2011 << T << D.getSourceRange();
2012 D.setEllipsisLoc(SourceLocation());
2014 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2018 case Declarator::TemplateParamContext:
2019 // C++0x [temp.param]p15:
2020 // If a template-parameter is a [...] is a parameter-declaration that
2021 // declares a parameter pack (8.3.5), then the template-parameter is a
2022 // template parameter pack (14.5.3).
2024 // Note: core issue 778 clarifies that, if there are any unexpanded
2025 // parameter packs in the type of the non-type template parameter, then
2026 // it expands those parameter packs.
2027 if (T->containsUnexpandedParameterPack())
2028 T = Context.getPackExpansionType(T, llvm::Optional<unsigned>());
2029 else if (!getLangOptions().CPlusPlus0x)
2030 Diag(D.getEllipsisLoc(), diag::ext_variadic_templates);
2033 case Declarator::FileContext:
2034 case Declarator::KNRTypeListContext:
2035 case Declarator::TypeNameContext:
2036 case Declarator::MemberContext:
2037 case Declarator::BlockContext:
2038 case Declarator::ForContext:
2039 case Declarator::ConditionContext:
2040 case Declarator::CXXCatchContext:
2041 case Declarator::BlockLiteralContext:
2042 case Declarator::TemplateTypeArgContext:
2043 // FIXME: We may want to allow parameter packs in block-literal contexts
2045 Diag(D.getEllipsisLoc(), diag::err_ellipsis_in_declarator_not_parameter);
2046 D.setEllipsisLoc(SourceLocation());
2052 return Context.getNullTypeSourceInfo();
2053 else if (D.isInvalidType())
2054 return Context.getTrivialTypeSourceInfo(T);
2055 return GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo);
2059 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
2060 ASTContext &Context;
2064 TypeSpecLocFiller(ASTContext &Context, const DeclSpec &DS)
2065 : Context(Context), DS(DS) {}
2067 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2068 Visit(TL.getUnqualifiedLoc());
2070 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
2071 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2073 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
2074 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2076 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) {
2077 // Handle the base type, which might not have been written explicitly.
2078 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
2079 TL.setHasBaseTypeAsWritten(false);
2080 TL.getBaseLoc().initialize(Context, SourceLocation());
2082 TL.setHasBaseTypeAsWritten(true);
2083 Visit(TL.getBaseLoc());
2086 // Protocol qualifiers.
2087 if (DS.getProtocolQualifiers()) {
2088 assert(TL.getNumProtocols() > 0);
2089 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
2090 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
2091 TL.setRAngleLoc(DS.getSourceRange().getEnd());
2092 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
2093 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
2095 assert(TL.getNumProtocols() == 0);
2096 TL.setLAngleLoc(SourceLocation());
2097 TL.setRAngleLoc(SourceLocation());
2100 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2101 TL.setStarLoc(SourceLocation());
2102 Visit(TL.getPointeeLoc());
2104 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
2105 TypeSourceInfo *TInfo = 0;
2106 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2108 // If we got no declarator info from previous Sema routines,
2109 // just fill with the typespec loc.
2111 TL.initialize(Context, DS.getTypeSpecTypeLoc());
2115 TypeLoc OldTL = TInfo->getTypeLoc();
2116 if (TInfo->getType()->getAs<ElaboratedType>()) {
2117 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL);
2118 TemplateSpecializationTypeLoc NamedTL =
2119 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc());
2123 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL));
2125 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) {
2126 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr);
2127 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2128 TL.setParensRange(DS.getTypeofParensRange());
2130 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) {
2131 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType);
2132 TL.setTypeofLoc(DS.getTypeSpecTypeLoc());
2133 TL.setParensRange(DS.getTypeofParensRange());
2134 assert(DS.getRepAsType());
2135 TypeSourceInfo *TInfo = 0;
2136 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2137 TL.setUnderlyingTInfo(TInfo);
2139 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) {
2140 // By default, use the source location of the type specifier.
2141 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc());
2142 if (TL.needsExtraLocalData()) {
2143 // Set info for the written builtin specifiers.
2144 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs();
2145 // Try to have a meaningful source location.
2146 if (TL.getWrittenSignSpec() != TSS_unspecified)
2147 // Sign spec loc overrides the others (e.g., 'unsigned long').
2148 TL.setBuiltinLoc(DS.getTypeSpecSignLoc());
2149 else if (TL.getWrittenWidthSpec() != TSW_unspecified)
2150 // Width spec loc overrides type spec loc (e.g., 'short int').
2151 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc());
2154 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) {
2155 ElaboratedTypeKeyword Keyword
2156 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2157 if (DS.getTypeSpecType() == TST_typename) {
2158 TypeSourceInfo *TInfo = 0;
2159 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2161 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc()));
2165 TL.setKeywordLoc(Keyword != ETK_None
2166 ? DS.getTypeSpecTypeLoc()
2167 : SourceLocation());
2168 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2169 TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange());
2170 Visit(TL.getNextTypeLoc().getUnqualifiedLoc());
2172 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) {
2173 ElaboratedTypeKeyword Keyword
2174 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2175 if (DS.getTypeSpecType() == TST_typename) {
2176 TypeSourceInfo *TInfo = 0;
2177 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2179 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc()));
2183 TL.setKeywordLoc(Keyword != ETK_None
2184 ? DS.getTypeSpecTypeLoc()
2185 : SourceLocation());
2186 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2187 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange());
2188 // FIXME: load appropriate source location.
2189 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2191 void VisitDependentTemplateSpecializationTypeLoc(
2192 DependentTemplateSpecializationTypeLoc TL) {
2193 ElaboratedTypeKeyword Keyword
2194 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType());
2195 if (Keyword == ETK_Typename) {
2196 TypeSourceInfo *TInfo = 0;
2197 Sema::GetTypeFromParser(DS.getRepAsType(), &TInfo);
2199 TL.copy(cast<DependentTemplateSpecializationTypeLoc>(
2200 TInfo->getTypeLoc()));
2204 TL.initializeLocal(Context, SourceLocation());
2205 TL.setKeywordLoc(Keyword != ETK_None
2206 ? DS.getTypeSpecTypeLoc()
2207 : SourceLocation());
2208 const CXXScopeSpec& SS = DS.getTypeSpecScope();
2209 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange());
2210 // FIXME: load appropriate source location.
2211 TL.setNameLoc(DS.getTypeSpecTypeLoc());
2214 void VisitTypeLoc(TypeLoc TL) {
2215 // FIXME: add other typespec types and change this to an assert.
2216 TL.initialize(Context, DS.getTypeSpecTypeLoc());
2220 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
2221 const DeclaratorChunk &Chunk;
2224 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
2226 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
2227 llvm_unreachable("qualified type locs not expected here!");
2230 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
2231 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
2232 TL.setCaretLoc(Chunk.Loc);
2234 void VisitPointerTypeLoc(PointerTypeLoc TL) {
2235 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2236 TL.setStarLoc(Chunk.Loc);
2238 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
2239 assert(Chunk.Kind == DeclaratorChunk::Pointer);
2240 TL.setStarLoc(Chunk.Loc);
2242 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
2243 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
2244 TL.setStarLoc(Chunk.Loc);
2245 // FIXME: nested name specifier
2247 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
2248 assert(Chunk.Kind == DeclaratorChunk::Reference);
2249 // 'Amp' is misleading: this might have been originally
2250 /// spelled with AmpAmp.
2251 TL.setAmpLoc(Chunk.Loc);
2253 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
2254 assert(Chunk.Kind == DeclaratorChunk::Reference);
2255 assert(!Chunk.Ref.LValueRef);
2256 TL.setAmpAmpLoc(Chunk.Loc);
2258 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
2259 assert(Chunk.Kind == DeclaratorChunk::Array);
2260 TL.setLBracketLoc(Chunk.Loc);
2261 TL.setRBracketLoc(Chunk.EndLoc);
2262 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
2264 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
2265 assert(Chunk.Kind == DeclaratorChunk::Function);
2266 TL.setLParenLoc(Chunk.Loc);
2267 TL.setRParenLoc(Chunk.EndLoc);
2268 TL.setTrailingReturn(!!Chunk.Fun.TrailingReturnType);
2270 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
2271 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
2272 ParmVarDecl *Param = cast<ParmVarDecl>(FTI.ArgInfo[i].Param);
2273 TL.setArg(tpi++, Param);
2275 // FIXME: exception specs
2277 void VisitParenTypeLoc(ParenTypeLoc TL) {
2278 assert(Chunk.Kind == DeclaratorChunk::Paren);
2279 TL.setLParenLoc(Chunk.Loc);
2280 TL.setRParenLoc(Chunk.EndLoc);
2283 void VisitTypeLoc(TypeLoc TL) {
2284 llvm_unreachable("unsupported TypeLoc kind in declarator!");
2289 /// \brief Create and instantiate a TypeSourceInfo with type source information.
2291 /// \param T QualType referring to the type as written in source code.
2293 /// \param ReturnTypeInfo For declarators whose return type does not show
2294 /// up in the normal place in the declaration specifiers (such as a C++
2295 /// conversion function), this pointer will refer to a type source information
2296 /// for that return type.
2298 Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T,
2299 TypeSourceInfo *ReturnTypeInfo) {
2300 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T);
2301 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc();
2303 // Handle parameter packs whose type is a pack expansion.
2304 if (isa<PackExpansionType>(T)) {
2305 cast<PackExpansionTypeLoc>(CurrTL).setEllipsisLoc(D.getEllipsisLoc());
2306 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2309 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
2310 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
2311 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
2314 // If we have different source information for the return type, use
2315 // that. This really only applies to C++ conversion functions.
2316 if (ReturnTypeInfo) {
2317 TypeLoc TL = ReturnTypeInfo->getTypeLoc();
2318 assert(TL.getFullDataSize() == CurrTL.getFullDataSize());
2319 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize());
2321 TypeSpecLocFiller(Context, D.getDeclSpec()).Visit(CurrTL);
2327 /// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo.
2328 ParsedType Sema::CreateParsedType(QualType T, TypeSourceInfo *TInfo) {
2329 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
2330 // and Sema during declaration parsing. Try deallocating/caching them when
2331 // it's appropriate, instead of allocating them and keeping them around.
2332 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType),
2334 new (LocT) LocInfoType(T, TInfo);
2335 assert(LocT->getTypeClass() != T->getTypeClass() &&
2336 "LocInfoType's TypeClass conflicts with an existing Type class");
2337 return ParsedType::make(QualType(LocT, 0));
2340 void LocInfoType::getAsStringInternal(std::string &Str,
2341 const PrintingPolicy &Policy) const {
2342 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
2343 " was used directly instead of getting the QualType through"
2344 " GetTypeFromParser");
2347 TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
2348 // C99 6.7.6: Type names have no identifier. This is already validated by
2350 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
2352 TagDecl *OwnedTag = 0;
2353 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedTag);
2354 QualType T = TInfo->getType();
2355 if (D.isInvalidType())
2358 if (getLangOptions().CPlusPlus) {
2359 // Check that there are no default arguments (C++ only).
2360 CheckExtraCXXDefaultArguments(D);
2362 // C++0x [dcl.type]p3:
2363 // A type-specifier-seq shall not define a class or enumeration
2364 // unless it appears in the type-id of an alias-declaration
2366 if (OwnedTag && OwnedTag->isDefinition())
2367 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
2368 << Context.getTypeDeclType(OwnedTag);
2371 return CreateParsedType(T, TInfo);
2376 //===----------------------------------------------------------------------===//
2377 // Type Attribute Processing
2378 //===----------------------------------------------------------------------===//
2380 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
2381 /// specified type. The attribute contains 1 argument, the id of the address
2382 /// space for the type.
2383 static void HandleAddressSpaceTypeAttribute(QualType &Type,
2384 const AttributeList &Attr, Sema &S){
2386 // If this type is already address space qualified, reject it.
2387 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
2388 // for two or more different address spaces."
2389 if (Type.getAddressSpace()) {
2390 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
2395 // Check the attribute arguments.
2396 if (Attr.getNumArgs() != 1) {
2397 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2401 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
2402 llvm::APSInt addrSpace(32);
2403 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() ||
2404 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
2405 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
2406 << ASArgExpr->getSourceRange();
2412 if (addrSpace.isSigned()) {
2413 if (addrSpace.isNegative()) {
2414 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
2415 << ASArgExpr->getSourceRange();
2419 addrSpace.setIsSigned(false);
2421 llvm::APSInt max(addrSpace.getBitWidth());
2422 max = Qualifiers::MaxAddressSpace;
2423 if (addrSpace > max) {
2424 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
2425 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
2430 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
2431 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
2434 /// handleObjCGCTypeAttr - Process the __attribute__((objc_gc)) type
2435 /// attribute on the specified type. Returns true to indicate that
2436 /// the attribute was handled, false to indicate that the type does
2437 /// not permit the attribute.
2438 static bool handleObjCGCTypeAttr(TypeProcessingState &state,
2439 AttributeList &attr,
2441 Sema &S = state.getSema();
2443 // Delay if this isn't some kind of pointer.
2444 if (!type->isPointerType() &&
2445 !type->isObjCObjectPointerType() &&
2446 !type->isBlockPointerType())
2449 if (type.getObjCGCAttr() != Qualifiers::GCNone) {
2450 S.Diag(attr.getLoc(), diag::err_attribute_multiple_objc_gc);
2455 // Check the attribute arguments.
2456 if (!attr.getParameterName()) {
2457 S.Diag(attr.getLoc(), diag::err_attribute_argument_n_not_string)
2462 Qualifiers::GC GCAttr;
2463 if (attr.getNumArgs() != 0) {
2464 S.Diag(attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2468 if (attr.getParameterName()->isStr("weak"))
2469 GCAttr = Qualifiers::Weak;
2470 else if (attr.getParameterName()->isStr("strong"))
2471 GCAttr = Qualifiers::Strong;
2473 S.Diag(attr.getLoc(), diag::warn_attribute_type_not_supported)
2474 << "objc_gc" << attr.getParameterName();
2479 type = S.Context.getObjCGCQualType(type, GCAttr);
2484 /// A helper class to unwrap a type down to a function for the
2485 /// purposes of applying attributes there.
2488 /// FunctionTypeUnwrapper unwrapped(SemaRef, T);
2489 /// if (unwrapped.isFunctionType()) {
2490 /// const FunctionType *fn = unwrapped.get();
2491 /// // change fn somehow
2492 /// T = unwrapped.wrap(fn);
2494 struct FunctionTypeUnwrapper {
2505 const FunctionType *Fn;
2506 llvm::SmallVector<unsigned char /*WrapKind*/, 8> Stack;
2508 FunctionTypeUnwrapper(Sema &S, QualType T) : Original(T) {
2510 const Type *Ty = T.getTypePtr();
2511 if (isa<FunctionType>(Ty)) {
2512 Fn = cast<FunctionType>(Ty);
2514 } else if (isa<ParenType>(Ty)) {
2515 T = cast<ParenType>(Ty)->getInnerType();
2516 Stack.push_back(Parens);
2517 } else if (isa<PointerType>(Ty)) {
2518 T = cast<PointerType>(Ty)->getPointeeType();
2519 Stack.push_back(Pointer);
2520 } else if (isa<BlockPointerType>(Ty)) {
2521 T = cast<BlockPointerType>(Ty)->getPointeeType();
2522 Stack.push_back(BlockPointer);
2523 } else if (isa<MemberPointerType>(Ty)) {
2524 T = cast<MemberPointerType>(Ty)->getPointeeType();
2525 Stack.push_back(MemberPointer);
2526 } else if (isa<ReferenceType>(Ty)) {
2527 T = cast<ReferenceType>(Ty)->getPointeeType();
2528 Stack.push_back(Reference);
2530 const Type *DTy = Ty->getUnqualifiedDesugaredType();
2536 T = QualType(DTy, 0);
2537 Stack.push_back(Desugar);
2542 bool isFunctionType() const { return (Fn != 0); }
2543 const FunctionType *get() const { return Fn; }
2545 QualType wrap(Sema &S, const FunctionType *New) {
2546 // If T wasn't modified from the unwrapped type, do nothing.
2547 if (New == get()) return Original;
2550 return wrap(S.Context, Original, 0);
2554 QualType wrap(ASTContext &C, QualType Old, unsigned I) {
2555 if (I == Stack.size())
2556 return C.getQualifiedType(Fn, Old.getQualifiers());
2558 // Build up the inner type, applying the qualifiers from the old
2559 // type to the new type.
2560 SplitQualType SplitOld = Old.split();
2562 // As a special case, tail-recurse if there are no qualifiers.
2563 if (SplitOld.second.empty())
2564 return wrap(C, SplitOld.first, I);
2565 return C.getQualifiedType(wrap(C, SplitOld.first, I), SplitOld.second);
2568 QualType wrap(ASTContext &C, const Type *Old, unsigned I) {
2569 if (I == Stack.size()) return QualType(Fn, 0);
2571 switch (static_cast<WrapKind>(Stack[I++])) {
2573 // This is the point at which we potentially lose source
2575 return wrap(C, Old->getUnqualifiedDesugaredType(), I);
2578 QualType New = wrap(C, cast<ParenType>(Old)->getInnerType(), I);
2579 return C.getParenType(New);
2583 QualType New = wrap(C, cast<PointerType>(Old)->getPointeeType(), I);
2584 return C.getPointerType(New);
2587 case BlockPointer: {
2588 QualType New = wrap(C, cast<BlockPointerType>(Old)->getPointeeType(),I);
2589 return C.getBlockPointerType(New);
2592 case MemberPointer: {
2593 const MemberPointerType *OldMPT = cast<MemberPointerType>(Old);
2594 QualType New = wrap(C, OldMPT->getPointeeType(), I);
2595 return C.getMemberPointerType(New, OldMPT->getClass());
2599 const ReferenceType *OldRef = cast<ReferenceType>(Old);
2600 QualType New = wrap(C, OldRef->getPointeeType(), I);
2601 if (isa<LValueReferenceType>(OldRef))
2602 return C.getLValueReferenceType(New, OldRef->isSpelledAsLValue());
2604 return C.getRValueReferenceType(New);
2608 llvm_unreachable("unknown wrapping kind");
2614 /// Process an individual function attribute. Returns true to
2615 /// indicate that the attribute was handled, false if it wasn't.
2616 static bool handleFunctionTypeAttr(TypeProcessingState &state,
2617 AttributeList &attr,
2619 Sema &S = state.getSema();
2621 FunctionTypeUnwrapper unwrapped(S, type);
2623 if (attr.getKind() == AttributeList::AT_noreturn) {
2624 if (S.CheckNoReturnAttr(attr))
2627 // Delay if this is not a function type.
2628 if (!unwrapped.isFunctionType())
2631 // Otherwise we can process right away.
2632 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withNoReturn(true);
2633 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2637 if (attr.getKind() == AttributeList::AT_regparm) {
2639 if (S.CheckRegparmAttr(attr, value))
2642 // Delay if this is not a function type.
2643 if (!unwrapped.isFunctionType())
2646 // Diagnose regparm with fastcall.
2647 const FunctionType *fn = unwrapped.get();
2648 CallingConv CC = fn->getCallConv();
2649 if (CC == CC_X86FastCall) {
2650 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2651 << FunctionType::getNameForCallConv(CC)
2657 FunctionType::ExtInfo EI =
2658 unwrapped.get()->getExtInfo().withRegParm(value);
2659 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2663 // Otherwise, a calling convention.
2665 if (S.CheckCallingConvAttr(attr, CC))
2668 // Delay if the type didn't work out to a function.
2669 if (!unwrapped.isFunctionType()) return false;
2671 const FunctionType *fn = unwrapped.get();
2672 CallingConv CCOld = fn->getCallConv();
2673 if (S.Context.getCanonicalCallConv(CC) ==
2674 S.Context.getCanonicalCallConv(CCOld)) {
2675 FunctionType::ExtInfo EI= unwrapped.get()->getExtInfo().withCallingConv(CC);
2676 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2680 if (CCOld != CC_Default) {
2681 // Should we diagnose reapplications of the same convention?
2682 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2683 << FunctionType::getNameForCallConv(CC)
2684 << FunctionType::getNameForCallConv(CCOld);
2689 // Diagnose the use of X86 fastcall on varargs or unprototyped functions.
2690 if (CC == CC_X86FastCall) {
2691 if (isa<FunctionNoProtoType>(fn)) {
2692 S.Diag(attr.getLoc(), diag::err_cconv_knr)
2693 << FunctionType::getNameForCallConv(CC);
2698 const FunctionProtoType *FnP = cast<FunctionProtoType>(fn);
2699 if (FnP->isVariadic()) {
2700 S.Diag(attr.getLoc(), diag::err_cconv_varargs)
2701 << FunctionType::getNameForCallConv(CC);
2706 // Also diagnose fastcall with regparm.
2707 if (fn->getRegParmType()) {
2708 S.Diag(attr.getLoc(), diag::err_attributes_are_not_compatible)
2710 << FunctionType::getNameForCallConv(CC);
2716 FunctionType::ExtInfo EI = unwrapped.get()->getExtInfo().withCallingConv(CC);
2717 type = unwrapped.wrap(S, S.Context.adjustFunctionType(unwrapped.get(), EI));
2721 /// HandleVectorSizeAttribute - this attribute is only applicable to integral
2722 /// and float scalars, although arrays, pointers, and function return values are
2723 /// allowed in conjunction with this construct. Aggregates with this attribute
2724 /// are invalid, even if they are of the same size as a corresponding scalar.
2725 /// The raw attribute should contain precisely 1 argument, the vector size for
2726 /// the variable, measured in bytes. If curType and rawAttr are well formed,
2727 /// this routine will return a new vector type.
2728 static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr,
2730 // Check the attribute arguments.
2731 if (Attr.getNumArgs() != 1) {
2732 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2736 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0));
2737 llvm::APSInt vecSize(32);
2738 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() ||
2739 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) {
2740 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2741 << "vector_size" << sizeExpr->getSourceRange();
2745 // the base type must be integer or float, and can't already be a vector.
2746 if (!CurType->isIntegerType() && !CurType->isRealFloatingType()) {
2747 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType;
2751 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
2752 // vecSize is specified in bytes - convert to bits.
2753 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8);
2755 // the vector size needs to be an integral multiple of the type size.
2756 if (vectorSize % typeSize) {
2757 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size)
2758 << sizeExpr->getSourceRange();
2762 if (vectorSize == 0) {
2763 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size)
2764 << sizeExpr->getSourceRange();
2769 // Success! Instantiate the vector type, the number of elements is > 0, and
2770 // not required to be a power of 2, unlike GCC.
2771 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize,
2772 VectorType::GenericVector);
2775 /// HandleNeonVectorTypeAttr - The "neon_vector_type" and
2776 /// "neon_polyvector_type" attributes are used to create vector types that
2777 /// are mangled according to ARM's ABI. Otherwise, these types are identical
2778 /// to those created with the "vector_size" attribute. Unlike "vector_size"
2779 /// the argument to these Neon attributes is the number of vector elements,
2780 /// not the vector size in bytes. The vector width and element type must
2781 /// match one of the standard Neon vector types.
2782 static void HandleNeonVectorTypeAttr(QualType& CurType,
2783 const AttributeList &Attr, Sema &S,
2784 VectorType::VectorKind VecKind,
2785 const char *AttrName) {
2786 // Check the attribute arguments.
2787 if (Attr.getNumArgs() != 1) {
2788 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
2792 // The number of elements must be an ICE.
2793 Expr *numEltsExpr = static_cast<Expr *>(Attr.getArg(0));
2794 llvm::APSInt numEltsInt(32);
2795 if (numEltsExpr->isTypeDependent() || numEltsExpr->isValueDependent() ||
2796 !numEltsExpr->isIntegerConstantExpr(numEltsInt, S.Context)) {
2797 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int)
2798 << AttrName << numEltsExpr->getSourceRange();
2802 // Only certain element types are supported for Neon vectors.
2803 const BuiltinType* BTy = CurType->getAs<BuiltinType>();
2805 (VecKind == VectorType::NeonPolyVector &&
2806 BTy->getKind() != BuiltinType::SChar &&
2807 BTy->getKind() != BuiltinType::Short) ||
2808 (BTy->getKind() != BuiltinType::SChar &&
2809 BTy->getKind() != BuiltinType::UChar &&
2810 BTy->getKind() != BuiltinType::Short &&
2811 BTy->getKind() != BuiltinType::UShort &&
2812 BTy->getKind() != BuiltinType::Int &&
2813 BTy->getKind() != BuiltinType::UInt &&
2814 BTy->getKind() != BuiltinType::LongLong &&
2815 BTy->getKind() != BuiltinType::ULongLong &&
2816 BTy->getKind() != BuiltinType::Float)) {
2817 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) <<CurType;
2821 // The total size of the vector must be 64 or 128 bits.
2822 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType));
2823 unsigned numElts = static_cast<unsigned>(numEltsInt.getZExtValue());
2824 unsigned vecSize = typeSize * numElts;
2825 if (vecSize != 64 && vecSize != 128) {
2826 S.Diag(Attr.getLoc(), diag::err_attribute_bad_neon_vector_size) << CurType;
2831 CurType = S.Context.getVectorType(CurType, numElts, VecKind);
2834 static void processTypeAttrs(TypeProcessingState &state, QualType &type,
2835 bool isDeclSpec, AttributeList *attrs) {
2836 // Scan through and apply attributes to this type where it makes sense. Some
2837 // attributes (such as __address_space__, __vector_size__, etc) apply to the
2838 // type, but others can be present in the type specifiers even though they
2839 // apply to the decl. Here we apply type attributes and ignore the rest.
2841 AttributeList *next;
2843 AttributeList &attr = *attrs;
2844 next = attr.getNext();
2846 // Skip attributes that were marked to be invalid.
2847 if (attr.isInvalid())
2850 // If this is an attribute we can handle, do so now,
2851 // otherwise, add it to the FnAttrs list for rechaining.
2852 switch (attr.getKind()) {
2855 case AttributeList::AT_address_space:
2856 HandleAddressSpaceTypeAttribute(type, attr, state.getSema());
2858 OBJC_POINTER_TYPE_ATTRS_CASELIST:
2859 if (!handleObjCPointerTypeAttr(state, attr, type))
2860 distributeObjCPointerTypeAttr(state, attr, type);
2862 case AttributeList::AT_vector_size:
2863 HandleVectorSizeAttr(type, attr, state.getSema());
2865 case AttributeList::AT_neon_vector_type:
2866 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
2867 VectorType::NeonVector, "neon_vector_type");
2869 case AttributeList::AT_neon_polyvector_type:
2870 HandleNeonVectorTypeAttr(type, attr, state.getSema(),
2871 VectorType::NeonPolyVector,
2872 "neon_polyvector_type");
2875 FUNCTION_TYPE_ATTRS_CASELIST:
2876 // Never process function type attributes as part of the
2877 // declaration-specifiers.
2879 distributeFunctionTypeAttrFromDeclSpec(state, attr, type);
2881 // Otherwise, handle the possible delays.
2882 else if (!handleFunctionTypeAttr(state, attr, type))
2883 distributeFunctionTypeAttr(state, attr, type);
2886 } while ((attrs = next));
2889 /// @brief Ensure that the type T is a complete type.
2891 /// This routine checks whether the type @p T is complete in any
2892 /// context where a complete type is required. If @p T is a complete
2893 /// type, returns false. If @p T is a class template specialization,
2894 /// this routine then attempts to perform class template
2895 /// instantiation. If instantiation fails, or if @p T is incomplete
2896 /// and cannot be completed, issues the diagnostic @p diag (giving it
2897 /// the type @p T) and returns true.
2899 /// @param Loc The location in the source that the incomplete type
2900 /// diagnostic should refer to.
2902 /// @param T The type that this routine is examining for completeness.
2904 /// @param PD The partial diagnostic that will be printed out if T is not a
2907 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
2908 /// @c false otherwise.
2909 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2910 const PartialDiagnostic &PD,
2911 std::pair<SourceLocation,
2912 PartialDiagnostic> Note) {
2913 unsigned diag = PD.getDiagID();
2915 // FIXME: Add this assertion to make sure we always get instantiation points.
2916 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
2917 // FIXME: Add this assertion to help us flush out problems with
2918 // checking for dependent types and type-dependent expressions.
2920 // assert(!T->isDependentType() &&
2921 // "Can't ask whether a dependent type is complete");
2923 // If we have a complete type, we're done.
2924 if (!T->isIncompleteType())
2927 // If we have a class template specialization or a class member of a
2928 // class template specialization, or an array with known size of such,
2929 // try to instantiate it.
2930 QualType MaybeTemplate = T;
2931 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
2932 MaybeTemplate = Array->getElementType();
2933 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
2934 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
2935 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
2936 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
2937 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
2938 TSK_ImplicitInstantiation,
2939 /*Complain=*/diag != 0);
2940 } else if (CXXRecordDecl *Rec
2941 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
2942 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
2943 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
2944 assert(MSInfo && "Missing member specialization information?");
2945 // This record was instantiated from a class within a template.
2946 if (MSInfo->getTemplateSpecializationKind()
2947 != TSK_ExplicitSpecialization)
2948 return InstantiateClass(Loc, Rec, Pattern,
2949 getTemplateInstantiationArgs(Rec),
2950 TSK_ImplicitInstantiation,
2951 /*Complain=*/diag != 0);
2959 const TagType *Tag = T->getAs<TagType>();
2961 // Avoid diagnosing invalid decls as incomplete.
2962 if (Tag && Tag->getDecl()->isInvalidDecl())
2965 // Give the external AST source a chance to complete the type.
2966 if (Tag && Tag->getDecl()->hasExternalLexicalStorage()) {
2967 Context.getExternalSource()->CompleteType(Tag->getDecl());
2968 if (!Tag->isIncompleteType())
2972 // We have an incomplete type. Produce a diagnostic.
2975 // If we have a note, produce it.
2976 if (!Note.first.isInvalid())
2977 Diag(Note.first, Note.second);
2979 // If the type was a forward declaration of a class/struct/union
2980 // type, produce a note.
2981 if (Tag && !Tag->getDecl()->isInvalidDecl())
2982 Diag(Tag->getDecl()->getLocation(),
2983 Tag->isBeingDefined() ? diag::note_type_being_defined
2984 : diag::note_forward_declaration)
2985 << QualType(Tag, 0);
2990 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2991 const PartialDiagnostic &PD) {
2992 return RequireCompleteType(Loc, T, PD,
2993 std::make_pair(SourceLocation(), PDiag(0)));
2996 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
2998 return RequireCompleteType(Loc, T, PDiag(DiagID),
2999 std::make_pair(SourceLocation(), PDiag(0)));
3002 /// \brief Retrieve a version of the type 'T' that is elaborated by Keyword
3003 /// and qualified by the nested-name-specifier contained in SS.
3004 QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword,
3005 const CXXScopeSpec &SS, QualType T) {
3008 NestedNameSpecifier *NNS;
3010 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
3012 if (Keyword == ETK_None)
3016 return Context.getElaboratedType(Keyword, NNS, T);
3019 QualType Sema::BuildTypeofExprType(Expr *E, SourceLocation Loc) {
3020 ExprResult ER = CheckPlaceholderExpr(E, Loc);
3021 if (ER.isInvalid()) return QualType();
3024 if (!E->isTypeDependent()) {
3025 QualType T = E->getType();
3026 if (const TagType *TT = T->getAs<TagType>())
3027 DiagnoseUseOfDecl(TT->getDecl(), E->getExprLoc());
3029 return Context.getTypeOfExprType(E);
3032 QualType Sema::BuildDecltypeType(Expr *E, SourceLocation Loc) {
3033 ExprResult ER = CheckPlaceholderExpr(E, Loc);
3034 if (ER.isInvalid()) return QualType();
3037 return Context.getDecltypeType(E);