SemaType.cpp revision 35366a67baa970c287c714c957cf78a4131cf60d
1//===--- SemaType.cpp - Semantic Analysis for Types -----------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements type-related semantic analysis. 11// 12//===----------------------------------------------------------------------===// 13 14#include "Sema.h" 15#include "SemaInherit.h" 16#include "clang/AST/ASTContext.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/Expr.h" 20#include "clang/Parse/DeclSpec.h" 21#include "llvm/ADT/SmallPtrSet.h" 22using namespace clang; 23 24/// \brief Perform adjustment on the parameter type of a function. 25/// 26/// This routine adjusts the given parameter type @p T to the actual 27/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 28/// C++ [dcl.fct]p3). The adjusted parameter type is returned. 29QualType Sema::adjustParameterType(QualType T) { 30 // C99 6.7.5.3p7: 31 if (T->isArrayType()) { 32 // C99 6.7.5.3p7: 33 // A declaration of a parameter as "array of type" shall be 34 // adjusted to "qualified pointer to type", where the type 35 // qualifiers (if any) are those specified within the [ and ] of 36 // the array type derivation. 37 return Context.getArrayDecayedType(T); 38 } else if (T->isFunctionType()) 39 // C99 6.7.5.3p8: 40 // A declaration of a parameter as "function returning type" 41 // shall be adjusted to "pointer to function returning type", as 42 // in 6.3.2.1. 43 return Context.getPointerType(T); 44 45 return T; 46} 47 48/// \brief Convert the specified declspec to the appropriate type 49/// object. 50/// \param DS the declaration specifiers 51/// \param DeclLoc The location of the declarator identifier or invalid if none. 52/// \returns The type described by the declaration specifiers. This function 53/// never returns null. 54QualType Sema::ConvertDeclSpecToType(const DeclSpec &DS, 55 SourceLocation DeclLoc, 56 bool &isInvalid) { 57 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 58 // checking. 59 QualType Result; 60 61 switch (DS.getTypeSpecType()) { 62 case DeclSpec::TST_void: 63 Result = Context.VoidTy; 64 break; 65 case DeclSpec::TST_char: 66 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 67 Result = Context.CharTy; 68 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 69 Result = Context.SignedCharTy; 70 else { 71 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 72 "Unknown TSS value"); 73 Result = Context.UnsignedCharTy; 74 } 75 break; 76 case DeclSpec::TST_wchar: 77 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 78 Result = Context.WCharTy; 79 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 80 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 81 << DS.getSpecifierName(DS.getTypeSpecType()); 82 Result = Context.getSignedWCharType(); 83 } else { 84 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 85 "Unknown TSS value"); 86 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 87 << DS.getSpecifierName(DS.getTypeSpecType()); 88 Result = Context.getUnsignedWCharType(); 89 } 90 break; 91 case DeclSpec::TST_char16: 92 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 93 "Unknown TSS value"); 94 Result = Context.Char16Ty; 95 break; 96 case DeclSpec::TST_char32: 97 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 98 "Unknown TSS value"); 99 Result = Context.Char32Ty; 100 break; 101 case DeclSpec::TST_unspecified: 102 // "<proto1,proto2>" is an objc qualified ID with a missing id. 103 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 104 Result = Context.getObjCObjectPointerType(QualType(), 105 (ObjCProtocolDecl**)PQ, 106 DS.getNumProtocolQualifiers()); 107 break; 108 } 109 110 // Unspecified typespec defaults to int in C90. However, the C90 grammar 111 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 112 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 113 // Note that the one exception to this is function definitions, which are 114 // allowed to be completely missing a declspec. This is handled in the 115 // parser already though by it pretending to have seen an 'int' in this 116 // case. 117 if (getLangOptions().ImplicitInt) { 118 // In C89 mode, we only warn if there is a completely missing declspec 119 // when one is not allowed. 120 if (DS.isEmpty()) { 121 if (DeclLoc.isInvalid()) 122 DeclLoc = DS.getSourceRange().getBegin(); 123 Diag(DeclLoc, diag::ext_missing_declspec) 124 << DS.getSourceRange() 125 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), 126 "int"); 127 } 128 } else if (!DS.hasTypeSpecifier()) { 129 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 130 // "At least one type specifier shall be given in the declaration 131 // specifiers in each declaration, and in the specifier-qualifier list in 132 // each struct declaration and type name." 133 // FIXME: Does Microsoft really have the implicit int extension in C++? 134 if (DeclLoc.isInvalid()) 135 DeclLoc = DS.getSourceRange().getBegin(); 136 137 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) { 138 Diag(DeclLoc, diag::err_missing_type_specifier) 139 << DS.getSourceRange(); 140 141 // When this occurs in C++ code, often something is very broken with the 142 // value being declared, poison it as invalid so we don't get chains of 143 // errors. 144 isInvalid = true; 145 } else { 146 Diag(DeclLoc, diag::ext_missing_type_specifier) 147 << DS.getSourceRange(); 148 } 149 } 150 151 // FALL THROUGH. 152 case DeclSpec::TST_int: { 153 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 154 switch (DS.getTypeSpecWidth()) { 155 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 156 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 157 case DeclSpec::TSW_long: Result = Context.LongTy; break; 158 case DeclSpec::TSW_longlong: Result = Context.LongLongTy; break; 159 } 160 } else { 161 switch (DS.getTypeSpecWidth()) { 162 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 163 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 164 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 165 case DeclSpec::TSW_longlong: Result =Context.UnsignedLongLongTy; break; 166 } 167 } 168 break; 169 } 170 case DeclSpec::TST_float: Result = Context.FloatTy; break; 171 case DeclSpec::TST_double: 172 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 173 Result = Context.LongDoubleTy; 174 else 175 Result = Context.DoubleTy; 176 break; 177 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 178 case DeclSpec::TST_decimal32: // _Decimal32 179 case DeclSpec::TST_decimal64: // _Decimal64 180 case DeclSpec::TST_decimal128: // _Decimal128 181 Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 182 Result = Context.IntTy; 183 isInvalid = true; 184 break; 185 case DeclSpec::TST_class: 186 case DeclSpec::TST_enum: 187 case DeclSpec::TST_union: 188 case DeclSpec::TST_struct: { 189 Decl *D = static_cast<Decl *>(DS.getTypeRep()); 190 assert(D && "Didn't get a decl for a class/enum/union/struct?"); 191 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 192 DS.getTypeSpecSign() == 0 && 193 "Can't handle qualifiers on typedef names yet!"); 194 // TypeQuals handled by caller. 195 Result = Context.getTypeDeclType(cast<TypeDecl>(D)); 196 197 if (D->isInvalidDecl()) 198 isInvalid = true; 199 break; 200 } 201 case DeclSpec::TST_typename: { 202 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 203 DS.getTypeSpecSign() == 0 && 204 "Can't handle qualifiers on typedef names yet!"); 205 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 206 207 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 208 // FIXME: Adding a TST_objcInterface clause doesn't seem ideal, so we have 209 // this "hack" for now... 210 if (const ObjCInterfaceType *Interface = Result->getAsObjCInterfaceType()) 211 // FIXME: Remove ObjCQualifiedInterfaceType (by moving the list of 212 // protocols 'up' to ObjCInterfaceType). 213 Result = Context.getObjCQualifiedInterfaceType(Interface->getDecl(), 214 (ObjCProtocolDecl**)PQ, 215 DS.getNumProtocolQualifiers()); 216 else if (Result->isObjCIdType()) 217 // id<protocol-list> 218 Result = Context.getObjCObjectPointerType(QualType(), 219 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); 220 else if (Result->isObjCClassType()) { 221 if (DeclLoc.isInvalid()) 222 DeclLoc = DS.getSourceRange().getBegin(); 223 // Class<protocol-list> 224 Diag(DeclLoc, diag::err_qualified_class_unsupported) 225 << DS.getSourceRange(); 226 } else { 227 if (DeclLoc.isInvalid()) 228 DeclLoc = DS.getSourceRange().getBegin(); 229 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 230 << DS.getSourceRange(); 231 isInvalid = true; 232 } 233 } 234 235 // If this is a reference to an invalid typedef, propagate the invalidity. 236 if (TypedefType *TDT = dyn_cast<TypedefType>(Result)) 237 if (TDT->getDecl()->isInvalidDecl()) 238 isInvalid = true; 239 240 // TypeQuals handled by caller. 241 break; 242 } 243 case DeclSpec::TST_typeofType: 244 Result = QualType::getFromOpaquePtr(DS.getTypeRep()); 245 assert(!Result.isNull() && "Didn't get a type for typeof?"); 246 // TypeQuals handled by caller. 247 Result = Context.getTypeOfType(Result); 248 break; 249 case DeclSpec::TST_typeofExpr: { 250 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 251 assert(E && "Didn't get an expression for typeof?"); 252 // TypeQuals handled by caller. 253 Result = Context.getTypeOfExprType(E); 254 break; 255 } 256 case DeclSpec::TST_decltype: { 257 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 258 assert(E && "Didn't get an expression for decltype?"); 259 // TypeQuals handled by caller. 260 Result = BuildDecltypeType(E); 261 if (Result.isNull()) { 262 Result = Context.IntTy; 263 isInvalid = true; 264 } 265 break; 266 } 267 case DeclSpec::TST_auto: { 268 // TypeQuals handled by caller. 269 Result = Context.UndeducedAutoTy; 270 break; 271 } 272 273 case DeclSpec::TST_error: 274 Result = Context.IntTy; 275 isInvalid = true; 276 break; 277 } 278 279 // Handle complex types. 280 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 281 if (getLangOptions().Freestanding) 282 Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 283 Result = Context.getComplexType(Result); 284 } 285 286 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 287 "FIXME: imaginary types not supported yet!"); 288 289 // See if there are any attributes on the declspec that apply to the type (as 290 // opposed to the decl). 291 if (const AttributeList *AL = DS.getAttributes()) 292 ProcessTypeAttributeList(Result, AL); 293 294 // Apply const/volatile/restrict qualifiers to T. 295 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 296 297 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 298 // or incomplete types shall not be restrict-qualified." C++ also allows 299 // restrict-qualified references. 300 if (TypeQuals & QualType::Restrict) { 301 if (Result->isPointerType() || Result->isReferenceType()) { 302 QualType EltTy = Result->isPointerType() ? 303 Result->getAsPointerType()->getPointeeType() : 304 Result->getAsReferenceType()->getPointeeType(); 305 306 // If we have a pointer or reference, the pointee must have an object 307 // incomplete type. 308 if (!EltTy->isIncompleteOrObjectType()) { 309 Diag(DS.getRestrictSpecLoc(), 310 diag::err_typecheck_invalid_restrict_invalid_pointee) 311 << EltTy << DS.getSourceRange(); 312 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 313 } 314 } else { 315 Diag(DS.getRestrictSpecLoc(), 316 diag::err_typecheck_invalid_restrict_not_pointer) 317 << Result << DS.getSourceRange(); 318 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 319 } 320 } 321 322 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 323 // of a function type includes any type qualifiers, the behavior is 324 // undefined." 325 if (Result->isFunctionType() && TypeQuals) { 326 // Get some location to point at, either the C or V location. 327 SourceLocation Loc; 328 if (TypeQuals & QualType::Const) 329 Loc = DS.getConstSpecLoc(); 330 else { 331 assert((TypeQuals & QualType::Volatile) && 332 "Has CV quals but not C or V?"); 333 Loc = DS.getVolatileSpecLoc(); 334 } 335 Diag(Loc, diag::warn_typecheck_function_qualifiers) 336 << Result << DS.getSourceRange(); 337 } 338 339 // C++ [dcl.ref]p1: 340 // Cv-qualified references are ill-formed except when the 341 // cv-qualifiers are introduced through the use of a typedef 342 // (7.1.3) or of a template type argument (14.3), in which 343 // case the cv-qualifiers are ignored. 344 // FIXME: Shouldn't we be checking SCS_typedef here? 345 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 346 TypeQuals && Result->isReferenceType()) { 347 TypeQuals &= ~QualType::Const; 348 TypeQuals &= ~QualType::Volatile; 349 } 350 351 Result = Result.getQualifiedType(TypeQuals); 352 } 353 return Result; 354} 355 356static std::string getPrintableNameForEntity(DeclarationName Entity) { 357 if (Entity) 358 return Entity.getAsString(); 359 360 return "type name"; 361} 362 363/// \brief Build a pointer type. 364/// 365/// \param T The type to which we'll be building a pointer. 366/// 367/// \param Quals The cvr-qualifiers to be applied to the pointer type. 368/// 369/// \param Loc The location of the entity whose type involves this 370/// pointer type or, if there is no such entity, the location of the 371/// type that will have pointer type. 372/// 373/// \param Entity The name of the entity that involves the pointer 374/// type, if known. 375/// 376/// \returns A suitable pointer type, if there are no 377/// errors. Otherwise, returns a NULL type. 378QualType Sema::BuildPointerType(QualType T, unsigned Quals, 379 SourceLocation Loc, DeclarationName Entity) { 380 if (T->isReferenceType()) { 381 // C++ 8.3.2p4: There shall be no ... pointers to references ... 382 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 383 << getPrintableNameForEntity(Entity); 384 return QualType(); 385 } 386 387 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 388 // object or incomplete types shall not be restrict-qualified." 389 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 390 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 391 << T; 392 Quals &= ~QualType::Restrict; 393 } 394 395 // Build the pointer type. 396 return Context.getPointerType(T).getQualifiedType(Quals); 397} 398 399/// \brief Build a reference type. 400/// 401/// \param T The type to which we'll be building a reference. 402/// 403/// \param Quals The cvr-qualifiers to be applied to the reference type. 404/// 405/// \param Loc The location of the entity whose type involves this 406/// reference type or, if there is no such entity, the location of the 407/// type that will have reference type. 408/// 409/// \param Entity The name of the entity that involves the reference 410/// type, if known. 411/// 412/// \returns A suitable reference type, if there are no 413/// errors. Otherwise, returns a NULL type. 414QualType Sema::BuildReferenceType(QualType T, bool LValueRef, unsigned Quals, 415 SourceLocation Loc, DeclarationName Entity) { 416 if (LValueRef) { 417 if (const RValueReferenceType *R = T->getAsRValueReferenceType()) { 418 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a 419 // reference to a type T, and attempt to create the type "lvalue 420 // reference to cv TD" creates the type "lvalue reference to T". 421 // We use the qualifiers (restrict or none) of the original reference, 422 // not the new ones. This is consistent with GCC. 423 return Context.getLValueReferenceType(R->getPointeeType()). 424 getQualifiedType(T.getCVRQualifiers()); 425 } 426 } 427 if (T->isReferenceType()) { 428 // C++ [dcl.ref]p4: There shall be no references to references. 429 // 430 // According to C++ DR 106, references to references are only 431 // diagnosed when they are written directly (e.g., "int & &"), 432 // but not when they happen via a typedef: 433 // 434 // typedef int& intref; 435 // typedef intref& intref2; 436 // 437 // Parser::ParserDeclaratorInternal diagnoses the case where 438 // references are written directly; here, we handle the 439 // collapsing of references-to-references as described in C++ 440 // DR 106 and amended by C++ DR 540. 441 return T; 442 } 443 444 // C++ [dcl.ref]p1: 445 // A declarator that specifies the type “reference to cv void” 446 // is ill-formed. 447 if (T->isVoidType()) { 448 Diag(Loc, diag::err_reference_to_void); 449 return QualType(); 450 } 451 452 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 453 // object or incomplete types shall not be restrict-qualified." 454 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 455 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 456 << T; 457 Quals &= ~QualType::Restrict; 458 } 459 460 // C++ [dcl.ref]p1: 461 // [...] Cv-qualified references are ill-formed except when the 462 // cv-qualifiers are introduced through the use of a typedef 463 // (7.1.3) or of a template type argument (14.3), in which case 464 // the cv-qualifiers are ignored. 465 // 466 // We diagnose extraneous cv-qualifiers for the non-typedef, 467 // non-template type argument case within the parser. Here, we just 468 // ignore any extraneous cv-qualifiers. 469 Quals &= ~QualType::Const; 470 Quals &= ~QualType::Volatile; 471 472 // Handle restrict on references. 473 if (LValueRef) 474 return Context.getLValueReferenceType(T).getQualifiedType(Quals); 475 return Context.getRValueReferenceType(T).getQualifiedType(Quals); 476} 477 478/// \brief Build an array type. 479/// 480/// \param T The type of each element in the array. 481/// 482/// \param ASM C99 array size modifier (e.g., '*', 'static'). 483/// 484/// \param ArraySize Expression describing the size of the array. 485/// 486/// \param Quals The cvr-qualifiers to be applied to the array's 487/// element type. 488/// 489/// \param Loc The location of the entity whose type involves this 490/// array type or, if there is no such entity, the location of the 491/// type that will have array type. 492/// 493/// \param Entity The name of the entity that involves the array 494/// type, if known. 495/// 496/// \returns A suitable array type, if there are no errors. Otherwise, 497/// returns a NULL type. 498QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 499 Expr *ArraySize, unsigned Quals, 500 SourceRange Brackets, DeclarationName Entity) { 501 SourceLocation Loc = Brackets.getBegin(); 502 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 503 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 504 if (RequireCompleteType(Loc, T, 505 diag::err_illegal_decl_array_incomplete_type)) 506 return QualType(); 507 508 if (T->isFunctionType()) { 509 Diag(Loc, diag::err_illegal_decl_array_of_functions) 510 << getPrintableNameForEntity(Entity); 511 return QualType(); 512 } 513 514 // C++ 8.3.2p4: There shall be no ... arrays of references ... 515 if (T->isReferenceType()) { 516 Diag(Loc, diag::err_illegal_decl_array_of_references) 517 << getPrintableNameForEntity(Entity); 518 return QualType(); 519 } 520 521 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) { 522 Diag(Loc, diag::err_illegal_decl_array_of_auto) 523 << getPrintableNameForEntity(Entity); 524 return QualType(); 525 } 526 527 if (const RecordType *EltTy = T->getAsRecordType()) { 528 // If the element type is a struct or union that contains a variadic 529 // array, accept it as a GNU extension: C99 6.7.2.1p2. 530 if (EltTy->getDecl()->hasFlexibleArrayMember()) 531 Diag(Loc, diag::ext_flexible_array_in_array) << T; 532 } else if (T->isObjCInterfaceType()) { 533 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 534 return QualType(); 535 } 536 537 // C99 6.7.5.2p1: The size expression shall have integer type. 538 if (ArraySize && !ArraySize->isTypeDependent() && 539 !ArraySize->getType()->isIntegerType()) { 540 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 541 << ArraySize->getType() << ArraySize->getSourceRange(); 542 ArraySize->Destroy(Context); 543 return QualType(); 544 } 545 llvm::APSInt ConstVal(32); 546 if (!ArraySize) { 547 if (ASM == ArrayType::Star) 548 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 549 else 550 T = Context.getIncompleteArrayType(T, ASM, Quals); 551 } else if (ArraySize->isValueDependent()) { 552 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 553 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 554 (!T->isDependentType() && !T->isConstantSizeType())) { 555 // Per C99, a variable array is an array with either a non-constant 556 // size or an element type that has a non-constant-size 557 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 558 } else { 559 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 560 // have a value greater than zero. 561 if (ConstVal.isSigned()) { 562 if (ConstVal.isNegative()) { 563 Diag(ArraySize->getLocStart(), 564 diag::err_typecheck_negative_array_size) 565 << ArraySize->getSourceRange(); 566 return QualType(); 567 } else if (ConstVal == 0) { 568 // GCC accepts zero sized static arrays. 569 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) 570 << ArraySize->getSourceRange(); 571 } 572 } 573 T = Context.getConstantArrayWithExprType(T, ConstVal, ArraySize, 574 ASM, Quals, Brackets); 575 } 576 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 577 if (!getLangOptions().C99) { 578 if (ArraySize && !ArraySize->isTypeDependent() && 579 !ArraySize->isValueDependent() && 580 !ArraySize->isIntegerConstantExpr(Context)) 581 Diag(Loc, diag::ext_vla); 582 else if (ASM != ArrayType::Normal || Quals != 0) 583 Diag(Loc, diag::ext_c99_array_usage); 584 } 585 586 return T; 587} 588 589/// \brief Build an ext-vector type. 590/// 591/// Run the required checks for the extended vector type. 592QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 593 SourceLocation AttrLoc) { 594 595 Expr *Arg = (Expr *)ArraySize.get(); 596 597 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 598 // in conjunction with complex types (pointers, arrays, functions, etc.). 599 if (!T->isDependentType() && 600 !T->isIntegerType() && !T->isRealFloatingType()) { 601 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 602 return QualType(); 603 } 604 605 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 606 llvm::APSInt vecSize(32); 607 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 608 Diag(AttrLoc, diag::err_attribute_argument_not_int) 609 << "ext_vector_type" << Arg->getSourceRange(); 610 return QualType(); 611 } 612 613 // unlike gcc's vector_size attribute, the size is specified as the 614 // number of elements, not the number of bytes. 615 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 616 617 if (vectorSize == 0) { 618 Diag(AttrLoc, diag::err_attribute_zero_size) 619 << Arg->getSourceRange(); 620 return QualType(); 621 } 622 623 if (!T->isDependentType()) 624 return Context.getExtVectorType(T, vectorSize); 625 } 626 627 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 628 AttrLoc); 629} 630 631/// \brief Build a function type. 632/// 633/// This routine checks the function type according to C++ rules and 634/// under the assumption that the result type and parameter types have 635/// just been instantiated from a template. It therefore duplicates 636/// some of the behavior of GetTypeForDeclarator, but in a much 637/// simpler form that is only suitable for this narrow use case. 638/// 639/// \param T The return type of the function. 640/// 641/// \param ParamTypes The parameter types of the function. This array 642/// will be modified to account for adjustments to the types of the 643/// function parameters. 644/// 645/// \param NumParamTypes The number of parameter types in ParamTypes. 646/// 647/// \param Variadic Whether this is a variadic function type. 648/// 649/// \param Quals The cvr-qualifiers to be applied to the function type. 650/// 651/// \param Loc The location of the entity whose type involves this 652/// function type or, if there is no such entity, the location of the 653/// type that will have function type. 654/// 655/// \param Entity The name of the entity that involves the function 656/// type, if known. 657/// 658/// \returns A suitable function type, if there are no 659/// errors. Otherwise, returns a NULL type. 660QualType Sema::BuildFunctionType(QualType T, 661 QualType *ParamTypes, 662 unsigned NumParamTypes, 663 bool Variadic, unsigned Quals, 664 SourceLocation Loc, DeclarationName Entity) { 665 if (T->isArrayType() || T->isFunctionType()) { 666 Diag(Loc, diag::err_func_returning_array_function) << T; 667 return QualType(); 668 } 669 670 bool Invalid = false; 671 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 672 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 673 if (ParamType->isVoidType()) { 674 Diag(Loc, diag::err_param_with_void_type); 675 Invalid = true; 676 } 677 678 ParamTypes[Idx] = ParamType; 679 } 680 681 if (Invalid) 682 return QualType(); 683 684 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 685 Quals); 686} 687 688/// \brief Build a member pointer type \c T Class::*. 689/// 690/// \param T the type to which the member pointer refers. 691/// \param Class the class type into which the member pointer points. 692/// \param Quals Qualifiers applied to the member pointer type 693/// \param Loc the location where this type begins 694/// \param Entity the name of the entity that will have this member pointer type 695/// 696/// \returns a member pointer type, if successful, or a NULL type if there was 697/// an error. 698QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 699 unsigned Quals, SourceLocation Loc, 700 DeclarationName Entity) { 701 // Verify that we're not building a pointer to pointer to function with 702 // exception specification. 703 if (CheckDistantExceptionSpec(T)) { 704 Diag(Loc, diag::err_distant_exception_spec); 705 706 // FIXME: If we're doing this as part of template instantiation, 707 // we should return immediately. 708 709 // Build the type anyway, but use the canonical type so that the 710 // exception specifiers are stripped off. 711 T = Context.getCanonicalType(T); 712 } 713 714 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 715 // with reference type, or "cv void." 716 if (T->isReferenceType()) { 717 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 718 << (Entity? Entity.getAsString() : "type name"); 719 return QualType(); 720 } 721 722 if (T->isVoidType()) { 723 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 724 << (Entity? Entity.getAsString() : "type name"); 725 return QualType(); 726 } 727 728 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 729 // object or incomplete types shall not be restrict-qualified." 730 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 731 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 732 << T; 733 734 // FIXME: If we're doing this as part of template instantiation, 735 // we should return immediately. 736 Quals &= ~QualType::Restrict; 737 } 738 739 if (!Class->isDependentType() && !Class->isRecordType()) { 740 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 741 return QualType(); 742 } 743 744 return Context.getMemberPointerType(T, Class.getTypePtr()) 745 .getQualifiedType(Quals); 746} 747 748/// \brief Build a block pointer type. 749/// 750/// \param T The type to which we'll be building a block pointer. 751/// 752/// \param Quals The cvr-qualifiers to be applied to the block pointer type. 753/// 754/// \param Loc The location of the entity whose type involves this 755/// block pointer type or, if there is no such entity, the location of the 756/// type that will have block pointer type. 757/// 758/// \param Entity The name of the entity that involves the block pointer 759/// type, if known. 760/// 761/// \returns A suitable block pointer type, if there are no 762/// errors. Otherwise, returns a NULL type. 763QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals, 764 SourceLocation Loc, 765 DeclarationName Entity) { 766 if (!T.getTypePtr()->isFunctionType()) { 767 Diag(Loc, diag::err_nonfunction_block_type); 768 return QualType(); 769 } 770 771 return Context.getBlockPointerType(T).getQualifiedType(Quals); 772} 773 774/// GetTypeForDeclarator - Convert the type for the specified 775/// declarator to Type instances. Skip the outermost Skip type 776/// objects. 777/// 778/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 779/// owns the declaration of a type (e.g., the definition of a struct 780/// type), then *OwnedDecl will receive the owned declaration. 781QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip, 782 TagDecl **OwnedDecl) { 783 bool OmittedReturnType = false; 784 785 if (D.getContext() == Declarator::BlockLiteralContext 786 && Skip == 0 787 && !D.getDeclSpec().hasTypeSpecifier() 788 && (D.getNumTypeObjects() == 0 789 || (D.getNumTypeObjects() == 1 790 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) 791 OmittedReturnType = true; 792 793 // long long is a C99 feature. 794 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 795 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) 796 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); 797 798 // Determine the type of the declarator. Not all forms of declarator 799 // have a type. 800 QualType T; 801 switch (D.getKind()) { 802 case Declarator::DK_Abstract: 803 case Declarator::DK_Normal: 804 case Declarator::DK_Operator: { 805 const DeclSpec &DS = D.getDeclSpec(); 806 if (OmittedReturnType) { 807 // We default to a dependent type initially. Can be modified by 808 // the first return statement. 809 T = Context.DependentTy; 810 } else { 811 bool isInvalid = false; 812 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid); 813 if (isInvalid) 814 D.setInvalidType(true); 815 else if (OwnedDecl && DS.isTypeSpecOwned()) 816 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep()); 817 } 818 break; 819 } 820 821 case Declarator::DK_Constructor: 822 case Declarator::DK_Destructor: 823 case Declarator::DK_Conversion: 824 // Constructors and destructors don't have return types. Use 825 // "void" instead. Conversion operators will check their return 826 // types separately. 827 T = Context.VoidTy; 828 break; 829 } 830 831 if (T == Context.UndeducedAutoTy) { 832 int Error = -1; 833 834 switch (D.getContext()) { 835 case Declarator::KNRTypeListContext: 836 assert(0 && "K&R type lists aren't allowed in C++"); 837 break; 838 case Declarator::PrototypeContext: 839 Error = 0; // Function prototype 840 break; 841 case Declarator::MemberContext: 842 switch (cast<TagDecl>(CurContext)->getTagKind()) { 843 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break; 844 case TagDecl::TK_struct: Error = 1; /* Struct member */ break; 845 case TagDecl::TK_union: Error = 2; /* Union member */ break; 846 case TagDecl::TK_class: Error = 3; /* Class member */ break; 847 } 848 break; 849 case Declarator::CXXCatchContext: 850 Error = 4; // Exception declaration 851 break; 852 case Declarator::TemplateParamContext: 853 Error = 5; // Template parameter 854 break; 855 case Declarator::BlockLiteralContext: 856 Error = 6; // Block literal 857 break; 858 case Declarator::FileContext: 859 case Declarator::BlockContext: 860 case Declarator::ForContext: 861 case Declarator::ConditionContext: 862 case Declarator::TypeNameContext: 863 break; 864 } 865 866 if (Error != -1) { 867 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 868 << Error; 869 T = Context.IntTy; 870 D.setInvalidType(true); 871 } 872 } 873 874 // The name we're declaring, if any. 875 DeclarationName Name; 876 if (D.getIdentifier()) 877 Name = D.getIdentifier(); 878 879 // Walk the DeclTypeInfo, building the recursive type as we go. 880 // DeclTypeInfos are ordered from the identifier out, which is 881 // opposite of what we want :). 882 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { 883 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); 884 switch (DeclType.Kind) { 885 default: assert(0 && "Unknown decltype!"); 886 case DeclaratorChunk::BlockPointer: 887 // If blocks are disabled, emit an error. 888 if (!LangOpts.Blocks) 889 Diag(DeclType.Loc, diag::err_blocks_disable); 890 891 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(), 892 Name); 893 break; 894 case DeclaratorChunk::Pointer: 895 // Verify that we're not building a pointer to pointer to function with 896 // exception specification. 897 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 898 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 899 D.setInvalidType(true); 900 // Build the type anyway. 901 } 902 if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) { 903 const ObjCInterfaceType *OIT = T->getAsObjCInterfaceType(); 904 T = Context.getObjCObjectPointerType(T, 905 (ObjCProtocolDecl **)OIT->qual_begin(), 906 OIT->getNumProtocols()); 907 break; 908 } 909 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 910 break; 911 case DeclaratorChunk::Reference: 912 // Verify that we're not building a reference to pointer to function with 913 // exception specification. 914 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 915 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 916 D.setInvalidType(true); 917 // Build the type anyway. 918 } 919 T = BuildReferenceType(T, DeclType.Ref.LValueRef, 920 DeclType.Ref.HasRestrict ? QualType::Restrict : 0, 921 DeclType.Loc, Name); 922 break; 923 case DeclaratorChunk::Array: { 924 // Verify that we're not building an array of pointers to function with 925 // exception specification. 926 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 927 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 928 D.setInvalidType(true); 929 // Build the type anyway. 930 } 931 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 932 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 933 ArrayType::ArraySizeModifier ASM; 934 if (ATI.isStar) 935 ASM = ArrayType::Star; 936 else if (ATI.hasStatic) 937 ASM = ArrayType::Static; 938 else 939 ASM = ArrayType::Normal; 940 if (ASM == ArrayType::Star && 941 D.getContext() != Declarator::PrototypeContext) { 942 // FIXME: This check isn't quite right: it allows star in prototypes 943 // for function definitions, and disallows some edge cases detailed 944 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 945 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 946 ASM = ArrayType::Normal; 947 D.setInvalidType(true); 948 } 949 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 950 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 951 break; 952 } 953 case DeclaratorChunk::Function: { 954 // If the function declarator has a prototype (i.e. it is not () and 955 // does not have a K&R-style identifier list), then the arguments are part 956 // of the type, otherwise the argument list is (). 957 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 958 959 // C99 6.7.5.3p1: The return type may not be a function or array type. 960 if (T->isArrayType() || T->isFunctionType()) { 961 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; 962 T = Context.IntTy; 963 D.setInvalidType(true); 964 } 965 966 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 967 // C++ [dcl.fct]p6: 968 // Types shall not be defined in return or parameter types. 969 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 970 if (Tag->isDefinition()) 971 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 972 << Context.getTypeDeclType(Tag); 973 } 974 975 // Exception specs are not allowed in typedefs. Complain, but add it 976 // anyway. 977 if (FTI.hasExceptionSpec && 978 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 979 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 980 981 if (FTI.NumArgs == 0) { 982 if (getLangOptions().CPlusPlus) { 983 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 984 // function takes no arguments. 985 llvm::SmallVector<QualType, 4> Exceptions; 986 Exceptions.reserve(FTI.NumExceptions); 987 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 988 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 989 // Check that the type is valid for an exception spec, and drop it 990 // if not. 991 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 992 Exceptions.push_back(ET); 993 } 994 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals, 995 FTI.hasExceptionSpec, 996 FTI.hasAnyExceptionSpec, 997 Exceptions.size(), Exceptions.data()); 998 } else if (FTI.isVariadic) { 999 // We allow a zero-parameter variadic function in C if the 1000 // function is marked with the "overloadable" 1001 // attribute. Scan for this attribute now. 1002 bool Overloadable = false; 1003 for (const AttributeList *Attrs = D.getAttributes(); 1004 Attrs; Attrs = Attrs->getNext()) { 1005 if (Attrs->getKind() == AttributeList::AT_overloadable) { 1006 Overloadable = true; 1007 break; 1008 } 1009 } 1010 1011 if (!Overloadable) 1012 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 1013 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0); 1014 } else { 1015 // Simple void foo(), where the incoming T is the result type. 1016 T = Context.getFunctionNoProtoType(T); 1017 } 1018 } else if (FTI.ArgInfo[0].Param == 0) { 1019 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 1020 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1021 } else { 1022 // Otherwise, we have a function with an argument list that is 1023 // potentially variadic. 1024 llvm::SmallVector<QualType, 16> ArgTys; 1025 1026 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1027 ParmVarDecl *Param = 1028 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1029 QualType ArgTy = Param->getType(); 1030 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1031 1032 // Adjust the parameter type. 1033 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1034 1035 // Look for 'void'. void is allowed only as a single argument to a 1036 // function with no other parameters (C99 6.7.5.3p10). We record 1037 // int(void) as a FunctionProtoType with an empty argument list. 1038 if (ArgTy->isVoidType()) { 1039 // If this is something like 'float(int, void)', reject it. 'void' 1040 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1041 // have arguments of incomplete type. 1042 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1043 Diag(DeclType.Loc, diag::err_void_only_param); 1044 ArgTy = Context.IntTy; 1045 Param->setType(ArgTy); 1046 } else if (FTI.ArgInfo[i].Ident) { 1047 // Reject, but continue to parse 'int(void abc)'. 1048 Diag(FTI.ArgInfo[i].IdentLoc, 1049 diag::err_param_with_void_type); 1050 ArgTy = Context.IntTy; 1051 Param->setType(ArgTy); 1052 } else { 1053 // Reject, but continue to parse 'float(const void)'. 1054 if (ArgTy.getCVRQualifiers()) 1055 Diag(DeclType.Loc, diag::err_void_param_qualified); 1056 1057 // Do not add 'void' to the ArgTys list. 1058 break; 1059 } 1060 } else if (!FTI.hasPrototype) { 1061 if (ArgTy->isPromotableIntegerType()) { 1062 ArgTy = Context.IntTy; 1063 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { 1064 if (BTy->getKind() == BuiltinType::Float) 1065 ArgTy = Context.DoubleTy; 1066 } 1067 } 1068 1069 ArgTys.push_back(ArgTy); 1070 } 1071 1072 llvm::SmallVector<QualType, 4> Exceptions; 1073 Exceptions.reserve(FTI.NumExceptions); 1074 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1075 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 1076 // Check that the type is valid for an exception spec, and drop it if 1077 // not. 1078 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1079 Exceptions.push_back(ET); 1080 } 1081 1082 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1083 FTI.isVariadic, FTI.TypeQuals, 1084 FTI.hasExceptionSpec, 1085 FTI.hasAnyExceptionSpec, 1086 Exceptions.size(), Exceptions.data()); 1087 } 1088 break; 1089 } 1090 case DeclaratorChunk::MemberPointer: 1091 // Verify that we're not building a pointer to pointer to function with 1092 // exception specification. 1093 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1094 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1095 D.setInvalidType(true); 1096 // Build the type anyway. 1097 } 1098 // The scope spec must refer to a class, or be dependent. 1099 QualType ClsType; 1100 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) { 1101 NestedNameSpecifier *NNS 1102 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1103 assert(NNS->getAsType() && "Nested-name-specifier must name a type"); 1104 ClsType = QualType(NNS->getAsType(), 0); 1105 } else if (CXXRecordDecl *RD 1106 = dyn_cast_or_null<CXXRecordDecl>( 1107 computeDeclContext(DeclType.Mem.Scope()))) { 1108 ClsType = Context.getTagDeclType(RD); 1109 } else { 1110 Diag(DeclType.Mem.Scope().getBeginLoc(), 1111 diag::err_illegal_decl_mempointer_in_nonclass) 1112 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1113 << DeclType.Mem.Scope().getRange(); 1114 D.setInvalidType(true); 1115 } 1116 1117 if (!ClsType.isNull()) 1118 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals, 1119 DeclType.Loc, D.getIdentifier()); 1120 if (T.isNull()) { 1121 T = Context.IntTy; 1122 D.setInvalidType(true); 1123 } 1124 break; 1125 } 1126 1127 if (T.isNull()) { 1128 D.setInvalidType(true); 1129 T = Context.IntTy; 1130 } 1131 1132 // See if there are any attributes on this declarator chunk. 1133 if (const AttributeList *AL = DeclType.getAttrs()) 1134 ProcessTypeAttributeList(T, AL); 1135 } 1136 1137 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1138 const FunctionProtoType *FnTy = T->getAsFunctionProtoType(); 1139 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?"); 1140 1141 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1142 // for a nonstatic member function, the function type to which a pointer 1143 // to member refers, or the top-level function type of a function typedef 1144 // declaration. 1145 if (FnTy->getTypeQuals() != 0 && 1146 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1147 ((D.getContext() != Declarator::MemberContext && 1148 (!D.getCXXScopeSpec().isSet() || 1149 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) || 1150 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1151 if (D.isFunctionDeclarator()) 1152 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1153 else 1154 Diag(D.getIdentifierLoc(), 1155 diag::err_invalid_qualified_typedef_function_type_use); 1156 1157 // Strip the cv-quals from the type. 1158 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1159 FnTy->getNumArgs(), FnTy->isVariadic(), 0); 1160 } 1161 } 1162 1163 // If there were any type attributes applied to the decl itself (not the 1164 // type, apply the type attribute to the type!) 1165 if (const AttributeList *Attrs = D.getAttributes()) 1166 ProcessTypeAttributeList(T, Attrs); 1167 1168 return T; 1169} 1170 1171/// CheckSpecifiedExceptionType - Check if the given type is valid in an 1172/// exception specification. Incomplete types, or pointers to incomplete types 1173/// other than void are not allowed. 1174bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) { 1175 // FIXME: This may not correctly work with the fix for core issue 437, 1176 // where a class's own type is considered complete within its body. 1177 1178 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1179 // an incomplete type. 1180 if (T->isIncompleteType()) 1181 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1182 << Range << T << /*direct*/0; 1183 1184 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1185 // an incomplete type a pointer or reference to an incomplete type, other 1186 // than (cv) void*. 1187 int kind; 1188 if (const PointerType* IT = T->getAsPointerType()) { 1189 T = IT->getPointeeType(); 1190 kind = 1; 1191 } else if (const ReferenceType* IT = T->getAsReferenceType()) { 1192 T = IT->getPointeeType(); 1193 kind = 2; 1194 } else 1195 return false; 1196 1197 if (T->isIncompleteType() && !T->isVoidType()) 1198 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1199 << Range << T << /*indirect*/kind; 1200 1201 return false; 1202} 1203 1204/// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer 1205/// to member to a function with an exception specification. This means that 1206/// it is invalid to add another level of indirection. 1207bool Sema::CheckDistantExceptionSpec(QualType T) { 1208 if (const PointerType *PT = T->getAsPointerType()) 1209 T = PT->getPointeeType(); 1210 else if (const MemberPointerType *PT = T->getAsMemberPointerType()) 1211 T = PT->getPointeeType(); 1212 else 1213 return false; 1214 1215 const FunctionProtoType *FnT = T->getAsFunctionProtoType(); 1216 if (!FnT) 1217 return false; 1218 1219 return FnT->hasExceptionSpec(); 1220} 1221 1222/// CheckEquivalentExceptionSpec - Check if the two types have equivalent 1223/// exception specifications. Exception specifications are equivalent if 1224/// they allow exactly the same set of exception types. It does not matter how 1225/// that is achieved. See C++ [except.spec]p2. 1226bool Sema::CheckEquivalentExceptionSpec( 1227 const FunctionProtoType *Old, SourceLocation OldLoc, 1228 const FunctionProtoType *New, SourceLocation NewLoc) { 1229 bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec(); 1230 bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec(); 1231 if (OldAny && NewAny) 1232 return false; 1233 if (OldAny || NewAny) { 1234 Diag(NewLoc, diag::err_mismatched_exception_spec); 1235 Diag(OldLoc, diag::note_previous_declaration); 1236 return true; 1237 } 1238 1239 bool Success = true; 1240 // Both have a definite exception spec. Collect the first set, then compare 1241 // to the second. 1242 llvm::SmallPtrSet<const Type*, 8> Types; 1243 for (FunctionProtoType::exception_iterator I = Old->exception_begin(), 1244 E = Old->exception_end(); I != E; ++I) 1245 Types.insert(Context.getCanonicalType(*I).getTypePtr()); 1246 1247 for (FunctionProtoType::exception_iterator I = New->exception_begin(), 1248 E = New->exception_end(); I != E && Success; ++I) 1249 Success = Types.erase(Context.getCanonicalType(*I).getTypePtr()); 1250 1251 Success = Success && Types.empty(); 1252 1253 if (Success) { 1254 return false; 1255 } 1256 Diag(NewLoc, diag::err_mismatched_exception_spec); 1257 Diag(OldLoc, diag::note_previous_declaration); 1258 return true; 1259} 1260 1261/// CheckExceptionSpecSubset - Check whether the second function type's 1262/// exception specification is a subset (or equivalent) of the first function 1263/// type. This is used by override and pointer assignment checks. 1264bool Sema::CheckExceptionSpecSubset(unsigned DiagID, unsigned NoteID, 1265 const FunctionProtoType *Superset, SourceLocation SuperLoc, 1266 const FunctionProtoType *Subset, SourceLocation SubLoc) 1267{ 1268 // FIXME: As usual, we could be more specific in our error messages, but 1269 // that better waits until we've got types with source locations. 1270 1271 // If superset contains everything, we're done. 1272 if (!Superset->hasExceptionSpec() || Superset->hasAnyExceptionSpec()) 1273 return false; 1274 1275 // It does not. If the subset contains everything, we've failed. 1276 if (!Subset->hasExceptionSpec() || Subset->hasAnyExceptionSpec()) { 1277 Diag(SubLoc, DiagID); 1278 Diag(SuperLoc, NoteID); 1279 return true; 1280 } 1281 1282 // Neither contains everything. Do a proper comparison. 1283 for (FunctionProtoType::exception_iterator SubI = Subset->exception_begin(), 1284 SubE = Subset->exception_end(); SubI != SubE; ++SubI) { 1285 // Take one type from the subset. 1286 QualType CanonicalSubT = Context.getCanonicalType(*SubI); 1287 bool SubIsPointer = false; 1288 if (const ReferenceType *RefTy = CanonicalSubT->getAsReferenceType()) 1289 CanonicalSubT = RefTy->getPointeeType(); 1290 if (const PointerType *PtrTy = CanonicalSubT->getAsPointerType()) { 1291 CanonicalSubT = PtrTy->getPointeeType(); 1292 SubIsPointer = true; 1293 } 1294 bool SubIsClass = CanonicalSubT->isRecordType(); 1295 CanonicalSubT.setCVRQualifiers(0); 1296 1297 BasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false, 1298 /*DetectVirtual=*/false); 1299 1300 bool Contained = false; 1301 // Make sure it's in the superset. 1302 for (FunctionProtoType::exception_iterator SuperI = 1303 Superset->exception_begin(), SuperE = Superset->exception_end(); 1304 SuperI != SuperE; ++SuperI) { 1305 QualType CanonicalSuperT = Context.getCanonicalType(*SuperI); 1306 // SubT must be SuperT or derived from it, or pointer or reference to 1307 // such types. 1308 if (const ReferenceType *RefTy = CanonicalSuperT->getAsReferenceType()) 1309 CanonicalSuperT = RefTy->getPointeeType(); 1310 if (SubIsPointer) { 1311 if (const PointerType *PtrTy = CanonicalSuperT->getAsPointerType()) 1312 CanonicalSuperT = PtrTy->getPointeeType(); 1313 else { 1314 continue; 1315 } 1316 } 1317 CanonicalSuperT.setCVRQualifiers(0); 1318 // If the types are the same, move on to the next type in the subset. 1319 if (CanonicalSubT == CanonicalSuperT) { 1320 Contained = true; 1321 break; 1322 } 1323 1324 // Otherwise we need to check the inheritance. 1325 if (!SubIsClass || !CanonicalSuperT->isRecordType()) 1326 continue; 1327 1328 Paths.clear(); 1329 if (!IsDerivedFrom(CanonicalSubT, CanonicalSuperT, Paths)) 1330 continue; 1331 1332 if (Paths.isAmbiguous(CanonicalSuperT)) 1333 continue; 1334 1335 // FIXME: Check base access. Don't forget to enable path recording. 1336 1337 Contained = true; 1338 break; 1339 } 1340 if (!Contained) { 1341 Diag(SubLoc, DiagID); 1342 Diag(SuperLoc, NoteID); 1343 return true; 1344 } 1345 } 1346 // We've run the gauntlet. 1347 return false; 1348} 1349 1350/// ObjCGetTypeForMethodDefinition - Builds the type for a method definition 1351/// declarator 1352QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) { 1353 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>()); 1354 QualType T = MDecl->getResultType(); 1355 llvm::SmallVector<QualType, 16> ArgTys; 1356 1357 // Add the first two invisible argument types for self and _cmd. 1358 if (MDecl->isInstanceMethod()) { 1359 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); 1360 selfTy = Context.getPointerType(selfTy); 1361 ArgTys.push_back(selfTy); 1362 } else 1363 ArgTys.push_back(Context.getObjCIdType()); 1364 ArgTys.push_back(Context.getObjCSelType()); 1365 1366 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 1367 E = MDecl->param_end(); PI != E; ++PI) { 1368 QualType ArgTy = (*PI)->getType(); 1369 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1370 ArgTy = adjustParameterType(ArgTy); 1371 ArgTys.push_back(ArgTy); 1372 } 1373 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 1374 MDecl->isVariadic(), 0); 1375 return T; 1376} 1377 1378/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 1379/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 1380/// they point to and return true. If T1 and T2 aren't pointer types 1381/// or pointer-to-member types, or if they are not similar at this 1382/// level, returns false and leaves T1 and T2 unchanged. Top-level 1383/// qualifiers on T1 and T2 are ignored. This function will typically 1384/// be called in a loop that successively "unwraps" pointer and 1385/// pointer-to-member types to compare them at each level. 1386bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 1387 const PointerType *T1PtrType = T1->getAsPointerType(), 1388 *T2PtrType = T2->getAsPointerType(); 1389 if (T1PtrType && T2PtrType) { 1390 T1 = T1PtrType->getPointeeType(); 1391 T2 = T2PtrType->getPointeeType(); 1392 return true; 1393 } 1394 1395 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), 1396 *T2MPType = T2->getAsMemberPointerType(); 1397 if (T1MPType && T2MPType && 1398 Context.getCanonicalType(T1MPType->getClass()) == 1399 Context.getCanonicalType(T2MPType->getClass())) { 1400 T1 = T1MPType->getPointeeType(); 1401 T2 = T2MPType->getPointeeType(); 1402 return true; 1403 } 1404 return false; 1405} 1406 1407Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1408 // C99 6.7.6: Type names have no identifier. This is already validated by 1409 // the parser. 1410 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1411 1412 TagDecl *OwnedTag = 0; 1413 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag); 1414 if (D.isInvalidType()) 1415 return true; 1416 1417 if (getLangOptions().CPlusPlus) { 1418 // Check that there are no default arguments (C++ only). 1419 CheckExtraCXXDefaultArguments(D); 1420 1421 // C++0x [dcl.type]p3: 1422 // A type-specifier-seq shall not define a class or enumeration 1423 // unless it appears in the type-id of an alias-declaration 1424 // (7.1.3). 1425 if (OwnedTag && OwnedTag->isDefinition()) 1426 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1427 << Context.getTypeDeclType(OwnedTag); 1428 } 1429 1430 return T.getAsOpaquePtr(); 1431} 1432 1433 1434 1435//===----------------------------------------------------------------------===// 1436// Type Attribute Processing 1437//===----------------------------------------------------------------------===// 1438 1439/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1440/// specified type. The attribute contains 1 argument, the id of the address 1441/// space for the type. 1442static void HandleAddressSpaceTypeAttribute(QualType &Type, 1443 const AttributeList &Attr, Sema &S){ 1444 // If this type is already address space qualified, reject it. 1445 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1446 // for two or more different address spaces." 1447 if (Type.getAddressSpace()) { 1448 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1449 return; 1450 } 1451 1452 // Check the attribute arguments. 1453 if (Attr.getNumArgs() != 1) { 1454 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1455 return; 1456 } 1457 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1458 llvm::APSInt addrSpace(32); 1459 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1460 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1461 << ASArgExpr->getSourceRange(); 1462 return; 1463 } 1464 1465 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1466 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1467} 1468 1469/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1470/// specified type. The attribute contains 1 argument, weak or strong. 1471static void HandleObjCGCTypeAttribute(QualType &Type, 1472 const AttributeList &Attr, Sema &S) { 1473 if (Type.getObjCGCAttr() != QualType::GCNone) { 1474 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1475 return; 1476 } 1477 1478 // Check the attribute arguments. 1479 if (!Attr.getParameterName()) { 1480 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1481 << "objc_gc" << 1; 1482 return; 1483 } 1484 QualType::GCAttrTypes GCAttr; 1485 if (Attr.getNumArgs() != 0) { 1486 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1487 return; 1488 } 1489 if (Attr.getParameterName()->isStr("weak")) 1490 GCAttr = QualType::Weak; 1491 else if (Attr.getParameterName()->isStr("strong")) 1492 GCAttr = QualType::Strong; 1493 else { 1494 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1495 << "objc_gc" << Attr.getParameterName(); 1496 return; 1497 } 1498 1499 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1500} 1501 1502void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { 1503 // Scan through and apply attributes to this type where it makes sense. Some 1504 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1505 // type, but others can be present in the type specifiers even though they 1506 // apply to the decl. Here we apply type attributes and ignore the rest. 1507 for (; AL; AL = AL->getNext()) { 1508 // If this is an attribute we can handle, do so now, otherwise, add it to 1509 // the LeftOverAttrs list for rechaining. 1510 switch (AL->getKind()) { 1511 default: break; 1512 case AttributeList::AT_address_space: 1513 HandleAddressSpaceTypeAttribute(Result, *AL, *this); 1514 break; 1515 case AttributeList::AT_objc_gc: 1516 HandleObjCGCTypeAttribute(Result, *AL, *this); 1517 break; 1518 } 1519 } 1520} 1521 1522/// @brief Ensure that the type T is a complete type. 1523/// 1524/// This routine checks whether the type @p T is complete in any 1525/// context where a complete type is required. If @p T is a complete 1526/// type, returns false. If @p T is a class template specialization, 1527/// this routine then attempts to perform class template 1528/// instantiation. If instantiation fails, or if @p T is incomplete 1529/// and cannot be completed, issues the diagnostic @p diag (giving it 1530/// the type @p T) and returns true. 1531/// 1532/// @param Loc The location in the source that the incomplete type 1533/// diagnostic should refer to. 1534/// 1535/// @param T The type that this routine is examining for completeness. 1536/// 1537/// @param diag The diagnostic value (e.g., 1538/// @c diag::err_typecheck_decl_incomplete_type) that will be used 1539/// for the error message if @p T is incomplete. 1540/// 1541/// @param Range1 An optional range in the source code that will be a 1542/// part of the "incomplete type" error message. 1543/// 1544/// @param Range2 An optional range in the source code that will be a 1545/// part of the "incomplete type" error message. 1546/// 1547/// @param PrintType If non-NULL, the type that should be printed 1548/// instead of @p T. This parameter should be used when the type that 1549/// we're checking for incompleteness isn't the type that should be 1550/// displayed to the user, e.g., when T is a type and PrintType is a 1551/// pointer to T. 1552/// 1553/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1554/// @c false otherwise. 1555bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag, 1556 SourceRange Range1, SourceRange Range2, 1557 QualType PrintType) { 1558 // FIXME: Add this assertion to help us flush out problems with 1559 // checking for dependent types and type-dependent expressions. 1560 // 1561 // assert(!T->isDependentType() && 1562 // "Can't ask whether a dependent type is complete"); 1563 1564 // If we have a complete type, we're done. 1565 if (!T->isIncompleteType()) 1566 return false; 1567 1568 // If we have a class template specialization or a class member of a 1569 // class template specialization, try to instantiate it. 1570 if (const RecordType *Record = T->getAsRecordType()) { 1571 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 1572 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 1573 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1574 // Update the class template specialization's location to 1575 // refer to the point of instantiation. 1576 if (Loc.isValid()) 1577 ClassTemplateSpec->setLocation(Loc); 1578 return InstantiateClassTemplateSpecialization(ClassTemplateSpec, 1579 /*ExplicitInstantiation=*/false); 1580 } 1581 } else if (CXXRecordDecl *Rec 1582 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 1583 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 1584 // Find the class template specialization that surrounds this 1585 // member class. 1586 ClassTemplateSpecializationDecl *Spec = 0; 1587 for (DeclContext *Parent = Rec->getDeclContext(); 1588 Parent && !Spec; Parent = Parent->getParent()) 1589 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent); 1590 assert(Spec && "Not a member of a class template specialization?"); 1591 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(), 1592 /*ExplicitInstantiation=*/false); 1593 } 1594 } 1595 } 1596 1597 if (PrintType.isNull()) 1598 PrintType = T; 1599 1600 // We have an incomplete type. Produce a diagnostic. 1601 Diag(Loc, diag) << PrintType << Range1 << Range2; 1602 1603 // If the type was a forward declaration of a class/struct/union 1604 // type, produce 1605 const TagType *Tag = 0; 1606 if (const RecordType *Record = T->getAsRecordType()) 1607 Tag = Record; 1608 else if (const EnumType *Enum = T->getAsEnumType()) 1609 Tag = Enum; 1610 1611 if (Tag && !Tag->getDecl()->isInvalidDecl()) 1612 Diag(Tag->getDecl()->getLocation(), 1613 Tag->isBeingDefined() ? diag::note_type_being_defined 1614 : diag::note_forward_declaration) 1615 << QualType(Tag, 0); 1616 1617 return true; 1618} 1619 1620/// \brief Retrieve a version of the type 'T' that is qualified by the 1621/// nested-name-specifier contained in SS. 1622QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { 1623 if (!SS.isSet() || SS.isInvalid() || T.isNull()) 1624 return T; 1625 1626 NestedNameSpecifier *NNS 1627 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1628 return Context.getQualifiedNameType(NNS, T); 1629} 1630 1631QualType Sema::BuildTypeofExprType(Expr *E) { 1632 return Context.getTypeOfExprType(E); 1633} 1634 1635QualType Sema::BuildDecltypeType(Expr *E) { 1636 if (E->getType() == Context.OverloadTy) { 1637 Diag(E->getLocStart(), 1638 diag::err_cannot_determine_declared_type_of_overloaded_function); 1639 return QualType(); 1640 } 1641 return Context.getDecltypeType(E); 1642} 1643