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 #include "llvm/ADT/SmallPtrSet.h"
21 using namespace clang;
23 /// \brief Perform adjustment on the parameter type of a function.
25 /// This routine adjusts the given parameter type @p T to the actual
26 /// parameter type used by semantic analysis (C99 6.7.5.3p[7,8],
27 /// C++ [dcl.fct]p3). The adjusted parameter type is returned.
28 QualType Sema::adjustParameterType(QualType T) {
30 if (T->isArrayType()) {
32 // A declaration of a parameter as "array of type" shall be
33 // adjusted to "qualified pointer to type", where the type
34 // qualifiers (if any) are those specified within the [ and ] of
35 // the array type derivation.
36 return Context.getArrayDecayedType(T);
37 } else if (T->isFunctionType())
39 // A declaration of a parameter as "function returning type"
40 // shall be adjusted to "pointer to function returning type", as
42 return Context.getPointerType(T);
47 /// \brief Convert the specified declspec to the appropriate type
49 /// \param DS the declaration specifiers
50 /// \param DeclLoc The location of the declarator identifier or invalid if none.
51 /// \returns The type described by the declaration specifiers. This function
52 /// never returns null.
53 QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS,
54 SourceLocation DeclLoc,
56 // FIXME: Should move the logic from DeclSpec::Finish to here for validity
60 switch (DS.getTypeSpecType()) {
61 case DeclSpec::TST_void:
62 Result = Context.VoidTy;
64 case DeclSpec::TST_char:
65 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
66 Result = Context.CharTy;
67 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed)
68 Result = Context.SignedCharTy;
70 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
72 Result = Context.UnsignedCharTy;
75 case DeclSpec::TST_wchar:
76 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified)
77 Result = Context.WCharTy;
78 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) {
79 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
80 << DS.getSpecifierName(DS.getTypeSpecType());
81 Result = Context.getSignedWCharType();
83 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned &&
85 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec)
86 << DS.getSpecifierName(DS.getTypeSpecType());
87 Result = Context.getUnsignedWCharType();
90 case DeclSpec::TST_unspecified:
91 // "<proto1,proto2>" is an objc qualified ID with a missing id.
92 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
93 Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ,
94 DS.getNumProtocolQualifiers());
98 // Unspecified typespec defaults to int in C90. However, the C90 grammar
99 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier,
100 // type-qualifier, or storage-class-specifier. If not, emit an extwarn.
101 // Note that the one exception to this is function definitions, which are
102 // allowed to be completely missing a declspec. This is handled in the
103 // parser already though by it pretending to have seen an 'int' in this
105 if (getLangOptions().ImplicitInt) {
106 // In C89 mode, we only warn if there is a completely missing declspec
107 // when one is not allowed.
109 if (DeclLoc.isInvalid())
110 DeclLoc = DS.getSourceRange().getBegin();
111 Diag(DeclLoc, diag::ext_missing_declspec)
112 << DS.getSourceRange()
113 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(),
116 } else if (!DS.hasTypeSpecifier()) {
117 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says:
118 // "At least one type specifier shall be given in the declaration
119 // specifiers in each declaration, and in the specifier-qualifier list in
120 // each struct declaration and type name."
121 // FIXME: Does Microsoft really have the implicit int extension in C++?
122 if (DeclLoc.isInvalid())
123 DeclLoc = DS.getSourceRange().getBegin();
125 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) {
126 Diag(DeclLoc, diag::err_missing_type_specifier)
127 << DS.getSourceRange();
129 // When this occurs in C++ code, often something is very broken with the
130 // value being declared, poison it as invalid so we don't get chains of
134 Diag(DeclLoc, diag::ext_missing_type_specifier)
135 << DS.getSourceRange();
140 case DeclSpec::TST_int: {
141 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) {
142 switch (DS.getTypeSpecWidth()) {
143 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break;
144 case DeclSpec::TSW_short: Result = Context.ShortTy; break;
145 case DeclSpec::TSW_long: Result = Context.LongTy; break;
146 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break;
149 switch (DS.getTypeSpecWidth()) {
150 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break;
151 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break;
152 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break;
153 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break;
158 case DeclSpec::TST_float: Result = Context.FloatTy; break;
159 case DeclSpec::TST_double:
160 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long)
161 Result = Context.LongDoubleTy;
163 Result = Context.DoubleTy;
165 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool
166 case DeclSpec::TST_decimal32: // _Decimal32
167 case DeclSpec::TST_decimal64: // _Decimal64
168 case DeclSpec::TST_decimal128: // _Decimal128
169 Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported);
170 Result = Context.IntTy;
173 case DeclSpec::TST_class:
174 case DeclSpec::TST_enum:
175 case DeclSpec::TST_union:
176 case DeclSpec::TST_struct: {
177 Decl *D = static_cast<Decl *>(DS.getTypeRep());
178 assert(D && "Didn't get a decl for a class/enum/union/struct?");
179 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
180 DS.getTypeSpecSign() == 0 &&
181 "Can't handle qualifiers on typedef names yet!");
182 // TypeQuals handled by caller.
183 Result = Context.getTypeDeclType(cast<TypeDecl>(D));
185 if (D->isInvalidDecl())
189 case DeclSpec::TST_typename: {
190 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 &&
191 DS.getTypeSpecSign() == 0 &&
192 "Can't handle qualifiers on typedef names yet!");
193 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
195 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) {
196 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have
197 // this "hack" for now...
198 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType())
199 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(),
200 (ObjCProtocolDecl**)PQ,
201 DS.getNumProtocolQualifiers());
202 else if (Result == Context.getObjCIdType())
204 Result = Context.getObjCObjectPointerType(0, (ObjCProtocolDecl**)PQ,
205 DS.getNumProtocolQualifiers());
206 else if (Result == Context.getObjCClassType()) {
207 if (DeclLoc.isInvalid())
208 DeclLoc = DS.getSourceRange().getBegin();
209 // Class<protocol-list>
210 Diag(DeclLoc, diag::err_qualified_class_unsupported)
211 << DS.getSourceRange();
213 if (DeclLoc.isInvalid())
214 DeclLoc = DS.getSourceRange().getBegin();
215 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers)
216 << DS.getSourceRange();
221 // If this is a reference to an invalid typedef, propagate the invalidity.
222 if (TypedefType *TDT = dyn_cast<TypedefType>(Result))
223 if (TDT->getDecl()->isInvalidDecl())
226 // TypeQuals handled by caller.
229 case DeclSpec::TST_typeofType:
230 Result = QualType::getFromOpaquePtr(DS.getTypeRep());
231 assert(!Result.isNull() && "Didn't get a type for typeof?");
232 // TypeQuals handled by caller.
233 Result = Context.getTypeOfType(Result);
235 case DeclSpec::TST_typeofExpr: {
236 Expr *E = static_cast<Expr *>(DS.getTypeRep());
237 assert(E && "Didn't get an expression for typeof?");
238 // TypeQuals handled by caller.
239 Result = Context.getTypeOfExprType(E);
242 case DeclSpec::TST_decltype: {
243 Expr *E = static_cast<Expr *>(DS.getTypeRep());
244 assert(E && "Didn't get an expression for decltype?");
245 // TypeQuals handled by caller.
246 Result = BuildDecltypeType(E);
247 if (Result.isNull()) {
248 Result = Context.IntTy;
253 case DeclSpec::TST_auto: {
254 // TypeQuals handled by caller.
255 Result = Context.UndeducedAutoTy;
259 case DeclSpec::TST_error:
260 Result = Context.IntTy;
265 // Handle complex types.
266 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) {
267 if (getLangOptions().Freestanding)
268 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex);
269 Result = Context.getComplexType(Result);
272 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary &&
273 "FIXME: imaginary types not supported yet!");
275 // See if there are any attributes on the declspec that apply to the type (as
276 // opposed to the decl).
277 if (const AttributeList *AL = DS.getAttributes())
278 ProcessTypeAttributeList(Result, AL);
280 // Apply const/volatile/restrict qualifiers to T.
281 if (unsigned TypeQuals = DS.getTypeQualifiers()) {
283 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
284 // or incomplete types shall not be restrict-qualified." C++ also allows
285 // restrict-qualified references.
286 if (TypeQuals & QualType::Restrict) {
287 if (Result->isPointerType() || Result->isReferenceType()) {
288 QualType EltTy = Result->isPointerType() ?
289 Result->getAsPointerType()->getPointeeType() :
290 Result->getAsReferenceType()->getPointeeType();
292 // If we have a pointer or reference, the pointee must have an object
294 if (!EltTy->isIncompleteOrObjectType()) {
295 Diag(DS.getRestrictSpecLoc(),
296 diag::err_typecheck_invalid_restrict_invalid_pointee)
297 << EltTy << DS.getSourceRange();
298 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
301 Diag(DS.getRestrictSpecLoc(),
302 diag::err_typecheck_invalid_restrict_not_pointer)
303 << Result << DS.getSourceRange();
304 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier.
308 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification
309 // of a function type includes any type qualifiers, the behavior is
311 if (Result->isFunctionType() && TypeQuals) {
312 // Get some location to point at, either the C or V location.
314 if (TypeQuals & QualType::Const)
315 Loc = DS.getConstSpecLoc();
317 assert((TypeQuals & QualType::Volatile) &&
318 "Has CV quals but not C or V?");
319 Loc = DS.getVolatileSpecLoc();
321 Diag(Loc, diag::warn_typecheck_function_qualifiers)
322 << Result << DS.getSourceRange();
326 // Cv-qualified references are ill-formed except when the
327 // cv-qualifiers are introduced through the use of a typedef
328 // (7.1.3) or of a template type argument (14.3), in which
329 // case the cv-qualifiers are ignored.
330 // FIXME: Shouldn't we be checking SCS_typedef here?
331 if (DS.getTypeSpecType() == DeclSpec::TST_typename &&
332 TypeQuals && Result->isReferenceType()) {
333 TypeQuals &= ~QualType::Const;
334 TypeQuals &= ~QualType::Volatile;
337 Result = Result.getQualifiedType(TypeQuals);
342 static std::string getPrintableNameForEntity(DeclarationName Entity) {
344 return Entity.getAsString();
349 /// \brief Build a pointer type.
351 /// \param T The type to which we'll be building a pointer.
353 /// \param Quals The cvr-qualifiers to be applied to the pointer type.
355 /// \param Loc The location of the entity whose type involves this
356 /// pointer type or, if there is no such entity, the location of the
357 /// type that will have pointer type.
359 /// \param Entity The name of the entity that involves the pointer
362 /// \returns A suitable pointer type, if there are no
363 /// errors. Otherwise, returns a NULL type.
364 QualType Sema::BuildPointerType(QualType T, unsigned Quals,
365 SourceLocation Loc, DeclarationName Entity) {
366 if (T->isReferenceType()) {
367 // C++ 8.3.2p4: There shall be no ... pointers to references ...
368 Diag(Loc, diag::err_illegal_decl_pointer_to_reference)
369 << getPrintableNameForEntity(Entity);
373 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
374 // object or incomplete types shall not be restrict-qualified."
375 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
376 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
378 Quals &= ~QualType::Restrict;
381 // Build the pointer type.
382 return Context.getPointerType(T).getQualifiedType(Quals);
385 /// \brief Build a reference type.
387 /// \param T The type to which we'll be building a reference.
389 /// \param Quals The cvr-qualifiers to be applied to the reference type.
391 /// \param Loc The location of the entity whose type involves this
392 /// reference type or, if there is no such entity, the location of the
393 /// type that will have reference type.
395 /// \param Entity The name of the entity that involves the reference
398 /// \returns A suitable reference type, if there are no
399 /// errors. Otherwise, returns a NULL type.
400 QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals,
401 SourceLocation Loc, DeclarationName Entity) {
403 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) {
404 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a
405 // reference to a type T, and attempt to create the type "lvalue
406 // reference to cv TD" creates the type "lvalue reference to T".
407 // We use the qualifiers (restrict or none) of the original reference,
408 // not the new ones. This is consistent with GCC.
409 return Context.getLValueReferenceType(R->getPointeeType()).
410 getQualifiedType(T.getCVRQualifiers());
413 if (T->isReferenceType()) {
414 // C++ [dcl.ref]p4: There shall be no references to references.
416 // According to C++ DR 106, references to references are only
417 // diagnosed when they are written directly (e.g., "int & &"),
418 // but not when they happen via a typedef:
420 // typedef int& intref;
421 // typedef intref& intref2;
423 // Parser::ParserDeclaratorInternal diagnoses the case where
424 // references are written directly; here, we handle the
425 // collapsing of references-to-references as described in C++
426 // DR 106 and amended by C++ DR 540.
431 // A declarator that specifies the type “reference to cv void”
433 if (T->isVoidType()) {
434 Diag(Loc, diag::err_reference_to_void);
438 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
439 // object or incomplete types shall not be restrict-qualified."
440 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
441 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
443 Quals &= ~QualType::Restrict;
447 // [...] Cv-qualified references are ill-formed except when the
448 // cv-qualifiers are introduced through the use of a typedef
449 // (7.1.3) or of a template type argument (14.3), in which case
450 // the cv-qualifiers are ignored.
452 // We diagnose extraneous cv-qualifiers for the non-typedef,
453 // non-template type argument case within the parser. Here, we just
454 // ignore any extraneous cv-qualifiers.
455 Quals &= ~QualType::Const;
456 Quals &= ~QualType::Volatile;
458 // Handle restrict on references.
460 return Context.getLValueReferenceType(T).getQualifiedType(Quals);
461 return Context.getRValueReferenceType(T).getQualifiedType(Quals);
464 /// \brief Build an array type.
466 /// \param T The type of each element in the array.
468 /// \param ASM C99 array size modifier (e.g., '*', 'static').
470 /// \param ArraySize Expression describing the size of the array.
472 /// \param Quals The cvr-qualifiers to be applied to the array's
475 /// \param Loc The location of the entity whose type involves this
476 /// array type or, if there is no such entity, the location of the
477 /// type that will have array type.
479 /// \param Entity The name of the entity that involves the array
482 /// \returns A suitable array type, if there are no errors. Otherwise,
483 /// returns a NULL type.
484 QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM,
485 Expr *ArraySize, unsigned Quals,
486 SourceLocation Loc, DeclarationName Entity) {
487 // C99 6.7.5.2p1: If the element type is an incomplete or function type,
488 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]())
489 if (RequireCompleteType(Loc, T,
490 diag::err_illegal_decl_array_incomplete_type))
493 if (T->isFunctionType()) {
494 Diag(Loc, diag::err_illegal_decl_array_of_functions)
495 << getPrintableNameForEntity(Entity);
499 // C++ 8.3.2p4: There shall be no ... arrays of references ...
500 if (T->isReferenceType()) {
501 Diag(Loc, diag::err_illegal_decl_array_of_references)
502 << getPrintableNameForEntity(Entity);
506 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) {
507 Diag(Loc, diag::err_illegal_decl_array_of_auto)
508 << getPrintableNameForEntity(Entity);
512 if (const RecordType *EltTy = T->getAsRecordType()) {
513 // If the element type is a struct or union that contains a variadic
514 // array, accept it as a GNU extension: C99 6.7.2.1p2.
515 if (EltTy->getDecl()->hasFlexibleArrayMember())
516 Diag(Loc, diag::ext_flexible_array_in_array) << T;
517 } else if (T->isObjCInterfaceType()) {
518 Diag(Loc, diag::err_objc_array_of_interfaces) << T;
522 // C99 6.7.5.2p1: The size expression shall have integer type.
523 if (ArraySize && !ArraySize->isTypeDependent() &&
524 !ArraySize->getType()->isIntegerType()) {
525 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int)
526 << ArraySize->getType() << ArraySize->getSourceRange();
527 ArraySize->Destroy(Context);
530 llvm::APSInt ConstVal(32);
532 if (ASM == ArrayType::Star)
533 T = Context.getVariableArrayType(T, 0, ASM, Quals);
535 T = Context.getIncompleteArrayType(T, ASM, Quals);
536 } else if (ArraySize->isValueDependent()) {
537 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals);
538 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) ||
539 (!T->isDependentType() && !T->isConstantSizeType())) {
540 // Per C99, a variable array is an array with either a non-constant
541 // size or an element type that has a non-constant-size
542 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals);
544 // C99 6.7.5.2p1: If the expression is a constant expression, it shall
545 // have a value greater than zero.
546 if (ConstVal.isSigned()) {
547 if (ConstVal.isNegative()) {
548 Diag(ArraySize->getLocStart(),
549 diag::err_typecheck_negative_array_size)
550 << ArraySize->getSourceRange();
552 } else if (ConstVal == 0) {
553 // GCC accepts zero sized static arrays.
554 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size)
555 << ArraySize->getSourceRange();
558 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals);
560 // If this is not C99, extwarn about VLA's and C99 array size modifiers.
561 if (!getLangOptions().C99) {
562 if (ArraySize && !ArraySize->isTypeDependent() &&
563 !ArraySize->isValueDependent() &&
564 !ArraySize->isIntegerConstantExpr(Context))
565 Diag(Loc, diag::ext_vla);
566 else if (ASM != ArrayType::Normal || Quals != 0)
567 Diag(Loc, diag::ext_c99_array_usage);
573 /// \brief Build an ext-vector type.
575 /// Run the required checks for the extended vector type.
576 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize,
577 SourceLocation AttrLoc) {
579 Expr *Arg = (Expr *)ArraySize.get();
581 // unlike gcc's vector_size attribute, we do not allow vectors to be defined
582 // in conjunction with complex types (pointers, arrays, functions, etc.).
583 if (!T->isDependentType() &&
584 !T->isIntegerType() && !T->isRealFloatingType()) {
585 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T;
589 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
590 llvm::APSInt vecSize(32);
591 if (!Arg->isIntegerConstantExpr(vecSize, Context)) {
592 Diag(AttrLoc, diag::err_attribute_argument_not_int)
593 << "ext_vector_type" << Arg->getSourceRange();
597 // unlike gcc's vector_size attribute, the size is specified as the
598 // number of elements, not the number of bytes.
599 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue());
601 if (vectorSize == 0) {
602 Diag(AttrLoc, diag::err_attribute_zero_size)
603 << Arg->getSourceRange();
607 if (!T->isDependentType())
608 return Context.getExtVectorType(T, vectorSize);
611 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(),
615 /// \brief Build a function type.
617 /// This routine checks the function type according to C++ rules and
618 /// under the assumption that the result type and parameter types have
619 /// just been instantiated from a template. It therefore duplicates
620 /// some of the behavior of GetTypeForDeclarator, but in a much
621 /// simpler form that is only suitable for this narrow use case.
623 /// \param T The return type of the function.
625 /// \param ParamTypes The parameter types of the function. This array
626 /// will be modified to account for adjustments to the types of the
627 /// function parameters.
629 /// \param NumParamTypes The number of parameter types in ParamTypes.
631 /// \param Variadic Whether this is a variadic function type.
633 /// \param Quals The cvr-qualifiers to be applied to the function type.
635 /// \param Loc The location of the entity whose type involves this
636 /// function type or, if there is no such entity, the location of the
637 /// type that will have function type.
639 /// \param Entity The name of the entity that involves the function
642 /// \returns A suitable function type, if there are no
643 /// errors. Otherwise, returns a NULL type.
644 QualType Sema::BuildFunctionType(QualType T,
645 QualType *ParamTypes,
646 unsigned NumParamTypes,
647 bool Variadic, unsigned Quals,
648 SourceLocation Loc, DeclarationName Entity) {
649 if (T->isArrayType() || T->isFunctionType()) {
650 Diag(Loc, diag::err_func_returning_array_function) << T;
654 bool Invalid = false;
655 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) {
656 QualType ParamType = adjustParameterType(ParamTypes[Idx]);
657 if (ParamType->isVoidType()) {
658 Diag(Loc, diag::err_param_with_void_type);
662 ParamTypes[Idx] = ParamType;
668 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic,
672 /// \brief Build a member pointer type \c T Class::*.
674 /// \param T the type to which the member pointer refers.
675 /// \param Class the class type into which the member pointer points.
676 /// \param Quals Qualifiers applied to the member pointer type
677 /// \param Loc the location where this type begins
678 /// \param Entity the name of the entity that will have this member pointer type
680 /// \returns a member pointer type, if successful, or a NULL type if there was
682 QualType Sema::BuildMemberPointerType(QualType T, QualType Class,
683 unsigned Quals, SourceLocation Loc,
684 DeclarationName Entity) {
685 // Verify that we're not building a pointer to pointer to function with
686 // exception specification.
687 if (CheckDistantExceptionSpec(T)) {
688 Diag(Loc, diag::err_distant_exception_spec);
690 // FIXME: If we're doing this as part of template instantiation,
691 // we should return immediately.
693 // Build the type anyway, but use the canonical type so that the
694 // exception specifiers are stripped off.
695 T = Context.getCanonicalType(T);
698 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member
699 // with reference type, or "cv void."
700 if (T->isReferenceType()) {
701 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference)
702 << (Entity? Entity.getAsString() : "type name");
706 if (T->isVoidType()) {
707 Diag(Loc, diag::err_illegal_decl_mempointer_to_void)
708 << (Entity? Entity.getAsString() : "type name");
712 // Enforce C99 6.7.3p2: "Types other than pointer types derived from
713 // object or incomplete types shall not be restrict-qualified."
714 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) {
715 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee)
718 // FIXME: If we're doing this as part of template instantiation,
719 // we should return immediately.
720 Quals &= ~QualType::Restrict;
723 if (!Class->isDependentType() && !Class->isRecordType()) {
724 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class;
728 return Context.getMemberPointerType(T, Class.getTypePtr())
729 .getQualifiedType(Quals);
732 /// \brief Build a block pointer type.
734 /// \param T The type to which we'll be building a block pointer.
736 /// \param Quals The cvr-qualifiers to be applied to the block pointer type.
738 /// \param Loc The location of the entity whose type involves this
739 /// block pointer type or, if there is no such entity, the location of the
740 /// type that will have block pointer type.
742 /// \param Entity The name of the entity that involves the block pointer
745 /// \returns A suitable block pointer type, if there are no
746 /// errors. Otherwise, returns a NULL type.
747 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals,
749 DeclarationName Entity) {
750 if (!T.getTypePtr()->isFunctionType()) {
751 Diag(Loc, diag::err_nonfunction_block_type);
755 return Context.getBlockPointerType(T).getQualifiedType(Quals);
758 /// GetTypeForDeclarator - Convert the type for the specified
759 /// declarator to Type instances. Skip the outermost Skip type
762 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq
763 /// owns the declaration of a type (e.g., the definition of a struct
764 /// type), then *OwnedDecl will receive the owned declaration.
765 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip,
766 TagDecl **OwnedDecl) {
767 bool OmittedReturnType = false;
769 if (D.getContext() == Declarator::BlockLiteralContext
771 && !D.getDeclSpec().hasTypeSpecifier()
772 && (D.getNumTypeObjects() == 0
773 || (D.getNumTypeObjects() == 1
774 && D.getTypeObject(0).Kind == DeclaratorChunk::Function)))
775 OmittedReturnType = true;
777 // long long is a C99 feature.
778 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x &&
779 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong)
780 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong);
782 // Determine the type of the declarator. Not all forms of declarator
785 switch (D.getKind()) {
786 case Declarator::DK_Abstract:
787 case Declarator::DK_Normal:
788 case Declarator::DK_Operator: {
789 const DeclSpec &DS = D.getDeclSpec();
790 if (OmittedReturnType) {
791 // We default to a dependent type initially. Can be modified by
792 // the first return statement.
793 T = Context.DependentTy;
795 bool isInvalid = false;
796 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid);
798 D.setInvalidType(true);
799 else if (OwnedDecl && DS.isTypeSpecOwned())
800 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep());
805 case Declarator::DK_Constructor:
806 case Declarator::DK_Destructor:
807 case Declarator::DK_Conversion:
808 // Constructors and destructors don't have return types. Use
809 // "void" instead. Conversion operators will check their return
815 if (T == Context.UndeducedAutoTy) {
818 switch (D.getContext()) {
819 case Declarator::KNRTypeListContext:
820 assert(0 && "K&R type lists aren't allowed in C++");
822 case Declarator::PrototypeContext:
823 Error = 0; // Function prototype
825 case Declarator::MemberContext:
826 switch (cast<TagDecl>(CurContext)->getTagKind()) {
827 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break;
828 case TagDecl::TK_struct: Error = 1; /* Struct member */ break;
829 case TagDecl::TK_union: Error = 2; /* Union member */ break;
830 case TagDecl::TK_class: Error = 3; /* Class member */ break;
833 case Declarator::CXXCatchContext:
834 Error = 4; // Exception declaration
836 case Declarator::TemplateParamContext:
837 Error = 5; // Template parameter
839 case Declarator::BlockLiteralContext:
840 Error = 6; // Block literal
842 case Declarator::FileContext:
843 case Declarator::BlockContext:
844 case Declarator::ForContext:
845 case Declarator::ConditionContext:
846 case Declarator::TypeNameContext:
851 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed)
854 D.setInvalidType(true);
858 // The name we're declaring, if any.
859 DeclarationName Name;
860 if (D.getIdentifier())
861 Name = D.getIdentifier();
863 // Walk the DeclTypeInfo, building the recursive type as we go.
864 // DeclTypeInfos are ordered from the identifier out, which is
865 // opposite of what we want :).
866 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) {
867 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip);
868 switch (DeclType.Kind) {
869 default: assert(0 && "Unknown decltype!");
870 case DeclaratorChunk::BlockPointer:
871 // If blocks are disabled, emit an error.
872 if (!LangOpts.Blocks)
873 Diag(DeclType.Loc, diag::err_blocks_disable);
875 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(),
878 case DeclaratorChunk::Pointer:
879 // Verify that we're not building a pointer to pointer to function with
880 // exception specification.
881 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
882 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
883 D.setInvalidType(true);
884 // Build the type anyway.
886 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name);
888 case DeclaratorChunk::Reference:
889 // Verify that we're not building a reference to pointer to function with
890 // exception specification.
891 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
892 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
893 D.setInvalidType(true);
894 // Build the type anyway.
896 T = BuildReferenceType(T, DeclType.Ref.LValueRef,
897 DeclType.Ref.HasRestrict ? QualType::Restrict : 0,
900 case DeclaratorChunk::Array: {
901 // Verify that we're not building an array of pointers to function with
902 // exception specification.
903 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
904 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
905 D.setInvalidType(true);
906 // Build the type anyway.
908 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr;
909 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts);
910 ArrayType::ArraySizeModifier ASM;
912 ASM = ArrayType::Star;
913 else if (ATI.hasStatic)
914 ASM = ArrayType::Static;
916 ASM = ArrayType::Normal;
917 if (ASM == ArrayType::Star &&
918 D.getContext() != Declarator::PrototypeContext) {
919 // FIXME: This check isn't quite right: it allows star in prototypes
920 // for function definitions, and disallows some edge cases detailed
921 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html
922 Diag(DeclType.Loc, diag::err_array_star_outside_prototype);
923 ASM = ArrayType::Normal;
924 D.setInvalidType(true);
926 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, DeclType.Loc, Name);
929 case DeclaratorChunk::Function: {
930 // If the function declarator has a prototype (i.e. it is not () and
931 // does not have a K&R-style identifier list), then the arguments are part
932 // of the type, otherwise the argument list is ().
933 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun;
935 // C99 6.7.5.3p1: The return type may not be a function or array type.
936 if (T->isArrayType() || T->isFunctionType()) {
937 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T;
939 D.setInvalidType(true);
942 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) {
944 // Types shall not be defined in return or parameter types.
945 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep());
946 if (Tag->isDefinition())
947 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type)
948 << Context.getTypeDeclType(Tag);
951 // Exception specs are not allowed in typedefs. Complain, but add it
953 if (FTI.hasExceptionSpec &&
954 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
955 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef);
957 if (FTI.NumArgs == 0) {
958 if (getLangOptions().CPlusPlus) {
959 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the
960 // function takes no arguments.
961 llvm::SmallVector<QualType, 4> Exceptions;
962 Exceptions.reserve(FTI.NumExceptions);
963 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
964 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
965 // Check that the type is valid for an exception spec, and drop it
967 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
968 Exceptions.push_back(ET);
970 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals,
971 FTI.hasExceptionSpec,
972 FTI.hasAnyExceptionSpec,
973 Exceptions.size(), Exceptions.data());
974 } else if (FTI.isVariadic) {
975 // We allow a zero-parameter variadic function in C if the
976 // function is marked with the "overloadable"
977 // attribute. Scan for this attribute now.
978 bool Overloadable = false;
979 for (const AttributeList *Attrs = D.getAttributes();
980 Attrs; Attrs = Attrs->getNext()) {
981 if (Attrs->getKind() == AttributeList::AT_overloadable) {
988 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg);
989 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0);
991 // Simple void foo(), where the incoming T is the result type.
992 T = Context.getFunctionNoProtoType(T);
994 } else if (FTI.ArgInfo[0].Param == 0) {
995 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition.
996 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration);
998 // Otherwise, we have a function with an argument list that is
999 // potentially variadic.
1000 llvm::SmallVector<QualType, 16> ArgTys;
1002 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
1003 ParmVarDecl *Param =
1004 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>());
1005 QualType ArgTy = Param->getType();
1006 assert(!ArgTy.isNull() && "Couldn't parse type?");
1008 // Adjust the parameter type.
1009 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?");
1011 // Look for 'void'. void is allowed only as a single argument to a
1012 // function with no other parameters (C99 6.7.5.3p10). We record
1013 // int(void) as a FunctionProtoType with an empty argument list.
1014 if (ArgTy->isVoidType()) {
1015 // If this is something like 'float(int, void)', reject it. 'void'
1016 // is an incomplete type (C99 6.2.5p19) and function decls cannot
1017 // have arguments of incomplete type.
1018 if (FTI.NumArgs != 1 || FTI.isVariadic) {
1019 Diag(DeclType.Loc, diag::err_void_only_param);
1020 ArgTy = Context.IntTy;
1021 Param->setType(ArgTy);
1022 } else if (FTI.ArgInfo[i].Ident) {
1023 // Reject, but continue to parse 'int(void abc)'.
1024 Diag(FTI.ArgInfo[i].IdentLoc,
1025 diag::err_param_with_void_type);
1026 ArgTy = Context.IntTy;
1027 Param->setType(ArgTy);
1029 // Reject, but continue to parse 'float(const void)'.
1030 if (ArgTy.getCVRQualifiers())
1031 Diag(DeclType.Loc, diag::err_void_param_qualified);
1033 // Do not add 'void' to the ArgTys list.
1036 } else if (!FTI.hasPrototype) {
1037 if (ArgTy->isPromotableIntegerType()) {
1038 ArgTy = Context.IntTy;
1039 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) {
1040 if (BTy->getKind() == BuiltinType::Float)
1041 ArgTy = Context.DoubleTy;
1045 ArgTys.push_back(ArgTy);
1048 llvm::SmallVector<QualType, 4> Exceptions;
1049 Exceptions.reserve(FTI.NumExceptions);
1050 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) {
1051 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty);
1052 // Check that the type is valid for an exception spec, and drop it if
1054 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range))
1055 Exceptions.push_back(ET);
1058 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(),
1059 FTI.isVariadic, FTI.TypeQuals,
1060 FTI.hasExceptionSpec,
1061 FTI.hasAnyExceptionSpec,
1062 Exceptions.size(), Exceptions.data());
1066 case DeclaratorChunk::MemberPointer:
1067 // Verify that we're not building a pointer to pointer to function with
1068 // exception specification.
1069 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) {
1070 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec);
1071 D.setInvalidType(true);
1072 // Build the type anyway.
1074 // The scope spec must refer to a class, or be dependent.
1076 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) {
1077 NestedNameSpecifier *NNS
1078 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep();
1079 assert(NNS->getAsType() && "Nested-name-specifier must name a type");
1080 ClsType = QualType(NNS->getAsType(), 0);
1081 } else if (CXXRecordDecl *RD
1082 = dyn_cast_or_null<CXXRecordDecl>(
1083 computeDeclContext(DeclType.Mem.Scope()))) {
1084 ClsType = Context.getTagDeclType(RD);
1086 Diag(DeclType.Mem.Scope().getBeginLoc(),
1087 diag::err_illegal_decl_mempointer_in_nonclass)
1088 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name")
1089 << DeclType.Mem.Scope().getRange();
1090 D.setInvalidType(true);
1093 if (!ClsType.isNull())
1094 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals,
1095 DeclType.Loc, D.getIdentifier());
1098 D.setInvalidType(true);
1104 D.setInvalidType(true);
1108 // See if there are any attributes on this declarator chunk.
1109 if (const AttributeList *AL = DeclType.getAttrs())
1110 ProcessTypeAttributeList(T, AL);
1113 if (getLangOptions().CPlusPlus && T->isFunctionType()) {
1114 const FunctionProtoType *FnTy = T->getAsFunctionProtoType();
1115 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?");
1117 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type
1118 // for a nonstatic member function, the function type to which a pointer
1119 // to member refers, or the top-level function type of a function typedef
1121 if (FnTy->getTypeQuals() != 0 &&
1122 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
1123 ((D.getContext() != Declarator::MemberContext &&
1124 (!D.getCXXScopeSpec().isSet() ||
1125 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) ||
1126 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) {
1127 if (D.isFunctionDeclarator())
1128 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type);
1130 Diag(D.getIdentifierLoc(),
1131 diag::err_invalid_qualified_typedef_function_type_use);
1133 // Strip the cv-quals from the type.
1134 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(),
1135 FnTy->getNumArgs(), FnTy->isVariadic(), 0);
1139 // If there were any type attributes applied to the decl itself (not the
1140 // type, apply the type attribute to the type!)
1141 if (const AttributeList *Attrs = D.getAttributes())
1142 ProcessTypeAttributeList(T, Attrs);
1147 /// CheckSpecifiedExceptionType - Check if the given type is valid in an
1148 /// exception specification. Incomplete types, or pointers to incomplete types
1149 /// other than void are not allowed.
1150 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) {
1151 // FIXME: This may not correctly work with the fix for core issue 437,
1152 // where a class's own type is considered complete within its body.
1154 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1155 // an incomplete type.
1156 if (T->isIncompleteType())
1157 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1158 << Range << T << /*direct*/0;
1160 // C++ 15.4p2: A type denoted in an exception-specification shall not denote
1161 // an incomplete type a pointer or reference to an incomplete type, other
1164 if (const PointerType* IT = T->getAsPointerType()) {
1165 T = IT->getPointeeType();
1167 } else if (const ReferenceType* IT = T->getAsReferenceType()) {
1168 T = IT->getPointeeType();
1173 if (T->isIncompleteType() && !T->isVoidType())
1174 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec)
1175 << Range << T << /*indirect*/kind;
1180 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer
1181 /// to member to a function with an exception specification. This means that
1182 /// it is invalid to add another level of indirection.
1183 bool Sema::CheckDistantExceptionSpec(QualType T) {
1184 if (const PointerType *PT = T->getAsPointerType())
1185 T = PT->getPointeeType();
1186 else if (const MemberPointerType *PT = T->getAsMemberPointerType())
1187 T = PT->getPointeeType();
1191 const FunctionProtoType *FnT = T->getAsFunctionProtoType();
1195 return FnT->hasExceptionSpec();
1198 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent
1199 /// exception specifications. Exception specifications are equivalent if
1200 /// they allow exactly the same set of exception types. It does not matter how
1201 /// that is achieved. See C++ [except.spec]p2.
1202 bool Sema::CheckEquivalentExceptionSpec(
1203 const FunctionProtoType *Old, SourceLocation OldLoc,
1204 const FunctionProtoType *New, SourceLocation NewLoc) {
1205 bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec();
1206 bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec();
1207 if (OldAny && NewAny)
1209 if (OldAny || NewAny) {
1210 Diag(NewLoc, diag::err_mismatched_exception_spec);
1211 Diag(OldLoc, diag::note_previous_declaration);
1215 bool Success = true;
1216 // Both have a definite exception spec. Collect the first set, then compare
1218 llvm::SmallPtrSet<const Type*, 8> Types;
1219 for (FunctionProtoType::exception_iterator I = Old->exception_begin(),
1220 E = Old->exception_end(); I != E; ++I)
1221 Types.insert(Context.getCanonicalType(*I).getTypePtr());
1223 for (FunctionProtoType::exception_iterator I = New->exception_begin(),
1224 E = New->exception_end(); I != E && Success; ++I)
1225 Success = Types.erase(Context.getCanonicalType(*I).getTypePtr());
1227 Success = Success && Types.empty();
1232 Diag(NewLoc, diag::err_mismatched_exception_spec);
1233 Diag(OldLoc, diag::note_previous_declaration);
1237 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition
1239 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) {
1240 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>());
1241 QualType T = MDecl->getResultType();
1242 llvm::SmallVector<QualType, 16> ArgTys;
1244 // Add the first two invisible argument types for self and _cmd.
1245 if (MDecl->isInstanceMethod()) {
1246 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface());
1247 selfTy = Context.getPointerType(selfTy);
1248 ArgTys.push_back(selfTy);
1250 ArgTys.push_back(Context.getObjCIdType());
1251 ArgTys.push_back(Context.getObjCSelType());
1253 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
1254 E = MDecl->param_end(); PI != E; ++PI) {
1255 QualType ArgTy = (*PI)->getType();
1256 assert(!ArgTy.isNull() && "Couldn't parse type?");
1257 ArgTy = adjustParameterType(ArgTy);
1258 ArgTys.push_back(ArgTy);
1260 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(),
1261 MDecl->isVariadic(), 0);
1265 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that
1266 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that
1267 /// they point to and return true. If T1 and T2 aren't pointer types
1268 /// or pointer-to-member types, or if they are not similar at this
1269 /// level, returns false and leaves T1 and T2 unchanged. Top-level
1270 /// qualifiers on T1 and T2 are ignored. This function will typically
1271 /// be called in a loop that successively "unwraps" pointer and
1272 /// pointer-to-member types to compare them at each level.
1273 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) {
1274 const PointerType *T1PtrType = T1->getAsPointerType(),
1275 *T2PtrType = T2->getAsPointerType();
1276 if (T1PtrType && T2PtrType) {
1277 T1 = T1PtrType->getPointeeType();
1278 T2 = T2PtrType->getPointeeType();
1282 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(),
1283 *T2MPType = T2->getAsMemberPointerType();
1284 if (T1MPType && T2MPType &&
1285 Context.getCanonicalType(T1MPType->getClass()) ==
1286 Context.getCanonicalType(T2MPType->getClass())) {
1287 T1 = T1MPType->getPointeeType();
1288 T2 = T2MPType->getPointeeType();
1294 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) {
1295 // C99 6.7.6: Type names have no identifier. This is already validated by
1297 assert(D.getIdentifier() == 0 && "Type name should have no identifier!");
1299 TagDecl *OwnedTag = 0;
1300 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag);
1301 if (D.isInvalidType())
1304 if (getLangOptions().CPlusPlus) {
1305 // Check that there are no default arguments (C++ only).
1306 CheckExtraCXXDefaultArguments(D);
1308 // C++0x [dcl.type]p3:
1309 // A type-specifier-seq shall not define a class or enumeration
1310 // unless it appears in the type-id of an alias-declaration
1312 if (OwnedTag && OwnedTag->isDefinition())
1313 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier)
1314 << Context.getTypeDeclType(OwnedTag);
1317 return T.getAsOpaquePtr();
1322 //===----------------------------------------------------------------------===//
1323 // Type Attribute Processing
1324 //===----------------------------------------------------------------------===//
1326 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the
1327 /// specified type. The attribute contains 1 argument, the id of the address
1328 /// space for the type.
1329 static void HandleAddressSpaceTypeAttribute(QualType &Type,
1330 const AttributeList &Attr, Sema &S){
1331 // If this type is already address space qualified, reject it.
1332 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers
1333 // for two or more different address spaces."
1334 if (Type.getAddressSpace()) {
1335 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers);
1339 // Check the attribute arguments.
1340 if (Attr.getNumArgs() != 1) {
1341 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1344 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0));
1345 llvm::APSInt addrSpace(32);
1346 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) {
1347 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int)
1348 << ASArgExpr->getSourceRange();
1352 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue());
1353 Type = S.Context.getAddrSpaceQualType(Type, ASIdx);
1356 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the
1357 /// specified type. The attribute contains 1 argument, weak or strong.
1358 static void HandleObjCGCTypeAttribute(QualType &Type,
1359 const AttributeList &Attr, Sema &S) {
1360 if (Type.getObjCGCAttr() != QualType::GCNone) {
1361 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc);
1365 // Check the attribute arguments.
1366 if (!Attr.getParameterName()) {
1367 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string)
1371 QualType::GCAttrTypes GCAttr;
1372 if (Attr.getNumArgs() != 0) {
1373 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1;
1376 if (Attr.getParameterName()->isStr("weak"))
1377 GCAttr = QualType::Weak;
1378 else if (Attr.getParameterName()->isStr("strong"))
1379 GCAttr = QualType::Strong;
1381 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
1382 << "objc_gc" << Attr.getParameterName();
1386 Type = S.Context.getObjCGCQualType(Type, GCAttr);
1389 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) {
1390 // Scan through and apply attributes to this type where it makes sense. Some
1391 // attributes (such as __address_space__, __vector_size__, etc) apply to the
1392 // type, but others can be present in the type specifiers even though they
1393 // apply to the decl. Here we apply type attributes and ignore the rest.
1394 for (; AL; AL = AL->getNext()) {
1395 // If this is an attribute we can handle, do so now, otherwise, add it to
1396 // the LeftOverAttrs list for rechaining.
1397 switch (AL->getKind()) {
1399 case AttributeList::AT_address_space:
1400 HandleAddressSpaceTypeAttribute(Result, *AL, *this);
1402 case AttributeList::AT_objc_gc:
1403 HandleObjCGCTypeAttribute(Result, *AL, *this);
1409 /// @brief Ensure that the type T is a complete type.
1411 /// This routine checks whether the type @p T is complete in any
1412 /// context where a complete type is required. If @p T is a complete
1413 /// type, returns false. If @p T is a class template specialization,
1414 /// this routine then attempts to perform class template
1415 /// instantiation. If instantiation fails, or if @p T is incomplete
1416 /// and cannot be completed, issues the diagnostic @p diag (giving it
1417 /// the type @p T) and returns true.
1419 /// @param Loc The location in the source that the incomplete type
1420 /// diagnostic should refer to.
1422 /// @param T The type that this routine is examining for completeness.
1424 /// @param diag The diagnostic value (e.g.,
1425 /// @c diag::err_typecheck_decl_incomplete_type) that will be used
1426 /// for the error message if @p T is incomplete.
1428 /// @param Range1 An optional range in the source code that will be a
1429 /// part of the "incomplete type" error message.
1431 /// @param Range2 An optional range in the source code that will be a
1432 /// part of the "incomplete type" error message.
1434 /// @param PrintType If non-NULL, the type that should be printed
1435 /// instead of @p T. This parameter should be used when the type that
1436 /// we're checking for incompleteness isn't the type that should be
1437 /// displayed to the user, e.g., when T is a type and PrintType is a
1440 /// @returns @c true if @p T is incomplete and a diagnostic was emitted,
1441 /// @c false otherwise.
1442 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag,
1443 SourceRange Range1, SourceRange Range2,
1444 QualType PrintType) {
1445 // FIXME: Add this assertion to help us flush out problems with
1446 // checking for dependent types and type-dependent expressions.
1448 // assert(!T->isDependentType() &&
1449 // "Can't ask whether a dependent type is complete");
1451 // If we have a complete type, we're done.
1452 if (!T->isIncompleteType())
1455 // If we have a class template specialization or a class member of a
1456 // class template specialization, try to instantiate it.
1457 if (const RecordType *Record = T->getAsRecordType()) {
1458 if (ClassTemplateSpecializationDecl *ClassTemplateSpec
1459 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) {
1460 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) {
1461 // Update the class template specialization's location to
1462 // refer to the point of instantiation.
1464 ClassTemplateSpec->setLocation(Loc);
1465 return InstantiateClassTemplateSpecialization(ClassTemplateSpec,
1466 /*ExplicitInstantiation=*/false);
1468 } else if (CXXRecordDecl *Rec
1469 = dyn_cast<CXXRecordDecl>(Record->getDecl())) {
1470 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) {
1471 // Find the class template specialization that surrounds this
1473 ClassTemplateSpecializationDecl *Spec = 0;
1474 for (DeclContext *Parent = Rec->getDeclContext();
1475 Parent && !Spec; Parent = Parent->getParent())
1476 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent);
1477 assert(Spec && "Not a member of a class template specialization?");
1478 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(),
1479 /*ExplicitInstantiation=*/false);
1484 if (PrintType.isNull())
1487 // We have an incomplete type. Produce a diagnostic.
1488 Diag(Loc, diag) << PrintType << Range1 << Range2;
1490 // If the type was a forward declaration of a class/struct/union
1492 const TagType *Tag = 0;
1493 if (const RecordType *Record = T->getAsRecordType())
1495 else if (const EnumType *Enum = T->getAsEnumType())
1498 if (Tag && !Tag->getDecl()->isInvalidDecl())
1499 Diag(Tag->getDecl()->getLocation(),
1500 Tag->isBeingDefined() ? diag::note_type_being_defined
1501 : diag::note_forward_declaration)
1502 << QualType(Tag, 0);
1507 /// \brief Retrieve a version of the type 'T' that is qualified by the
1508 /// nested-name-specifier contained in SS.
1509 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) {
1510 if (!SS.isSet() || SS.isInvalid() || T.isNull())
1513 NestedNameSpecifier *NNS
1514 = static_cast<NestedNameSpecifier *>(SS.getScopeRep());
1515 return Context.getQualifiedNameType(NNS, T);
1518 QualType Sema::BuildTypeofExprType(Expr *E) {
1519 return Context.getTypeOfExprType(E);
1522 QualType Sema::BuildDecltypeType(Expr *E) {
1523 if (E->getType() == Context.OverloadTy) {
1524 Diag(E->getLocStart(),
1525 diag::err_cannot_determine_declared_type_of_overloaded_function);
1528 return Context.getDecltypeType(E);