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