SemaType.cpp revision 8072597e1d95bcd34bf81697f2eeff70c1a54909
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/CXXInheritance.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/TypeLocVisitor.h" 21#include "clang/AST/Expr.h" 22#include "clang/Basic/PartialDiagnostic.h" 23#include "clang/Parse/DeclSpec.h" 24#include "llvm/ADT/SmallPtrSet.h" 25#include "llvm/Support/ErrorHandling.h" 26using namespace clang; 27 28/// \brief Perform adjustment on the parameter type of a function. 29/// 30/// This routine adjusts the given parameter type @p T to the actual 31/// parameter type used by semantic analysis (C99 6.7.5.3p[7,8], 32/// C++ [dcl.fct]p3). The adjusted parameter type is returned. 33QualType Sema::adjustParameterType(QualType T) { 34 // C99 6.7.5.3p7: 35 // A declaration of a parameter as "array of type" shall be 36 // adjusted to "qualified pointer to type", where the type 37 // qualifiers (if any) are those specified within the [ and ] of 38 // the array type derivation. 39 if (T->isArrayType()) 40 return Context.getArrayDecayedType(T); 41 42 // C99 6.7.5.3p8: 43 // A declaration of a parameter as "function returning type" 44 // shall be adjusted to "pointer to function returning type", as 45 // in 6.3.2.1. 46 if (T->isFunctionType()) 47 return Context.getPointerType(T); 48 49 return T; 50} 51 52 53 54/// isOmittedBlockReturnType - Return true if this declarator is missing a 55/// return type because this is a omitted return type on a block literal. 56static bool isOmittedBlockReturnType(const Declarator &D) { 57 if (D.getContext() != Declarator::BlockLiteralContext || 58 D.getDeclSpec().hasTypeSpecifier()) 59 return false; 60 61 if (D.getNumTypeObjects() == 0) 62 return true; // ^{ ... } 63 64 if (D.getNumTypeObjects() == 1 && 65 D.getTypeObject(0).Kind == DeclaratorChunk::Function) 66 return true; // ^(int X, float Y) { ... } 67 68 return false; 69} 70 71typedef std::pair<const AttributeList*,QualType> DelayedAttribute; 72typedef llvm::SmallVectorImpl<DelayedAttribute> DelayedAttributeSet; 73 74static void ProcessTypeAttributeList(Sema &S, QualType &Type, 75 bool IsDeclSpec, 76 const AttributeList *Attrs, 77 DelayedAttributeSet &DelayedFnAttrs); 78static bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr); 79 80static void ProcessDelayedFnAttrs(Sema &S, QualType &Type, 81 DelayedAttributeSet &Attrs) { 82 for (DelayedAttributeSet::iterator I = Attrs.begin(), 83 E = Attrs.end(); I != E; ++I) 84 if (ProcessFnAttr(S, Type, *I->first)) 85 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type) 86 << I->first->getName() << I->second; 87 Attrs.clear(); 88} 89 90static void DiagnoseDelayedFnAttrs(Sema &S, DelayedAttributeSet &Attrs) { 91 for (DelayedAttributeSet::iterator I = Attrs.begin(), 92 E = Attrs.end(); I != E; ++I) { 93 S.Diag(I->first->getLoc(), diag::warn_function_attribute_wrong_type) 94 << I->first->getName() << I->second; 95 } 96 Attrs.clear(); 97} 98 99/// \brief Convert the specified declspec to the appropriate type 100/// object. 101/// \param D the declarator containing the declaration specifier. 102/// \returns The type described by the declaration specifiers. This function 103/// never returns null. 104static QualType ConvertDeclSpecToType(Sema &TheSema, 105 Declarator &TheDeclarator, 106 DelayedAttributeSet &Delayed) { 107 // FIXME: Should move the logic from DeclSpec::Finish to here for validity 108 // checking. 109 const DeclSpec &DS = TheDeclarator.getDeclSpec(); 110 SourceLocation DeclLoc = TheDeclarator.getIdentifierLoc(); 111 if (DeclLoc.isInvalid()) 112 DeclLoc = DS.getSourceRange().getBegin(); 113 114 ASTContext &Context = TheSema.Context; 115 116 QualType Result; 117 switch (DS.getTypeSpecType()) { 118 case DeclSpec::TST_void: 119 Result = Context.VoidTy; 120 break; 121 case DeclSpec::TST_char: 122 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 123 Result = Context.CharTy; 124 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) 125 Result = Context.SignedCharTy; 126 else { 127 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 128 "Unknown TSS value"); 129 Result = Context.UnsignedCharTy; 130 } 131 break; 132 case DeclSpec::TST_wchar: 133 if (DS.getTypeSpecSign() == DeclSpec::TSS_unspecified) 134 Result = Context.WCharTy; 135 else if (DS.getTypeSpecSign() == DeclSpec::TSS_signed) { 136 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 137 << DS.getSpecifierName(DS.getTypeSpecType()); 138 Result = Context.getSignedWCharType(); 139 } else { 140 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unsigned && 141 "Unknown TSS value"); 142 TheSema.Diag(DS.getTypeSpecSignLoc(), diag::ext_invalid_sign_spec) 143 << DS.getSpecifierName(DS.getTypeSpecType()); 144 Result = Context.getUnsignedWCharType(); 145 } 146 break; 147 case DeclSpec::TST_char16: 148 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 149 "Unknown TSS value"); 150 Result = Context.Char16Ty; 151 break; 152 case DeclSpec::TST_char32: 153 assert(DS.getTypeSpecSign() == DeclSpec::TSS_unspecified && 154 "Unknown TSS value"); 155 Result = Context.Char32Ty; 156 break; 157 case DeclSpec::TST_unspecified: 158 // "<proto1,proto2>" is an objc qualified ID with a missing id. 159 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 160 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy, 161 (ObjCProtocolDecl**)PQ, 162 DS.getNumProtocolQualifiers()); 163 break; 164 } 165 166 // If this is a missing declspec in a block literal return context, then it 167 // is inferred from the return statements inside the block. 168 if (isOmittedBlockReturnType(TheDeclarator)) { 169 Result = Context.DependentTy; 170 break; 171 } 172 173 // Unspecified typespec defaults to int in C90. However, the C90 grammar 174 // [C90 6.5] only allows a decl-spec if there was *some* type-specifier, 175 // type-qualifier, or storage-class-specifier. If not, emit an extwarn. 176 // Note that the one exception to this is function definitions, which are 177 // allowed to be completely missing a declspec. This is handled in the 178 // parser already though by it pretending to have seen an 'int' in this 179 // case. 180 if (TheSema.getLangOptions().ImplicitInt) { 181 // In C89 mode, we only warn if there is a completely missing declspec 182 // when one is not allowed. 183 if (DS.isEmpty()) { 184 TheSema.Diag(DeclLoc, diag::ext_missing_declspec) 185 << DS.getSourceRange() 186 << CodeModificationHint::CreateInsertion(DS.getSourceRange().getBegin(), 187 "int"); 188 } 189 } else if (!DS.hasTypeSpecifier()) { 190 // C99 and C++ require a type specifier. For example, C99 6.7.2p2 says: 191 // "At least one type specifier shall be given in the declaration 192 // specifiers in each declaration, and in the specifier-qualifier list in 193 // each struct declaration and type name." 194 // FIXME: Does Microsoft really have the implicit int extension in C++? 195 if (TheSema.getLangOptions().CPlusPlus && 196 !TheSema.getLangOptions().Microsoft) { 197 TheSema.Diag(DeclLoc, diag::err_missing_type_specifier) 198 << DS.getSourceRange(); 199 200 // When this occurs in C++ code, often something is very broken with the 201 // value being declared, poison it as invalid so we don't get chains of 202 // errors. 203 TheDeclarator.setInvalidType(true); 204 } else { 205 TheSema.Diag(DeclLoc, diag::ext_missing_type_specifier) 206 << DS.getSourceRange(); 207 } 208 } 209 210 // FALL THROUGH. 211 case DeclSpec::TST_int: { 212 if (DS.getTypeSpecSign() != DeclSpec::TSS_unsigned) { 213 switch (DS.getTypeSpecWidth()) { 214 case DeclSpec::TSW_unspecified: Result = Context.IntTy; break; 215 case DeclSpec::TSW_short: Result = Context.ShortTy; break; 216 case DeclSpec::TSW_long: Result = Context.LongTy; break; 217 case DeclSpec::TSW_longlong: 218 Result = Context.LongLongTy; 219 220 // long long is a C99 feature. 221 if (!TheSema.getLangOptions().C99 && 222 !TheSema.getLangOptions().CPlusPlus0x) 223 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 224 break; 225 } 226 } else { 227 switch (DS.getTypeSpecWidth()) { 228 case DeclSpec::TSW_unspecified: Result = Context.UnsignedIntTy; break; 229 case DeclSpec::TSW_short: Result = Context.UnsignedShortTy; break; 230 case DeclSpec::TSW_long: Result = Context.UnsignedLongTy; break; 231 case DeclSpec::TSW_longlong: 232 Result = Context.UnsignedLongLongTy; 233 234 // long long is a C99 feature. 235 if (!TheSema.getLangOptions().C99 && 236 !TheSema.getLangOptions().CPlusPlus0x) 237 TheSema.Diag(DS.getTypeSpecWidthLoc(), diag::ext_longlong); 238 break; 239 } 240 } 241 break; 242 } 243 case DeclSpec::TST_float: Result = Context.FloatTy; break; 244 case DeclSpec::TST_double: 245 if (DS.getTypeSpecWidth() == DeclSpec::TSW_long) 246 Result = Context.LongDoubleTy; 247 else 248 Result = Context.DoubleTy; 249 break; 250 case DeclSpec::TST_bool: Result = Context.BoolTy; break; // _Bool or bool 251 case DeclSpec::TST_decimal32: // _Decimal32 252 case DeclSpec::TST_decimal64: // _Decimal64 253 case DeclSpec::TST_decimal128: // _Decimal128 254 TheSema.Diag(DS.getTypeSpecTypeLoc(), diag::err_decimal_unsupported); 255 Result = Context.IntTy; 256 TheDeclarator.setInvalidType(true); 257 break; 258 case DeclSpec::TST_class: 259 case DeclSpec::TST_enum: 260 case DeclSpec::TST_union: 261 case DeclSpec::TST_struct: { 262 TypeDecl *D 263 = dyn_cast_or_null<TypeDecl>(static_cast<Decl *>(DS.getTypeRep())); 264 if (!D) { 265 // This can happen in C++ with ambiguous lookups. 266 Result = Context.IntTy; 267 TheDeclarator.setInvalidType(true); 268 break; 269 } 270 271 // If the type is deprecated or unavailable, diagnose it. 272 TheSema.DiagnoseUseOfDecl(D, DS.getTypeSpecTypeLoc()); 273 274 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 275 DS.getTypeSpecSign() == 0 && "No qualifiers on tag names!"); 276 277 // TypeQuals handled by caller. 278 Result = Context.getTypeDeclType(D); 279 280 // In C++, make an ElaboratedType. 281 if (TheSema.getLangOptions().CPlusPlus) { 282 TagDecl::TagKind Tag 283 = TagDecl::getTagKindForTypeSpec(DS.getTypeSpecType()); 284 Result = Context.getElaboratedType(Result, Tag); 285 } 286 287 if (D->isInvalidDecl()) 288 TheDeclarator.setInvalidType(true); 289 break; 290 } 291 case DeclSpec::TST_typename: { 292 assert(DS.getTypeSpecWidth() == 0 && DS.getTypeSpecComplex() == 0 && 293 DS.getTypeSpecSign() == 0 && 294 "Can't handle qualifiers on typedef names yet!"); 295 Result = TheSema.GetTypeFromParser(DS.getTypeRep()); 296 297 if (DeclSpec::ProtocolQualifierListTy PQ = DS.getProtocolQualifiers()) { 298 if (const ObjCInterfaceType * 299 Interface = Result->getAs<ObjCInterfaceType>()) { 300 // It would be nice if protocol qualifiers were only stored with the 301 // ObjCObjectPointerType. Unfortunately, this isn't possible due 302 // to the following typedef idiom (which is uncommon, but allowed): 303 // 304 // typedef Foo<P> T; 305 // static void func() { 306 // Foo<P> *yy; 307 // T *zz; 308 // } 309 Result = Context.getObjCInterfaceType(Interface->getDecl(), 310 (ObjCProtocolDecl**)PQ, 311 DS.getNumProtocolQualifiers()); 312 } else if (Result->isObjCIdType()) 313 // id<protocol-list> 314 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy, 315 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); 316 else if (Result->isObjCClassType()) { 317 // Class<protocol-list> 318 Result = Context.getObjCObjectPointerType(Context.ObjCBuiltinClassTy, 319 (ObjCProtocolDecl**)PQ, DS.getNumProtocolQualifiers()); 320 } else { 321 TheSema.Diag(DeclLoc, diag::err_invalid_protocol_qualifiers) 322 << DS.getSourceRange(); 323 TheDeclarator.setInvalidType(true); 324 } 325 } 326 327 // TypeQuals handled by caller. 328 break; 329 } 330 case DeclSpec::TST_typeofType: 331 // FIXME: Preserve type source info. 332 Result = TheSema.GetTypeFromParser(DS.getTypeRep()); 333 assert(!Result.isNull() && "Didn't get a type for typeof?"); 334 // TypeQuals handled by caller. 335 Result = Context.getTypeOfType(Result); 336 break; 337 case DeclSpec::TST_typeofExpr: { 338 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 339 assert(E && "Didn't get an expression for typeof?"); 340 // TypeQuals handled by caller. 341 Result = TheSema.BuildTypeofExprType(E); 342 if (Result.isNull()) { 343 Result = Context.IntTy; 344 TheDeclarator.setInvalidType(true); 345 } 346 break; 347 } 348 case DeclSpec::TST_decltype: { 349 Expr *E = static_cast<Expr *>(DS.getTypeRep()); 350 assert(E && "Didn't get an expression for decltype?"); 351 // TypeQuals handled by caller. 352 Result = TheSema.BuildDecltypeType(E); 353 if (Result.isNull()) { 354 Result = Context.IntTy; 355 TheDeclarator.setInvalidType(true); 356 } 357 break; 358 } 359 case DeclSpec::TST_auto: { 360 // TypeQuals handled by caller. 361 Result = Context.UndeducedAutoTy; 362 break; 363 } 364 365 case DeclSpec::TST_error: 366 Result = Context.IntTy; 367 TheDeclarator.setInvalidType(true); 368 break; 369 } 370 371 // Handle complex types. 372 if (DS.getTypeSpecComplex() == DeclSpec::TSC_complex) { 373 if (TheSema.getLangOptions().Freestanding) 374 TheSema.Diag(DS.getTypeSpecComplexLoc(), diag::ext_freestanding_complex); 375 Result = Context.getComplexType(Result); 376 } else if (DS.isTypeAltiVecVector()) { 377 unsigned typeSize = static_cast<unsigned>(Context.getTypeSize(Result)); 378 assert(typeSize > 0 && "type size for vector must be greater than 0 bits"); 379 Result = Context.getVectorType(Result, 128/typeSize, true, 380 DS.isTypeAltiVecPixel()); 381 } 382 383 assert(DS.getTypeSpecComplex() != DeclSpec::TSC_imaginary && 384 "FIXME: imaginary types not supported yet!"); 385 386 // See if there are any attributes on the declspec that apply to the type (as 387 // opposed to the decl). 388 if (const AttributeList *AL = DS.getAttributes()) 389 ProcessTypeAttributeList(TheSema, Result, true, AL, Delayed); 390 391 // Apply const/volatile/restrict qualifiers to T. 392 if (unsigned TypeQuals = DS.getTypeQualifiers()) { 393 394 // Enforce C99 6.7.3p2: "Types other than pointer types derived from object 395 // or incomplete types shall not be restrict-qualified." C++ also allows 396 // restrict-qualified references. 397 if (TypeQuals & DeclSpec::TQ_restrict) { 398 if (Result->isAnyPointerType() || Result->isReferenceType()) { 399 QualType EltTy; 400 if (Result->isObjCObjectPointerType()) 401 EltTy = Result; 402 else 403 EltTy = Result->isPointerType() ? 404 Result->getAs<PointerType>()->getPointeeType() : 405 Result->getAs<ReferenceType>()->getPointeeType(); 406 407 // If we have a pointer or reference, the pointee must have an object 408 // incomplete type. 409 if (!EltTy->isIncompleteOrObjectType()) { 410 TheSema.Diag(DS.getRestrictSpecLoc(), 411 diag::err_typecheck_invalid_restrict_invalid_pointee) 412 << EltTy << DS.getSourceRange(); 413 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 414 } 415 } else { 416 TheSema.Diag(DS.getRestrictSpecLoc(), 417 diag::err_typecheck_invalid_restrict_not_pointer) 418 << Result << DS.getSourceRange(); 419 TypeQuals &= ~DeclSpec::TQ_restrict; // Remove the restrict qualifier. 420 } 421 } 422 423 // Warn about CV qualifiers on functions: C99 6.7.3p8: "If the specification 424 // of a function type includes any type qualifiers, the behavior is 425 // undefined." 426 if (Result->isFunctionType() && TypeQuals) { 427 // Get some location to point at, either the C or V location. 428 SourceLocation Loc; 429 if (TypeQuals & DeclSpec::TQ_const) 430 Loc = DS.getConstSpecLoc(); 431 else if (TypeQuals & DeclSpec::TQ_volatile) 432 Loc = DS.getVolatileSpecLoc(); 433 else { 434 assert((TypeQuals & DeclSpec::TQ_restrict) && 435 "Has CVR quals but not C, V, or R?"); 436 Loc = DS.getRestrictSpecLoc(); 437 } 438 TheSema.Diag(Loc, diag::warn_typecheck_function_qualifiers) 439 << Result << DS.getSourceRange(); 440 } 441 442 // C++ [dcl.ref]p1: 443 // Cv-qualified references are ill-formed except when the 444 // cv-qualifiers are introduced through the use of a typedef 445 // (7.1.3) or of a template type argument (14.3), in which 446 // case the cv-qualifiers are ignored. 447 // FIXME: Shouldn't we be checking SCS_typedef here? 448 if (DS.getTypeSpecType() == DeclSpec::TST_typename && 449 TypeQuals && Result->isReferenceType()) { 450 TypeQuals &= ~DeclSpec::TQ_const; 451 TypeQuals &= ~DeclSpec::TQ_volatile; 452 } 453 454 Qualifiers Quals = Qualifiers::fromCVRMask(TypeQuals); 455 Result = Context.getQualifiedType(Result, Quals); 456 } 457 458 return Result; 459} 460 461static std::string getPrintableNameForEntity(DeclarationName Entity) { 462 if (Entity) 463 return Entity.getAsString(); 464 465 return "type name"; 466} 467 468/// \brief Build a pointer type. 469/// 470/// \param T The type to which we'll be building a pointer. 471/// 472/// \param Quals The cvr-qualifiers to be applied to the pointer type. 473/// 474/// \param Loc The location of the entity whose type involves this 475/// pointer type or, if there is no such entity, the location of the 476/// type that will have pointer type. 477/// 478/// \param Entity The name of the entity that involves the pointer 479/// type, if known. 480/// 481/// \returns A suitable pointer type, if there are no 482/// errors. Otherwise, returns a NULL type. 483QualType Sema::BuildPointerType(QualType T, unsigned Quals, 484 SourceLocation Loc, DeclarationName Entity) { 485 if (T->isReferenceType()) { 486 // C++ 8.3.2p4: There shall be no ... pointers to references ... 487 Diag(Loc, diag::err_illegal_decl_pointer_to_reference) 488 << getPrintableNameForEntity(Entity) << T; 489 return QualType(); 490 } 491 492 Qualifiers Qs = Qualifiers::fromCVRMask(Quals); 493 494 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 495 // object or incomplete types shall not be restrict-qualified." 496 if (Qs.hasRestrict() && !T->isIncompleteOrObjectType()) { 497 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 498 << T; 499 Qs.removeRestrict(); 500 } 501 502 // Build the pointer type. 503 return Context.getQualifiedType(Context.getPointerType(T), Qs); 504} 505 506/// \brief Build a reference type. 507/// 508/// \param T The type to which we'll be building a reference. 509/// 510/// \param CVR The cvr-qualifiers to be applied to the reference type. 511/// 512/// \param Loc The location of the entity whose type involves this 513/// reference type or, if there is no such entity, the location of the 514/// type that will have reference type. 515/// 516/// \param Entity The name of the entity that involves the reference 517/// type, if known. 518/// 519/// \returns A suitable reference type, if there are no 520/// errors. Otherwise, returns a NULL type. 521QualType Sema::BuildReferenceType(QualType T, bool SpelledAsLValue, 522 unsigned CVR, SourceLocation Loc, 523 DeclarationName Entity) { 524 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 525 526 bool LValueRef = SpelledAsLValue || T->getAs<LValueReferenceType>(); 527 528 // C++0x [dcl.typedef]p9: If a typedef TD names a type that is a 529 // reference to a type T, and attempt to create the type "lvalue 530 // reference to cv TD" creates the type "lvalue reference to T". 531 // We use the qualifiers (restrict or none) of the original reference, 532 // not the new ones. This is consistent with GCC. 533 534 // C++ [dcl.ref]p4: There shall be no references to references. 535 // 536 // According to C++ DR 106, references to references are only 537 // diagnosed when they are written directly (e.g., "int & &"), 538 // but not when they happen via a typedef: 539 // 540 // typedef int& intref; 541 // typedef intref& intref2; 542 // 543 // Parser::ParseDeclaratorInternal diagnoses the case where 544 // references are written directly; here, we handle the 545 // collapsing of references-to-references as described in C++ 546 // DR 106 and amended by C++ DR 540. 547 548 // C++ [dcl.ref]p1: 549 // A declarator that specifies the type "reference to cv void" 550 // is ill-formed. 551 if (T->isVoidType()) { 552 Diag(Loc, diag::err_reference_to_void); 553 return QualType(); 554 } 555 556 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 557 // object or incomplete types shall not be restrict-qualified." 558 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) { 559 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 560 << T; 561 Quals.removeRestrict(); 562 } 563 564 // C++ [dcl.ref]p1: 565 // [...] Cv-qualified references are ill-formed except when the 566 // cv-qualifiers are introduced through the use of a typedef 567 // (7.1.3) or of a template type argument (14.3), in which case 568 // the cv-qualifiers are ignored. 569 // 570 // We diagnose extraneous cv-qualifiers for the non-typedef, 571 // non-template type argument case within the parser. Here, we just 572 // ignore any extraneous cv-qualifiers. 573 Quals.removeConst(); 574 Quals.removeVolatile(); 575 576 // Handle restrict on references. 577 if (LValueRef) 578 return Context.getQualifiedType( 579 Context.getLValueReferenceType(T, SpelledAsLValue), Quals); 580 return Context.getQualifiedType(Context.getRValueReferenceType(T), Quals); 581} 582 583/// \brief Build an array type. 584/// 585/// \param T The type of each element in the array. 586/// 587/// \param ASM C99 array size modifier (e.g., '*', 'static'). 588/// 589/// \param ArraySize Expression describing the size of the array. 590/// 591/// \param Quals The cvr-qualifiers to be applied to the array's 592/// element type. 593/// 594/// \param Loc The location of the entity whose type involves this 595/// array type or, if there is no such entity, the location of the 596/// type that will have array type. 597/// 598/// \param Entity The name of the entity that involves the array 599/// type, if known. 600/// 601/// \returns A suitable array type, if there are no errors. Otherwise, 602/// returns a NULL type. 603QualType Sema::BuildArrayType(QualType T, ArrayType::ArraySizeModifier ASM, 604 Expr *ArraySize, unsigned Quals, 605 SourceRange Brackets, DeclarationName Entity) { 606 607 SourceLocation Loc = Brackets.getBegin(); 608 // C99 6.7.5.2p1: If the element type is an incomplete or function type, 609 // reject it (e.g. void ary[7], struct foo ary[7], void ary[7]()) 610 // Not in C++, though. There we only dislike void. 611 if (getLangOptions().CPlusPlus) { 612 if (T->isVoidType()) { 613 Diag(Loc, diag::err_illegal_decl_array_incomplete_type) << T; 614 return QualType(); 615 } 616 } else { 617 if (RequireCompleteType(Loc, T, 618 diag::err_illegal_decl_array_incomplete_type)) 619 return QualType(); 620 } 621 622 if (T->isFunctionType()) { 623 Diag(Loc, diag::err_illegal_decl_array_of_functions) 624 << getPrintableNameForEntity(Entity) << T; 625 return QualType(); 626 } 627 628 // C++ 8.3.2p4: There shall be no ... arrays of references ... 629 if (T->isReferenceType()) { 630 Diag(Loc, diag::err_illegal_decl_array_of_references) 631 << getPrintableNameForEntity(Entity) << T; 632 return QualType(); 633 } 634 635 if (Context.getCanonicalType(T) == Context.UndeducedAutoTy) { 636 Diag(Loc, diag::err_illegal_decl_array_of_auto) 637 << getPrintableNameForEntity(Entity); 638 return QualType(); 639 } 640 641 if (const RecordType *EltTy = T->getAs<RecordType>()) { 642 // If the element type is a struct or union that contains a variadic 643 // array, accept it as a GNU extension: C99 6.7.2.1p2. 644 if (EltTy->getDecl()->hasFlexibleArrayMember()) 645 Diag(Loc, diag::ext_flexible_array_in_array) << T; 646 } else if (T->isObjCInterfaceType()) { 647 Diag(Loc, diag::err_objc_array_of_interfaces) << T; 648 return QualType(); 649 } 650 651 // C99 6.7.5.2p1: The size expression shall have integer type. 652 if (ArraySize && !ArraySize->isTypeDependent() && 653 !ArraySize->getType()->isIntegerType()) { 654 Diag(ArraySize->getLocStart(), diag::err_array_size_non_int) 655 << ArraySize->getType() << ArraySize->getSourceRange(); 656 ArraySize->Destroy(Context); 657 return QualType(); 658 } 659 llvm::APSInt ConstVal(32); 660 if (!ArraySize) { 661 if (ASM == ArrayType::Star) 662 T = Context.getVariableArrayType(T, 0, ASM, Quals, Brackets); 663 else 664 T = Context.getIncompleteArrayType(T, ASM, Quals); 665 } else if (ArraySize->isValueDependent()) { 666 T = Context.getDependentSizedArrayType(T, ArraySize, ASM, Quals, Brackets); 667 } else if (!ArraySize->isIntegerConstantExpr(ConstVal, Context) || 668 (!T->isDependentType() && !T->isIncompleteType() && 669 !T->isConstantSizeType())) { 670 // Per C99, a variable array is an array with either a non-constant 671 // size or an element type that has a non-constant-size 672 T = Context.getVariableArrayType(T, ArraySize, ASM, Quals, Brackets); 673 } else { 674 // C99 6.7.5.2p1: If the expression is a constant expression, it shall 675 // have a value greater than zero. 676 if (ConstVal.isSigned() && ConstVal.isNegative()) { 677 Diag(ArraySize->getLocStart(), 678 diag::err_typecheck_negative_array_size) 679 << ArraySize->getSourceRange(); 680 return QualType(); 681 } 682 if (ConstVal == 0) { 683 // GCC accepts zero sized static arrays. We allow them when 684 // we're not in a SFINAE context. 685 Diag(ArraySize->getLocStart(), 686 isSFINAEContext()? diag::err_typecheck_zero_array_size 687 : diag::ext_typecheck_zero_array_size) 688 << ArraySize->getSourceRange(); 689 } 690 T = Context.getConstantArrayType(T, ConstVal, ASM, Quals); 691 } 692 // If this is not C99, extwarn about VLA's and C99 array size modifiers. 693 if (!getLangOptions().C99) { 694 if (ArraySize && !ArraySize->isTypeDependent() && 695 !ArraySize->isValueDependent() && 696 !ArraySize->isIntegerConstantExpr(Context)) 697 Diag(Loc, getLangOptions().CPlusPlus? diag::err_vla_cxx : diag::ext_vla); 698 else if (ASM != ArrayType::Normal || Quals != 0) 699 Diag(Loc, 700 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx 701 : diag::ext_c99_array_usage); 702 } 703 704 return T; 705} 706 707/// \brief Build an ext-vector type. 708/// 709/// Run the required checks for the extended vector type. 710QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 711 SourceLocation AttrLoc) { 712 713 Expr *Arg = (Expr *)ArraySize.get(); 714 715 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 716 // in conjunction with complex types (pointers, arrays, functions, etc.). 717 if (!T->isDependentType() && 718 !T->isIntegerType() && !T->isRealFloatingType()) { 719 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 720 return QualType(); 721 } 722 723 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 724 llvm::APSInt vecSize(32); 725 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 726 Diag(AttrLoc, diag::err_attribute_argument_not_int) 727 << "ext_vector_type" << Arg->getSourceRange(); 728 return QualType(); 729 } 730 731 // unlike gcc's vector_size attribute, the size is specified as the 732 // number of elements, not the number of bytes. 733 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 734 735 if (vectorSize == 0) { 736 Diag(AttrLoc, diag::err_attribute_zero_size) 737 << Arg->getSourceRange(); 738 return QualType(); 739 } 740 741 if (!T->isDependentType()) 742 return Context.getExtVectorType(T, vectorSize); 743 } 744 745 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 746 AttrLoc); 747} 748 749/// \brief Build a function type. 750/// 751/// This routine checks the function type according to C++ rules and 752/// under the assumption that the result type and parameter types have 753/// just been instantiated from a template. It therefore duplicates 754/// some of the behavior of GetTypeForDeclarator, but in a much 755/// simpler form that is only suitable for this narrow use case. 756/// 757/// \param T The return type of the function. 758/// 759/// \param ParamTypes The parameter types of the function. This array 760/// will be modified to account for adjustments to the types of the 761/// function parameters. 762/// 763/// \param NumParamTypes The number of parameter types in ParamTypes. 764/// 765/// \param Variadic Whether this is a variadic function type. 766/// 767/// \param Quals The cvr-qualifiers to be applied to the function type. 768/// 769/// \param Loc The location of the entity whose type involves this 770/// function type or, if there is no such entity, the location of the 771/// type that will have function type. 772/// 773/// \param Entity The name of the entity that involves the function 774/// type, if known. 775/// 776/// \returns A suitable function type, if there are no 777/// errors. Otherwise, returns a NULL type. 778QualType Sema::BuildFunctionType(QualType T, 779 QualType *ParamTypes, 780 unsigned NumParamTypes, 781 bool Variadic, unsigned Quals, 782 SourceLocation Loc, DeclarationName Entity) { 783 if (T->isArrayType() || T->isFunctionType()) { 784 Diag(Loc, diag::err_func_returning_array_function) 785 << T->isFunctionType() << T; 786 return QualType(); 787 } 788 789 bool Invalid = false; 790 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 791 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 792 if (ParamType->isVoidType()) { 793 Diag(Loc, diag::err_param_with_void_type); 794 Invalid = true; 795 } 796 797 ParamTypes[Idx] = ParamType; 798 } 799 800 if (Invalid) 801 return QualType(); 802 803 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 804 Quals, false, false, 0, 0, false, CC_Default); 805} 806 807/// \brief Build a member pointer type \c T Class::*. 808/// 809/// \param T the type to which the member pointer refers. 810/// \param Class the class type into which the member pointer points. 811/// \param CVR Qualifiers applied to the member pointer type 812/// \param Loc the location where this type begins 813/// \param Entity the name of the entity that will have this member pointer type 814/// 815/// \returns a member pointer type, if successful, or a NULL type if there was 816/// an error. 817QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 818 unsigned CVR, SourceLocation Loc, 819 DeclarationName Entity) { 820 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 821 822 // Verify that we're not building a pointer to pointer to function with 823 // exception specification. 824 if (CheckDistantExceptionSpec(T)) { 825 Diag(Loc, diag::err_distant_exception_spec); 826 827 // FIXME: If we're doing this as part of template instantiation, 828 // we should return immediately. 829 830 // Build the type anyway, but use the canonical type so that the 831 // exception specifiers are stripped off. 832 T = Context.getCanonicalType(T); 833 } 834 835 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 836 // with reference type, or "cv void." 837 if (T->isReferenceType()) { 838 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 839 << (Entity? Entity.getAsString() : "type name") << T; 840 return QualType(); 841 } 842 843 if (T->isVoidType()) { 844 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 845 << (Entity? Entity.getAsString() : "type name"); 846 return QualType(); 847 } 848 849 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 850 // object or incomplete types shall not be restrict-qualified." 851 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) { 852 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 853 << T; 854 855 // FIXME: If we're doing this as part of template instantiation, 856 // we should return immediately. 857 Quals.removeRestrict(); 858 } 859 860 if (!Class->isDependentType() && !Class->isRecordType()) { 861 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 862 return QualType(); 863 } 864 865 return Context.getQualifiedType( 866 Context.getMemberPointerType(T, Class.getTypePtr()), Quals); 867} 868 869/// \brief Build a block pointer type. 870/// 871/// \param T The type to which we'll be building a block pointer. 872/// 873/// \param CVR The cvr-qualifiers to be applied to the block pointer type. 874/// 875/// \param Loc The location of the entity whose type involves this 876/// block pointer type or, if there is no such entity, the location of the 877/// type that will have block pointer type. 878/// 879/// \param Entity The name of the entity that involves the block pointer 880/// type, if known. 881/// 882/// \returns A suitable block pointer type, if there are no 883/// errors. Otherwise, returns a NULL type. 884QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR, 885 SourceLocation Loc, 886 DeclarationName Entity) { 887 if (!T->isFunctionType()) { 888 Diag(Loc, diag::err_nonfunction_block_type); 889 return QualType(); 890 } 891 892 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 893 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals); 894} 895 896QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) { 897 QualType QT = QualType::getFromOpaquePtr(Ty); 898 if (QT.isNull()) { 899 if (TInfo) *TInfo = 0; 900 return QualType(); 901 } 902 903 TypeSourceInfo *DI = 0; 904 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 905 QT = LIT->getType(); 906 DI = LIT->getTypeSourceInfo(); 907 } 908 909 if (TInfo) *TInfo = DI; 910 return QT; 911} 912 913/// GetTypeForDeclarator - Convert the type for the specified 914/// declarator to Type instances. 915/// 916/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 917/// owns the declaration of a type (e.g., the definition of a struct 918/// type), then *OwnedDecl will receive the owned declaration. 919QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, 920 TypeSourceInfo **TInfo, 921 TagDecl **OwnedDecl) { 922 // Determine the type of the declarator. Not all forms of declarator 923 // have a type. 924 QualType T; 925 926 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec; 927 928 switch (D.getName().getKind()) { 929 case UnqualifiedId::IK_Identifier: 930 case UnqualifiedId::IK_OperatorFunctionId: 931 case UnqualifiedId::IK_LiteralOperatorId: 932 case UnqualifiedId::IK_TemplateId: 933 T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec); 934 935 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 936 TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 937 // Owned is embedded if it was defined here, or if it is the 938 // very first (i.e., canonical) declaration of this tag type. 939 Owned->setEmbeddedInDeclarator(Owned->isDefinition() || 940 Owned->isCanonicalDecl()); 941 if (OwnedDecl) *OwnedDecl = Owned; 942 } 943 break; 944 945 case UnqualifiedId::IK_ConstructorName: 946 case UnqualifiedId::IK_ConstructorTemplateId: 947 case UnqualifiedId::IK_DestructorName: 948 // Constructors and destructors don't have return types. Use 949 // "void" instead. 950 T = Context.VoidTy; 951 break; 952 953 case UnqualifiedId::IK_ConversionFunctionId: 954 // The result type of a conversion function is the type that it 955 // converts to. 956 T = GetTypeFromParser(D.getName().ConversionFunctionId); 957 break; 958 } 959 960 if (T.isNull()) 961 return T; 962 963 if (T == Context.UndeducedAutoTy) { 964 int Error = -1; 965 966 switch (D.getContext()) { 967 case Declarator::KNRTypeListContext: 968 assert(0 && "K&R type lists aren't allowed in C++"); 969 break; 970 case Declarator::PrototypeContext: 971 Error = 0; // Function prototype 972 break; 973 case Declarator::MemberContext: 974 switch (cast<TagDecl>(CurContext)->getTagKind()) { 975 case TagDecl::TK_enum: assert(0 && "unhandled tag kind"); break; 976 case TagDecl::TK_struct: Error = 1; /* Struct member */ break; 977 case TagDecl::TK_union: Error = 2; /* Union member */ break; 978 case TagDecl::TK_class: Error = 3; /* Class member */ break; 979 } 980 break; 981 case Declarator::CXXCatchContext: 982 Error = 4; // Exception declaration 983 break; 984 case Declarator::TemplateParamContext: 985 Error = 5; // Template parameter 986 break; 987 case Declarator::BlockLiteralContext: 988 Error = 6; // Block literal 989 break; 990 case Declarator::FileContext: 991 case Declarator::BlockContext: 992 case Declarator::ForContext: 993 case Declarator::ConditionContext: 994 case Declarator::TypeNameContext: 995 break; 996 } 997 998 if (Error != -1) { 999 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 1000 << Error; 1001 T = Context.IntTy; 1002 D.setInvalidType(true); 1003 } 1004 } 1005 1006 // The name we're declaring, if any. 1007 DeclarationName Name; 1008 if (D.getIdentifier()) 1009 Name = D.getIdentifier(); 1010 1011 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk; 1012 1013 // Walk the DeclTypeInfo, building the recursive type as we go. 1014 // DeclTypeInfos are ordered from the identifier out, which is 1015 // opposite of what we want :). 1016 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1017 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1); 1018 switch (DeclType.Kind) { 1019 default: assert(0 && "Unknown decltype!"); 1020 case DeclaratorChunk::BlockPointer: 1021 // If blocks are disabled, emit an error. 1022 if (!LangOpts.Blocks) 1023 Diag(DeclType.Loc, diag::err_blocks_disable); 1024 1025 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(), 1026 Name); 1027 break; 1028 case DeclaratorChunk::Pointer: 1029 // Verify that we're not building a pointer to pointer to function with 1030 // exception specification. 1031 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1032 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1033 D.setInvalidType(true); 1034 // Build the type anyway. 1035 } 1036 if (getLangOptions().ObjC1 && T->isObjCInterfaceType()) { 1037 const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>(); 1038 T = Context.getObjCObjectPointerType(T, 1039 (ObjCProtocolDecl **)OIT->qual_begin(), 1040 OIT->getNumProtocols(), 1041 DeclType.Ptr.TypeQuals); 1042 break; 1043 } 1044 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 1045 break; 1046 case DeclaratorChunk::Reference: { 1047 Qualifiers Quals; 1048 if (DeclType.Ref.HasRestrict) Quals.addRestrict(); 1049 1050 // Verify that we're not building a reference to pointer to function with 1051 // exception specification. 1052 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1053 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1054 D.setInvalidType(true); 1055 // Build the type anyway. 1056 } 1057 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals, 1058 DeclType.Loc, Name); 1059 break; 1060 } 1061 case DeclaratorChunk::Array: { 1062 // Verify that we're not building an array of pointers to function with 1063 // exception specification. 1064 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1065 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1066 D.setInvalidType(true); 1067 // Build the type anyway. 1068 } 1069 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 1070 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 1071 ArrayType::ArraySizeModifier ASM; 1072 if (ATI.isStar) 1073 ASM = ArrayType::Star; 1074 else if (ATI.hasStatic) 1075 ASM = ArrayType::Static; 1076 else 1077 ASM = ArrayType::Normal; 1078 if (ASM == ArrayType::Star && 1079 D.getContext() != Declarator::PrototypeContext) { 1080 // FIXME: This check isn't quite right: it allows star in prototypes 1081 // for function definitions, and disallows some edge cases detailed 1082 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 1083 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 1084 ASM = ArrayType::Normal; 1085 D.setInvalidType(true); 1086 } 1087 T = BuildArrayType(T, ASM, ArraySize, 1088 Qualifiers::fromCVRMask(ATI.TypeQuals), 1089 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 1090 break; 1091 } 1092 case DeclaratorChunk::Function: { 1093 // If the function declarator has a prototype (i.e. it is not () and 1094 // does not have a K&R-style identifier list), then the arguments are part 1095 // of the type, otherwise the argument list is (). 1096 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1097 1098 // C99 6.7.5.3p1: The return type may not be a function or array type. 1099 // For conversion functions, we'll diagnose this particular error later. 1100 if ((T->isArrayType() || T->isFunctionType()) && 1101 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 1102 Diag(DeclType.Loc, diag::err_func_returning_array_function) 1103 << T->isFunctionType() << T; 1104 T = Context.IntTy; 1105 D.setInvalidType(true); 1106 } 1107 1108 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 1109 // C++ [dcl.fct]p6: 1110 // Types shall not be defined in return or parameter types. 1111 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 1112 if (Tag->isDefinition()) 1113 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 1114 << Context.getTypeDeclType(Tag); 1115 } 1116 1117 // Exception specs are not allowed in typedefs. Complain, but add it 1118 // anyway. 1119 if (FTI.hasExceptionSpec && 1120 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1121 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 1122 1123 if (FTI.NumArgs == 0) { 1124 if (getLangOptions().CPlusPlus) { 1125 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 1126 // function takes no arguments. 1127 llvm::SmallVector<QualType, 4> Exceptions; 1128 Exceptions.reserve(FTI.NumExceptions); 1129 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1130 // FIXME: Preserve type source info. 1131 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1132 // Check that the type is valid for an exception spec, and drop it 1133 // if not. 1134 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1135 Exceptions.push_back(ET); 1136 } 1137 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals, 1138 FTI.hasExceptionSpec, 1139 FTI.hasAnyExceptionSpec, 1140 Exceptions.size(), Exceptions.data(), 1141 false, CC_Default); 1142 } else if (FTI.isVariadic) { 1143 // We allow a zero-parameter variadic function in C if the 1144 // function is marked with the "overloadable" 1145 // attribute. Scan for this attribute now. 1146 bool Overloadable = false; 1147 for (const AttributeList *Attrs = D.getAttributes(); 1148 Attrs; Attrs = Attrs->getNext()) { 1149 if (Attrs->getKind() == AttributeList::AT_overloadable) { 1150 Overloadable = true; 1151 break; 1152 } 1153 } 1154 1155 if (!Overloadable) 1156 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 1157 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0, 1158 false, false, 0, 0, false, CC_Default); 1159 } else { 1160 // Simple void foo(), where the incoming T is the result type. 1161 T = Context.getFunctionNoProtoType(T); 1162 } 1163 } else if (FTI.ArgInfo[0].Param == 0) { 1164 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 1165 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1166 D.setInvalidType(true); 1167 } else { 1168 // Otherwise, we have a function with an argument list that is 1169 // potentially variadic. 1170 llvm::SmallVector<QualType, 16> ArgTys; 1171 1172 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1173 ParmVarDecl *Param = 1174 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1175 QualType ArgTy = Param->getType(); 1176 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1177 1178 // Adjust the parameter type. 1179 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1180 1181 // Look for 'void'. void is allowed only as a single argument to a 1182 // function with no other parameters (C99 6.7.5.3p10). We record 1183 // int(void) as a FunctionProtoType with an empty argument list. 1184 if (ArgTy->isVoidType()) { 1185 // If this is something like 'float(int, void)', reject it. 'void' 1186 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1187 // have arguments of incomplete type. 1188 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1189 Diag(DeclType.Loc, diag::err_void_only_param); 1190 ArgTy = Context.IntTy; 1191 Param->setType(ArgTy); 1192 } else if (FTI.ArgInfo[i].Ident) { 1193 // Reject, but continue to parse 'int(void abc)'. 1194 Diag(FTI.ArgInfo[i].IdentLoc, 1195 diag::err_param_with_void_type); 1196 ArgTy = Context.IntTy; 1197 Param->setType(ArgTy); 1198 } else { 1199 // Reject, but continue to parse 'float(const void)'. 1200 if (ArgTy.hasQualifiers()) 1201 Diag(DeclType.Loc, diag::err_void_param_qualified); 1202 1203 // Do not add 'void' to the ArgTys list. 1204 break; 1205 } 1206 } else if (!FTI.hasPrototype) { 1207 if (ArgTy->isPromotableIntegerType()) { 1208 ArgTy = Context.getPromotedIntegerType(ArgTy); 1209 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 1210 if (BTy->getKind() == BuiltinType::Float) 1211 ArgTy = Context.DoubleTy; 1212 } 1213 } 1214 1215 ArgTys.push_back(ArgTy); 1216 } 1217 1218 llvm::SmallVector<QualType, 4> Exceptions; 1219 Exceptions.reserve(FTI.NumExceptions); 1220 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1221 // FIXME: Preserve type source info. 1222 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1223 // Check that the type is valid for an exception spec, and drop it if 1224 // not. 1225 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1226 Exceptions.push_back(ET); 1227 } 1228 1229 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1230 FTI.isVariadic, FTI.TypeQuals, 1231 FTI.hasExceptionSpec, 1232 FTI.hasAnyExceptionSpec, 1233 Exceptions.size(), Exceptions.data(), 1234 false, CC_Default); 1235 } 1236 1237 // For GCC compatibility, we allow attributes that apply only to 1238 // function types to be placed on a function's return type 1239 // instead (as long as that type doesn't happen to be function 1240 // or function-pointer itself). 1241 ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk); 1242 1243 break; 1244 } 1245 case DeclaratorChunk::MemberPointer: 1246 // Verify that we're not building a pointer to pointer to function with 1247 // exception specification. 1248 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1249 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1250 D.setInvalidType(true); 1251 // Build the type anyway. 1252 } 1253 // The scope spec must refer to a class, or be dependent. 1254 QualType ClsType; 1255 if (isDependentScopeSpecifier(DeclType.Mem.Scope()) 1256 || dyn_cast_or_null<CXXRecordDecl>( 1257 computeDeclContext(DeclType.Mem.Scope()))) { 1258 NestedNameSpecifier *NNS 1259 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1260 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 1261 switch (NNS->getKind()) { 1262 case NestedNameSpecifier::Identifier: 1263 ClsType = Context.getTypenameType(NNSPrefix, NNS->getAsIdentifier()); 1264 break; 1265 1266 case NestedNameSpecifier::Namespace: 1267 case NestedNameSpecifier::Global: 1268 llvm_unreachable("Nested-name-specifier must name a type"); 1269 break; 1270 1271 case NestedNameSpecifier::TypeSpec: 1272 case NestedNameSpecifier::TypeSpecWithTemplate: 1273 ClsType = QualType(NNS->getAsType(), 0); 1274 if (NNSPrefix) 1275 ClsType = Context.getQualifiedNameType(NNSPrefix, ClsType); 1276 break; 1277 } 1278 } else { 1279 Diag(DeclType.Mem.Scope().getBeginLoc(), 1280 diag::err_illegal_decl_mempointer_in_nonclass) 1281 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1282 << DeclType.Mem.Scope().getRange(); 1283 D.setInvalidType(true); 1284 } 1285 1286 if (!ClsType.isNull()) 1287 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals, 1288 DeclType.Loc, D.getIdentifier()); 1289 if (T.isNull()) { 1290 T = Context.IntTy; 1291 D.setInvalidType(true); 1292 } 1293 break; 1294 } 1295 1296 if (T.isNull()) { 1297 D.setInvalidType(true); 1298 T = Context.IntTy; 1299 } 1300 1301 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1302 1303 // See if there are any attributes on this declarator chunk. 1304 if (const AttributeList *AL = DeclType.getAttrs()) 1305 ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk); 1306 } 1307 1308 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1309 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 1310 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 1311 1312 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1313 // for a nonstatic member function, the function type to which a pointer 1314 // to member refers, or the top-level function type of a function typedef 1315 // declaration. 1316 if (FnTy->getTypeQuals() != 0 && 1317 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1318 ((D.getContext() != Declarator::MemberContext && 1319 (!D.getCXXScopeSpec().isSet() || 1320 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true) 1321 ->isRecord())) || 1322 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1323 if (D.isFunctionDeclarator()) 1324 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1325 else 1326 Diag(D.getIdentifierLoc(), 1327 diag::err_invalid_qualified_typedef_function_type_use); 1328 1329 // Strip the cv-quals from the type. 1330 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1331 FnTy->getNumArgs(), FnTy->isVariadic(), 0, 1332 false, false, 0, 0, false, CC_Default); 1333 } 1334 } 1335 1336 // Process any function attributes we might have delayed from the 1337 // declaration-specifiers. 1338 ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec); 1339 1340 // If there were any type attributes applied to the decl itself, not 1341 // the type, apply them to the result type. But don't do this for 1342 // block-literal expressions, which are parsed wierdly. 1343 if (D.getContext() != Declarator::BlockLiteralContext) 1344 if (const AttributeList *Attrs = D.getAttributes()) 1345 ProcessTypeAttributeList(*this, T, false, Attrs, 1346 FnAttrsFromPreviousChunk); 1347 1348 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1349 1350 if (TInfo) { 1351 if (D.isInvalidType()) 1352 *TInfo = 0; 1353 else 1354 *TInfo = GetTypeSourceInfoForDeclarator(D, T); 1355 } 1356 1357 return T; 1358} 1359 1360namespace { 1361 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 1362 const DeclSpec &DS; 1363 1364 public: 1365 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {} 1366 1367 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1368 Visit(TL.getUnqualifiedLoc()); 1369 } 1370 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1371 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1372 } 1373 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1374 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1375 1376 if (DS.getProtocolQualifiers()) { 1377 assert(TL.getNumProtocols() > 0); 1378 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 1379 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 1380 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 1381 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 1382 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 1383 } else { 1384 assert(TL.getNumProtocols() == 0); 1385 TL.setLAngleLoc(SourceLocation()); 1386 TL.setRAngleLoc(SourceLocation()); 1387 } 1388 } 1389 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1390 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 1391 1392 TL.setStarLoc(SourceLocation()); 1393 1394 if (DS.getProtocolQualifiers()) { 1395 assert(TL.getNumProtocols() > 0); 1396 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 1397 TL.setHasProtocolsAsWritten(true); 1398 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 1399 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 1400 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 1401 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 1402 1403 } else { 1404 assert(TL.getNumProtocols() == 0); 1405 TL.setHasProtocolsAsWritten(false); 1406 TL.setLAngleLoc(SourceLocation()); 1407 TL.setRAngleLoc(SourceLocation()); 1408 } 1409 1410 // This might not have been written with an inner type. 1411 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 1412 TL.setHasBaseTypeAsWritten(false); 1413 TL.getBaseTypeLoc().initialize(SourceLocation()); 1414 } else { 1415 TL.setHasBaseTypeAsWritten(true); 1416 Visit(TL.getBaseTypeLoc()); 1417 } 1418 } 1419 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 1420 TypeSourceInfo *TInfo = 0; 1421 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1422 1423 // If we got no declarator info from previous Sema routines, 1424 // just fill with the typespec loc. 1425 if (!TInfo) { 1426 TL.initialize(DS.getTypeSpecTypeLoc()); 1427 return; 1428 } 1429 1430 TemplateSpecializationTypeLoc OldTL = 1431 cast<TemplateSpecializationTypeLoc>(TInfo->getTypeLoc()); 1432 TL.copy(OldTL); 1433 } 1434 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1435 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 1436 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1437 TL.setParensRange(DS.getTypeofParensRange()); 1438 } 1439 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1440 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 1441 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1442 TL.setParensRange(DS.getTypeofParensRange()); 1443 assert(DS.getTypeRep()); 1444 TypeSourceInfo *TInfo = 0; 1445 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1446 TL.setUnderlyingTInfo(TInfo); 1447 } 1448 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1449 // By default, use the source location of the type specifier. 1450 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 1451 if (TL.needsExtraLocalData()) { 1452 // Set info for the written builtin specifiers. 1453 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 1454 // Try to have a meaningful source location. 1455 if (TL.getWrittenSignSpec() != TSS_unspecified) 1456 // Sign spec loc overrides the others (e.g., 'unsigned long'). 1457 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 1458 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 1459 // Width spec loc overrides type spec loc (e.g., 'short int'). 1460 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 1461 } 1462 } 1463 void VisitTypeLoc(TypeLoc TL) { 1464 // FIXME: add other typespec types and change this to an assert. 1465 TL.initialize(DS.getTypeSpecTypeLoc()); 1466 } 1467 }; 1468 1469 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 1470 const DeclaratorChunk &Chunk; 1471 1472 public: 1473 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {} 1474 1475 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1476 llvm_unreachable("qualified type locs not expected here!"); 1477 } 1478 1479 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1480 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 1481 TL.setCaretLoc(Chunk.Loc); 1482 } 1483 void VisitPointerTypeLoc(PointerTypeLoc TL) { 1484 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1485 TL.setStarLoc(Chunk.Loc); 1486 } 1487 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1488 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1489 TL.setStarLoc(Chunk.Loc); 1490 TL.setHasBaseTypeAsWritten(true); 1491 TL.setHasProtocolsAsWritten(false); 1492 TL.setLAngleLoc(SourceLocation()); 1493 TL.setRAngleLoc(SourceLocation()); 1494 } 1495 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1496 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 1497 TL.setStarLoc(Chunk.Loc); 1498 // FIXME: nested name specifier 1499 } 1500 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1501 assert(Chunk.Kind == DeclaratorChunk::Reference); 1502 // 'Amp' is misleading: this might have been originally 1503 /// spelled with AmpAmp. 1504 TL.setAmpLoc(Chunk.Loc); 1505 } 1506 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1507 assert(Chunk.Kind == DeclaratorChunk::Reference); 1508 assert(!Chunk.Ref.LValueRef); 1509 TL.setAmpAmpLoc(Chunk.Loc); 1510 } 1511 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 1512 assert(Chunk.Kind == DeclaratorChunk::Array); 1513 TL.setLBracketLoc(Chunk.Loc); 1514 TL.setRBracketLoc(Chunk.EndLoc); 1515 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 1516 } 1517 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 1518 assert(Chunk.Kind == DeclaratorChunk::Function); 1519 TL.setLParenLoc(Chunk.Loc); 1520 TL.setRParenLoc(Chunk.EndLoc); 1521 1522 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 1523 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 1524 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 1525 TL.setArg(tpi++, Param); 1526 } 1527 // FIXME: exception specs 1528 } 1529 1530 void VisitTypeLoc(TypeLoc TL) { 1531 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 1532 } 1533 }; 1534} 1535 1536/// \brief Create and instantiate a TypeSourceInfo with type source information. 1537/// 1538/// \param T QualType referring to the type as written in source code. 1539TypeSourceInfo * 1540Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T) { 1541 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 1542 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 1543 1544 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1545 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL); 1546 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 1547 } 1548 1549 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL); 1550 1551 return TInfo; 1552} 1553 1554/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 1555QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) { 1556 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 1557 // and Sema during declaration parsing. Try deallocating/caching them when 1558 // it's appropriate, instead of allocating them and keeping them around. 1559 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8); 1560 new (LocT) LocInfoType(T, TInfo); 1561 assert(LocT->getTypeClass() != T->getTypeClass() && 1562 "LocInfoType's TypeClass conflicts with an existing Type class"); 1563 return QualType(LocT, 0); 1564} 1565 1566void LocInfoType::getAsStringInternal(std::string &Str, 1567 const PrintingPolicy &Policy) const { 1568 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*" 1569 " was used directly instead of getting the QualType through" 1570 " GetTypeFromParser"); 1571} 1572 1573/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 1574/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 1575/// they point to and return true. If T1 and T2 aren't pointer types 1576/// or pointer-to-member types, or if they are not similar at this 1577/// level, returns false and leaves T1 and T2 unchanged. Top-level 1578/// qualifiers on T1 and T2 are ignored. This function will typically 1579/// be called in a loop that successively "unwraps" pointer and 1580/// pointer-to-member types to compare them at each level. 1581bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 1582 const PointerType *T1PtrType = T1->getAs<PointerType>(), 1583 *T2PtrType = T2->getAs<PointerType>(); 1584 if (T1PtrType && T2PtrType) { 1585 T1 = T1PtrType->getPointeeType(); 1586 T2 = T2PtrType->getPointeeType(); 1587 return true; 1588 } 1589 1590 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 1591 *T2MPType = T2->getAs<MemberPointerType>(); 1592 if (T1MPType && T2MPType && 1593 Context.getCanonicalType(T1MPType->getClass()) == 1594 Context.getCanonicalType(T2MPType->getClass())) { 1595 T1 = T1MPType->getPointeeType(); 1596 T2 = T2MPType->getPointeeType(); 1597 return true; 1598 } 1599 return false; 1600} 1601 1602Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1603 // C99 6.7.6: Type names have no identifier. This is already validated by 1604 // the parser. 1605 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1606 1607 TypeSourceInfo *TInfo = 0; 1608 TagDecl *OwnedTag = 0; 1609 QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 1610 if (D.isInvalidType()) 1611 return true; 1612 1613 if (getLangOptions().CPlusPlus) { 1614 // Check that there are no default arguments (C++ only). 1615 CheckExtraCXXDefaultArguments(D); 1616 1617 // C++0x [dcl.type]p3: 1618 // A type-specifier-seq shall not define a class or enumeration 1619 // unless it appears in the type-id of an alias-declaration 1620 // (7.1.3). 1621 if (OwnedTag && OwnedTag->isDefinition()) 1622 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1623 << Context.getTypeDeclType(OwnedTag); 1624 } 1625 1626 if (TInfo) 1627 T = CreateLocInfoType(T, TInfo); 1628 1629 return T.getAsOpaquePtr(); 1630} 1631 1632 1633 1634//===----------------------------------------------------------------------===// 1635// Type Attribute Processing 1636//===----------------------------------------------------------------------===// 1637 1638/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1639/// specified type. The attribute contains 1 argument, the id of the address 1640/// space for the type. 1641static void HandleAddressSpaceTypeAttribute(QualType &Type, 1642 const AttributeList &Attr, Sema &S){ 1643 1644 // If this type is already address space qualified, reject it. 1645 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1646 // for two or more different address spaces." 1647 if (Type.getAddressSpace()) { 1648 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1649 return; 1650 } 1651 1652 // Check the attribute arguments. 1653 if (Attr.getNumArgs() != 1) { 1654 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1655 return; 1656 } 1657 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1658 llvm::APSInt addrSpace(32); 1659 if (!ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1660 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1661 << ASArgExpr->getSourceRange(); 1662 return; 1663 } 1664 1665 // Bounds checking. 1666 if (addrSpace.isSigned()) { 1667 if (addrSpace.isNegative()) { 1668 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 1669 << ASArgExpr->getSourceRange(); 1670 return; 1671 } 1672 addrSpace.setIsSigned(false); 1673 } 1674 llvm::APSInt max(addrSpace.getBitWidth()); 1675 max = Qualifiers::MaxAddressSpace; 1676 if (addrSpace > max) { 1677 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 1678 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 1679 return; 1680 } 1681 1682 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1683 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1684} 1685 1686/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1687/// specified type. The attribute contains 1 argument, weak or strong. 1688static void HandleObjCGCTypeAttribute(QualType &Type, 1689 const AttributeList &Attr, Sema &S) { 1690 if (Type.getObjCGCAttr() != Qualifiers::GCNone) { 1691 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1692 return; 1693 } 1694 1695 // Check the attribute arguments. 1696 if (!Attr.getParameterName()) { 1697 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1698 << "objc_gc" << 1; 1699 return; 1700 } 1701 Qualifiers::GC GCAttr; 1702 if (Attr.getNumArgs() != 0) { 1703 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1704 return; 1705 } 1706 if (Attr.getParameterName()->isStr("weak")) 1707 GCAttr = Qualifiers::Weak; 1708 else if (Attr.getParameterName()->isStr("strong")) 1709 GCAttr = Qualifiers::Strong; 1710 else { 1711 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1712 << "objc_gc" << Attr.getParameterName(); 1713 return; 1714 } 1715 1716 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1717} 1718 1719/// Process an individual function attribute. Returns true if the 1720/// attribute does not make sense to apply to this type. 1721bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) { 1722 if (Attr.getKind() == AttributeList::AT_noreturn) { 1723 // Complain immediately if the arg count is wrong. 1724 if (Attr.getNumArgs() != 0) { 1725 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1726 return false; 1727 } 1728 1729 // Delay if this is not a function or pointer to block. 1730 if (!Type->isFunctionPointerType() 1731 && !Type->isBlockPointerType() 1732 && !Type->isFunctionType()) 1733 return true; 1734 1735 // Otherwise we can process right away. 1736 Type = S.Context.getNoReturnType(Type); 1737 return false; 1738 } 1739 1740 // Otherwise, a calling convention. 1741 if (Attr.getNumArgs() != 0) { 1742 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1743 return false; 1744 } 1745 1746 QualType T = Type; 1747 if (const PointerType *PT = Type->getAs<PointerType>()) 1748 T = PT->getPointeeType(); 1749 const FunctionType *Fn = T->getAs<FunctionType>(); 1750 1751 // Delay if the type didn't work out to a function. 1752 if (!Fn) return true; 1753 1754 // TODO: diagnose uses of these conventions on the wrong target. 1755 CallingConv CC; 1756 switch (Attr.getKind()) { 1757 case AttributeList::AT_cdecl: CC = CC_C; break; 1758 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break; 1759 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break; 1760 default: llvm_unreachable("unexpected attribute kind"); return false; 1761 } 1762 1763 CallingConv CCOld = Fn->getCallConv(); 1764 if (S.Context.getCanonicalCallConv(CC) == 1765 S.Context.getCanonicalCallConv(CCOld)) return false; 1766 1767 if (CCOld != CC_Default) { 1768 // Should we diagnose reapplications of the same convention? 1769 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 1770 << FunctionType::getNameForCallConv(CC) 1771 << FunctionType::getNameForCallConv(CCOld); 1772 return false; 1773 } 1774 1775 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 1776 if (CC == CC_X86FastCall) { 1777 if (isa<FunctionNoProtoType>(Fn)) { 1778 S.Diag(Attr.getLoc(), diag::err_cconv_knr) 1779 << FunctionType::getNameForCallConv(CC); 1780 return false; 1781 } 1782 1783 const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn); 1784 if (FnP->isVariadic()) { 1785 S.Diag(Attr.getLoc(), diag::err_cconv_varargs) 1786 << FunctionType::getNameForCallConv(CC); 1787 return false; 1788 } 1789 } 1790 1791 Type = S.Context.getCallConvType(Type, CC); 1792 return false; 1793} 1794 1795/// HandleVectorSizeAttribute - this attribute is only applicable to integral 1796/// and float scalars, although arrays, pointers, and function return values are 1797/// allowed in conjunction with this construct. Aggregates with this attribute 1798/// are invalid, even if they are of the same size as a corresponding scalar. 1799/// The raw attribute should contain precisely 1 argument, the vector size for 1800/// the variable, measured in bytes. If curType and rawAttr are well formed, 1801/// this routine will return a new vector type. 1802static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) { 1803 // Check the attribute arugments. 1804 if (Attr.getNumArgs() != 1) { 1805 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1806 return; 1807 } 1808 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 1809 llvm::APSInt vecSize(32); 1810 if (!sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 1811 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 1812 << "vector_size" << sizeExpr->getSourceRange(); 1813 return; 1814 } 1815 // the base type must be integer or float, and can't already be a vector. 1816 if (CurType->isVectorType() || 1817 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 1818 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 1819 return; 1820 } 1821 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 1822 // vecSize is specified in bytes - convert to bits. 1823 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 1824 1825 // the vector size needs to be an integral multiple of the type size. 1826 if (vectorSize % typeSize) { 1827 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 1828 << sizeExpr->getSourceRange(); 1829 return; 1830 } 1831 if (vectorSize == 0) { 1832 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 1833 << sizeExpr->getSourceRange(); 1834 return; 1835 } 1836 1837 // Success! Instantiate the vector type, the number of elements is > 0, and 1838 // not required to be a power of 2, unlike GCC. 1839 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false); 1840} 1841 1842void ProcessTypeAttributeList(Sema &S, QualType &Result, 1843 bool IsDeclSpec, const AttributeList *AL, 1844 DelayedAttributeSet &FnAttrs) { 1845 // Scan through and apply attributes to this type where it makes sense. Some 1846 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1847 // type, but others can be present in the type specifiers even though they 1848 // apply to the decl. Here we apply type attributes and ignore the rest. 1849 for (; AL; AL = AL->getNext()) { 1850 // If this is an attribute we can handle, do so now, otherwise, add it to 1851 // the LeftOverAttrs list for rechaining. 1852 switch (AL->getKind()) { 1853 default: break; 1854 1855 case AttributeList::AT_address_space: 1856 HandleAddressSpaceTypeAttribute(Result, *AL, S); 1857 break; 1858 case AttributeList::AT_objc_gc: 1859 HandleObjCGCTypeAttribute(Result, *AL, S); 1860 break; 1861 case AttributeList::AT_vector_size: 1862 HandleVectorSizeAttr(Result, *AL, S); 1863 break; 1864 1865 case AttributeList::AT_noreturn: 1866 case AttributeList::AT_cdecl: 1867 case AttributeList::AT_fastcall: 1868 case AttributeList::AT_stdcall: 1869 // Don't process these on the DeclSpec. 1870 if (IsDeclSpec || 1871 ProcessFnAttr(S, Result, *AL)) 1872 FnAttrs.push_back(DelayedAttribute(AL, Result)); 1873 break; 1874 } 1875 } 1876} 1877 1878/// @brief Ensure that the type T is a complete type. 1879/// 1880/// This routine checks whether the type @p T is complete in any 1881/// context where a complete type is required. If @p T is a complete 1882/// type, returns false. If @p T is a class template specialization, 1883/// this routine then attempts to perform class template 1884/// instantiation. If instantiation fails, or if @p T is incomplete 1885/// and cannot be completed, issues the diagnostic @p diag (giving it 1886/// the type @p T) and returns true. 1887/// 1888/// @param Loc The location in the source that the incomplete type 1889/// diagnostic should refer to. 1890/// 1891/// @param T The type that this routine is examining for completeness. 1892/// 1893/// @param PD The partial diagnostic that will be printed out if T is not a 1894/// complete type. 1895/// 1896/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 1897/// @c false otherwise. 1898bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 1899 const PartialDiagnostic &PD, 1900 std::pair<SourceLocation, 1901 PartialDiagnostic> Note) { 1902 unsigned diag = PD.getDiagID(); 1903 1904 // FIXME: Add this assertion to make sure we always get instantiation points. 1905 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 1906 // FIXME: Add this assertion to help us flush out problems with 1907 // checking for dependent types and type-dependent expressions. 1908 // 1909 // assert(!T->isDependentType() && 1910 // "Can't ask whether a dependent type is complete"); 1911 1912 // If we have a complete type, we're done. 1913 if (!T->isIncompleteType()) 1914 return false; 1915 1916 // If we have a class template specialization or a class member of a 1917 // class template specialization, or an array with known size of such, 1918 // try to instantiate it. 1919 QualType MaybeTemplate = T; 1920 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T)) 1921 MaybeTemplate = Array->getElementType(); 1922 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 1923 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 1924 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 1925 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 1926 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 1927 TSK_ImplicitInstantiation, 1928 /*Complain=*/diag != 0); 1929 } else if (CXXRecordDecl *Rec 1930 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 1931 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 1932 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo(); 1933 assert(MSInfo && "Missing member specialization information?"); 1934 // This record was instantiated from a class within a template. 1935 if (MSInfo->getTemplateSpecializationKind() 1936 != TSK_ExplicitSpecialization) 1937 return InstantiateClass(Loc, Rec, Pattern, 1938 getTemplateInstantiationArgs(Rec), 1939 TSK_ImplicitInstantiation, 1940 /*Complain=*/diag != 0); 1941 } 1942 } 1943 } 1944 1945 if (diag == 0) 1946 return true; 1947 1948 const TagType *Tag = 0; 1949 if (const RecordType *Record = T->getAs<RecordType>()) 1950 Tag = Record; 1951 else if (const EnumType *Enum = T->getAs<EnumType>()) 1952 Tag = Enum; 1953 1954 // Avoid diagnosing invalid decls as incomplete. 1955 if (Tag && Tag->getDecl()->isInvalidDecl()) 1956 return true; 1957 1958 // We have an incomplete type. Produce a diagnostic. 1959 Diag(Loc, PD) << T; 1960 1961 // If we have a note, produce it. 1962 if (!Note.first.isInvalid()) 1963 Diag(Note.first, Note.second); 1964 1965 // If the type was a forward declaration of a class/struct/union 1966 // type, produce a note. 1967 if (Tag && !Tag->getDecl()->isInvalidDecl()) 1968 Diag(Tag->getDecl()->getLocation(), 1969 Tag->isBeingDefined() ? diag::note_type_being_defined 1970 : diag::note_forward_declaration) 1971 << QualType(Tag, 0); 1972 1973 return true; 1974} 1975 1976bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 1977 const PartialDiagnostic &PD) { 1978 return RequireCompleteType(Loc, T, PD, 1979 std::make_pair(SourceLocation(), PDiag(0))); 1980} 1981 1982bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 1983 unsigned DiagID) { 1984 return RequireCompleteType(Loc, T, PDiag(DiagID), 1985 std::make_pair(SourceLocation(), PDiag(0))); 1986} 1987 1988/// \brief Retrieve a version of the type 'T' that is qualified by the 1989/// nested-name-specifier contained in SS. 1990QualType Sema::getQualifiedNameType(const CXXScopeSpec &SS, QualType T) { 1991 if (!SS.isSet() || SS.isInvalid() || T.isNull()) 1992 return T; 1993 1994 NestedNameSpecifier *NNS 1995 = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 1996 return Context.getQualifiedNameType(NNS, T); 1997} 1998 1999QualType Sema::BuildTypeofExprType(Expr *E) { 2000 if (E->getType() == Context.OverloadTy) { 2001 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2002 // function template specialization wherever deduction cannot occur. 2003 if (FunctionDecl *Specialization 2004 = ResolveSingleFunctionTemplateSpecialization(E)) { 2005 E = FixOverloadedFunctionReference(E, Specialization); 2006 if (!E) 2007 return QualType(); 2008 } else { 2009 Diag(E->getLocStart(), 2010 diag::err_cannot_determine_declared_type_of_overloaded_function) 2011 << false << E->getSourceRange(); 2012 return QualType(); 2013 } 2014 } 2015 2016 return Context.getTypeOfExprType(E); 2017} 2018 2019QualType Sema::BuildDecltypeType(Expr *E) { 2020 if (E->getType() == Context.OverloadTy) { 2021 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2022 // function template specialization wherever deduction cannot occur. 2023 if (FunctionDecl *Specialization 2024 = ResolveSingleFunctionTemplateSpecialization(E)) { 2025 E = FixOverloadedFunctionReference(E, Specialization); 2026 if (!E) 2027 return QualType(); 2028 } else { 2029 Diag(E->getLocStart(), 2030 diag::err_cannot_determine_declared_type_of_overloaded_function) 2031 << true << E->getSourceRange(); 2032 return QualType(); 2033 } 2034 } 2035 2036 return Context.getDecltypeType(E); 2037} 2038