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/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/Expr.h"
19 #include "clang/Parse/DeclSpec.h"
20 using namespace clang;
22 /// \brief Perform adjustment on the parameter type of a function.
24 /// This routine adjusts the given parameter type @p T to the actual
25 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
26 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
27 QualType Sema::adjustParameterType(QualType T) {
29 if (T->isArrayType()) {
31 // A declaration of a parameter as "array of type" shall be
32 // adjusted to "qualified pointer to type", where the type
33 // qualifiers (if any) are those specified within the [ and ] of
34 // the array type derivation.
35 return Context.getArrayDecayedType(T);
36 } else if (T->isFunctionType())
38 // A declaration of a parameter as "function returning type"
39 // shall be adjusted to "pointer to function returning type", as
41 return Context.getPointerType(T);
46 /// \brief Convert the specified declspec to the appropriate type
48 /// \param DS the declaration specifiers
49 /// \param DeclLoc The location of the declarator identifier or invalid if none.
50 /// \returns The type described by the declaration specifiers. This function
51 /// never returns null.
52 QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
53 SourceLocation DeclLoc,
55 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
59 switch (DS.getTypeSpecType()) {
60 case DeclSpec::TST_void:
61 Result = Context.VoidTy;
63 case DeclSpec::TST_char:
64 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
65 Result = Context.CharTy;
66 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
67 Result = Context.SignedCharTy;
69 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
71 Result = Context.UnsignedCharTy;
74 case DeclSpec::TST_wchar:
75 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
76 Result = Context.WCharTy;
77 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
78 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
79 << DS.getSpecifierName(DS.getTypeSpecType());
80 Result = Context.getSignedWCharType();
82 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
84 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
85 << DS.getSpecifierName(DS.getTypeSpecType());
86 Result = Context.getUnsignedWCharType();
89 case DeclSpec::TST_unspecified:
90 // "<proto1,proto2>" is an objc qualified ID with a missing id.
91 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
92 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
93 DS.getNumProtocolQualifiers());
97 // Unspecified typespec defaults to int in C90. However, the C90 grammar
98 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
99 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
100 // Note that the one exception to this is function definitions, which are
101 // allowed to be completely missing a declspec. This is handled in the
102 // parser already though by it pretending to have seen an 'int' in this
104 if (getLangOptions().ImplicitInt) {
105 // In C89 mode, we only warn if there is a completely missing declspec
106 // when one is not allowed.
108 if (DeclLoc.isInvalid())
109 DeclLoc = DS.getSourceRange().getBegin();
110 Diag(DeclLoc, diag::ext_missing_declspec)
111 << DS.getSourceRange()
112 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
115 } else if (!DS.hasTypeSpecifier()) {
116 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
117 // "At least one type specifier shall be given in the declaration
118 // specifiers in each declaration, and in the specifier-qualifier list in
119 // each struct declaration and type name."
120 // FIXME: Does Microsoft really have the implicit int extension in C++?
121 if (DeclLoc.isInvalid())
122 DeclLoc = DS.getSourceRange().getBegin();
124 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) {
125 Diag(DeclLoc, diag::err_missing_type_specifier)
126 << DS.getSourceRange();
128 // When this occurs in C++ code, often something is very broken with the
129 // value being declared, poison it as invalid so we don't get chains of
133 Diag(DeclLoc, diag::ext_missing_type_specifier)
134 << DS.getSourceRange();
139 case DeclSpec::TST_int: {
140 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
141 switch (DS.getTypeSpecWidth()) {
142 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
143 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
144 case DeclSpec::TSW_long: Result = Context.LongTy; break;
145 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break;
148 switch (DS.getTypeSpecWidth()) {
149 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
150 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
151 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
152 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break;
157 case DeclSpec::TST_float: Result = Context.FloatTy; break;
158 case DeclSpec::TST_double:
159 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
160 Result = Context.LongDoubleTy;
162 Result = Context.DoubleTy;
164 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
165 case DeclSpec::TST_decimal32: // _Decimal32
166 case DeclSpec::TST_decimal64: // _Decimal64
167 case DeclSpec::TST_decimal128: // _Decimal128
168 Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
169 Result = Context.IntTy;
172 case DeclSpec::TST_class:
173 case DeclSpec::TST_enum:
174 case DeclSpec::TST_union:
175 case DeclSpec::TST_struct: {
176 Decl *D = static_cast<Decl *>(DS.getTypeRep());
177 assert(D && "Didn't get a decl for a class/enum/union/struct?");
178 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
179 DS.getTypeSpecSign() == 0 &&
180 "Can't handle qualifiers on typedef names yet!");
181 // TypeQuals handled by caller.
182 Result = Context.getTypeDeclType(cast<TypeDecl>(D));
184 if (D->isInvalidDecl())
188 case DeclSpec::TST_typename: {
189 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
190 DS.getTypeSpecSign() == 0 &&
191 "Can't handle qualifiers on typedef names yet!");
192 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
194 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
195 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have
196 // this "hack" for now...
197 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
198 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
199 (ObjCProtocolDecl**)PQ,
200 DS.getNumProtocolQualifiers());
201 else if (Result == Context.getObjCIdType())
203 Result = Context.getObjCQualifiedIdType((ObjCProtocolDecl**)PQ,
204 DS.getNumProtocolQualifiers());
205 else if (Result == Context.getObjCClassType()) {
206 if (DeclLoc.isInvalid())
207 DeclLoc = DS.getSourceRange().getBegin();
208 // Class<protocol-list>
209 Diag(DeclLoc, diag::err_qualified_class_unsupported)
210 << DS.getSourceRange();
212 if (DeclLoc.isInvalid())
213 DeclLoc = DS.getSourceRange().getBegin();
214 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
215 << DS.getSourceRange();
220 // If this is a reference to an invalid typedef, propagate the invalidity.
221 if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
222 if (TDT->getDecl()->isInvalidDecl())
225 // TypeQuals handled by caller.
228 case DeclSpec::TST_typeofType:
229 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
230 assert(!Result.isNull() && "Didn't get a type for typeof?");
231 // TypeQuals handled by caller.
232 Result = Context.getTypeOfType(Result);
234 case DeclSpec::TST_typeofExpr: {
235 Expr *E = static_cast<Expr *>(DS.getTypeRep());
236 assert(E && "Didn't get an expression for typeof?");
237 // TypeQuals handled by caller.
238 Result = Context.getTypeOfExprType(E);
241 case DeclSpec::TST_decltype: {
242 Expr *E = static_cast<Expr *>(DS.getTypeRep());
243 assert(E && "Didn't get an expression for decltype?");
244 // TypeQuals handled by caller.
245 Result = Context.getDecltypeType(E);
248 case DeclSpec::TST_auto: {
249 // TypeQuals handled by caller.
250 Result = Context.UndeducedAutoTy;
254 case DeclSpec::TST_error:
255 Result = Context.IntTy;
260 // Handle complex types.
261 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
262 if (getLangOptions().Freestanding)
263 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
264 Result = Context.getComplexType(Result);
267 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
268 "FIXME: imaginary types not supported yet!");
270 // See if there are any attributes on the declspec that apply to the type (as
271 // opposed to the decl).
272 if (const AttributeList *AL = DS.getAttributes())
273 ProcessTypeAttributeList(Result, AL);
275 // Apply const/volatile/restrict qualifiers to T.
276 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
278 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
279 // or incomplete types shall not be restrict-qualified." C++ also allows
280 // restrict-qualified references.
281 if (TypeQuals & QualType::Restrict) {
282 if (Result->isPointerType() || Result->isReferenceType()) {
283 QualType EltTy = Result->isPointerType() ?
284 Result->getAsPointerType()->getPointeeType() :
285 Result->getAsReferenceType()->getPointeeType();
287 // If we have a pointer or reference, the pointee must have an object
289 if (!EltTy->isIncompleteOrObjectType()) {
290 Diag(DS.getRestrictSpecLoc(),
291 diag::err_typecheck_invalid_restrict_invalid_pointee)
292 << EltTy << DS.getSourceRange();
293 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
296 Diag(DS.getRestrictSpecLoc(),
297 diag::err_typecheck_invalid_restrict_not_pointer)
298 << Result << DS.getSourceRange();
299 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
303 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
304 // of a function type includes any type qualifiers, the behavior is
306 if (Result->isFunctionType() && TypeQuals) {
307 // Get some location to point at, either the C or V location.
309 if (TypeQuals & QualType::Const)
310 Loc = DS.getConstSpecLoc();
312 assert((TypeQuals & QualType::Volatile) &&
313 "Has CV quals but not C or V?");
314 Loc = DS.getVolatileSpecLoc();
316 Diag(Loc, diag::warn_typecheck_function_qualifiers)
317 << Result << DS.getSourceRange();
321 // Cv-qualified references are ill-formed except when the
322 // cv-qualifiers are introduced through the use of a typedef
323 // (7.1.3) or of a template type argument (14.3), in which
324 // case the cv-qualifiers are ignored.
325 // FIXME: Shouldn't we be checking SCS_typedef here?
326 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
327 TypeQuals && Result->isReferenceType()) {
328 TypeQuals &= ~QualType::Const;
329 TypeQuals &= ~QualType::Volatile;
332 Result = Result.getQualifiedType(TypeQuals);
337 static std::string getPrintableNameForEntity(DeclarationName Entity) {
339 return Entity.getAsString();
344 /// \brief Build a pointer type.
346 /// \param T The type to which we'll be building a pointer.
348 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
350 /// \param Loc The location of the entity whose type involves this
351 /// pointer type or, if there is no such entity, the location of the
352 /// type that will have pointer type.
354 /// \param Entity The name of the entity that involves the pointer
357 /// \returns A suitable pointer type, if there are no
358 /// errors. Otherwise, returns a NULL type.
359 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
360 SourceLocation Loc, DeclarationName Entity) {
361 if (T->isReferenceType()) {
362 // C++ 8.3.2p4: There shall be no ... pointers to references ...
363 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
364 << getPrintableNameForEntity(Entity);
368 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
369 // object or incomplete types shall not be restrict-qualified."
370 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
371 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
373 Quals &= ~QualType::Restrict;
376 // Build the pointer type.
377 return Context.getPointerType(T).getQualifiedType(Quals);
380 /// \brief Build a reference type.
382 /// \param T The type to which we'll be building a reference.
384 /// \param Quals The cvr-qualifiers to be applied to the reference type.
386 /// \param Loc The location of the entity whose type involves this
387 /// reference type or, if there is no such entity, the location of the
388 /// type that will have reference type.
390 /// \param Entity The name of the entity that involves the reference
393 /// \returns A suitable reference type, if there are no
394 /// errors. Otherwise, returns a NULL type.
395 QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
396 SourceLocation Loc, DeclarationName Entity) {
398 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
399 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
400 // reference to a type T, and attempt to create the type "lvalue
401 // reference to cv TD" creates the type "lvalue reference to T".
402 // We use the qualifiers (restrict or none) of the original reference,
403 // not the new ones. This is consistent with GCC.
404 return Context.getLValueReferenceType(R->getPointeeType()).
405 getQualifiedType(T.getCVRQualifiers());
408 if (T->isReferenceType()) {
409 // C++ [dcl.ref]p4: There shall be no references to references.
411 // According to C++ DR 106, references to references are only
412 // diagnosed when they are written directly (e.g., "int & &"),
413 // but not when they happen via a typedef:
415 // typedef int& intref;
416 // typedef intref& intref2;
418 // Parser::ParserDeclaratorInternal diagnoses the case where
419 // references are written directly; here, we handle the
420 // collapsing of references-to-references as described in C++
421 // DR 106 and amended by C++ DR 540.
426 // A declarator that specifies the type “reference to cv void”
428 if (T->isVoidType()) {
429 Diag(Loc, diag::err_reference_to_void);
433 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
434 // object or incomplete types shall not be restrict-qualified."
435 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
436 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
438 Quals &= ~QualType::Restrict;
442 // [...] Cv-qualified references are ill-formed except when the
443 // cv-qualifiers are introduced through the use of a typedef
444 // (7.1.3) or of a template type argument (14.3), in which case
445 // the cv-qualifiers are ignored.
447 // We diagnose extraneous cv-qualifiers for the non-typedef,
448 // non-template type argument case within the parser. Here, we just
449 // ignore any extraneous cv-qualifiers.
450 Quals &= ~QualType::Const;
451 Quals &= ~QualType::Volatile;
453 // Handle restrict on references.
455 return Context.getLValueReferenceType(T).getQualifiedType(Quals);
456 return Context.getRValueReferenceType(T).getQualifiedType(Quals);
459 /// \brief Build an array type.
461 /// \param T The type of each element in the array.
463 /// \param ASM C99 array size modifier (e.g., '*', 'static').
465 /// \param ArraySize Expression describing the size of the array.
467 /// \param Quals The cvr-qualifiers to be applied to the array's
470 /// \param Loc The location of the entity whose type involves this
471 /// array type or, if there is no such entity, the location of the
472 /// type that will have array type.
474 /// \param Entity The name of the entity that involves the array
477 /// \returns A suitable array type, if there are no errors. Otherwise,
478 /// returns a NULL type.
479 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
480 Expr *ArraySize, unsigned Quals,
481 SourceLocation Loc, DeclarationName Entity) {
482 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
483 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
484 if (RequireCompleteType(Loc, T,
485 diag::err_illegal_decl_array_incomplete_type))
488 if (T->isFunctionType()) {
489 Diag(Loc, diag::err_illegal_decl_array_of_functions)
490 << getPrintableNameForEntity(Entity);
494 // C++ 8.3.2p4: There shall be no ... arrays of references ...
495 if (T->isReferenceType()) {
496 Diag(Loc, diag::err_illegal_decl_array_of_references)
497 << getPrintableNameForEntity(Entity);
501 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
502 Diag(Loc, diag::err_illegal_decl_array_of_auto)
503 << getPrintableNameForEntity(Entity);
507 if (const RecordType *EltTy = T->getAsRecordType()) {
508 // If the element type is a struct or union that contains a variadic
509 // array, accept it as a GNU extension: C99 6.7.2.1p2.
510 if (EltTy->getDecl()->hasFlexibleArrayMember())
511 Diag(Loc, diag::ext_flexible_array_in_array) << T;
512 } else if (T->isObjCInterfaceType()) {
513 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
517 // C99 6.7.5.2p1: The size expression shall have integer type.
518 if (ArraySize && !ArraySize->isTypeDependent() &&
519 !ArraySize->getType()->isIntegerType()) {
520 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
521 << ArraySize->getType() << ArraySize->getSourceRange();
522 ArraySize->Destroy(Context);
525 llvm::APSInt ConstVal(32);
527 if (ASM == ArrayType::Star)
528 T = Context.getVariableArrayType(T, 0, ASM, Quals);
530 T = Context.getIncompleteArrayType(T, ASM, Quals);
531 } else if (ArraySize->isValueDependent()) {
532 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
533 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
534 (!T->isDependentType() && !T->isConstantSizeType())) {
535 // Per C99, a variable array is an array with either a non-constant
536 // size or an element type that has a non-constant-size
537 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
539 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
540 // have a value greater than zero.
541 if (ConstVal.isSigned()) {
542 if (ConstVal.isNegative()) {
543 Diag(ArraySize->getLocStart(),
544 diag::err_typecheck_negative_array_size)
545 << ArraySize->getSourceRange();
547 } else if (ConstVal == 0) {
548 // GCC accepts zero sized static arrays.
549 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
550 << ArraySize->getSourceRange();
553 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
555 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
556 if (!getLangOptions().C99) {
557 if (ArraySize && !ArraySize->isTypeDependent() &&
558 !ArraySize->isValueDependent() &&
559 !ArraySize->isIntegerConstantExpr(Context))
560 Diag(Loc, diag::ext_vla);
561 else if (ASM != ArrayType::Normal || Quals != 0)
562 Diag(Loc, diag::ext_c99_array_usage);
568 /// \brief Build an ext-vector type.
570 /// Run the required checks for the extended vector type.
571 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
572 SourceLocation AttrLoc) {
574 Expr *Arg = (Expr *)ArraySize.get();
576 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
577 // in conjunction with complex types (pointers, arrays, functions, etc.).
578 if (!T->isDependentType() &&
579 !T->isIntegerType() && !T->isRealFloatingType()) {
580 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
584 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
585 llvm::APSInt vecSize(32);
586 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
587 Diag(AttrLoc, diag::err_attribute_argument_not_int)
588 << "ext_vector_type" << Arg->getSourceRange();
592 // unlike gcc's vector_size attribute, the size is specified as the
593 // number of elements, not the number of bytes.
594 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
596 if (vectorSize == 0) {
597 Diag(AttrLoc, diag::err_attribute_zero_size)
598 << Arg->getSourceRange();
602 if (!T->isDependentType())
603 return Context.getExtVectorType(T, vectorSize);
606 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
610 /// \brief Build a function type.
612 /// This routine checks the function type according to C++ rules and
613 /// under the assumption that the result type and parameter types have
614 /// just been instantiated from a template. It therefore duplicates
615 /// some of the behavior of GetTypeForDeclarator, but in a much
616 /// simpler form that is only suitable for this narrow use case.
618 /// \param T The return type of the function.
620 /// \param ParamTypes The parameter types of the function. This array
621 /// will be modified to account for adjustments to the types of the
622 /// function parameters.
624 /// \param NumParamTypes The number of parameter types in ParamTypes.
626 /// \param Variadic Whether this is a variadic function type.
628 /// \param Quals The cvr-qualifiers to be applied to the function type.
630 /// \param Loc The location of the entity whose type involves this
631 /// function type or, if there is no such entity, the location of the
632 /// type that will have function type.
634 /// \param Entity The name of the entity that involves the function
637 /// \returns A suitable function type, if there are no
638 /// errors. Otherwise, returns a NULL type.
639 QualType Sema::BuildFunctionType(QualType T,
640 QualType *ParamTypes,
641 unsigned NumParamTypes,
642 bool Variadic, unsigned Quals,
643 SourceLocation Loc, DeclarationName Entity) {
644 if (T->isArrayType() || T->isFunctionType()) {
645 Diag(Loc, diag::err_func_returning_array_function) << T;
649 bool Invalid = false;
650 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
651 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
652 if (ParamType->isVoidType()) {
653 Diag(Loc, diag::err_param_with_void_type);
657 ParamTypes[Idx] = ParamType;
663 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
667 /// \brief Build a member pointer type \c T Class::*.
669 /// \param T the type to which the member pointer refers.
670 /// \param Class the class type into which the member pointer points.
671 /// \param Quals Qualifiers applied to the member pointer type
672 /// \param Loc the location where this type begins
673 /// \param Entity the name of the entity that will have this member pointer type
675 /// \returns a member pointer type, if successful, or a NULL type if there was
677 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
678 unsigned Quals, SourceLocation Loc,
679 DeclarationName Entity) {
680 // Verify that we're not building a pointer to pointer to function with
681 // exception specification.
682 if (CheckDistantExceptionSpec(T)) {
683 Diag(Loc, diag::err_distant_exception_spec);
685 // FIXME: If we're doing this as part of template instantiation,
686 // we should return immediately.
688 // Build the type anyway, but use the canonical type so that the
689 // exception specifiers are stripped off.
690 T = Context.getCanonicalType(T);
693 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
694 // with reference type, or "cv void."
695 if (T->isReferenceType()) {
696 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
697 << (Entity? Entity.getAsString() : "type name");
701 if (T->isVoidType()) {
702 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
703 << (Entity? Entity.getAsString() : "type name");
707 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
708 // object or incomplete types shall not be restrict-qualified."
709 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
710 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
713 // FIXME: If we're doing this as part of template instantiation,
714 // we should return immediately.
715 Quals &= ~QualType::Restrict;
718 if (!Class->isDependentType() && !Class->isRecordType()) {
719 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
723 return Context.getMemberPointerType(T, Class.getTypePtr())
724 .getQualifiedType(Quals);
727 /// \brief Build a block pointer type.
729 /// \param T The type to which we'll be building a block pointer.
731 /// \param Quals The cvr-qualifiers to be applied to the block pointer type.
733 /// \param Loc The location of the entity whose type involves this
734 /// block pointer type or, if there is no such entity, the location of the
735 /// type that will have block pointer type.
737 /// \param Entity The name of the entity that involves the block pointer
740 /// \returns A suitable block pointer type, if there are no
741 /// errors. Otherwise, returns a NULL type.
742 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
744 DeclarationName Entity) {
745 if (!T.getTypePtr()->isFunctionType()) {
746 Diag(Loc, diag::err_nonfunction_block_type);
750 return Context.getBlockPointerType(T).getQualifiedType(Quals);
753 /// GetTypeForDeclarator - Convert the type for the specified
754 /// declarator to Type instances. Skip the outermost Skip type
757 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
758 /// owns the declaration of a type (e.g., the definition of a struct
759 /// type), then *OwnedDecl will receive the owned declaration.
760 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
761 TagDecl **OwnedDecl) {
762 bool OmittedReturnType = false;
764 if (D.getContext() == Declarator::BlockLiteralContext
766 && !D.getDeclSpec().hasTypeSpecifier()
767 && (D.getNumTypeObjects() == 0
768 || (D.getNumTypeObjects() == 1
769 && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
770 OmittedReturnType = true;
772 // long long is a C99 feature.
773 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
774 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
775 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
777 // Determine the type of the declarator. Not all forms of declarator
780 switch (D.getKind()) {
781 case Declarator::DK_Abstract:
782 case Declarator::DK_Normal:
783 case Declarator::DK_Operator: {
784 const DeclSpec &DS = D.getDeclSpec();
785 if (OmittedReturnType) {
786 // We default to a dependent type initially. Can be modified by
787 // the first return statement.
788 T = Context.DependentTy;
790 bool isInvalid = false;
791 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
793 D.setInvalidType(true);
794 else if (OwnedDecl && DS.isTypeSpecOwned())
795 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
800 case Declarator::DK_Constructor:
801 case Declarator::DK_Destructor:
802 case Declarator::DK_Conversion:
803 // Constructors and destructors don't have return types. Use
804 // "void" instead. Conversion operators will check their return
810 if (T == Context.UndeducedAutoTy) {
813 switch (D.getContext()) {
814 case Declarator::KNRTypeListContext:
815 assert(0 && "K&R type lists aren't allowed in C++");
818 printf("context: %d\n", D.getContext());
820 case Declarator::PrototypeContext:
821 Error = 0; // Function prototype
823 case Declarator::MemberContext:
824 switch (cast<TagDecl>(CurContext)->getTagKind()) {
825 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
826 case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
827 case TagDecl::TK_union: Error = 2; /* Union member */ break;
828 case TagDecl::TK_class: Error = 3; /* Class member */ break;
831 case Declarator::CXXCatchContext:
832 Error = 4; // Exception declaration
834 case Declarator::TemplateParamContext:
835 Error = 5; // Template parameter
837 case Declarator::BlockLiteralContext:
838 Error = 6; // Block literal
840 case Declarator::FileContext:
841 case Declarator::BlockContext:
842 case Declarator::ForContext:
843 case Declarator::ConditionContext:
844 case Declarator::TypeNameContext:
849 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
852 D.setInvalidType(true);
856 // The name we're declaring, if any.
857 DeclarationName Name;
858 if (D.getIdentifier())
859 Name = D.getIdentifier();
861 // Walk the DeclTypeInfo, building the recursive type as we go.
862 // DeclTypeInfos are ordered from the identifier out, which is
863 // opposite of what we want :).
864 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
865 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
866 switch (DeclType.Kind) {
867 default: assert(0 && "Unknown decltype!");
868 case DeclaratorChunk::BlockPointer:
869 // If blocks are disabled, emit an error.
870 if (!LangOpts.Blocks)
871 Diag(DeclType.Loc, diag::err_blocks_disable);
873 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
876 case DeclaratorChunk::Pointer:
877 // Verify that we're not building a pointer to pointer to function with
878 // exception specification.
879 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
880 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
881 D.setInvalidType(true);
882 // Build the type anyway.
884 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
886 case DeclaratorChunk::Reference:
887 // Verify that we're not building a reference to pointer to function with
888 // exception specification.
889 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
890 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
891 D.setInvalidType(true);
892 // Build the type anyway.
894 T = BuildReferenceType(T, DeclType.Ref.LValueRef,
895 DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
898 case DeclaratorChunk::Array: {
899 // Verify that we're not building an array of pointers to function with
900 // exception specification.
901 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
902 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
903 D.setInvalidType(true);
904 // Build the type anyway.
906 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
907 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
908 ArrayType::ArraySizeModifier ASM;
910 ASM = ArrayType::Star;
911 else if (ATI.hasStatic)
912 ASM = ArrayType::Static;
914 ASM = ArrayType::Normal;
915 if (ASM == ArrayType::Star &&
916 D.getContext() != Declarator::PrototypeContext) {
917 // FIXME: This check isn't quite right: it allows star in prototypes
918 // for function definitions, and disallows some edge cases detailed
919 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
920 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
921 ASM = ArrayType::Normal;
922 D.setInvalidType(true);
924 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
927 case DeclaratorChunk::Function: {
928 // If the function declarator has a prototype (i.e. it is not () and
929 // does not have a K&R-style identifier list), then the arguments are part
930 // of the type, otherwise the argument list is ().
931 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
933 // C99 6.7.5.3p1: The return type may not be a function or array type.
934 if (T->isArrayType() || T->isFunctionType()) {
935 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
937 D.setInvalidType(true);
940 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
942 // Types shall not be defined in return or parameter types.
943 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
944 if (Tag->isDefinition())
945 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
946 << Context.getTypeDeclType(Tag);
949 // Exception specs are not allowed in typedefs. Complain, but add it
951 if (FTI.hasExceptionSpec &&
952 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
953 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
955 if (FTI.NumArgs == 0) {
956 if (getLangOptions().CPlusPlus) {
957 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
958 // function takes no arguments.
959 llvm::SmallVector<QualType, 4> Exceptions;
960 Exceptions.reserve(FTI.NumExceptions);
961 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
962 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
963 // Check that the type is valid for an exception spec, and drop it
965 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
966 Exceptions.push_back(ET);
968 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
969 FTI.hasExceptionSpec,
970 FTI.hasAnyExceptionSpec,
971 Exceptions.size(), Exceptions.data());
972 } else if (FTI.isVariadic) {
973 // We allow a zero-parameter variadic function in C if the
974 // function is marked with the "overloadable"
975 // attribute. Scan for this attribute now.
976 bool Overloadable = false;
977 for (const AttributeList *Attrs = D.getAttributes();
978 Attrs; Attrs = Attrs->getNext()) {
979 if (Attrs->getKind() == AttributeList::AT_overloadable) {
986 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
987 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
989 // Simple void foo(), where the incoming T is the result type.
990 T = Context.getFunctionNoProtoType(T);
992 } else if (FTI.ArgInfo[0].Param == 0) {
993 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
994 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
996 // Otherwise, we have a function with an argument list that is
997 // potentially variadic.
998 llvm::SmallVector<QualType, 16> ArgTys;
1000 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1001 ParmVarDecl *Param =
1002 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1003 QualType ArgTy = Param->getType();
1004 assert(!ArgTy.isNull() && "Couldn't parse type?");
1006 // Adjust the parameter type.
1007 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1009 // Look for 'void'. void is allowed only as a single argument to a
1010 // function with no other parameters (C99 6.7.5.3p10). We record
1011 // int(void) as a FunctionProtoType with an empty argument list.
1012 if (ArgTy->isVoidType()) {
1013 // If this is something like 'float(int, void)', reject it. 'void'
1014 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1015 // have arguments of incomplete type.
1016 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1017 Diag(DeclType.Loc, diag::err_void_only_param);
1018 ArgTy = Context.IntTy;
1019 Param->setType(ArgTy);
1020 } else if (FTI.ArgInfo[i].Ident) {
1021 // Reject, but continue to parse 'int(void abc)'.
1022 Diag(FTI.ArgInfo[i].IdentLoc,
1023 diag::err_param_with_void_type);
1024 ArgTy = Context.IntTy;
1025 Param->setType(ArgTy);
1027 // Reject, but continue to parse 'float(const void)'.
1028 if (ArgTy.getCVRQualifiers())
1029 Diag(DeclType.Loc, diag::err_void_param_qualified);
1031 // Do not add 'void' to the ArgTys list.
1034 } else if (!FTI.hasPrototype) {
1035 if (ArgTy->isPromotableIntegerType()) {
1036 ArgTy = Context.IntTy;
1037 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
1038 if (BTy->getKind() == BuiltinType::Float)
1039 ArgTy = Context.DoubleTy;
1043 ArgTys.push_back(ArgTy);
1046 llvm::SmallVector<QualType, 4> Exceptions;
1047 Exceptions.reserve(FTI.NumExceptions);
1048 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1049 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
1050 // Check that the type is valid for an exception spec, and drop it if
1052 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1053 Exceptions.push_back(ET);
1056 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1057 FTI.isVariadic, FTI.TypeQuals,
1058 FTI.hasExceptionSpec,
1059 FTI.hasAnyExceptionSpec,
1060 Exceptions.size(), Exceptions.data());
1064 case DeclaratorChunk::MemberPointer:
1065 // The scope spec must refer to a class, or be dependent.
1067 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1068 NestedNameSpecifier *NNS
1069 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1070 assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1071 ClsType = QualType(NNS->getAsType(), 0);
1072 } else if (CXXRecordDecl *RD
1073 = dyn_cast_or_null<CXXRecordDecl>(
1074 computeDeclContext(DeclType.Mem.Scope()))) {
1075 ClsType = Context.getTagDeclType(RD);
1077 Diag(DeclType.Mem.Scope().getBeginLoc(),
1078 diag::err_illegal_decl_mempointer_in_nonclass)
1079 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1080 << DeclType.Mem.Scope().getRange();
1081 D.setInvalidType(true);
1084 if (!ClsType.isNull())
1085 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1086 DeclType.Loc, D.getIdentifier());
1089 D.setInvalidType(true);
1095 D.setInvalidType(true);
1099 // See if there are any attributes on this declarator chunk.
1100 if (const AttributeList *AL = DeclType.getAttrs())
1101 ProcessTypeAttributeList(T, AL);
1104 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1105 const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
1106 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
1108 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1109 // for a nonstatic member function, the function type to which a pointer
1110 // to member refers, or the top-level function type of a function typedef
1112 if (FnTy->getTypeQuals() != 0 &&
1113 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1114 ((D.getContext() != Declarator::MemberContext &&
1115 (!D.getCXXScopeSpec().isSet() ||
1116 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
1117 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1118 if (D.isFunctionDeclarator())
1119 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1121 Diag(D.getIdentifierLoc(),
1122 diag::err_invalid_qualified_typedef_function_type_use);
1124 // Strip the cv-quals from the type.
1125 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1126 FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1130 // If there were any type attributes applied to the decl itself (not the
1131 // type, apply the type attribute to the type!)
1132 if (const AttributeList *Attrs = D.getAttributes())
1133 ProcessTypeAttributeList(T, Attrs);
1138 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
1139 /// exception specification. Incomplete types, or pointers to incomplete types
1140 /// other than void are not allowed.
1141 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1142 // FIXME: This may not correctly work with the fix for core issue 437,
1143 // where a class's own type is considered complete within its body.
1145 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1146 // an incomplete type.
1147 if (T->isIncompleteType())
1148 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1149 << Range << T << /*direct*/0;
1151 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1152 // an incomplete type a pointer or reference to an incomplete type, other
1155 if (const PointerType* IT = T->getAsPointerType()) {
1156 T = IT->getPointeeType();
1158 } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1159 T = IT->getPointeeType();
1164 if (T->isIncompleteType() && !T->isVoidType())
1165 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1166 << Range << T << /*indirect*/kind;
1171 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1172 /// to member to a function with an exception specification. This means that
1173 /// it is invalid to add another level of indirection.
1174 bool Sema::CheckDistantExceptionSpec(QualType T) {
1175 if (const PointerType *PT = T->getAsPointerType())
1176 T = PT->getPointeeType();
1177 else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1178 T = PT->getPointeeType();
1182 const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1186 return FnT->hasExceptionSpec();
1189 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1191 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1192 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1193 QualType T = MDecl->getResultType();
1194 llvm::SmallVector<QualType, 16> ArgTys;
1196 // Add the first two invisible argument types for self and _cmd.
1197 if (MDecl->isInstanceMethod()) {
1198 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1199 selfTy = Context.getPointerType(selfTy);
1200 ArgTys.push_back(selfTy);
1202 ArgTys.push_back(Context.getObjCIdType());
1203 ArgTys.push_back(Context.getObjCSelType());
1205 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1206 E = MDecl->param_end(); PI != E; ++PI) {
1207 QualType ArgTy = (*PI)->getType();
1208 assert(!ArgTy.isNull() && "Couldn't parse type?");
1209 ArgTy = adjustParameterType(ArgTy);
1210 ArgTys.push_back(ArgTy);
1212 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1213 MDecl->isVariadic(), 0);
1217 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1218 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1219 /// they point to and return true. If T1 and T2 aren't pointer types
1220 /// or pointer-to-member types, or if they are not similar at this
1221 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1222 /// qualifiers on T1 and T2 are ignored. This function will typically
1223 /// be called in a loop that successively "unwraps" pointer and
1224 /// pointer-to-member types to compare them at each level.
1225 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1226 const PointerType *T1PtrType = T1->getAsPointerType(),
1227 *T2PtrType = T2->getAsPointerType();
1228 if (T1PtrType && T2PtrType) {
1229 T1 = T1PtrType->getPointeeType();
1230 T2 = T2PtrType->getPointeeType();
1234 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1235 *T2MPType = T2->getAsMemberPointerType();
1236 if (T1MPType && T2MPType &&
1237 Context.getCanonicalType(T1MPType->getClass()) ==
1238 Context.getCanonicalType(T2MPType->getClass())) {
1239 T1 = T1MPType->getPointeeType();
1240 T2 = T2MPType->getPointeeType();
1246 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1247 // C99 6.7.6: Type names have no identifier. This is already validated by
1249 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1251 TagDecl *OwnedTag = 0;
1252 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1253 if (D.isInvalidType())
1256 if (getLangOptions().CPlusPlus) {
1257 // Check that there are no default arguments (C++ only).
1258 CheckExtraCXXDefaultArguments(D);
1260 // C++0x [dcl.type]p3:
1261 // A type-specifier-seq shall not define a class or enumeration
1262 // unless it appears in the type-id of an alias-declaration
1264 if (OwnedTag && OwnedTag->isDefinition())
1265 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1266 << Context.getTypeDeclType(OwnedTag);
1269 return T.getAsOpaquePtr();
1274 //===----------------------------------------------------------------------===//
1275 // Type Attribute Processing
1276 //===----------------------------------------------------------------------===//
1278 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1279 /// specified type. The attribute contains 1 argument, the id of the address
1280 /// space for the type.
1281 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1282 const AttributeList &Attr, Sema &S){
1283 // If this type is already address space qualified, reject it.
1284 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1285 // for two or more different address spaces."
1286 if (Type.getAddressSpace()) {
1287 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1291 // Check the attribute arguments.
1292 if (Attr.getNumArgs() != 1) {
1293 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1296 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1297 llvm::APSInt addrSpace(32);
1298 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1299 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1300 << ASArgExpr->getSourceRange();
1304 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1305 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1308 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1309 /// specified type. The attribute contains 1 argument, weak or strong.
1310 static void HandleObjCGCTypeAttribute(QualType &Type,
1311 const AttributeList &Attr, Sema &S) {
1312 if (Type.getObjCGCAttr() != QualType::GCNone) {
1313 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1317 // Check the attribute arguments.
1318 if (!Attr.getParameterName()) {
1319 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1323 QualType::GCAttrTypes GCAttr;
1324 if (Attr.getNumArgs() != 0) {
1325 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1328 if (Attr.getParameterName()->isStr("weak"))
1329 GCAttr = QualType::Weak;
1330 else if (Attr.getParameterName()->isStr("strong"))
1331 GCAttr = QualType::Strong;
1333 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1334 << "objc_gc" << Attr.getParameterName();
1338 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1341 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1342 // Scan through and apply attributes to this type where it makes sense. Some
1343 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1344 // type, but others can be present in the type specifiers even though they
1345 // apply to the decl. Here we apply type attributes and ignore the rest.
1346 for (; AL; AL = AL->getNext()) {
1347 // If this is an attribute we can handle, do so now, otherwise, add it to
1348 // the LeftOverAttrs list for rechaining.
1349 switch (AL->getKind()) {
1351 case AttributeList::AT_address_space:
1352 HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1354 case AttributeList::AT_objc_gc:
1355 HandleObjCGCTypeAttribute(Result, *AL, *this);
1361 /// @brief Ensure that the type T is a complete type.
1363 /// This routine checks whether the type @p T is complete in any
1364 /// context where a complete type is required. If @p T is a complete
1365 /// type, returns false. If @p T is a class template specialization,
1366 /// this routine then attempts to perform class template
1367 /// instantiation. If instantiation fails, or if @p T is incomplete
1368 /// and cannot be completed, issues the diagnostic @p diag (giving it
1369 /// the type @p T) and returns true.
1371 /// @param Loc The location in the source that the incomplete type
1372 /// diagnostic should refer to.
1374 /// @param T The type that this routine is examining for completeness.
1376 /// @param diag The diagnostic value (e.g.,
1377 /// @c diag::err_typecheck_decl_incomplete_type) that will be used
1378 /// for the error message if @p T is incomplete.
1380 /// @param Range1 An optional range in the source code that will be a
1381 /// part of the "incomplete type" error message.
1383 /// @param Range2 An optional range in the source code that will be a
1384 /// part of the "incomplete type" error message.
1386 /// @param PrintType If non-NULL, the type that should be printed
1387 /// instead of @p T. This parameter should be used when the type that
1388 /// we're checking for incompleteness isn't the type that should be
1389 /// displayed to the user, e.g., when T is a type and PrintType is a
1392 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1393 /// @c false otherwise.
1394 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1395 SourceRange Range1, SourceRange Range2,
1396 QualType PrintType) {
1397 // FIXME: Add this assertion to help us flush out problems with
1398 // checking for dependent types and type-dependent expressions.
1400 // assert(!T->isDependentType() &&
1401 // "Can't ask whether a dependent type is complete");
1403 // If we have a complete type, we're done.
1404 if (!T->isIncompleteType())
1407 // If we have a class template specialization or a class member of a
1408 // class template specialization, try to instantiate it.
1409 if (const RecordType *Record = T->getAsRecordType()) {
1410 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1411 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1412 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1413 // Update the class template specialization's location to
1414 // refer to the point of instantiation.
1416 ClassTemplateSpec->setLocation(Loc);
1417 return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1418 /*ExplicitInstantiation=*/false);
1420 } else if (CXXRecordDecl *Rec
1421 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1422 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1423 // Find the class template specialization that surrounds this
1425 ClassTemplateSpecializationDecl *Spec = 0;
1426 for (DeclContext *Parent = Rec->getDeclContext();
1427 Parent && !Spec; Parent = Parent->getParent())
1428 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1429 assert(Spec && "Not a member of a class template specialization?");
1430 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1431 /*ExplicitInstantiation=*/false);
1436 if (PrintType.isNull())
1439 // We have an incomplete type. Produce a diagnostic.
1440 Diag(Loc, diag) << PrintType << Range1 << Range2;
1442 // If the type was a forward declaration of a class/struct/union
1444 const TagType *Tag = 0;
1445 if (const RecordType *Record = T->getAsRecordType())
1447 else if (const EnumType *Enum = T->getAsEnumType())
1450 if (Tag && !Tag->getDecl()->isInvalidDecl())
1451 Diag(Tag->getDecl()->getLocation(),
1452 Tag->isBeingDefined() ? diag::note_type_being_defined
1453 : diag::note_forward_declaration)
1454 << QualType(Tag, 0);
1459 /// \brief Retrieve a version of the type 'T' that is qualified by the
1460 /// nested-name-specifier contained in SS.
1461 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1462 if (!SS.isSet() || SS.isInvalid() || T.isNull())
1465 NestedNameSpecifier *NNS
1466 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1467 return Context.getQualifiedNameType(NNS, T);