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 "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; 22 23 /// \brief Perform adjustment on the parameter type of a function. 24 /// 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) { 29 // C99 6.7.5.3p7: 30 if (T->isArrayType()) { 31 // C99 6.7.5.3p7: 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()) 38 // C99 6.7.5.3p8: 39 // A declaration of a parameter as "function returning type" 40 // shall be adjusted to "pointer to function returning type", as 41 // in 6.3.2.1. 42 return Context.getPointerType(T); 43 44 return T; 45 } 46 47 /// \brief Convert the specified declspec to the appropriate type 48 /// object. 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, 55 bool &isInvalid) { 56 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 57 // checking. 58 QualType Result; 59 60 switch (DS.getTypeSpecType()) { 61 case DeclSpec::TST_void: 62 Result = Context.VoidTy; 63 break; 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; 69 else { 70 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 71 "Unknown TSS value"); 72 Result = Context.UnsignedCharTy; 73 } 74 break; 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(); 82 } else { 83 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 84 "Unknown TSS value"); 85 Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 86 << DS.getSpecifierName(DS.getTypeSpecType()); 87 Result = Context.getUnsignedWCharType(); 88 } 89 break; 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()); 95 break; 96 } 97 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 104 // case. 105 if (getLangOptions().ImplicitInt) { 106 // In C89 mode, we only warn if there is a completely missing declspec 107 // when one is not allowed. 108 if (DS.isEmpty()) { 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(), 114 "int"); 115 } 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(); 124 125 if (getLangOptions().CPlusPlus && !getLangOptions().Microsoft) { 126 Diag(DeclLoc, diag::err_missing_type_specifier) 127 << DS.getSourceRange(); 128 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 131 // errors. 132 isInvalid = true; 133 } else { 134 Diag(DeclLoc, diag::ext_missing_type_specifier) 135 << DS.getSourceRange(); 136 } 137 } 138 139 // FALL THROUGH. 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; 147 } 148 } else { 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; 154 } 155 } 156 break; 157 } 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; 162 else 163 Result = Context.DoubleTy; 164 break; 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; 171 isInvalid = true; 172 break; 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)); 184 185 if (D->isInvalidDecl()) 186 isInvalid = true; 187 break; 188 } 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()); 194 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()) 203 // id<protocol-list> 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(); 212 } else { 213 if (DeclLoc.isInvalid()) 214 DeclLoc = DS.getSourceRange().getBegin(); 215 Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 216 << DS.getSourceRange(); 217 isInvalid = true; 218 } 219 } 220 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()) 224 isInvalid = true; 225 226 // TypeQuals handled by caller. 227 break; 228 } 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); 234 break; 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); 240 break; 241 } 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; 249 isInvalid = true; 250 } 251 break; 252 } 253 case DeclSpec::TST_auto: { 254 // TypeQuals handled by caller. 255 Result = Context.UndeducedAutoTy; 256 break; 257 } 258 259 case DeclSpec::TST_error: 260 Result = Context.IntTy; 261 isInvalid = true; 262 break; 263 } 264 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); 270 } 271 272 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 273 "FIXME: imaginary types not supported yet!"); 274 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); 279 280 // Apply const/volatile/restrict qualifiers to T. 281 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 282 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(); 291 292 // If we have a pointer or reference, the pointee must have an object 293 // incomplete type. 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. 299 } 300 } else { 301 Diag(DS.getRestrictSpecLoc(), 302 diag::err_typecheck_invalid_restrict_not_pointer) 303 << Result << DS.getSourceRange(); 304 TypeQuals &= ~QualType::Restrict; // Remove the restrict qualifier. 305 } 306 } 307 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 310 // undefined." 311 if (Result->isFunctionType() && TypeQuals) { 312 // Get some location to point at, either the C or V location. 313 SourceLocation Loc; 314 if (TypeQuals & QualType::Const) 315 Loc = DS.getConstSpecLoc(); 316 else { 317 assert((TypeQuals & QualType::Volatile) && 318 "Has CV quals but not C or V?"); 319 Loc = DS.getVolatileSpecLoc(); 320 } 321 Diag(Loc, diag::warn_typecheck_function_qualifiers) 322 << Result << DS.getSourceRange(); 323 } 324 325 // C++ [dcl.ref]p1: 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; 335 } 336 337 Result = Result.getQualifiedType(TypeQuals); 338 } 339 return Result; 340 } 341 342 static std::string getPrintableNameForEntity(DeclarationName Entity) { 343 if (Entity) 344 return Entity.getAsString(); 345 346 return "type name"; 347 } 348 349 /// \brief Build a pointer type. 350 /// 351 /// \param T The type to which we'll be building a pointer. 352 /// 353 /// \param Quals The cvr-qualifiers to be applied to the pointer type. 354 /// 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. 358 /// 359 /// \param Entity The name of the entity that involves the pointer 360 /// type, if known. 361 /// 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); 370 return QualType(); 371 } 372 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) 377 << T; 378 Quals &= ~QualType::Restrict; 379 } 380 381 // Build the pointer type. 382 return Context.getPointerType(T).getQualifiedType(Quals); 383 } 384 385 /// \brief Build a reference type. 386 /// 387 /// \param T The type to which we'll be building a reference. 388 /// 389 /// \param Quals The cvr-qualifiers to be applied to the reference type. 390 /// 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. 394 /// 395 /// \param Entity The name of the entity that involves the reference 396 /// type, if known. 397 /// 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) { 402 if (LValueRef) { 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()); 411 } 412 } 413 if (T->isReferenceType()) { 414 // C++ [dcl.ref]p4: There shall be no references to references. 415 // 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: 419 // 420 // typedef int& intref; 421 // typedef intref& intref2; 422 // 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. 427 return T; 428 } 429 430 // C++ [dcl.ref]p1: 431 // A declarator that specifies the type “reference to cv void” 432 // is ill-formed. 433 if (T->isVoidType()) { 434 Diag(Loc, diag::err_reference_to_void); 435 return QualType(); 436 } 437 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) 442 << T; 443 Quals &= ~QualType::Restrict; 444 } 445 446 // C++ [dcl.ref]p1: 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. 451 // 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; 457 458 // Handle restrict on references. 459 if (LValueRef) 460 return Context.getLValueReferenceType(T).getQualifiedType(Quals); 461 return Context.getRValueReferenceType(T).getQualifiedType(Quals); 462 } 463 464 /// \brief Build an array type. 465 /// 466 /// \param T The type of each element in the array. 467 /// 468 /// \param ASM C99 array size modifier (e.g., '*', 'static'). 469 /// 470 /// \param ArraySize Expression describing the size of the array. 471 /// 472 /// \param Quals The cvr-qualifiers to be applied to the array's 473 /// element type. 474 /// 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. 478 /// 479 /// \param Entity The name of the entity that involves the array 480 /// type, if known. 481 /// 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 SourceRange Brackets, DeclarationName Entity) { 487 SourceLocation Loc = Brackets.getBegin(); 488 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 489 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 490 if (RequireCompleteType(Loc, T, 491 diag::err_illegal_decl_array_incomplete_type)) 492 return QualType(); 493 494 if (T->isFunctionType()) { 495 Diag(Loc, diag::err_illegal_decl_array_of_functions) 496 << getPrintableNameForEntity(Entity); 497 return QualType(); 498 } 499 500 // C++ 8.3.2p4: There shall be no ... arrays of references ... 501 if (T->isReferenceType()) { 502 Diag(Loc, diag::err_illegal_decl_array_of_references) 503 << getPrintableNameForEntity(Entity); 504 return QualType(); 505 } 506 507 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) { 508 Diag(Loc, diag::err_illegal_decl_array_of_auto) 509 << getPrintableNameForEntity(Entity); 510 return QualType(); 511 } 512 513 if (const RecordType *EltTy = T->getAsRecordType()) { 514 // If the element type is a struct or union that contains a variadic 515 // array, accept it as a GNU extension: C99 6.7.2.1p2. 516 if (EltTy->getDecl()->hasFlexibleArrayMember()) 517 Diag(Loc, diag::ext_flexible_array_in_array) << T; 518 } else if (T->isObjCInterfaceType()) { 519 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 520 return QualType(); 521 } 522 523 // C99 6.7.5.2p1: The size expression shall have integer type. 524 if (ArraySize && !ArraySize->isTypeDependent() && 525 !ArraySize->getType()->isIntegerType()) { 526 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 527 << ArraySize->getType() << ArraySize->getSourceRange(); 528 ArraySize->Destroy(Context); 529 return QualType(); 530 } 531 llvm::APSInt ConstVal(32); 532 if (!ArraySize) { 533 if (ASM == ArrayType::Star) 534 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 535 else 536 T = Context.getIncompleteArrayType(T, ASM, Quals); 537 } else if (ArraySize->isValueDependent()) { 538 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 539 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 540 (!T->isDependentType() && !T->isConstantSizeType())) { 541 // Per C99, a variable array is an array with either a non-constant 542 // size or an element type that has a non-constant-size 543 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 544 } else { 545 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 546 // have a value greater than zero. 547 if (ConstVal.isSigned()) { 548 if (ConstVal.isNegative()) { 549 Diag(ArraySize->getLocStart(), 550 diag::err_typecheck_negative_array_size) 551 << ArraySize->getSourceRange(); 552 return QualType(); 553 } else if (ConstVal == 0) { 554 // GCC accepts zero sized static arrays. 555 Diag(ArraySize->getLocStart(), diag::ext_typecheck_zero_array_size) 556 << ArraySize->getSourceRange(); 557 } 558 } 559 T = Context.getConstantArrayWithExprType(T, ConstVal, ArraySize, 560 ASM, Quals, Brackets); 561 } 562 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 563 if (!getLangOptions().C99) { 564 if (ArraySize && !ArraySize->isTypeDependent() && 565 !ArraySize->isValueDependent() && 566 !ArraySize->isIntegerConstantExpr(Context)) 567 Diag(Loc, diag::ext_vla); 568 else if (ASM != ArrayType::Normal || Quals != 0) 569 Diag(Loc, diag::ext_c99_array_usage); 570 } 571 572 return T; 573 } 574 575 /// \brief Build an ext-vector type. 576 /// 577 /// Run the required checks for the extended vector type. 578 QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 579 SourceLocation AttrLoc) { 580 581 Expr *Arg = (Expr *)ArraySize.get(); 582 583 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 584 // in conjunction with complex types (pointers, arrays, functions, etc.). 585 if (!T->isDependentType() && 586 !T->isIntegerType() && !T->isRealFloatingType()) { 587 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 588 return QualType(); 589 } 590 591 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 592 llvm::APSInt vecSize(32); 593 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 594 Diag(AttrLoc, diag::err_attribute_argument_not_int) 595 << "ext_vector_type" << Arg->getSourceRange(); 596 return QualType(); 597 } 598 599 // unlike gcc's vector_size attribute, the size is specified as the 600 // number of elements, not the number of bytes. 601 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 602 603 if (vectorSize == 0) { 604 Diag(AttrLoc, diag::err_attribute_zero_size) 605 << Arg->getSourceRange(); 606 return QualType(); 607 } 608 609 if (!T->isDependentType()) 610 return Context.getExtVectorType(T, vectorSize); 611 } 612 613 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 614 AttrLoc); 615 } 616 617 /// \brief Build a function type. 618 /// 619 /// This routine checks the function type according to C++ rules and 620 /// under the assumption that the result type and parameter types have 621 /// just been instantiated from a template. It therefore duplicates 622 /// some of the behavior of GetTypeForDeclarator, but in a much 623 /// simpler form that is only suitable for this narrow use case. 624 /// 625 /// \param T The return type of the function. 626 /// 627 /// \param ParamTypes The parameter types of the function. This array 628 /// will be modified to account for adjustments to the types of the 629 /// function parameters. 630 /// 631 /// \param NumParamTypes The number of parameter types in ParamTypes. 632 /// 633 /// \param Variadic Whether this is a variadic function type. 634 /// 635 /// \param Quals The cvr-qualifiers to be applied to the function type. 636 /// 637 /// \param Loc The location of the entity whose type involves this 638 /// function type or, if there is no such entity, the location of the 639 /// type that will have function type. 640 /// 641 /// \param Entity The name of the entity that involves the function 642 /// type, if known. 643 /// 644 /// \returns A suitable function type, if there are no 645 /// errors. Otherwise, returns a NULL type. 646 QualType Sema::BuildFunctionType(QualType T, 647 QualType *ParamTypes, 648 unsigned NumParamTypes, 649 bool Variadic, unsigned Quals, 650 SourceLocation Loc, DeclarationName Entity) { 651 if (T->isArrayType() || T->isFunctionType()) { 652 Diag(Loc, diag::err_func_returning_array_function) << T; 653 return QualType(); 654 } 655 656 bool Invalid = false; 657 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 658 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 659 if (ParamType->isVoidType()) { 660 Diag(Loc, diag::err_param_with_void_type); 661 Invalid = true; 662 } 663 664 ParamTypes[Idx] = ParamType; 665 } 666 667 if (Invalid) 668 return QualType(); 669 670 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 671 Quals); 672 } 673 674 /// \brief Build a member pointer type \c T Class::*. 675 /// 676 /// \param T the type to which the member pointer refers. 677 /// \param Class the class type into which the member pointer points. 678 /// \param Quals Qualifiers applied to the member pointer type 679 /// \param Loc the location where this type begins 680 /// \param Entity the name of the entity that will have this member pointer type 681 /// 682 /// \returns a member pointer type, if successful, or a NULL type if there was 683 /// an error. 684 QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 685 unsigned Quals, SourceLocation Loc, 686 DeclarationName Entity) { 687 // Verify that we're not building a pointer to pointer to function with 688 // exception specification. 689 if (CheckDistantExceptionSpec(T)) { 690 Diag(Loc, diag::err_distant_exception_spec); 691 692 // FIXME: If we're doing this as part of template instantiation, 693 // we should return immediately. 694 695 // Build the type anyway, but use the canonical type so that the 696 // exception specifiers are stripped off. 697 T = Context.getCanonicalType(T); 698 } 699 700 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 701 // with reference type, or "cv void." 702 if (T->isReferenceType()) { 703 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 704 << (Entity? Entity.getAsString() : "type name"); 705 return QualType(); 706 } 707 708 if (T->isVoidType()) { 709 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 710 << (Entity? Entity.getAsString() : "type name"); 711 return QualType(); 712 } 713 714 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 715 // object or incomplete types shall not be restrict-qualified." 716 if ((Quals & QualType::Restrict) && !T->isIncompleteOrObjectType()) { 717 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 718 << T; 719 720 // FIXME: If we're doing this as part of template instantiation, 721 // we should return immediately. 722 Quals &= ~QualType::Restrict; 723 } 724 725 if (!Class->isDependentType() && !Class->isRecordType()) { 726 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 727 return QualType(); 728 } 729 730 return Context.getMemberPointerType(T, Class.getTypePtr()) 731 .getQualifiedType(Quals); 732 } 733 734 /// \brief Build a block pointer type. 735 /// 736 /// \param T The type to which we'll be building a block pointer. 737 /// 738 /// \param Quals The cvr-qualifiers to be applied to the block pointer type. 739 /// 740 /// \param Loc The location of the entity whose type involves this 741 /// block pointer type or, if there is no such entity, the location of the 742 /// type that will have block pointer type. 743 /// 744 /// \param Entity The name of the entity that involves the block pointer 745 /// type, if known. 746 /// 747 /// \returns A suitable block pointer type, if there are no 748 /// errors. Otherwise, returns a NULL type. 749 QualType Sema::BuildBlockPointerType(QualType T, unsigned Quals, 750 SourceLocation Loc, 751 DeclarationName Entity) { 752 if (!T.getTypePtr()->isFunctionType()) { 753 Diag(Loc, diag::err_nonfunction_block_type); 754 return QualType(); 755 } 756 757 return Context.getBlockPointerType(T).getQualifiedType(Quals); 758 } 759 760 /// GetTypeForDeclarator - Convert the type for the specified 761 /// declarator to Type instances. Skip the outermost Skip type 762 /// objects. 763 /// 764 /// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 765 /// owns the declaration of a type (e.g., the definition of a struct 766 /// type), then *OwnedDecl will receive the owned declaration. 767 QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, unsigned Skip, 768 TagDecl **OwnedDecl) { 769 bool OmittedReturnType = false; 770 771 if (D.getContext() == Declarator::BlockLiteralContext 772 && Skip == 0 773 && !D.getDeclSpec().hasTypeSpecifier() 774 && (D.getNumTypeObjects() == 0 775 || (D.getNumTypeObjects() == 1 776 && D.getTypeObject(0).Kind == DeclaratorChunk::Function))) 777 OmittedReturnType = true; 778 779 // long long is a C99 feature. 780 if (!getLangOptions().C99 && !getLangOptions().CPlusPlus0x && 781 D.getDeclSpec().getTypeSpecWidth() == DeclSpec::TSW_longlong) 782 Diag(D.getDeclSpec().getTypeSpecWidthLoc(), diag::ext_longlong); 783 784 // Determine the type of the declarator. Not all forms of declarator 785 // have a type. 786 QualType T; 787 switch (D.getKind()) { 788 case Declarator::DK_Abstract: 789 case Declarator::DK_Normal: 790 case Declarator::DK_Operator: { 791 const DeclSpec &DS = D.getDeclSpec(); 792 if (OmittedReturnType) { 793 // We default to a dependent type initially. Can be modified by 794 // the first return statement. 795 T = Context.DependentTy; 796 } else { 797 bool isInvalid = false; 798 T = ConvertDeclSpecToType(DS, D.getIdentifierLoc(), isInvalid); 799 if (isInvalid) 800 D.setInvalidType(true); 801 else if (OwnedDecl && DS.isTypeSpecOwned()) 802 *OwnedDecl = cast<TagDecl>((Decl *)DS.getTypeRep()); 803 } 804 break; 805 } 806 807 case Declarator::DK_Constructor: 808 case Declarator::DK_Destructor: 809 case Declarator::DK_Conversion: 810 // Constructors and destructors don't have return types. Use 811 // "void" instead. Conversion operators will check their return 812 // types separately. 813 T = Context.VoidTy; 814 break; 815 } 816 817 if (T == Context.UndeducedAutoTy) { 818 int Error = -1; 819 820 switch (D.getContext()) { 821 case Declarator::KNRTypeListContext: 822 assert(0 && "K&R type lists aren't allowed in C++"); 823 break; 824 case Declarator::PrototypeContext: 825 Error = 0; // Function prototype 826 break; 827 case Declarator::MemberContext: 828 switch (cast<TagDecl>(CurContext)->getTagKind()) { 829 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break; 830 case TagDecl::TK_struct: Error = 1; /* Struct member */ break; 831 case TagDecl::TK_union: Error = 2; /* Union member */ break; 832 case TagDecl::TK_class: Error = 3; /* Class member */ break; 833 } 834 break; 835 case Declarator::CXXCatchContext: 836 Error = 4; // Exception declaration 837 break; 838 case Declarator::TemplateParamContext: 839 Error = 5; // Template parameter 840 break; 841 case Declarator::BlockLiteralContext: 842 Error = 6; // Block literal 843 break; 844 case Declarator::FileContext: 845 case Declarator::BlockContext: 846 case Declarator::ForContext: 847 case Declarator::ConditionContext: 848 case Declarator::TypeNameContext: 849 break; 850 } 851 852 if (Error != -1) { 853 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 854 << Error; 855 T = Context.IntTy; 856 D.setInvalidType(true); 857 } 858 } 859 860 // The name we're declaring, if any. 861 DeclarationName Name; 862 if (D.getIdentifier()) 863 Name = D.getIdentifier(); 864 865 // Walk the DeclTypeInfo, building the recursive type as we go. 866 // DeclTypeInfos are ordered from the identifier out, which is 867 // opposite of what we want :). 868 for (unsigned i = Skip, e = D.getNumTypeObjects(); i != e; ++i) { 869 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1+Skip); 870 switch (DeclType.Kind) { 871 default: assert(0 && "Unknown decltype!"); 872 case DeclaratorChunk::BlockPointer: 873 // If blocks are disabled, emit an error. 874 if (!LangOpts.Blocks) 875 Diag(DeclType.Loc, diag::err_blocks_disable); 876 877 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(), 878 Name); 879 break; 880 case DeclaratorChunk::Pointer: 881 // Verify that we're not building a pointer to pointer to function with 882 // exception specification. 883 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 884 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 885 D.setInvalidType(true); 886 // Build the type anyway. 887 } 888 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 889 break; 890 case DeclaratorChunk::Reference: 891 // Verify that we're not building a reference to pointer to function with 892 // exception specification. 893 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 894 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 895 D.setInvalidType(true); 896 // Build the type anyway. 897 } 898 T = BuildReferenceType(T, DeclType.Ref.LValueRef, 899 DeclType.Ref.HasRestrict ? QualType::Restrict : 0, 900 DeclType.Loc, Name); 901 break; 902 case DeclaratorChunk::Array: { 903 // Verify that we're not building an array of pointers to function with 904 // exception specification. 905 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 906 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 907 D.setInvalidType(true); 908 // Build the type anyway. 909 } 910 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 911 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 912 ArrayType::ArraySizeModifier ASM; 913 if (ATI.isStar) 914 ASM = ArrayType::Star; 915 else if (ATI.hasStatic) 916 ASM = ArrayType::Static; 917 else 918 ASM = ArrayType::Normal; 919 if (ASM == ArrayType::Star && 920 D.getContext() != Declarator::PrototypeContext) { 921 // FIXME: This check isn't quite right: it allows star in prototypes 922 // for function definitions, and disallows some edge cases detailed 923 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 924 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 925 ASM = ArrayType::Normal; 926 D.setInvalidType(true); 927 } 928 T = BuildArrayType(T, ASM, ArraySize, ATI.TypeQuals, 929 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 930 break; 931 } 932 case DeclaratorChunk::Function: { 933 // If the function declarator has a prototype (i.e. it is not () and 934 // does not have a K&R-style identifier list), then the arguments are part 935 // of the type, otherwise the argument list is (). 936 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 937 938 // C99 6.7.5.3p1: The return type may not be a function or array type. 939 if (T->isArrayType() || T->isFunctionType()) { 940 Diag(DeclType.Loc, diag::err_func_returning_array_function) << T; 941 T = Context.IntTy; 942 D.setInvalidType(true); 943 } 944 945 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 946 // C++ [dcl.fct]p6: 947 // Types shall not be defined in return or parameter types. 948 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 949 if (Tag->isDefinition()) 950 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 951 << Context.getTypeDeclType(Tag); 952 } 953 954 // Exception specs are not allowed in typedefs. Complain, but add it 955 // anyway. 956 if (FTI.hasExceptionSpec && 957 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 958 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 959 960 if (FTI.NumArgs == 0) { 961 if (getLangOptions().CPlusPlus) { 962 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 963 // function takes no arguments. 964 llvm::SmallVector<QualType, 4> Exceptions; 965 Exceptions.reserve(FTI.NumExceptions); 966 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 967 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 968 // Check that the type is valid for an exception spec, and drop it 969 // if not. 970 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 971 Exceptions.push_back(ET); 972 } 973 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals, 974 FTI.hasExceptionSpec, 975 FTI.hasAnyExceptionSpec, 976 Exceptions.size(), Exceptions.data()); 977 } else if (FTI.isVariadic) { 978 // We allow a zero-parameter variadic function in C if the 979 // function is marked with the "overloadable" 980 // attribute. Scan for this attribute now. 981 bool Overloadable = false; 982 for (const AttributeList *Attrs = D.getAttributes(); 983 Attrs; Attrs = Attrs->getNext()) { 984 if (Attrs->getKind() == AttributeList::AT_overloadable) { 985 Overloadable = true; 986 break; 987 } 988 } 989 990 if (!Overloadable) 991 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 992 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0); 993 } else { 994 // Simple void foo(), where the incoming T is the result type. 995 T = Context.getFunctionNoProtoType(T); 996 } 997 } else if (FTI.ArgInfo[0].Param == 0) { 998 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 999 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1000 } else { 1001 // Otherwise, we have a function with an argument list that is 1002 // potentially variadic. 1003 llvm::SmallVector<QualType, 16> ArgTys; 1004 1005 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1006 ParmVarDecl *Param = 1007 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1008 QualType ArgTy = Param->getType(); 1009 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1010 1011 // Adjust the parameter type. 1012 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1013 1014 // Look for 'void'. void is allowed only as a single argument to a 1015 // function with no other parameters (C99 6.7.5.3p10). We record 1016 // int(void) as a FunctionProtoType with an empty argument list. 1017 if (ArgTy->isVoidType()) { 1018 // If this is something like 'float(int, void)', reject it. 'void' 1019 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1020 // have arguments of incomplete type. 1021 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1022 Diag(DeclType.Loc, diag::err_void_only_param); 1023 ArgTy = Context.IntTy; 1024 Param->setType(ArgTy); 1025 } else if (FTI.ArgInfo[i].Ident) { 1026 // Reject, but continue to parse 'int(void abc)'. 1027 Diag(FTI.ArgInfo[i].IdentLoc, 1028 diag::err_param_with_void_type); 1029 ArgTy = Context.IntTy; 1030 Param->setType(ArgTy); 1031 } else { 1032 // Reject, but continue to parse 'float(const void)'. 1033 if (ArgTy.getCVRQualifiers()) 1034 Diag(DeclType.Loc, diag::err_void_param_qualified); 1035 1036 // Do not add 'void' to the ArgTys list. 1037 break; 1038 } 1039 } else if (!FTI.hasPrototype) { 1040 if (ArgTy->isPromotableIntegerType()) { 1041 ArgTy = Context.IntTy; 1042 } else if (const BuiltinType* BTy = ArgTy->getAsBuiltinType()) { 1043 if (BTy->getKind() == BuiltinType::Float) 1044 ArgTy = Context.DoubleTy; 1045 } 1046 } 1047 1048 ArgTys.push_back(ArgTy); 1049 } 1050 1051 llvm::SmallVector<QualType, 4> Exceptions; 1052 Exceptions.reserve(FTI.NumExceptions); 1053 for(unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1054 QualType ET = QualType::getFromOpaquePtr(FTI.Exceptions[ei].Ty); 1055 // Check that the type is valid for an exception spec, and drop it if 1056 // not. 1057 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1058 Exceptions.push_back(ET); 1059 } 1060 1061 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1062 FTI.isVariadic, FTI.TypeQuals, 1063 FTI.hasExceptionSpec, 1064 FTI.hasAnyExceptionSpec, 1065 Exceptions.size(), Exceptions.data()); 1066 } 1067 break; 1068 } 1069 case DeclaratorChunk::MemberPointer: 1070 // Verify that we're not building a pointer to pointer to function with 1071 // exception specification. 1072 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1073 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1074 D.setInvalidType(true); 1075 // Build the type anyway. 1076 } 1077 // The scope spec must refer to a class, or be dependent. 1078 QualType ClsType; 1079 if (isDependentScopeSpecifier(DeclType.Mem.Scope())) { 1080 NestedNameSpecifier *NNS 1081 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1082 assert(NNS->getAsType() && "Nested-name-specifier must name a type"); 1083 ClsType = QualType(NNS->getAsType(), 0); 1084 } else if (CXXRecordDecl *RD 1085 = dyn_cast_or_null<CXXRecordDecl>( 1086 computeDeclContext(DeclType.Mem.Scope()))) { 1087 ClsType = Context.getTagDeclType(RD); 1088 } else { 1089 Diag(DeclType.Mem.Scope().getBeginLoc(), 1090 diag::err_illegal_decl_mempointer_in_nonclass) 1091 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1092 << DeclType.Mem.Scope().getRange(); 1093 D.setInvalidType(true); 1094 } 1095 1096 if (!ClsType.isNull()) 1097 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals, 1098 DeclType.Loc, D.getIdentifier()); 1099 if (T.isNull()) { 1100 T = Context.IntTy; 1101 D.setInvalidType(true); 1102 } 1103 break; 1104 } 1105 1106 if (T.isNull()) { 1107 D.setInvalidType(true); 1108 T = Context.IntTy; 1109 } 1110 1111 // See if there are any attributes on this declarator chunk. 1112 if (const AttributeList *AL = DeclType.getAttrs()) 1113 ProcessTypeAttributeList(T, AL); 1114 } 1115 1116 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1117 const FunctionProtoType *FnTy = T->getAsFunctionProtoType(); 1118 assert(FnTy && "Why oh why is there not a FunctionProtoType here ?"); 1119 1120 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1121 // for a nonstatic member function, the function type to which a pointer 1122 // to member refers, or the top-level function type of a function typedef 1123 // declaration. 1124 if (FnTy->getTypeQuals() != 0 && 1125 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1126 ((D.getContext() != Declarator::MemberContext && 1127 (!D.getCXXScopeSpec().isSet() || 1128 !computeDeclContext(D.getCXXScopeSpec())->isRecord())) || 1129 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1130 if (D.isFunctionDeclarator()) 1131 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1132 else 1133 Diag(D.getIdentifierLoc(), 1134 diag::err_invalid_qualified_typedef_function_type_use); 1135 1136 // Strip the cv-quals from the type. 1137 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1138 FnTy->getNumArgs(), FnTy->isVariadic(), 0); 1139 } 1140 } 1141 1142 // If there were any type attributes applied to the decl itself (not the 1143 // type, apply the type attribute to the type!) 1144 if (const AttributeList *Attrs = D.getAttributes()) 1145 ProcessTypeAttributeList(T, Attrs); 1146 1147 return T; 1148 } 1149 1150 /// CheckSpecifiedExceptionType - Check if the given type is valid in an 1151 /// exception specification. Incomplete types, or pointers to incomplete types 1152 /// other than void are not allowed. 1153 bool Sema::CheckSpecifiedExceptionType(QualType T, const SourceRange &Range) { 1154 // FIXME: This may not correctly work with the fix for core issue 437, 1155 // where a class's own type is considered complete within its body. 1156 1157 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1158 // an incomplete type. 1159 if (T->isIncompleteType()) 1160 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1161 << Range << T << /*direct*/0; 1162 1163 // C++ 15.4p2: A type denoted in an exception-specification shall not denote 1164 // an incomplete type a pointer or reference to an incomplete type, other 1165 // than (cv) void*. 1166 int kind; 1167 if (const PointerType* IT = T->getAsPointerType()) { 1168 T = IT->getPointeeType(); 1169 kind = 1; 1170 } else if (const ReferenceType* IT = T->getAsReferenceType()) { 1171 T = IT->getPointeeType(); 1172 kind = 2; 1173 } else 1174 return false; 1175 1176 if (T->isIncompleteType() && !T->isVoidType()) 1177 return Diag(Range.getBegin(), diag::err_incomplete_in_exception_spec) 1178 << Range << T << /*indirect*/kind; 1179 1180 return false; 1181 } 1182 1183 /// CheckDistantExceptionSpec - Check if the given type is a pointer or pointer 1184 /// to member to a function with an exception specification. This means that 1185 /// it is invalid to add another level of indirection. 1186 bool Sema::CheckDistantExceptionSpec(QualType T) { 1187 if (const PointerType *PT = T->getAsPointerType()) 1188 T = PT->getPointeeType(); 1189 else if (const MemberPointerType *PT = T->getAsMemberPointerType()) 1190 T = PT->getPointeeType(); 1191 else 1192 return false; 1193 1194 const FunctionProtoType *FnT = T->getAsFunctionProtoType(); 1195 if (!FnT) 1196 return false; 1197 1198 return FnT->hasExceptionSpec(); 1199 } 1200 1201 /// CheckEquivalentExceptionSpec - Check if the two types have equivalent 1202 /// exception specifications. Exception specifications are equivalent if 1203 /// they allow exactly the same set of exception types. It does not matter how 1204 /// that is achieved. See C++ [except.spec]p2. 1205 bool Sema::CheckEquivalentExceptionSpec( 1206 const FunctionProtoType *Old, SourceLocation OldLoc, 1207 const FunctionProtoType *New, SourceLocation NewLoc) { 1208 bool OldAny = !Old->hasExceptionSpec() || Old->hasAnyExceptionSpec(); 1209 bool NewAny = !New->hasExceptionSpec() || New->hasAnyExceptionSpec(); 1210 if (OldAny && NewAny) 1211 return false; 1212 if (OldAny || NewAny) { 1213 Diag(NewLoc, diag::err_mismatched_exception_spec); 1214 Diag(OldLoc, diag::note_previous_declaration); 1215 return true; 1216 } 1217 1218 bool Success = true; 1219 // Both have a definite exception spec. Collect the first set, then compare 1220 // to the second. 1221 llvm::SmallPtrSet<const Type*, 8> Types; 1222 for (FunctionProtoType::exception_iterator I = Old->exception_begin(), 1223 E = Old->exception_end(); I != E; ++I) 1224 Types.insert(Context.getCanonicalType(*I).getTypePtr()); 1225 1226 for (FunctionProtoType::exception_iterator I = New->exception_begin(), 1227 E = New->exception_end(); I != E && Success; ++I) 1228 Success = Types.erase(Context.getCanonicalType(*I).getTypePtr()); 1229 1230 Success = Success && Types.empty(); 1231 1232 if (Success) { 1233 return false; 1234 } 1235 Diag(NewLoc, diag::err_mismatched_exception_spec); 1236 Diag(OldLoc, diag::note_previous_declaration); 1237 return true; 1238 } 1239 1240 /// ObjCGetTypeForMethodDefinition - Builds the type for a method definition 1241 /// declarator 1242 QualType Sema::ObjCGetTypeForMethodDefinition(DeclPtrTy D) { 1243 ObjCMethodDecl *MDecl = cast<ObjCMethodDecl>(D.getAs<Decl>()); 1244 QualType T = MDecl->getResultType(); 1245 llvm::SmallVector<QualType, 16> ArgTys; 1246 1247 // Add the first two invisible argument types for self and _cmd. 1248 if (MDecl->isInstanceMethod()) { 1249 QualType selfTy = Context.getObjCInterfaceType(MDecl->getClassInterface()); 1250 selfTy = Context.getPointerType(selfTy); 1251 ArgTys.push_back(selfTy); 1252 } else 1253 ArgTys.push_back(Context.getObjCIdType()); 1254 ArgTys.push_back(Context.getObjCSelType()); 1255 1256 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(), 1257 E = MDecl->param_end(); PI != E; ++PI) { 1258 QualType ArgTy = (*PI)->getType(); 1259 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1260 ArgTy = adjustParameterType(ArgTy); 1261 ArgTys.push_back(ArgTy); 1262 } 1263 T = Context.getFunctionType(T, &ArgTys[0], ArgTys.size(), 1264 MDecl->isVariadic(), 0); 1265 return T; 1266 } 1267 1268 /// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 1269 /// may be similar (C++ 4.4), replaces T1 and T2 with the type that 1270 /// they point to and return true. If T1 and T2 aren't pointer types 1271 /// or pointer-to-member types, or if they are not similar at this 1272 /// level, returns false and leaves T1 and T2 unchanged. Top-level 1273 /// qualifiers on T1 and T2 are ignored. This function will typically 1274 /// be called in a loop that successively "unwraps" pointer and 1275 /// pointer-to-member types to compare them at each level. 1276 bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 1277 const PointerType *T1PtrType = T1->getAsPointerType(), 1278 *T2PtrType = T2->getAsPointerType(); 1279 if (T1PtrType && T2PtrType) { 1280 T1 = T1PtrType->getPointeeType(); 1281 T2 = T2PtrType->getPointeeType(); 1282 return true; 1283 } 1284 1285 const MemberPointerType *T1MPType = T1->getAsMemberPointerType(), 1286 *T2MPType = T2->getAsMemberPointerType(); 1287 if (T1MPType && T2MPType && 1288 Context.getCanonicalType(T1MPType->getClass()) == 1289 Context.getCanonicalType(T2MPType->getClass())) { 1290 T1 = T1MPType->getPointeeType(); 1291 T2 = T2MPType->getPointeeType(); 1292 return true; 1293 } 1294 return false; 1295 } 1296 1297 Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1298 // C99 6.7.6: Type names have no identifier. This is already validated by 1299 // the parser. 1300 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1301 1302 TagDecl *OwnedTag = 0; 1303 QualType T = GetTypeForDeclarator(D, S, /*Skip=*/0, &OwnedTag); 1304 if (D.isInvalidType()) 1305 return true; 1306 1307 if (getLangOptions().CPlusPlus) { 1308 // Check that there are no default arguments (C++ only). 1309 CheckExtraCXXDefaultArguments(D); 1310 1311 // C++0x [dcl.type]p3: 1312 // A type-specifier-seq shall not define a class or enumeration 1313 // unless it appears in the type-id of an alias-declaration 1314 // (7.1.3). 1315 if (OwnedTag && OwnedTag->isDefinition()) 1316 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1317 << Context.getTypeDeclType(OwnedTag); 1318 } 1319 1320 return T.getAsOpaquePtr(); 1321 } 1322 1323 1324 1325 //===----------------------------------------------------------------------===// 1326 // Type Attribute Processing 1327 //===----------------------------------------------------------------------===// 1328 1329 /// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1330 /// specified type. The attribute contains 1 argument, the id of the address 1331 /// space for the type. 1332 static void HandleAddressSpaceTypeAttribute(QualType &Type, 1333 const AttributeList &Attr, Sema &S){ 1334 // If this type is already address space qualified, reject it. 1335 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1336 // for two or more different address spaces." 1337 if (Type.getAddressSpace()) { 1338 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1339 return; 1340 } 1341 1342 // Check the attribute arguments. 1343 if (Attr.getNumArgs() != 1) { 1344 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1345 return; 1346 } 1347 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1348 llvm::APSInt addrSpace(32); 1349 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1350 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1351 << ASArgExpr->getSourceRange(); 1352 return; 1353 } 1354 1355 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1356 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1357 } 1358 1359 /// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1360 /// specified type. The attribute contains 1 argument, weak or strong. 1361 static void HandleObjCGCTypeAttribute(QualType &Type, 1362 const AttributeList &Attr, Sema &S) { 1363 if (Type.getObjCGCAttr() != QualType::GCNone) { 1364 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1365 return; 1366 } 1367 1368 // Check the attribute arguments. 1369 if (!Attr.getParameterName()) { 1370 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1371 << "objc_gc" << 1; 1372 return; 1373 } 1374 QualType::GCAttrTypes GCAttr; 1375 if (Attr.getNumArgs() != 0) { 1376 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1377 return; 1378 } 1379 if (Attr.getParameterName()->isStr("weak")) 1380 GCAttr = QualType::Weak; 1381 else if (Attr.getParameterName()->isStr("strong")) 1382 GCAttr = QualType::Strong; 1383 else { 1384 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1385 << "objc_gc" << Attr.getParameterName(); 1386 return; 1387 } 1388 1389 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1390 } 1391 1392 void Sema::ProcessTypeAttributeList(QualType &Result, const AttributeList *AL) { 1393 // Scan through and apply attributes to this type where it makes sense. Some 1394 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1395 // type, but others can be present in the type specifiers even though they 1396 // apply to the decl. Here we apply type attributes and ignore the rest. 1397 for (; AL; AL = AL->getNext()) { 1398 // If this is an attribute we can handle, do so now, otherwise, add it to 1399 // the LeftOverAttrs list for rechaining. 1400 switch (AL->getKind()) { 1401 default: break; 1402 case AttributeList::AT_address_space: 1403 HandleAddressSpaceTypeAttribute(Result, *AL, *this); 1404 break; 1405 case AttributeList::AT_objc_gc: 1406 HandleObjCGCTypeAttribute(Result, *AL, *this); 1407 break; 1408 } 1409 } 1410 } 1411 1412 /// @brief Ensure that the type T is a complete type. 1413 /// 1414 /// This routine checks whether the type @p T is complete in any 1415 /// context where a complete type is required. If @p T is a complete 1416 /// type, returns false. If @p T is a class template specialization, 1417 /// this routine then attempts to perform class template 1418 /// instantiation. If instantiation fails, or if @p T is incomplete 1419 /// and cannot be completed, issues the diagnostic @p diag (giving it 1420 /// the type @p T) and returns true. 1421 /// 1422 /// @param Loc The location in the source that the incomplete type 1423 /// diagnostic should refer to. 1424 /// 1425 /// @param T The type that this routine is examining for completeness. 1426 /// 1427 /// @param diag The diagnostic value (e.g., 1428 /// @c diag::err_typecheck_decl_incomplete_type) that will be used 1429 /// for the error message if @p T is incomplete. 1430 /// 1431 /// @param Range1 An optional range in the source code that will be a 1432 /// part of the "incomplete type" error message. 1433 /// 1434 /// @param Range2 An optional range in the source code that will be a 1435 /// part of the "incomplete type" error message. 1436 /// 1437 /// @param PrintType If non-NULL, the type that should be printed 1438 /// instead of @p T. This parameter should be used when the type that 1439 /// we're checking for incompleteness isn't the type that should be 1440 /// displayed to the user, e.g., when T is a type and PrintType is a 1441 /// pointer to T. 1442 /// 1443 /// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1444 /// @c false otherwise. 1445 bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, unsigned diag, 1446 SourceRange Range1, SourceRange Range2, 1447 QualType PrintType) { 1448 // FIXME: Add this assertion to help us flush out problems with 1449 // checking for dependent types and type-dependent expressions. 1450 // 1451 // assert(!T->isDependentType() && 1452 // "Can't ask whether a dependent type is complete"); 1453 1454 // If we have a complete type, we're done. 1455 if (!T->isIncompleteType()) 1456 return false; 1457 1458 // If we have a class template specialization or a class member of a 1459 // class template specialization, try to instantiate it. 1460 if (const RecordType *Record = T->getAsRecordType()) { 1461 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 1462 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 1463 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) { 1464 // Update the class template specialization's location to 1465 // refer to the point of instantiation. 1466 if (Loc.isValid()) 1467 ClassTemplateSpec->setLocation(Loc); 1468 return InstantiateClassTemplateSpecialization(ClassTemplateSpec, 1469 /*ExplicitInstantiation=*/false); 1470 } 1471 } else if (CXXRecordDecl *Rec 1472 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 1473 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 1474 // Find the class template specialization that surrounds this 1475 // member class. 1476 ClassTemplateSpecializationDecl *Spec = 0; 1477 for (DeclContext *Parent = Rec->getDeclContext(); 1478 Parent && !Spec; Parent = Parent->getParent()) 1479 Spec = dyn_cast<ClassTemplateSpecializationDecl>(Parent); 1480 assert(Spec && "Not a member of a class template specialization?"); 1481 return InstantiateClass(Loc, Rec, Pattern, Spec->getTemplateArgs(), 1482 /*ExplicitInstantiation=*/false); 1483 } 1484 } 1485 } 1486 1487 if (PrintType.isNull()) 1488 PrintType = T; 1489 1490 // We have an incomplete type. Produce a diagnostic. 1491 Diag(Loc, diag) << PrintType << Range1 << Range2; 1492 1493 // If the type was a forward declaration of a class/struct/union 1494 // type, produce 1495 const TagType *Tag = 0; 1496 if (const RecordType *Record = T->getAsRecordType()) 1497 Tag = Record; 1498 else if (const EnumType *Enum = T->getAsEnumType()) 1499 Tag = Enum; 1500 1501 if (Tag && !Tag->getDecl()->isInvalidDecl()) 1502 Diag(Tag->getDecl()->getLocation(), 1503 Tag->isBeingDefined() ? diag::note_type_being_defined 1504 : diag::note_forward_declaration) 1505 << QualType(Tag, 0); 1506 1507 return true; 1508 } 1509 1510 /// \brief Retrieve a version of the type 'T' that is qualified by the 1511 /// nested-name-specifier contained in SS. 1512 QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { 1513 if (!SS.isSet() || SS.isInvalid() || T.isNull()) 1514 return T; 1515 1516 NestedNameSpecifier *NNS 1517 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1518 return Context.getQualifiedNameType(NNS, T); 1519 } 1520 1521 QualType Sema::BuildTypeofExprType(Expr *E) { 1522 return Context.getTypeOfExprType(E); 1523 } 1524 1525 QualType Sema::BuildDecltypeType(Expr *E) { 1526 if (E->getType() == Context.OverloadTy) { 1527 Diag(E->getLocStart(), 1528 diag::err_cannot_determine_declared_type_of_overloaded_function); 1529 return QualType(); 1530 } 1531 return Context.getDecltypeType(E); 1532 } 1533