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 //===----------------------------------------------------------------------===//
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CXXInheritance.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/AST/TypeLoc.h"
20 #include "clang/AST/TypeLocVisitor.h"
21 #include "clang/AST/Expr.h"
22 #include "clang/Basic/PartialDiagnostic.h"
23 #include "clang/Parse/DeclSpec.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/Support/ErrorHandling.h"
26 using namespace clang;
28 /// \brief Perform adjustment on the parameter type of a function.
30 /// This routine adjusts the given parameter type @p T to the actual
31 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
32 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
33 QualType Sema::adjustParameterType(QualType T) {
35 // A declaration of a parameter as "array of type" shall be
36 // adjusted to "qualified pointer to type", where the type
37 // qualifiers (if any) are those specified within the [ and ] of
38 // the array type derivation.
40 return Context.getArrayDecayedType(T);
43 // A declaration of a parameter as "function returning type"
44 // shall be adjusted to "pointer to function returning type", as
46 if (T->isFunctionType())
47 return Context.getPointerType(T);
54 /// isOmittedBlockReturnType - Return true if this declarator is missing a
55 /// return type because this is a omitted return type on a block literal.
56 static bool isOmittedBlockReturnType(const Declarator &D) {
57 if (D.getContext() != Declarator::BlockLiteralContext ||
58 D.getDeclSpec().hasTypeSpecifier())
61 if (D.getNumTypeObjects() == 0)
62 return true; // ^{ ... }
64 if (D.getNumTypeObjects() == 1 &&
65 D.getTypeObject(0).Kind == DeclaratorChunk::Function)
66 return true; // ^(int X, float Y) { ... }
71 /// \brief Convert the specified declspec to the appropriate type
73 /// \param D the declarator containing the declaration specifier.
74 /// \returns The type described by the declaration specifiers. This function
75 /// never returns null.
76 static QualType ConvertDeclSpecToType(Declarator &TheDeclarator, Sema &TheSema){
77 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
79 const DeclSpec &DS = TheDeclarator.getDeclSpec();
80 SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc();
81 if (DeclLoc.isInvalid())
82 DeclLoc = DS.getSourceRange().getBegin();
84 ASTContext &Context = TheSema.Context;
87 switch (DS.getTypeSpecType()) {
88 case DeclSpec::TST_void:
89 Result = Context.VoidTy;
91 case DeclSpec::TST_char:
92 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
93 Result = Context.CharTy;
94 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
95 Result = Context.SignedCharTy;
97 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
99 Result = Context.UnsignedCharTy;
102 case DeclSpec::TST_wchar:
103 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
104 Result = Context.WCharTy;
105 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
106 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
107 << DS.getSpecifierName(DS.getTypeSpecType());
108 Result = Context.getSignedWCharType();
110 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
111 "Unknown TSS value");
112 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
113 << DS.getSpecifierName(DS.getTypeSpecType());
114 Result = Context.getUnsignedWCharType();
117 case DeclSpec::TST_char16:
118 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
119 "Unknown TSS value");
120 Result = Context.Char16Ty;
122 case DeclSpec::TST_char32:
123 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified &&
124 "Unknown TSS value");
125 Result = Context.Char32Ty;
127 case DeclSpec::TST_unspecified:
128 // "<proto1,proto2>" is an objc qualified ID with a missing id.
129 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
130 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
131 (ObjCProtocolDecl**)PQ,
132 DS.getNumProtocolQualifiers());
136 // If this is a missing declspec in a block literal return context, then it
137 // is inferred from the return statements inside the block.
138 if (isOmittedBlockReturnType(TheDeclarator)) {
139 Result = Context.DependentTy;
143 // Unspecified typespec defaults to int in C90. However, the C90 grammar
144 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
145 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
146 // Note that the one exception to this is function definitions, which are
147 // allowed to be completely missing a declspec. This is handled in the
148 // parser already though by it pretending to have seen an 'int' in this
150 if (TheSema.getLangOptions().ImplicitInt) {
151 // In C89 mode, we only warn if there is a completely missing declspec
152 // when one is not allowed.
154 TheSema.Diag(DeclLoc, diag::ext_missing_declspec)
155 << DS.getSourceRange()
156 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
159 } else if (!DS.hasTypeSpecifier()) {
160 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
161 // "At least one type specifier shall be given in the declaration
162 // specifiers in each declaration, and in the specifier-qualifier list in
163 // each struct declaration and type name."
164 // FIXME: Does Microsoft really have the implicit int extension in C++?
165 if (TheSema.getLangOptions().CPlusPlus &&
166 !TheSema.getLangOptions().Microsoft) {
167 TheSema.Diag(DeclLoc, diag::err_missing_type_specifier)
168 << DS.getSourceRange();
170 // When this occurs in C++ code, often something is very broken with the
171 // value being declared, poison it as invalid so we don't get chains of
173 TheDeclarator.setInvalidType(true);
175 TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier)
176 << DS.getSourceRange();
181 case DeclSpec::TST_int: {
182 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
183 switch (DS.getTypeSpecWidth()) {
184 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
185 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
186 case DeclSpec::TSW_long: Result = Context.LongTy; break;
187 case DeclSpec::TSW_longlong:
188 Result = Context.LongLongTy;
190 // long long is a C99 feature.
191 if (!TheSema.getLangOptions().C99 &&
192 !TheSema.getLangOptions().CPlusPlus0x)
193 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
197 switch (DS.getTypeSpecWidth()) {
198 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
199 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
200 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
201 case DeclSpec::TSW_longlong:
202 Result = Context.UnsignedLongLongTy;
204 // long long is a C99 feature.
205 if (!TheSema.getLangOptions().C99 &&
206 !TheSema.getLangOptions().CPlusPlus0x)
207 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong);
213 case DeclSpec::TST_float: Result = Context.FloatTy; break;
214 case DeclSpec::TST_double:
215 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
216 Result = Context.LongDoubleTy;
218 Result = Context.DoubleTy;
220 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
221 case DeclSpec::TST_decimal32: // _Decimal32
222 case DeclSpec::TST_decimal64: // _Decimal64
223 case DeclSpec::TST_decimal128: // _Decimal128
224 TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
225 Result = Context.IntTy;
226 TheDeclarator.setInvalidType(true);
228 case DeclSpec::TST_class:
229 case DeclSpec::TST_enum:
230 case DeclSpec::TST_union:
231 case DeclSpec::TST_struct: {
233 = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
235 // This can happen in C++ with ambiguous lookups.
236 Result = Context.IntTy;
237 TheDeclarator.setInvalidType(true);
241 // If the type is deprecated or unavailable, diagnose it.
242 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
244 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
245 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
247 // TypeQuals handled by caller.
248 Result = Context.getTypeDeclType(D);
250 // In C++, make an ElaboratedType.
251 if (TheSema.getLangOptions().CPlusPlus) {
253 = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
254 Result = Context.getElaboratedType(Result, Tag);
257 if (D->isInvalidDecl())
258 TheDeclarator.setInvalidType(true);
261 case DeclSpec::TST_typename: {
262 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
263 DS.getTypeSpecSign() == 0 &&
264 "Can't handle qualifiers on typedef names yet!");
265 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
267 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
268 if (const ObjCInterfaceType *
269 Interface = Result->getAs<ObjCInterfaceType>()) {
270 // It would be nice if protocol qualifiers were only stored with the
271 // ObjCObjectPointerType. Unfortunately, this isn't possible due
272 // to the following typedef idiom (which is uncommon, but allowed):
275 // static void func() {
279 Result = Context.getObjCInterfaceType(Interface->getDecl(),
280 (ObjCProtocolDecl**)PQ,
281 DS.getNumProtocolQualifiers());
282 } else if (Result->isObjCIdType())
284 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
285 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
286 else if (Result->isObjCClassType()) {
287 // Class<protocol-list>
288 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
289 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
291 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
292 << DS.getSourceRange();
293 TheDeclarator.setInvalidType(true);
297 // TypeQuals handled by caller.
300 case DeclSpec::TST_typeofType:
301 // FIXME: Preserve type source info.
302 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
303 assert(!Result.isNull() && "Didn't get a type for typeof?");
304 // TypeQuals handled by caller.
305 Result = Context.getTypeOfType(Result);
307 case DeclSpec::TST_typeofExpr: {
308 Expr *E = static_cast<Expr *>(DS.getTypeRep());
309 assert(E && "Didn't get an expression for typeof?");
310 // TypeQuals handled by caller.
311 Result = Context.getTypeOfExprType(E);
314 case DeclSpec::TST_decltype: {
315 Expr *E = static_cast<Expr *>(DS.getTypeRep());
316 assert(E && "Didn't get an expression for decltype?");
317 // TypeQuals handled by caller.
318 Result = TheSema.BuildDecltypeType(E);
319 if (Result.isNull()) {
320 Result = Context.IntTy;
321 TheDeclarator.setInvalidType(true);
325 case DeclSpec::TST_auto: {
326 // TypeQuals handled by caller.
327 Result = Context.UndeducedAutoTy;
331 case DeclSpec::TST_error:
332 Result = Context.IntTy;
333 TheDeclarator.setInvalidType(true);
337 // Handle complex types.
338 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
339 if (TheSema.getLangOptions().Freestanding)
340 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
341 Result = Context.getComplexType(Result);
344 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
345 "FIXME: imaginary types not supported yet!");
347 // See if there are any attributes on the declspec that apply to the type (as
348 // opposed to the decl).
349 if (const AttributeList *AL = DS.getAttributes())
350 TheSema.ProcessTypeAttributeList(Result, AL);
352 // Apply const/volatile/restrict qualifiers to T.
353 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
355 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
356 // or incomplete types shall not be restrict-qualified." C++ also allows
357 // restrict-qualified references.
358 if (TypeQuals & DeclSpec::TQ_restrict) {
359 if (Result->isPointerType() || Result->isReferenceType()) {
360 QualType EltTy = Result->isPointerType() ?
361 Result->getAs<PointerType>()->getPointeeType() :
362 Result->getAs<ReferenceType>()->getPointeeType();
364 // If we have a pointer or reference, the pointee must have an object
366 if (!EltTy->isIncompleteOrObjectType()) {
367 TheSema.Diag(DS.getRestrictSpecLoc(),
368 diag::err_typecheck_invalid_restrict_invalid_pointee)
369 << EltTy << DS.getSourceRange();
370 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
373 TheSema.Diag(DS.getRestrictSpecLoc(),
374 diag::err_typecheck_invalid_restrict_not_pointer)
375 << Result << DS.getSourceRange();
376 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
380 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
381 // of a function type includes any type qualifiers, the behavior is
383 if (Result->isFunctionType() && TypeQuals) {
384 // Get some location to point at, either the C or V location.
386 if (TypeQuals & DeclSpec::TQ_const)
387 Loc = DS.getConstSpecLoc();
388 else if (TypeQuals & DeclSpec::TQ_volatile)
389 Loc = DS.getVolatileSpecLoc();
391 assert((TypeQuals & DeclSpec::TQ_restrict) &&
392 "Has CVR quals but not C, V, or R?");
393 Loc = DS.getRestrictSpecLoc();
395 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
396 << Result << DS.getSourceRange();
400 // Cv-qualified references are ill-formed except when the
401 // cv-qualifiers are introduced through the use of a typedef
402 // (7.1.3) or of a template type argument (14.3), in which
403 // case the cv-qualifiers are ignored.
404 // FIXME: Shouldn't we be checking SCS_typedef here?
405 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
406 TypeQuals && Result->isReferenceType()) {
407 TypeQuals &= ~DeclSpec::TQ_const;
408 TypeQuals &= ~DeclSpec::TQ_volatile;
411 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
412 Result = Context.getQualifiedType(Result, Quals);
418 static std::string getPrintableNameForEntity(DeclarationName Entity) {
420 return Entity.getAsString();
425 /// \brief Build a pointer type.
427 /// \param T The type to which we'll be building a pointer.
429 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
431 /// \param Loc The location of the entity whose type involves this
432 /// pointer type or, if there is no such entity, the location of the
433 /// type that will have pointer type.
435 /// \param Entity The name of the entity that involves the pointer
438 /// \returns A suitable pointer type, if there are no
439 /// errors. Otherwise, returns a NULL type.
440 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
441 SourceLocation Loc, DeclarationName Entity) {
442 if (T->isReferenceType()) {
443 // C++ 8.3.2p4: There shall be no ... pointers to references ...
444 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
445 << getPrintableNameForEntity(Entity) << T;
449 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
451 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
452 // object or incomplete types shall not be restrict-qualified."
453 if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
454 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
459 // Build the pointer type.
460 return Context.getQualifiedType(Context.getPointerType(T), Qs);
463 /// \brief Build a reference type.
465 /// \param T The type to which we'll be building a reference.
467 /// \param CVR The cvr-qualifiers to be applied to the reference type.
469 /// \param Loc The location of the entity whose type involves this
470 /// reference type or, if there is no such entity, the location of the
471 /// type that will have reference type.
473 /// \param Entity The name of the entity that involves the reference
476 /// \returns A suitable reference type, if there are no
477 /// errors. Otherwise, returns a NULL type.
478 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
479 unsigned CVR, SourceLocation Loc,
480 DeclarationName Entity) {
481 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
483 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
485 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
486 // reference to a type T, and attempt to create the type "lvalue
487 // reference to cv TD" creates the type "lvalue reference to T".
488 // We use the qualifiers (restrict or none) of the original reference,
489 // not the new ones. This is consistent with GCC.
491 // C++ [dcl.ref]p4: There shall be no references to references.
493 // According to C++ DR 106, references to references are only
494 // diagnosed when they are written directly (e.g., "int & &"),
495 // but not when they happen via a typedef:
497 // typedef int& intref;
498 // typedef intref& intref2;
500 // Parser::ParseDeclaratorInternal diagnoses the case where
501 // references are written directly; here, we handle the
502 // collapsing of references-to-references as described in C++
503 // DR 106 and amended by C++ DR 540.
506 // A declarator that specifies the type "reference to cv void"
508 if (T->isVoidType()) {
509 Diag(Loc, diag::err_reference_to_void);
513 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
514 // object or incomplete types shall not be restrict-qualified."
515 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
516 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
518 Quals.removeRestrict();
522 // [...] Cv-qualified references are ill-formed except when the
523 // cv-qualifiers are introduced through the use of a typedef
524 // (7.1.3) or of a template type argument (14.3), in which case
525 // the cv-qualifiers are ignored.
527 // We diagnose extraneous cv-qualifiers for the non-typedef,
528 // non-template type argument case within the parser. Here, we just
529 // ignore any extraneous cv-qualifiers.
531 Quals.removeVolatile();
533 // Handle restrict on references.
535 return Context.getQualifiedType(
536 Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
537 return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
540 /// \brief Build an array type.
542 /// \param T The type of each element in the array.
544 /// \param ASM C99 array size modifier (e.g., '*', 'static').
546 /// \param ArraySize Expression describing the size of the array.
548 /// \param Quals The cvr-qualifiers to be applied to the array's
551 /// \param Loc The location of the entity whose type involves this
552 /// array type or, if there is no such entity, the location of the
553 /// type that will have array type.
555 /// \param Entity The name of the entity that involves the array
558 /// \returns A suitable array type, if there are no errors. Otherwise,
559 /// returns a NULL type.
560 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
561 Expr *ArraySize, unsigned Quals,
562 SourceRange Brackets, DeclarationName Entity) {
564 SourceLocation Loc = Brackets.getBegin();
565 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
566 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
567 // Not in C++, though. There we only dislike void.
568 if (getLangOptions().CPlusPlus) {
569 if (T->isVoidType()) {
570 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
574 if (RequireCompleteType(Loc, T,
575 diag::err_illegal_decl_array_incomplete_type))
579 if (T->isFunctionType()) {
580 Diag(Loc, diag::err_illegal_decl_array_of_functions)
581 << getPrintableNameForEntity(Entity) << T;
585 // C++ 8.3.2p4: There shall be no ... arrays of references ...
586 if (T->isReferenceType()) {
587 Diag(Loc, diag::err_illegal_decl_array_of_references)
588 << getPrintableNameForEntity(Entity) << T;
592 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
593 Diag(Loc, diag::err_illegal_decl_array_of_auto)
594 << getPrintableNameForEntity(Entity);
598 if (const RecordType *EltTy = T->getAs<RecordType>()) {
599 // If the element type is a struct or union that contains a variadic
600 // array, accept it as a GNU extension: C99 6.7.2.1p2.
601 if (EltTy->getDecl()->hasFlexibleArrayMember())
602 Diag(Loc, diag::ext_flexible_array_in_array) << T;
603 } else if (T->isObjCInterfaceType()) {
604 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
608 // C99 6.7.5.2p1: The size expression shall have integer type.
609 if (ArraySize && !ArraySize->isTypeDependent() &&
610 !ArraySize->getType()->isIntegerType()) {
611 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
612 << ArraySize->getType() << ArraySize->getSourceRange();
613 ArraySize->Destroy(Context);
616 llvm::APSInt ConstVal(32);
618 if (ASM == ArrayType::Star)
619 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
621 T = Context.getIncompleteArrayType(T, ASM, Quals);
622 } else if (ArraySize->isValueDependent()) {
623 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
624 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
625 (!T->isDependentType() && !T->isIncompleteType() &&
626 !T->isConstantSizeType())) {
627 // Per C99, a variable array is an array with either a non-constant
628 // size or an element type that has a non-constant-size
629 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
631 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
632 // have a value greater than zero.
633 if (ConstVal.isSigned() && ConstVal.isNegative()) {
634 Diag(ArraySize->getLocStart(),
635 diag::err_typecheck_negative_array_size)
636 << ArraySize->getSourceRange();
640 // GCC accepts zero sized static arrays.
641 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
642 << ArraySize->getSourceRange();
644 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
646 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
647 if (!getLangOptions().C99) {
648 if (ArraySize && !ArraySize->isTypeDependent() &&
649 !ArraySize->isValueDependent() &&
650 !ArraySize->isIntegerConstantExpr(Context))
651 Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
652 else if (ASM != ArrayType::Normal || Quals != 0)
654 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
655 : diag::ext_c99_array_usage);
661 /// \brief Build an ext-vector type.
663 /// Run the required checks for the extended vector type.
664 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
665 SourceLocation AttrLoc) {
667 Expr *Arg = (Expr *)ArraySize.get();
669 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
670 // in conjunction with complex types (pointers, arrays, functions, etc.).
671 if (!T->isDependentType() &&
672 !T->isIntegerType() && !T->isRealFloatingType()) {
673 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
677 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
678 llvm::APSInt vecSize(32);
679 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
680 Diag(AttrLoc, diag::err_attribute_argument_not_int)
681 << "ext_vector_type" << Arg->getSourceRange();
685 // unlike gcc's vector_size attribute, the size is specified as the
686 // number of elements, not the number of bytes.
687 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
689 if (vectorSize == 0) {
690 Diag(AttrLoc, diag::err_attribute_zero_size)
691 << Arg->getSourceRange();
695 if (!T->isDependentType())
696 return Context.getExtVectorType(T, vectorSize);
699 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
703 /// \brief Build a function type.
705 /// This routine checks the function type according to C++ rules and
706 /// under the assumption that the result type and parameter types have
707 /// just been instantiated from a template. It therefore duplicates
708 /// some of the behavior of GetTypeForDeclarator, but in a much
709 /// simpler form that is only suitable for this narrow use case.
711 /// \param T The return type of the function.
713 /// \param ParamTypes The parameter types of the function. This array
714 /// will be modified to account for adjustments to the types of the
715 /// function parameters.
717 /// \param NumParamTypes The number of parameter types in ParamTypes.
719 /// \param Variadic Whether this is a variadic function type.
721 /// \param Quals The cvr-qualifiers to be applied to the function type.
723 /// \param Loc The location of the entity whose type involves this
724 /// function type or, if there is no such entity, the location of the
725 /// type that will have function type.
727 /// \param Entity The name of the entity that involves the function
730 /// \returns A suitable function type, if there are no
731 /// errors. Otherwise, returns a NULL type.
732 QualType Sema::BuildFunctionType(QualType T,
733 QualType *ParamTypes,
734 unsigned NumParamTypes,
735 bool Variadic, unsigned Quals,
736 SourceLocation Loc, DeclarationName Entity) {
737 if (T->isArrayType() || T->isFunctionType()) {
738 Diag(Loc, diag::err_func_returning_array_function) << T;
742 bool Invalid = false;
743 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
744 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
745 if (ParamType->isVoidType()) {
746 Diag(Loc, diag::err_param_with_void_type);
750 ParamTypes[Idx] = ParamType;
756 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
760 /// \brief Build a member pointer type \c T Class::*.
762 /// \param T the type to which the member pointer refers.
763 /// \param Class the class type into which the member pointer points.
764 /// \param CVR Qualifiers applied to the member pointer type
765 /// \param Loc the location where this type begins
766 /// \param Entity the name of the entity that will have this member pointer type
768 /// \returns a member pointer type, if successful, or a NULL type if there was
770 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
771 unsigned CVR, SourceLocation Loc,
772 DeclarationName Entity) {
773 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
775 // Verify that we're not building a pointer to pointer to function with
776 // exception specification.
777 if (CheckDistantExceptionSpec(T)) {
778 Diag(Loc, diag::err_distant_exception_spec);
780 // FIXME: If we're doing this as part of template instantiation,
781 // we should return immediately.
783 // Build the type anyway, but use the canonical type so that the
784 // exception specifiers are stripped off.
785 T = Context.getCanonicalType(T);
788 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
789 // with reference type, or "cv void."
790 if (T->isReferenceType()) {
791 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
792 << (Entity? Entity.getAsString() : "type name") << T;
796 if (T->isVoidType()) {
797 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
798 << (Entity? Entity.getAsString() : "type name");
802 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
803 // object or incomplete types shall not be restrict-qualified."
804 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
805 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
808 // FIXME: If we're doing this as part of template instantiation,
809 // we should return immediately.
810 Quals.removeRestrict();
813 if (!Class->isDependentType() && !Class->isRecordType()) {
814 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
818 return Context.getQualifiedType(
819 Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
822 /// \brief Build a block pointer type.
824 /// \param T The type to which we'll be building a block pointer.
826 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
828 /// \param Loc The location of the entity whose type involves this
829 /// block pointer type or, if there is no such entity, the location of the
830 /// type that will have block pointer type.
832 /// \param Entity The name of the entity that involves the block pointer
835 /// \returns A suitable block pointer type, if there are no
836 /// errors. Otherwise, returns a NULL type.
837 QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
839 DeclarationName Entity) {
840 if (!T->isFunctionType()) {
841 Diag(Loc, diag::err_nonfunction_block_type);
845 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
846 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
849 QualType Sema::GetTypeFromParser(TypeTy *Ty, DeclaratorInfo **DInfo) {
850 QualType QT = QualType::getFromOpaquePtr(Ty);
852 if (DInfo) *DInfo = 0;
856 DeclaratorInfo *DI = 0;
857 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
859 DI = LIT->getDeclaratorInfo();
862 if (DInfo) *DInfo = DI;
866 /// GetTypeForDeclarator - Convert the type for the specified
867 /// declarator to Type instances.
869 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
870 /// owns the declaration of a type (e.g., the definition of a struct
871 /// type), then *OwnedDecl will receive the owned declaration.
872 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
873 DeclaratorInfo **DInfo,
874 TagDecl **OwnedDecl) {
875 // Determine the type of the declarator. Not all forms of declarator
879 switch (D.getName().getKind()) {
880 case UnqualifiedId::IK_Identifier:
881 case UnqualifiedId::IK_OperatorFunctionId:
882 case UnqualifiedId::IK_TemplateId:
883 T = ConvertDeclSpecToType(D, *this);
885 if (!D.isInvalidType() && OwnedDecl && D.getDeclSpec().isTypeSpecOwned())
886 *OwnedDecl = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
889 case UnqualifiedId::IK_ConstructorName:
890 case UnqualifiedId::IK_DestructorName:
891 case UnqualifiedId::IK_ConversionFunctionId:
892 // Constructors and destructors don't have return types. Use
893 // "void" instead. Conversion operators will check their return
899 if (T == Context.UndeducedAutoTy) {
902 switch (D.getContext()) {
903 case Declarator::KNRTypeListContext:
904 assert(0 && "K&R type lists aren't allowed in C++");
906 case Declarator::PrototypeContext:
907 Error = 0; // Function prototype
909 case Declarator::MemberContext:
910 switch (cast<TagDecl>(CurContext)->getTagKind()) {
911 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
912 case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
913 case TagDecl::TK_union: Error = 2; /* Union member */ break;
914 case TagDecl::TK_class: Error = 3; /* Class member */ break;
917 case Declarator::CXXCatchContext:
918 Error = 4; // Exception declaration
920 case Declarator::TemplateParamContext:
921 Error = 5; // Template parameter
923 case Declarator::BlockLiteralContext:
924 Error = 6; // Block literal
926 case Declarator::FileContext:
927 case Declarator::BlockContext:
928 case Declarator::ForContext:
929 case Declarator::ConditionContext:
930 case Declarator::TypeNameContext:
935 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
938 D.setInvalidType(true);
942 // The name we're declaring, if any.
943 DeclarationName Name;
944 if (D.getIdentifier())
945 Name = D.getIdentifier();
947 // Walk the DeclTypeInfo, building the recursive type as we go.
948 // DeclTypeInfos are ordered from the identifier out, which is
949 // opposite of what we want :).
950 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
951 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
952 switch (DeclType.Kind) {
953 default: assert(0 && "Unknown decltype!");
954 case DeclaratorChunk::BlockPointer:
955 // If blocks are disabled, emit an error.
956 if (!LangOpts.Blocks)
957 Diag(DeclType.Loc, diag::err_blocks_disable);
959 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
962 case DeclaratorChunk::Pointer:
963 // Verify that we're not building a pointer to pointer to function with
964 // exception specification.
965 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
966 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
967 D.setInvalidType(true);
968 // Build the type anyway.
970 if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
971 const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
972 T = Context.getObjCObjectPointerType(T,
973 (ObjCProtocolDecl **)OIT->qual_begin(),
974 OIT->getNumProtocols());
977 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
979 case DeclaratorChunk::Reference: {
981 if (DeclType.Ref.HasRestrict) Quals.addRestrict();
983 // Verify that we're not building a reference to pointer to function with
984 // exception specification.
985 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
986 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
987 D.setInvalidType(true);
988 // Build the type anyway.
990 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
994 case DeclaratorChunk::Array: {
995 // Verify that we're not building an array of pointers to function with
996 // exception specification.
997 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
998 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
999 D.setInvalidType(true);
1000 // Build the type anyway.
1002 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1003 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1004 ArrayType::ArraySizeModifier ASM;
1006 ASM = ArrayType::Star;
1007 else if (ATI.hasStatic)
1008 ASM = ArrayType::Static;
1010 ASM = ArrayType::Normal;
1011 if (ASM == ArrayType::Star &&
1012 D.getContext() != Declarator::PrototypeContext) {
1013 // FIXME: This check isn't quite right: it allows star in prototypes
1014 // for function definitions, and disallows some edge cases detailed
1015 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1016 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1017 ASM = ArrayType::Normal;
1018 D.setInvalidType(true);
1020 T = BuildArrayType(T, ASM, ArraySize,
1021 Qualifiers::fromCVRMask(ATI.TypeQuals),
1022 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1025 case DeclaratorChunk::Function: {
1026 // If the function declarator has a prototype (i.e. it is not () and
1027 // does not have a K&R-style identifier list), then the arguments are part
1028 // of the type, otherwise the argument list is ().
1029 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1031 // C99 6.7.5.3p1: The return type may not be a function or array type.
1032 if (T->isArrayType() || T->isFunctionType()) {
1033 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
1035 D.setInvalidType(true);
1038 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1040 // Types shall not be defined in return or parameter types.
1041 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1042 if (Tag->isDefinition())
1043 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1044 << Context.getTypeDeclType(Tag);
1047 // Exception specs are not allowed in typedefs. Complain, but add it
1049 if (FTI.hasExceptionSpec &&
1050 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1051 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1053 if (FTI.NumArgs == 0) {
1054 if (getLangOptions().CPlusPlus) {
1055 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1056 // function takes no arguments.
1057 llvm::SmallVector<QualType, 4> Exceptions;
1058 Exceptions.reserve(FTI.NumExceptions);
1059 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1060 // FIXME: Preserve type source info.
1061 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1062 // Check that the type is valid for an exception spec, and drop it
1064 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1065 Exceptions.push_back(ET);
1067 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1068 FTI.hasExceptionSpec,
1069 FTI.hasAnyExceptionSpec,
1070 Exceptions.size(), Exceptions.data());
1071 } else if (FTI.isVariadic) {
1072 // We allow a zero-parameter variadic function in C if the
1073 // function is marked with the "overloadable"
1074 // attribute. Scan for this attribute now.
1075 bool Overloadable = false;
1076 for (const AttributeList *Attrs = D.getAttributes();
1077 Attrs; Attrs = Attrs->getNext()) {
1078 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1079 Overloadable = true;
1085 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1086 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
1088 // Simple void foo(), where the incoming T is the result type.
1089 T = Context.getFunctionNoProtoType(T);
1091 } else if (FTI.ArgInfo[0].Param == 0) {
1092 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1093 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1094 D.setInvalidType(true);
1096 // Otherwise, we have a function with an argument list that is
1097 // potentially variadic.
1098 llvm::SmallVector<QualType, 16> ArgTys;
1100 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1101 ParmVarDecl *Param =
1102 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1103 QualType ArgTy = Param->getType();
1104 assert(!ArgTy.isNull() && "Couldn't parse type?");
1106 // Adjust the parameter type.
1107 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1109 // Look for 'void'. void is allowed only as a single argument to a
1110 // function with no other parameters (C99 6.7.5.3p10). We record
1111 // int(void) as a FunctionProtoType with an empty argument list.
1112 if (ArgTy->isVoidType()) {
1113 // If this is something like 'float(int, void)', reject it. 'void'
1114 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1115 // have arguments of incomplete type.
1116 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1117 Diag(DeclType.Loc, diag::err_void_only_param);
1118 ArgTy = Context.IntTy;
1119 Param->setType(ArgTy);
1120 } else if (FTI.ArgInfo[i].Ident) {
1121 // Reject, but continue to parse 'int(void abc)'.
1122 Diag(FTI.ArgInfo[i].IdentLoc,
1123 diag::err_param_with_void_type);
1124 ArgTy = Context.IntTy;
1125 Param->setType(ArgTy);
1127 // Reject, but continue to parse 'float(const void)'.
1128 if (ArgTy.hasQualifiers())
1129 Diag(DeclType.Loc, diag::err_void_param_qualified);
1131 // Do not add 'void' to the ArgTys list.
1134 } else if (!FTI.hasPrototype) {
1135 if (ArgTy->isPromotableIntegerType()) {
1136 ArgTy = Context.getPromotedIntegerType(ArgTy);
1137 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1138 if (BTy->getKind() == BuiltinType::Float)
1139 ArgTy = Context.DoubleTy;
1143 ArgTys.push_back(ArgTy);
1146 llvm::SmallVector<QualType, 4> Exceptions;
1147 Exceptions.reserve(FTI.NumExceptions);
1148 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1149 // FIXME: Preserve type source info.
1150 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1151 // Check that the type is valid for an exception spec, and drop it if
1153 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1154 Exceptions.push_back(ET);
1157 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1158 FTI.isVariadic, FTI.TypeQuals,
1159 FTI.hasExceptionSpec,
1160 FTI.hasAnyExceptionSpec,
1161 Exceptions.size(), Exceptions.data());
1165 case DeclaratorChunk::MemberPointer:
1166 // Verify that we're not building a pointer to pointer to function with
1167 // exception specification.
1168 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1169 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1170 D.setInvalidType(true);
1171 // Build the type anyway.
1173 // The scope spec must refer to a class, or be dependent.
1175 if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1176 || dyn_cast_or_null<CXXRecordDecl>(
1177 computeDeclContext(DeclType.Mem.Scope()))) {
1178 NestedNameSpecifier *NNS
1179 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1180 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1181 switch (NNS->getKind()) {
1182 case NestedNameSpecifier::Identifier:
1183 ClsType = Context.getTypenameType(NNSPrefix, NNS->getAsIdentifier());
1186 case NestedNameSpecifier::Namespace:
1187 case NestedNameSpecifier::Global:
1188 llvm::llvm_unreachable("Nested-name-specifier must name a type");
1191 case NestedNameSpecifier::TypeSpec:
1192 case NestedNameSpecifier::TypeSpecWithTemplate:
1193 ClsType = QualType(NNS->getAsType(), 0);
1195 ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType);
1199 Diag(DeclType.Mem.Scope().getBeginLoc(),
1200 diag::err_illegal_decl_mempointer_in_nonclass)
1201 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1202 << DeclType.Mem.Scope().getRange();
1203 D.setInvalidType(true);
1206 if (!ClsType.isNull())
1207 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1208 DeclType.Loc, D.getIdentifier());
1211 D.setInvalidType(true);
1217 D.setInvalidType(true);
1221 // See if there are any attributes on this declarator chunk.
1222 if (const AttributeList *AL = DeclType.getAttrs())
1223 ProcessTypeAttributeList(T, AL);
1226 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1227 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1228 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1230 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1231 // for a nonstatic member function, the function type to which a pointer
1232 // to member refers, or the top-level function type of a function typedef
1234 if (FnTy->getTypeQuals() != 0 &&
1235 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1236 ((D.getContext() != Declarator::MemberContext &&
1237 (!D.getCXXScopeSpec().isSet() ||
1238 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1240 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1241 if (D.isFunctionDeclarator())
1242 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1244 Diag(D.getIdentifierLoc(),
1245 diag::err_invalid_qualified_typedef_function_type_use);
1247 // Strip the cv-quals from the type.
1248 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1249 FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1253 // If there were any type attributes applied to the decl itself (not the
1254 // type, apply the type attribute to the type!)
1255 if (const AttributeList *Attrs = D.getAttributes())
1256 ProcessTypeAttributeList(T, Attrs);
1259 if (D.isInvalidType())
1262 *DInfo = GetDeclaratorInfoForDeclarator(D, T);
1269 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1273 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1275 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1276 Visit(TL.getUnqualifiedLoc());
1278 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1279 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1281 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1282 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1284 if (DS.getProtocolQualifiers()) {
1285 assert(TL.getNumProtocols() > 0);
1286 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1287 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1288 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1289 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1290 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1292 assert(TL.getNumProtocols() == 0);
1293 TL.setLAngleLoc(SourceLocation());
1294 TL.setRAngleLoc(SourceLocation());
1297 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1298 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1300 TL.setStarLoc(SourceLocation());
1302 if (DS.getProtocolQualifiers()) {
1303 assert(TL.getNumProtocols() > 0);
1304 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1305 TL.setHasProtocolsAsWritten(true);
1306 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1307 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1308 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1309 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1312 assert(TL.getNumProtocols() == 0);
1313 TL.setHasProtocolsAsWritten(false);
1314 TL.setLAngleLoc(SourceLocation());
1315 TL.setRAngleLoc(SourceLocation());
1318 // This might not have been written with an inner type.
1319 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1320 TL.setHasBaseTypeAsWritten(false);
1321 TL.getBaseTypeLoc().initialize(SourceLocation());
1323 TL.setHasBaseTypeAsWritten(true);
1324 Visit(TL.getBaseTypeLoc());
1327 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1328 DeclaratorInfo *DInfo = 0;
1329 Sema::GetTypeFromParser(DS.getTypeRep(), &DInfo);
1331 // If we got no declarator info from previous Sema routines,
1332 // just fill with the typespec loc.
1334 TL.initialize(DS.getTypeSpecTypeLoc());
1338 TemplateSpecializationTypeLoc OldTL =
1339 cast<TemplateSpecializationTypeLoc>(DInfo->getTypeLoc());
1342 void VisitTypeLoc(TypeLoc TL) {
1343 // FIXME: add other typespec types and change this to an assert.
1344 TL.initialize(DS.getTypeSpecTypeLoc());
1348 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1349 const DeclaratorChunk &Chunk;
1352 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1354 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1355 llvm::llvm_unreachable("qualified type locs not expected here!");
1358 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1359 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1360 TL.setCaretLoc(Chunk.Loc);
1362 void VisitPointerTypeLoc(PointerTypeLoc TL) {
1363 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1364 TL.setStarLoc(Chunk.Loc);
1366 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1367 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1368 TL.setStarLoc(Chunk.Loc);
1369 TL.setHasBaseTypeAsWritten(true);
1370 TL.setHasProtocolsAsWritten(false);
1371 TL.setLAngleLoc(SourceLocation());
1372 TL.setRAngleLoc(SourceLocation());
1374 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1375 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1376 TL.setStarLoc(Chunk.Loc);
1377 // FIXME: nested name specifier
1379 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1380 assert(Chunk.Kind == DeclaratorChunk::Reference);
1381 // 'Amp' is misleading: this might have been originally
1382 /// spelled with AmpAmp.
1383 TL.setAmpLoc(Chunk.Loc);
1385 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1386 assert(Chunk.Kind == DeclaratorChunk::Reference);
1387 assert(!Chunk.Ref.LValueRef);
1388 TL.setAmpAmpLoc(Chunk.Loc);
1390 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1391 assert(Chunk.Kind == DeclaratorChunk::Array);
1392 TL.setLBracketLoc(Chunk.Loc);
1393 TL.setRBracketLoc(Chunk.EndLoc);
1394 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1396 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1397 assert(Chunk.Kind == DeclaratorChunk::Function);
1398 TL.setLParenLoc(Chunk.Loc);
1399 TL.setRParenLoc(Chunk.EndLoc);
1401 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1402 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1403 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1404 TL.setArg(tpi++, Param);
1406 // FIXME: exception specs
1409 void VisitTypeLoc(TypeLoc TL) {
1410 llvm::llvm_unreachable("unsupported TypeLoc kind in declarator!");
1415 /// \brief Create and instantiate a DeclaratorInfo with type source information.
1417 /// \param T QualType referring to the type as written in source code.
1419 Sema::GetDeclaratorInfoForDeclarator(Declarator &D, QualType T) {
1420 DeclaratorInfo *DInfo = Context.CreateDeclaratorInfo(T);
1421 UnqualTypeLoc CurrTL = DInfo->getTypeLoc().getUnqualifiedLoc();
1423 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1424 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1425 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1428 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1433 /// \brief Create a LocInfoType to hold the given QualType and DeclaratorInfo.
1434 QualType Sema::CreateLocInfoType(QualType T, DeclaratorInfo *DInfo) {
1435 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1436 // and Sema during declaration parsing. Try deallocating/caching them when
1437 // it's appropriate, instead of allocating them and keeping them around.
1438 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1439 new (LocT) LocInfoType(T, DInfo);
1440 assert(LocT->getTypeClass() != T->getTypeClass() &&
1441 "LocInfoType's TypeClass conflicts with an existing Type class");
1442 return QualType(LocT, 0);
1445 void LocInfoType::getAsStringInternal(std::string &Str,
1446 const PrintingPolicy &Policy) const {
1447 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1448 " was used directly instead of getting the QualType through"
1449 " GetTypeFromParser");
1452 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1454 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1455 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1456 QualType T = MDecl->getResultType();
1457 llvm::SmallVector<QualType, 16> ArgTys;
1459 // Add the first two invisible argument types for self and _cmd.
1460 if (MDecl->isInstanceMethod()) {
1461 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1462 selfTy = Context.getPointerType(selfTy);
1463 ArgTys.push_back(selfTy);
1465 ArgTys.push_back(Context.getObjCIdType());
1466 ArgTys.push_back(Context.getObjCSelType());
1468 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1469 E = MDecl->param_end(); PI != E; ++PI) {
1470 QualType ArgTy = (*PI)->getType();
1471 assert(!ArgTy.isNull() && "Couldn't parse type?");
1472 ArgTy = adjustParameterType(ArgTy);
1473 ArgTys.push_back(ArgTy);
1475 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1476 MDecl->isVariadic(), 0);
1480 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1481 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1482 /// they point to and return true. If T1 and T2 aren't pointer types
1483 /// or pointer-to-member types, or if they are not similar at this
1484 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1485 /// qualifiers on T1 and T2 are ignored. This function will typically
1486 /// be called in a loop that successively "unwraps" pointer and
1487 /// pointer-to-member types to compare them at each level.
1488 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1489 const PointerType *T1PtrType = T1->getAs<PointerType>(),
1490 *T2PtrType = T2->getAs<PointerType>();
1491 if (T1PtrType && T2PtrType) {
1492 T1 = T1PtrType->getPointeeType();
1493 T2 = T2PtrType->getPointeeType();
1497 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1498 *T2MPType = T2->getAs<MemberPointerType>();
1499 if (T1MPType && T2MPType &&
1500 Context.getCanonicalType(T1MPType->getClass()) ==
1501 Context.getCanonicalType(T2MPType->getClass())) {
1502 T1 = T1MPType->getPointeeType();
1503 T2 = T2MPType->getPointeeType();
1509 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1510 // C99 6.7.6: Type names have no identifier. This is already validated by
1512 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1514 DeclaratorInfo *DInfo = 0;
1515 TagDecl *OwnedTag = 0;
1516 QualType T = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
1517 if (D.isInvalidType())
1520 if (getLangOptions().CPlusPlus) {
1521 // Check that there are no default arguments (C++ only).
1522 CheckExtraCXXDefaultArguments(D);
1524 // C++0x [dcl.type]p3:
1525 // A type-specifier-seq shall not define a class or enumeration
1526 // unless it appears in the type-id of an alias-declaration
1528 if (OwnedTag && OwnedTag->isDefinition())
1529 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1530 << Context.getTypeDeclType(OwnedTag);
1534 T = CreateLocInfoType(T, DInfo);
1536 return T.getAsOpaquePtr();
1541 //===----------------------------------------------------------------------===//
1542 // Type Attribute Processing
1543 //===----------------------------------------------------------------------===//
1545 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1546 /// specified type. The attribute contains 1 argument, the id of the address
1547 /// space for the type.
1548 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1549 const AttributeList &Attr, Sema &S){
1551 // If this type is already address space qualified, reject it.
1552 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1553 // for two or more different address spaces."
1554 if (Type.getAddressSpace()) {
1555 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1559 // Check the attribute arguments.
1560 if (Attr.getNumArgs() != 1) {
1561 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1564 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1565 llvm::APSInt addrSpace(32);
1566 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1567 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1568 << ASArgExpr->getSourceRange();
1573 if (addrSpace.isSigned()) {
1574 if (addrSpace.isNegative()) {
1575 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1576 << ASArgExpr->getSourceRange();
1579 addrSpace.setIsSigned(false);
1581 llvm::APSInt max(addrSpace.getBitWidth());
1582 max = Qualifiers::MaxAddressSpace;
1583 if (addrSpace > max) {
1584 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1585 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1589 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1590 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1593 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1594 /// specified type. The attribute contains 1 argument, weak or strong.
1595 static void HandleObjCGCTypeAttribute(QualType &Type,
1596 const AttributeList &Attr, Sema &S) {
1597 if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1598 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1602 // Check the attribute arguments.
1603 if (!Attr.getParameterName()) {
1604 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1608 Qualifiers::GC GCAttr;
1609 if (Attr.getNumArgs() != 0) {
1610 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1613 if (Attr.getParameterName()->isStr("weak"))
1614 GCAttr = Qualifiers::Weak;
1615 else if (Attr.getParameterName()->isStr("strong"))
1616 GCAttr = Qualifiers::Strong;
1618 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1619 << "objc_gc" << Attr.getParameterName();
1623 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1626 /// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1627 /// specified type. The attribute contains 0 arguments.
1628 static void HandleNoReturnTypeAttribute(QualType &Type,
1629 const AttributeList &Attr, Sema &S) {
1630 if (Attr.getNumArgs() != 0)
1633 // We only apply this to a pointer to function or a pointer to block.
1634 if (!Type->isFunctionPointerType()
1635 && !Type->isBlockPointerType()
1636 && !Type->isFunctionType())
1639 Type = S.Context.getNoReturnType(Type);
1642 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1643 // Scan through and apply attributes to this type where it makes sense. Some
1644 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1645 // type, but others can be present in the type specifiers even though they
1646 // apply to the decl. Here we apply type attributes and ignore the rest.
1647 for (; AL; AL = AL->getNext()) {
1648 // If this is an attribute we can handle, do so now, otherwise, add it to
1649 // the LeftOverAttrs list for rechaining.
1650 switch (AL->getKind()) {
1652 case AttributeList::AT_address_space:
1653 HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1655 case AttributeList::AT_objc_gc:
1656 HandleObjCGCTypeAttribute(Result, *AL, *this);
1658 case AttributeList::AT_noreturn:
1659 HandleNoReturnTypeAttribute(Result, *AL, *this);
1665 /// @brief Ensure that the type T is a complete type.
1667 /// This routine checks whether the type @p T is complete in any
1668 /// context where a complete type is required. If @p T is a complete
1669 /// type, returns false. If @p T is a class template specialization,
1670 /// this routine then attempts to perform class template
1671 /// instantiation. If instantiation fails, or if @p T is incomplete
1672 /// and cannot be completed, issues the diagnostic @p diag (giving it
1673 /// the type @p T) and returns true.
1675 /// @param Loc The location in the source that the incomplete type
1676 /// diagnostic should refer to.
1678 /// @param T The type that this routine is examining for completeness.
1680 /// @param PD The partial diagnostic that will be printed out if T is not a
1683 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1684 /// @c false otherwise.
1685 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1686 const PartialDiagnostic &PD,
1687 std::pair<SourceLocation,
1688 PartialDiagnostic> Note) {
1689 unsigned diag = PD.getDiagID();
1691 // FIXME: Add this assertion to make sure we always get instantiation points.
1692 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1693 // FIXME: Add this assertion to help us flush out problems with
1694 // checking for dependent types and type-dependent expressions.
1696 // assert(!T->isDependentType() &&
1697 // "Can't ask whether a dependent type is complete");
1699 // If we have a complete type, we're done.
1700 if (!T->isIncompleteType())
1703 // If we have a class template specialization or a class member of a
1704 // class template specialization, or an array with known size of such,
1705 // try to instantiate it.
1706 QualType MaybeTemplate = T;
1707 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T))
1708 MaybeTemplate = Array->getElementType();
1709 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
1710 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1711 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1712 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
1713 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
1714 TSK_ImplicitInstantiation,
1715 /*Complain=*/diag != 0);
1716 } else if (CXXRecordDecl *Rec
1717 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1718 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1719 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1720 assert(MSInfo && "Missing member specialization information?");
1721 // This record was instantiated from a class within a template.
1722 if (MSInfo->getTemplateSpecializationKind()
1723 != TSK_ExplicitSpecialization)
1724 return InstantiateClass(Loc, Rec, Pattern,
1725 getTemplateInstantiationArgs(Rec),
1726 TSK_ImplicitInstantiation,
1727 /*Complain=*/diag != 0);
1735 // We have an incomplete type. Produce a diagnostic.
1738 // If we have a note, produce it.
1739 if (!Note.first.isInvalid())
1740 Diag(Note.first, Note.second);
1742 // If the type was a forward declaration of a class/struct/union
1744 const TagType *Tag = 0;
1745 if (const RecordType *Record = T->getAs<RecordType>())
1747 else if (const EnumType *Enum = T->getAs<EnumType>())
1750 if (Tag && !Tag->getDecl()->isInvalidDecl())
1751 Diag(Tag->getDecl()->getLocation(),
1752 Tag->isBeingDefined() ? diag::note_type_being_defined
1753 : diag::note_forward_declaration)
1754 << QualType(Tag, 0);
1759 /// \brief Retrieve a version of the type 'T' that is qualified by the
1760 /// nested-name-specifier contained in SS.
1761 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1762 if (!SS.isSet() || SS.isInvalid() || T.isNull())
1765 NestedNameSpecifier *NNS
1766 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1767 return Context.getQualifiedNameType(NNS, T);
1770 QualType Sema::BuildTypeofExprType(Expr *E) {
1771 return Context.getTypeOfExprType(E);
1774 QualType Sema::BuildDecltypeType(Expr *E) {
1775 if (E->getType() == Context.OverloadTy) {
1776 Diag(E->getLocStart(),
1777 diag::err_cannot_determine_declared_type_of_overloaded_function);
1780 return Context.getDecltypeType(E);