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