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: {
232 TypeDecl *D = cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep()));
234 // This can happen in C++ with ambiguous lookups.
235 Result = Context.IntTy;
236 TheDeclarator.setInvalidType(true);
240 // If the type is deprecated or unavailable, diagnose it.
241 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc());
243 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
244 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!");
246 // TypeQuals handled by caller.
247 Result = Context.getTypeDeclType(D);
249 // In C++, make an ElaboratedType.
250 if (TheSema.getLangOptions().CPlusPlus) {
252 = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType());
253 Result = Context.getElaboratedType(Result, Tag);
256 if (D->isInvalidDecl())
257 TheDeclarator.setInvalidType(true);
260 case DeclSpec::TST_typename: {
261 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
262 DS.getTypeSpecSign() == 0 &&
263 "Can't handle qualifiers on typedef names yet!");
264 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
266 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
267 if (const ObjCInterfaceType *
268 Interface = Result->getAs<ObjCInterfaceType>()) {
269 // It would be nice if protocol qualifiers were only stored with the
270 // ObjCObjectPointerType. Unfortunately, this isn't possible due
271 // to the following typedef idiom (which is uncommon, but allowed):
274 // static void func() {
278 Result = Context.getObjCInterfaceType(Interface->getDecl(),
279 (ObjCProtocolDecl**)PQ,
280 DS.getNumProtocolQualifiers());
281 } else if (Result->isObjCIdType())
283 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy,
284 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
285 else if (Result->isObjCClassType()) {
286 // Class<protocol-list>
287 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy,
288 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers());
290 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
291 << DS.getSourceRange();
292 TheDeclarator.setInvalidType(true);
296 // TypeQuals handled by caller.
299 case DeclSpec::TST_typeofType:
300 // FIXME: Preserve type source info.
301 Result = TheSema.GetTypeFromParser(DS.getTypeRep());
302 assert(!Result.isNull() && "Didn't get a type for typeof?");
303 // TypeQuals handled by caller.
304 Result = Context.getTypeOfType(Result);
306 case DeclSpec::TST_typeofExpr: {
307 Expr *E = static_cast<Expr *>(DS.getTypeRep());
308 assert(E && "Didn't get an expression for typeof?");
309 // TypeQuals handled by caller.
310 Result = Context.getTypeOfExprType(E);
313 case DeclSpec::TST_decltype: {
314 Expr *E = static_cast<Expr *>(DS.getTypeRep());
315 assert(E && "Didn't get an expression for decltype?");
316 // TypeQuals handled by caller.
317 Result = TheSema.BuildDecltypeType(E);
318 if (Result.isNull()) {
319 Result = Context.IntTy;
320 TheDeclarator.setInvalidType(true);
324 case DeclSpec::TST_auto: {
325 // TypeQuals handled by caller.
326 Result = Context.UndeducedAutoTy;
330 case DeclSpec::TST_error:
331 Result = Context.IntTy;
332 TheDeclarator.setInvalidType(true);
336 // Handle complex types.
337 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
338 if (TheSema.getLangOptions().Freestanding)
339 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
340 Result = Context.getComplexType(Result);
343 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
344 "FIXME: imaginary types not supported yet!");
346 // See if there are any attributes on the declspec that apply to the type (as
347 // opposed to the decl).
348 if (const AttributeList *AL = DS.getAttributes())
349 TheSema.ProcessTypeAttributeList(Result, AL);
351 // Apply const/volatile/restrict qualifiers to T.
352 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
354 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
355 // or incomplete types shall not be restrict-qualified." C++ also allows
356 // restrict-qualified references.
357 if (TypeQuals & DeclSpec::TQ_restrict) {
358 if (Result->isPointerType() || Result->isReferenceType()) {
359 QualType EltTy = Result->isPointerType() ?
360 Result->getAs<PointerType>()->getPointeeType() :
361 Result->getAs<ReferenceType>()->getPointeeType();
363 // If we have a pointer or reference, the pointee must have an object
365 if (!EltTy->isIncompleteOrObjectType()) {
366 TheSema.Diag(DS.getRestrictSpecLoc(),
367 diag::err_typecheck_invalid_restrict_invalid_pointee)
368 << EltTy << DS.getSourceRange();
369 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
372 TheSema.Diag(DS.getRestrictSpecLoc(),
373 diag::err_typecheck_invalid_restrict_not_pointer)
374 << Result << DS.getSourceRange();
375 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier.
379 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
380 // of a function type includes any type qualifiers, the behavior is
382 if (Result->isFunctionType() && TypeQuals) {
383 // Get some location to point at, either the C or V location.
385 if (TypeQuals & DeclSpec::TQ_const)
386 Loc = DS.getConstSpecLoc();
387 else if (TypeQuals & DeclSpec::TQ_volatile)
388 Loc = DS.getVolatileSpecLoc();
390 assert((TypeQuals & DeclSpec::TQ_restrict) &&
391 "Has CVR quals but not C, V, or R?");
392 Loc = DS.getRestrictSpecLoc();
394 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers)
395 << Result << DS.getSourceRange();
399 // Cv-qualified references are ill-formed except when the
400 // cv-qualifiers are introduced through the use of a typedef
401 // (7.1.3) or of a template type argument (14.3), in which
402 // case the cv-qualifiers are ignored.
403 // FIXME: Shouldn't we be checking SCS_typedef here?
404 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
405 TypeQuals && Result->isReferenceType()) {
406 TypeQuals &= ~DeclSpec::TQ_const;
407 TypeQuals &= ~DeclSpec::TQ_volatile;
410 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals);
411 Result = Context.getQualifiedType(Result, Quals);
417 static std::string getPrintableNameForEntity(DeclarationName Entity) {
419 return Entity.getAsString();
424 /// \brief Build a pointer type.
426 /// \param T The type to which we'll be building a pointer.
428 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
430 /// \param Loc The location of the entity whose type involves this
431 /// pointer type or, if there is no such entity, the location of the
432 /// type that will have pointer type.
434 /// \param Entity The name of the entity that involves the pointer
437 /// \returns A suitable pointer type, if there are no
438 /// errors. Otherwise, returns a NULL type.
439 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
440 SourceLocation Loc, DeclarationName Entity) {
441 if (T->isReferenceType()) {
442 // C++ 8.3.2p4: There shall be no ... pointers to references ...
443 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
444 << getPrintableNameForEntity(Entity) << T;
448 Qualifiers Qs = Qualifiers::fromCVRMask(Quals);
450 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
451 // object or incomplete types shall not be restrict-qualified."
452 if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) {
453 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
458 // Build the pointer type.
459 return Context.getQualifiedType(Context.getPointerType(T), Qs);
462 /// \brief Build a reference type.
464 /// \param T The type to which we'll be building a reference.
466 /// \param CVR The cvr-qualifiers to be applied to the reference type.
468 /// \param Loc The location of the entity whose type involves this
469 /// reference type or, if there is no such entity, the location of the
470 /// type that will have reference type.
472 /// \param Entity The name of the entity that involves the reference
475 /// \returns A suitable reference type, if there are no
476 /// errors. Otherwise, returns a NULL type.
477 QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue,
478 unsigned CVR, SourceLocation Loc,
479 DeclarationName Entity) {
480 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
482 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>();
484 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
485 // reference to a type T, and attempt to create the type "lvalue
486 // reference to cv TD" creates the type "lvalue reference to T".
487 // We use the qualifiers (restrict or none) of the original reference,
488 // not the new ones. This is consistent with GCC.
490 // C++ [dcl.ref]p4: There shall be no references to references.
492 // According to C++ DR 106, references to references are only
493 // diagnosed when they are written directly (e.g., "int & &"),
494 // but not when they happen via a typedef:
496 // typedef int& intref;
497 // typedef intref& intref2;
499 // Parser::ParseDeclaratorInternal diagnoses the case where
500 // references are written directly; here, we handle the
501 // collapsing of references-to-references as described in C++
502 // DR 106 and amended by C++ DR 540.
505 // A declarator that specifies the type "reference to cv void"
507 if (T->isVoidType()) {
508 Diag(Loc, diag::err_reference_to_void);
512 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
513 // object or incomplete types shall not be restrict-qualified."
514 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
515 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
517 Quals.removeRestrict();
521 // [...] Cv-qualified references are ill-formed except when the
522 // cv-qualifiers are introduced through the use of a typedef
523 // (7.1.3) or of a template type argument (14.3), in which case
524 // the cv-qualifiers are ignored.
526 // We diagnose extraneous cv-qualifiers for the non-typedef,
527 // non-template type argument case within the parser. Here, we just
528 // ignore any extraneous cv-qualifiers.
530 Quals.removeVolatile();
532 // Handle restrict on references.
534 return Context.getQualifiedType(
535 Context.getLValueReferenceType(T, SpelledAsLValue), Quals);
536 return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals);
539 /// \brief Build an array type.
541 /// \param T The type of each element in the array.
543 /// \param ASM C99 array size modifier (e.g., '*', 'static').
545 /// \param ArraySize Expression describing the size of the array.
547 /// \param Quals The cvr-qualifiers to be applied to the array's
550 /// \param Loc The location of the entity whose type involves this
551 /// array type or, if there is no such entity, the location of the
552 /// type that will have array type.
554 /// \param Entity The name of the entity that involves the array
557 /// \returns A suitable array type, if there are no errors. Otherwise,
558 /// returns a NULL type.
559 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
560 Expr *ArraySize, unsigned Quals,
561 SourceRange Brackets, DeclarationName Entity) {
563 SourceLocation Loc = Brackets.getBegin();
564 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
565 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
566 // Not in C++, though. There we only dislike void.
567 if (getLangOptions().CPlusPlus) {
568 if (T->isVoidType()) {
569 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T;
573 if (RequireCompleteType(Loc, T,
574 diag::err_illegal_decl_array_incomplete_type))
578 if (T->isFunctionType()) {
579 Diag(Loc, diag::err_illegal_decl_array_of_functions)
580 << getPrintableNameForEntity(Entity) << T;
584 // C++ 8.3.2p4: There shall be no ... arrays of references ...
585 if (T->isReferenceType()) {
586 Diag(Loc, diag::err_illegal_decl_array_of_references)
587 << getPrintableNameForEntity(Entity) << T;
591 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
592 Diag(Loc, diag::err_illegal_decl_array_of_auto)
593 << getPrintableNameForEntity(Entity);
597 if (const RecordType *EltTy = T->getAs<RecordType>()) {
598 // If the element type is a struct or union that contains a variadic
599 // array, accept it as a GNU extension: C99 6.7.2.1p2.
600 if (EltTy->getDecl()->hasFlexibleArrayMember())
601 Diag(Loc, diag::ext_flexible_array_in_array) << T;
602 } else if (T->isObjCInterfaceType()) {
603 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
607 // C99 6.7.5.2p1: The size expression shall have integer type.
608 if (ArraySize && !ArraySize->isTypeDependent() &&
609 !ArraySize->getType()->isIntegerType()) {
610 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
611 << ArraySize->getType() << ArraySize->getSourceRange();
612 ArraySize->Destroy(Context);
615 llvm::APSInt ConstVal(32);
617 if (ASM == ArrayType::Star)
618 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets);
620 T = Context.getIncompleteArrayType(T, ASM, Quals);
621 } else if (ArraySize->isValueDependent()) {
622 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets);
623 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
624 (!T->isDependentType() && !T->isIncompleteType() &&
625 !T->isConstantSizeType())) {
626 // Per C99, a variable array is an array with either a non-constant
627 // size or an element type that has a non-constant-size
628 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets);
630 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
631 // have a value greater than zero.
632 if (ConstVal.isSigned() && ConstVal.isNegative()) {
633 Diag(ArraySize->getLocStart(),
634 diag::err_typecheck_negative_array_size)
635 << ArraySize->getSourceRange();
639 // GCC accepts zero sized static arrays.
640 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
641 << ArraySize->getSourceRange();
643 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
645 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
646 if (!getLangOptions().C99) {
647 if (ArraySize && !ArraySize->isTypeDependent() &&
648 !ArraySize->isValueDependent() &&
649 !ArraySize->isIntegerConstantExpr(Context))
650 Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla);
651 else if (ASM != ArrayType::Normal || Quals != 0)
653 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx
654 : diag::ext_c99_array_usage);
660 /// \brief Build an ext-vector type.
662 /// Run the required checks for the extended vector type.
663 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
664 SourceLocation AttrLoc) {
666 Expr *Arg = (Expr *)ArraySize.get();
668 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
669 // in conjunction with complex types (pointers, arrays, functions, etc.).
670 if (!T->isDependentType() &&
671 !T->isIntegerType() && !T->isRealFloatingType()) {
672 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
676 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
677 llvm::APSInt vecSize(32);
678 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
679 Diag(AttrLoc, diag::err_attribute_argument_not_int)
680 << "ext_vector_type" << Arg->getSourceRange();
684 // unlike gcc's vector_size attribute, the size is specified as the
685 // number of elements, not the number of bytes.
686 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
688 if (vectorSize == 0) {
689 Diag(AttrLoc, diag::err_attribute_zero_size)
690 << Arg->getSourceRange();
694 if (!T->isDependentType())
695 return Context.getExtVectorType(T, vectorSize);
698 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
702 /// \brief Build a function type.
704 /// This routine checks the function type according to C++ rules and
705 /// under the assumption that the result type and parameter types have
706 /// just been instantiated from a template. It therefore duplicates
707 /// some of the behavior of GetTypeForDeclarator, but in a much
708 /// simpler form that is only suitable for this narrow use case.
710 /// \param T The return type of the function.
712 /// \param ParamTypes The parameter types of the function. This array
713 /// will be modified to account for adjustments to the types of the
714 /// function parameters.
716 /// \param NumParamTypes The number of parameter types in ParamTypes.
718 /// \param Variadic Whether this is a variadic function type.
720 /// \param Quals The cvr-qualifiers to be applied to the function type.
722 /// \param Loc The location of the entity whose type involves this
723 /// function type or, if there is no such entity, the location of the
724 /// type that will have function type.
726 /// \param Entity The name of the entity that involves the function
729 /// \returns A suitable function type, if there are no
730 /// errors. Otherwise, returns a NULL type.
731 QualType Sema::BuildFunctionType(QualType T,
732 QualType *ParamTypes,
733 unsigned NumParamTypes,
734 bool Variadic, unsigned Quals,
735 SourceLocation Loc, DeclarationName Entity) {
736 if (T->isArrayType() || T->isFunctionType()) {
737 Diag(Loc, diag::err_func_returning_array_function) << T;
741 bool Invalid = false;
742 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
743 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
744 if (ParamType->isVoidType()) {
745 Diag(Loc, diag::err_param_with_void_type);
749 ParamTypes[Idx] = ParamType;
755 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
759 /// \brief Build a member pointer type \c T Class::*.
761 /// \param T the type to which the member pointer refers.
762 /// \param Class the class type into which the member pointer points.
763 /// \param CVR Qualifiers applied to the member pointer type
764 /// \param Loc the location where this type begins
765 /// \param Entity the name of the entity that will have this member pointer type
767 /// \returns a member pointer type, if successful, or a NULL type if there was
769 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
770 unsigned CVR, SourceLocation Loc,
771 DeclarationName Entity) {
772 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
774 // Verify that we're not building a pointer to pointer to function with
775 // exception specification.
776 if (CheckDistantExceptionSpec(T)) {
777 Diag(Loc, diag::err_distant_exception_spec);
779 // FIXME: If we're doing this as part of template instantiation,
780 // we should return immediately.
782 // Build the type anyway, but use the canonical type so that the
783 // exception specifiers are stripped off.
784 T = Context.getCanonicalType(T);
787 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
788 // with reference type, or "cv void."
789 if (T->isReferenceType()) {
790 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
791 << (Entity? Entity.getAsString() : "type name") << T;
795 if (T->isVoidType()) {
796 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
797 << (Entity? Entity.getAsString() : "type name");
801 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
802 // object or incomplete types shall not be restrict-qualified."
803 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) {
804 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
807 // FIXME: If we're doing this as part of template instantiation,
808 // we should return immediately.
809 Quals.removeRestrict();
812 if (!Class->isDependentType() && !Class->isRecordType()) {
813 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
817 return Context.getQualifiedType(
818 Context.getMemberPointerType(T, Class.getTypePtr()), Quals);
821 /// \brief Build a block pointer type.
823 /// \param T The type to which we'll be building a block pointer.
825 /// \param CVR The cvr-qualifiers to be applied to the block pointer type.
827 /// \param Loc The location of the entity whose type involves this
828 /// block pointer type or, if there is no such entity, the location of the
829 /// type that will have block pointer type.
831 /// \param Entity The name of the entity that involves the block pointer
834 /// \returns A suitable block pointer type, if there are no
835 /// errors. Otherwise, returns a NULL type.
836 QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR,
838 DeclarationName Entity) {
839 if (!T->isFunctionType()) {
840 Diag(Loc, diag::err_nonfunction_block_type);
844 Qualifiers Quals = Qualifiers::fromCVRMask(CVR);
845 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals);
848 QualType Sema::GetTypeFromParser(TypeTy *Ty, DeclaratorInfo **DInfo) {
849 QualType QT = QualType::getFromOpaquePtr(Ty);
851 if (DInfo) *DInfo = 0;
855 DeclaratorInfo *DI = 0;
856 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) {
858 DI = LIT->getDeclaratorInfo();
861 if (DInfo) *DInfo = DI;
865 /// GetTypeForDeclarator - Convert the type for the specified
866 /// declarator to Type instances.
868 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
869 /// owns the declaration of a type (e.g., the definition of a struct
870 /// type), then *OwnedDecl will receive the owned declaration.
871 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S,
872 DeclaratorInfo **DInfo,
873 TagDecl **OwnedDecl) {
874 // Determine the type of the declarator. Not all forms of declarator
878 switch (D.getName().getKind()) {
879 case UnqualifiedId::IK_Identifier:
880 case UnqualifiedId::IK_OperatorFunctionId:
881 case UnqualifiedId::IK_TemplateId:
882 T = ConvertDeclSpecToType(D, *this);
884 if (!D.isInvalidType() && OwnedDecl && D.getDeclSpec().isTypeSpecOwned())
885 *OwnedDecl = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
888 case UnqualifiedId::IK_ConstructorName:
889 case UnqualifiedId::IK_DestructorName:
890 case UnqualifiedId::IK_ConversionFunctionId:
891 // Constructors and destructors don't have return types. Use
892 // "void" instead. Conversion operators will check their return
898 if (T == Context.UndeducedAutoTy) {
901 switch (D.getContext()) {
902 case Declarator::KNRTypeListContext:
903 assert(0 && "K&R type lists aren't allowed in C++");
905 case Declarator::PrototypeContext:
906 Error = 0; // Function prototype
908 case Declarator::MemberContext:
909 switch (cast<TagDecl>(CurContext)->getTagKind()) {
910 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
911 case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
912 case TagDecl::TK_union: Error = 2; /* Union member */ break;
913 case TagDecl::TK_class: Error = 3; /* Class member */ break;
916 case Declarator::CXXCatchContext:
917 Error = 4; // Exception declaration
919 case Declarator::TemplateParamContext:
920 Error = 5; // Template parameter
922 case Declarator::BlockLiteralContext:
923 Error = 6; // Block literal
925 case Declarator::FileContext:
926 case Declarator::BlockContext:
927 case Declarator::ForContext:
928 case Declarator::ConditionContext:
929 case Declarator::TypeNameContext:
934 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
937 D.setInvalidType(true);
941 // The name we're declaring, if any.
942 DeclarationName Name;
943 if (D.getIdentifier())
944 Name = D.getIdentifier();
946 // Walk the DeclTypeInfo, building the recursive type as we go.
947 // DeclTypeInfos are ordered from the identifier out, which is
948 // opposite of what we want :).
949 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
950 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1);
951 switch (DeclType.Kind) {
952 default: assert(0 && "Unknown decltype!");
953 case DeclaratorChunk::BlockPointer:
954 // If blocks are disabled, emit an error.
955 if (!LangOpts.Blocks)
956 Diag(DeclType.Loc, diag::err_blocks_disable);
958 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
961 case DeclaratorChunk::Pointer:
962 // Verify that we're not building a pointer to pointer to function with
963 // exception specification.
964 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
965 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
966 D.setInvalidType(true);
967 // Build the type anyway.
969 if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) {
970 const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>();
971 T = Context.getObjCObjectPointerType(T,
972 (ObjCProtocolDecl **)OIT->qual_begin(),
973 OIT->getNumProtocols());
976 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
978 case DeclaratorChunk::Reference: {
980 if (DeclType.Ref.HasRestrict) Quals.addRestrict();
982 // Verify that we're not building a reference to pointer to function with
983 // exception specification.
984 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
985 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
986 D.setInvalidType(true);
987 // Build the type anyway.
989 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals,
993 case DeclaratorChunk::Array: {
994 // Verify that we're not building an array of pointers to function with
995 // exception specification.
996 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
997 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
998 D.setInvalidType(true);
999 // Build the type anyway.
1001 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
1002 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
1003 ArrayType::ArraySizeModifier ASM;
1005 ASM = ArrayType::Star;
1006 else if (ATI.hasStatic)
1007 ASM = ArrayType::Static;
1009 ASM = ArrayType::Normal;
1010 if (ASM == ArrayType::Star &&
1011 D.getContext() != Declarator::PrototypeContext) {
1012 // FIXME: This check isn't quite right: it allows star in prototypes
1013 // for function definitions, and disallows some edge cases detailed
1014 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
1015 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
1016 ASM = ArrayType::Normal;
1017 D.setInvalidType(true);
1019 T = BuildArrayType(T, ASM, ArraySize,
1020 Qualifiers::fromCVRMask(ATI.TypeQuals),
1021 SourceRange(DeclType.Loc, DeclType.EndLoc), Name);
1024 case DeclaratorChunk::Function: {
1025 // If the function declarator has a prototype (i.e. it is not () and
1026 // does not have a K&R-style identifier list), then the arguments are part
1027 // of the type, otherwise the argument list is ().
1028 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
1030 // C99 6.7.5.3p1: The return type may not be a function or array type.
1031 if (T->isArrayType() || T->isFunctionType()) {
1032 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
1034 D.setInvalidType(true);
1037 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
1039 // Types shall not be defined in return or parameter types.
1040 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
1041 if (Tag->isDefinition())
1042 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
1043 << Context.getTypeDeclType(Tag);
1046 // Exception specs are not allowed in typedefs. Complain, but add it
1048 if (FTI.hasExceptionSpec &&
1049 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1050 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
1052 if (FTI.NumArgs == 0) {
1053 if (getLangOptions().CPlusPlus) {
1054 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
1055 // function takes no arguments.
1056 llvm::SmallVector<QualType, 4> Exceptions;
1057 Exceptions.reserve(FTI.NumExceptions);
1058 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1059 // FIXME: Preserve type source info.
1060 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1061 // Check that the type is valid for an exception spec, and drop it
1063 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1064 Exceptions.push_back(ET);
1066 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
1067 FTI.hasExceptionSpec,
1068 FTI.hasAnyExceptionSpec,
1069 Exceptions.size(), Exceptions.data());
1070 } else if (FTI.isVariadic) {
1071 // We allow a zero-parameter variadic function in C if the
1072 // function is marked with the "overloadable"
1073 // attribute. Scan for this attribute now.
1074 bool Overloadable = false;
1075 for (const AttributeList *Attrs = D.getAttributes();
1076 Attrs; Attrs = Attrs->getNext()) {
1077 if (Attrs->getKind() == AttributeList::AT_overloadable) {
1078 Overloadable = true;
1084 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
1085 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
1087 // Simple void foo(), where the incoming T is the result type.
1088 T = Context.getFunctionNoProtoType(T);
1090 } else if (FTI.ArgInfo[0].Param == 0) {
1091 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
1092 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
1093 D.setInvalidType(true);
1095 // Otherwise, we have a function with an argument list that is
1096 // potentially variadic.
1097 llvm::SmallVector<QualType, 16> ArgTys;
1099 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1100 ParmVarDecl *Param =
1101 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1102 QualType ArgTy = Param->getType();
1103 assert(!ArgTy.isNull() && "Couldn't parse type?");
1105 // Adjust the parameter type.
1106 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1108 // Look for 'void'. void is allowed only as a single argument to a
1109 // function with no other parameters (C99 6.7.5.3p10). We record
1110 // int(void) as a FunctionProtoType with an empty argument list.
1111 if (ArgTy->isVoidType()) {
1112 // If this is something like 'float(int, void)', reject it. 'void'
1113 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1114 // have arguments of incomplete type.
1115 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1116 Diag(DeclType.Loc, diag::err_void_only_param);
1117 ArgTy = Context.IntTy;
1118 Param->setType(ArgTy);
1119 } else if (FTI.ArgInfo[i].Ident) {
1120 // Reject, but continue to parse 'int(void abc)'.
1121 Diag(FTI.ArgInfo[i].IdentLoc,
1122 diag::err_param_with_void_type);
1123 ArgTy = Context.IntTy;
1124 Param->setType(ArgTy);
1126 // Reject, but continue to parse 'float(const void)'.
1127 if (ArgTy.hasQualifiers())
1128 Diag(DeclType.Loc, diag::err_void_param_qualified);
1130 // Do not add 'void' to the ArgTys list.
1133 } else if (!FTI.hasPrototype) {
1134 if (ArgTy->isPromotableIntegerType()) {
1135 ArgTy = Context.getPromotedIntegerType(ArgTy);
1136 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) {
1137 if (BTy->getKind() == BuiltinType::Float)
1138 ArgTy = Context.DoubleTy;
1142 ArgTys.push_back(ArgTy);
1145 llvm::SmallVector<QualType, 4> Exceptions;
1146 Exceptions.reserve(FTI.NumExceptions);
1147 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1148 // FIXME: Preserve type source info.
1149 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty);
1150 // Check that the type is valid for an exception spec, and drop it if
1152 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1153 Exceptions.push_back(ET);
1156 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1157 FTI.isVariadic, FTI.TypeQuals,
1158 FTI.hasExceptionSpec,
1159 FTI.hasAnyExceptionSpec,
1160 Exceptions.size(), Exceptions.data());
1164 case DeclaratorChunk::MemberPointer:
1165 // Verify that we're not building a pointer to pointer to function with
1166 // exception specification.
1167 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1168 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1169 D.setInvalidType(true);
1170 // Build the type anyway.
1172 // The scope spec must refer to a class, or be dependent.
1174 if (isDependentScopeSpecifier(DeclType.Mem.Scope())
1175 || dyn_cast_or_null<CXXRecordDecl>(
1176 computeDeclContext(DeclType.Mem.Scope()))) {
1177 NestedNameSpecifier *NNS
1178 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1179 NestedNameSpecifier *NNSPrefix = NNS->getPrefix();
1180 switch (NNS->getKind()) {
1181 case NestedNameSpecifier::Identifier:
1182 ClsType = Context.getTypenameType(NNSPrefix, NNS->getAsIdentifier());
1185 case NestedNameSpecifier::Namespace:
1186 case NestedNameSpecifier::Global:
1187 llvm::llvm_unreachable("Nested-name-specifier must name a type");
1190 case NestedNameSpecifier::TypeSpec:
1191 case NestedNameSpecifier::TypeSpecWithTemplate:
1192 ClsType = QualType(NNS->getAsType(), 0);
1194 ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType);
1198 Diag(DeclType.Mem.Scope().getBeginLoc(),
1199 diag::err_illegal_decl_mempointer_in_nonclass)
1200 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1201 << DeclType.Mem.Scope().getRange();
1202 D.setInvalidType(true);
1205 if (!ClsType.isNull())
1206 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1207 DeclType.Loc, D.getIdentifier());
1210 D.setInvalidType(true);
1216 D.setInvalidType(true);
1220 // See if there are any attributes on this declarator chunk.
1221 if (const AttributeList *AL = DeclType.getAttrs())
1222 ProcessTypeAttributeList(T, AL);
1225 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1226 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>();
1227 assert(FnTy && "Why oh why is there not a FunctionProtoType here?");
1229 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1230 // for a nonstatic member function, the function type to which a pointer
1231 // to member refers, or the top-level function type of a function typedef
1233 if (FnTy->getTypeQuals() != 0 &&
1234 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1235 ((D.getContext() != Declarator::MemberContext &&
1236 (!D.getCXXScopeSpec().isSet() ||
1237 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true)
1239 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1240 if (D.isFunctionDeclarator())
1241 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1243 Diag(D.getIdentifierLoc(),
1244 diag::err_invalid_qualified_typedef_function_type_use);
1246 // Strip the cv-quals from the type.
1247 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1248 FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1252 // If there were any type attributes applied to the decl itself (not the
1253 // type, apply the type attribute to the type!)
1254 if (const AttributeList *Attrs = D.getAttributes())
1255 ProcessTypeAttributeList(T, Attrs);
1258 if (D.isInvalidType())
1261 *DInfo = GetDeclaratorInfoForDeclarator(D, T);
1268 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> {
1272 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {}
1274 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1275 Visit(TL.getUnqualifiedLoc());
1277 void VisitTypedefTypeLoc(TypedefTypeLoc TL) {
1278 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1280 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) {
1281 TL.setNameLoc(DS.getTypeSpecTypeLoc());
1283 if (DS.getProtocolQualifiers()) {
1284 assert(TL.getNumProtocols() > 0);
1285 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1286 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1287 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1288 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1289 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1291 assert(TL.getNumProtocols() == 0);
1292 TL.setLAngleLoc(SourceLocation());
1293 TL.setRAngleLoc(SourceLocation());
1296 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1297 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1299 TL.setStarLoc(SourceLocation());
1301 if (DS.getProtocolQualifiers()) {
1302 assert(TL.getNumProtocols() > 0);
1303 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers());
1304 TL.setHasProtocolsAsWritten(true);
1305 TL.setLAngleLoc(DS.getProtocolLAngleLoc());
1306 TL.setRAngleLoc(DS.getSourceRange().getEnd());
1307 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i)
1308 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]);
1311 assert(TL.getNumProtocols() == 0);
1312 TL.setHasProtocolsAsWritten(false);
1313 TL.setLAngleLoc(SourceLocation());
1314 TL.setRAngleLoc(SourceLocation());
1317 // This might not have been written with an inner type.
1318 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) {
1319 TL.setHasBaseTypeAsWritten(false);
1320 TL.getBaseTypeLoc().initialize(SourceLocation());
1322 TL.setHasBaseTypeAsWritten(true);
1323 Visit(TL.getBaseTypeLoc());
1326 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) {
1327 DeclaratorInfo *DInfo = 0;
1328 Sema::GetTypeFromParser(DS.getTypeRep(), &DInfo);
1330 // If we got no declarator info from previous Sema routines,
1331 // just fill with the typespec loc.
1333 TL.initialize(DS.getTypeSpecTypeLoc());
1337 TemplateSpecializationTypeLoc OldTL =
1338 cast<TemplateSpecializationTypeLoc>(DInfo->getTypeLoc());
1341 void VisitTypeLoc(TypeLoc TL) {
1342 // FIXME: add other typespec types and change this to an assert.
1343 TL.initialize(DS.getTypeSpecTypeLoc());
1347 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> {
1348 const DeclaratorChunk &Chunk;
1351 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {}
1353 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) {
1354 llvm::llvm_unreachable("qualified type locs not expected here!");
1357 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) {
1358 assert(Chunk.Kind == DeclaratorChunk::BlockPointer);
1359 TL.setCaretLoc(Chunk.Loc);
1361 void VisitPointerTypeLoc(PointerTypeLoc TL) {
1362 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1363 TL.setStarLoc(Chunk.Loc);
1365 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) {
1366 assert(Chunk.Kind == DeclaratorChunk::Pointer);
1367 TL.setStarLoc(Chunk.Loc);
1368 TL.setHasBaseTypeAsWritten(true);
1369 TL.setHasProtocolsAsWritten(false);
1370 TL.setLAngleLoc(SourceLocation());
1371 TL.setRAngleLoc(SourceLocation());
1373 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) {
1374 assert(Chunk.Kind == DeclaratorChunk::MemberPointer);
1375 TL.setStarLoc(Chunk.Loc);
1376 // FIXME: nested name specifier
1378 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) {
1379 assert(Chunk.Kind == DeclaratorChunk::Reference);
1380 // 'Amp' is misleading: this might have been originally
1381 /// spelled with AmpAmp.
1382 TL.setAmpLoc(Chunk.Loc);
1384 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) {
1385 assert(Chunk.Kind == DeclaratorChunk::Reference);
1386 assert(!Chunk.Ref.LValueRef);
1387 TL.setAmpAmpLoc(Chunk.Loc);
1389 void VisitArrayTypeLoc(ArrayTypeLoc TL) {
1390 assert(Chunk.Kind == DeclaratorChunk::Array);
1391 TL.setLBracketLoc(Chunk.Loc);
1392 TL.setRBracketLoc(Chunk.EndLoc);
1393 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts));
1395 void VisitFunctionTypeLoc(FunctionTypeLoc TL) {
1396 assert(Chunk.Kind == DeclaratorChunk::Function);
1397 TL.setLParenLoc(Chunk.Loc);
1398 TL.setRParenLoc(Chunk.EndLoc);
1400 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun;
1401 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) {
1402 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>();
1403 TL.setArg(tpi++, Param);
1405 // FIXME: exception specs
1408 void VisitTypeLoc(TypeLoc TL) {
1409 llvm::llvm_unreachable("unsupported TypeLoc kind in declarator!");
1414 /// \brief Create and instantiate a DeclaratorInfo with type source information.
1416 /// \param T QualType referring to the type as written in source code.
1418 Sema::GetDeclaratorInfoForDeclarator(Declarator &D, QualType T) {
1419 DeclaratorInfo *DInfo = Context.CreateDeclaratorInfo(T);
1420 UnqualTypeLoc CurrTL = DInfo->getTypeLoc().getUnqualifiedLoc();
1422 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
1423 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL);
1424 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc();
1427 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL);
1432 /// \brief Create a LocInfoType to hold the given QualType and DeclaratorInfo.
1433 QualType Sema::CreateLocInfoType(QualType T, DeclaratorInfo *DInfo) {
1434 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser
1435 // and Sema during declaration parsing. Try deallocating/caching them when
1436 // it's appropriate, instead of allocating them and keeping them around.
1437 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8);
1438 new (LocT) LocInfoType(T, DInfo);
1439 assert(LocT->getTypeClass() != T->getTypeClass() &&
1440 "LocInfoType's TypeClass conflicts with an existing Type class");
1441 return QualType(LocT, 0);
1444 void LocInfoType::getAsStringInternal(std::string &Str,
1445 const PrintingPolicy &Policy) const {
1446 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*"
1447 " was used directly instead of getting the QualType through"
1448 " GetTypeFromParser");
1451 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1453 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1454 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1455 QualType T = MDecl->getResultType();
1456 llvm::SmallVector<QualType, 16> ArgTys;
1458 // Add the first two invisible argument types for self and _cmd.
1459 if (MDecl->isInstanceMethod()) {
1460 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1461 selfTy = Context.getPointerType(selfTy);
1462 ArgTys.push_back(selfTy);
1464 ArgTys.push_back(Context.getObjCIdType());
1465 ArgTys.push_back(Context.getObjCSelType());
1467 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1468 E = MDecl->param_end(); PI != E; ++PI) {
1469 QualType ArgTy = (*PI)->getType();
1470 assert(!ArgTy.isNull() && "Couldn't parse type?");
1471 ArgTy = adjustParameterType(ArgTy);
1472 ArgTys.push_back(ArgTy);
1474 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1475 MDecl->isVariadic(), 0);
1479 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1480 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1481 /// they point to and return true. If T1 and T2 aren't pointer types
1482 /// or pointer-to-member types, or if they are not similar at this
1483 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1484 /// qualifiers on T1 and T2 are ignored. This function will typically
1485 /// be called in a loop that successively "unwraps" pointer and
1486 /// pointer-to-member types to compare them at each level.
1487 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1488 const PointerType *T1PtrType = T1->getAs<PointerType>(),
1489 *T2PtrType = T2->getAs<PointerType>();
1490 if (T1PtrType && T2PtrType) {
1491 T1 = T1PtrType->getPointeeType();
1492 T2 = T2PtrType->getPointeeType();
1496 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(),
1497 *T2MPType = T2->getAs<MemberPointerType>();
1498 if (T1MPType && T2MPType &&
1499 Context.getCanonicalType(T1MPType->getClass()) ==
1500 Context.getCanonicalType(T2MPType->getClass())) {
1501 T1 = T1MPType->getPointeeType();
1502 T2 = T2MPType->getPointeeType();
1508 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1509 // C99 6.7.6: Type names have no identifier. This is already validated by
1511 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1513 DeclaratorInfo *DInfo = 0;
1514 TagDecl *OwnedTag = 0;
1515 QualType T = GetTypeForDeclarator(D, S, &DInfo, &OwnedTag);
1516 if (D.isInvalidType())
1519 if (getLangOptions().CPlusPlus) {
1520 // Check that there are no default arguments (C++ only).
1521 CheckExtraCXXDefaultArguments(D);
1523 // C++0x [dcl.type]p3:
1524 // A type-specifier-seq shall not define a class or enumeration
1525 // unless it appears in the type-id of an alias-declaration
1527 if (OwnedTag && OwnedTag->isDefinition())
1528 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1529 << Context.getTypeDeclType(OwnedTag);
1533 T = CreateLocInfoType(T, DInfo);
1535 return T.getAsOpaquePtr();
1540 //===----------------------------------------------------------------------===//
1541 // Type Attribute Processing
1542 //===----------------------------------------------------------------------===//
1544 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1545 /// specified type. The attribute contains 1 argument, the id of the address
1546 /// space for the type.
1547 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1548 const AttributeList &Attr, Sema &S){
1550 // If this type is already address space qualified, reject it.
1551 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1552 // for two or more different address spaces."
1553 if (Type.getAddressSpace()) {
1554 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1558 // Check the attribute arguments.
1559 if (Attr.getNumArgs() != 1) {
1560 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1563 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1564 llvm::APSInt addrSpace(32);
1565 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1566 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1567 << ASArgExpr->getSourceRange();
1572 if (addrSpace.isSigned()) {
1573 if (addrSpace.isNegative()) {
1574 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative)
1575 << ASArgExpr->getSourceRange();
1578 addrSpace.setIsSigned(false);
1580 llvm::APSInt max(addrSpace.getBitWidth());
1581 max = Qualifiers::MaxAddressSpace;
1582 if (addrSpace > max) {
1583 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high)
1584 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange();
1588 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1589 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1592 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1593 /// specified type. The attribute contains 1 argument, weak or strong.
1594 static void HandleObjCGCTypeAttribute(QualType &Type,
1595 const AttributeList &Attr, Sema &S) {
1596 if (Type.getObjCGCAttr() != Qualifiers::GCNone) {
1597 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1601 // Check the attribute arguments.
1602 if (!Attr.getParameterName()) {
1603 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1607 Qualifiers::GC GCAttr;
1608 if (Attr.getNumArgs() != 0) {
1609 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1612 if (Attr.getParameterName()->isStr("weak"))
1613 GCAttr = Qualifiers::Weak;
1614 else if (Attr.getParameterName()->isStr("strong"))
1615 GCAttr = Qualifiers::Strong;
1617 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1618 << "objc_gc" << Attr.getParameterName();
1622 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1625 /// HandleNoReturnTypeAttribute - Process the noreturn attribute on the
1626 /// specified type. The attribute contains 0 arguments.
1627 static void HandleNoReturnTypeAttribute(QualType &Type,
1628 const AttributeList &Attr, Sema &S) {
1629 if (Attr.getNumArgs() != 0)
1632 // We only apply this to a pointer to function or a pointer to block.
1633 if (!Type->isFunctionPointerType()
1634 && !Type->isBlockPointerType()
1635 && !Type->isFunctionType())
1638 Type = S.Context.getNoReturnType(Type);
1641 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1642 // Scan through and apply attributes to this type where it makes sense. Some
1643 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1644 // type, but others can be present in the type specifiers even though they
1645 // apply to the decl. Here we apply type attributes and ignore the rest.
1646 for (; AL; AL = AL->getNext()) {
1647 // If this is an attribute we can handle, do so now, otherwise, add it to
1648 // the LeftOverAttrs list for rechaining.
1649 switch (AL->getKind()) {
1651 case AttributeList::AT_address_space:
1652 HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1654 case AttributeList::AT_objc_gc:
1655 HandleObjCGCTypeAttribute(Result, *AL, *this);
1657 case AttributeList::AT_noreturn:
1658 HandleNoReturnTypeAttribute(Result, *AL, *this);
1664 /// @brief Ensure that the type T is a complete type.
1666 /// This routine checks whether the type @p T is complete in any
1667 /// context where a complete type is required. If @p T is a complete
1668 /// type, returns false. If @p T is a class template specialization,
1669 /// this routine then attempts to perform class template
1670 /// instantiation. If instantiation fails, or if @p T is incomplete
1671 /// and cannot be completed, issues the diagnostic @p diag (giving it
1672 /// the type @p T) and returns true.
1674 /// @param Loc The location in the source that the incomplete type
1675 /// diagnostic should refer to.
1677 /// @param T The type that this routine is examining for completeness.
1679 /// @param PD The partial diagnostic that will be printed out if T is not a
1682 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1683 /// @c false otherwise.
1684 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T,
1685 const PartialDiagnostic &PD,
1686 std::pair<SourceLocation,
1687 PartialDiagnostic> Note) {
1688 unsigned diag = PD.getDiagID();
1690 // FIXME: Add this assertion to make sure we always get instantiation points.
1691 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType");
1692 // FIXME: Add this assertion to help us flush out problems with
1693 // checking for dependent types and type-dependent expressions.
1695 // assert(!T->isDependentType() &&
1696 // "Can't ask whether a dependent type is complete");
1698 // If we have a complete type, we're done.
1699 if (!T->isIncompleteType())
1702 // If we have a class template specialization or a class member of a
1703 // class template specialization, or an array with known size of such,
1704 // try to instantiate it.
1705 QualType MaybeTemplate = T;
1706 if (const ConstantArrayType *Array = T->getAs<ConstantArrayType>())
1707 MaybeTemplate = Array->getElementType();
1708 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) {
1709 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1710 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1711 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared)
1712 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec,
1713 TSK_ImplicitInstantiation,
1714 /*Complain=*/diag != 0);
1715 } else if (CXXRecordDecl *Rec
1716 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1717 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1718 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo();
1719 assert(MSInfo && "Missing member specialization information?");
1720 // This record was instantiated from a class within a template.
1721 if (MSInfo->getTemplateSpecializationKind()
1722 != TSK_ExplicitSpecialization)
1723 return InstantiateClass(Loc, Rec, Pattern,
1724 getTemplateInstantiationArgs(Rec),
1725 TSK_ImplicitInstantiation,
1726 /*Complain=*/diag != 0);
1734 // We have an incomplete type. Produce a diagnostic.
1737 // If we have a note, produce it.
1738 if (!Note.first.isInvalid())
1739 Diag(Note.first, Note.second);
1741 // If the type was a forward declaration of a class/struct/union
1743 const TagType *Tag = 0;
1744 if (const RecordType *Record = T->getAs<RecordType>())
1746 else if (const EnumType *Enum = T->getAs<EnumType>())
1749 if (Tag && !Tag->getDecl()->isInvalidDecl())
1750 Diag(Tag->getDecl()->getLocation(),
1751 Tag->isBeingDefined() ? diag::note_type_being_defined
1752 : diag::note_forward_declaration)
1753 << QualType(Tag, 0);
1758 /// \brief Retrieve a version of the type 'T' that is qualified by the
1759 /// nested-name-specifier contained in SS.
1760 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1761 if (!SS.isSet() || SS.isInvalid() || T.isNull())
1764 NestedNameSpecifier *NNS
1765 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1766 return Context.getQualifiedNameType(NNS, T);
1769 QualType Sema::BuildTypeofExprType(Expr *E) {
1770 return Context.getTypeOfExprType(E);
1773 QualType Sema::BuildDecltypeType(Expr *E) {
1774 if (E->getType() == Context.OverloadTy) {
1775 Diag(E->getLocStart(),
1776 diag::err_cannot_determine_declared_type_of_overloaded_function);
1779 return Context.getDecltypeType(E);