SemaType.cpp revision a481ec4150ad203440852a2bfee0883dd26f7530
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 (T->isVariableArrayType()) { 713 // Prohibit the use of non-POD types in VLAs. 714 if (!Context.getBaseElementType(T)->isPODType()) { 715 Diag(Loc, diag::err_vla_non_pod) 716 << Context.getBaseElementType(T); 717 return QualType(); 718 } 719 // Prohibit the use of VLAs during template argument deduction. 720 else if (isSFINAEContext()) { 721 Diag(Loc, diag::err_vla_in_sfinae); 722 return QualType(); 723 } 724 // Just extwarn about VLAs. 725 else 726 Diag(Loc, diag::ext_vla); 727 } else if (ASM != ArrayType::Normal || Quals != 0) 728 Diag(Loc, 729 getLangOptions().CPlusPlus? diag::err_c99_array_usage_cxx 730 : diag::ext_c99_array_usage); 731 } 732 733 return T; 734} 735 736/// \brief Build an ext-vector type. 737/// 738/// Run the required checks for the extended vector type. 739QualType Sema::BuildExtVectorType(QualType T, ExprArg ArraySize, 740 SourceLocation AttrLoc) { 741 742 Expr *Arg = (Expr *)ArraySize.get(); 743 744 // unlike gcc's vector_size attribute, we do not allow vectors to be defined 745 // in conjunction with complex types (pointers, arrays, functions, etc.). 746 if (!T->isDependentType() && 747 !T->isIntegerType() && !T->isRealFloatingType()) { 748 Diag(AttrLoc, diag::err_attribute_invalid_vector_type) << T; 749 return QualType(); 750 } 751 752 if (!Arg->isTypeDependent() && !Arg->isValueDependent()) { 753 llvm::APSInt vecSize(32); 754 if (!Arg->isIntegerConstantExpr(vecSize, Context)) { 755 Diag(AttrLoc, diag::err_attribute_argument_not_int) 756 << "ext_vector_type" << Arg->getSourceRange(); 757 return QualType(); 758 } 759 760 // unlike gcc's vector_size attribute, the size is specified as the 761 // number of elements, not the number of bytes. 762 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue()); 763 764 if (vectorSize == 0) { 765 Diag(AttrLoc, diag::err_attribute_zero_size) 766 << Arg->getSourceRange(); 767 return QualType(); 768 } 769 770 if (!T->isDependentType()) 771 return Context.getExtVectorType(T, vectorSize); 772 } 773 774 return Context.getDependentSizedExtVectorType(T, ArraySize.takeAs<Expr>(), 775 AttrLoc); 776} 777 778/// \brief Build a function type. 779/// 780/// This routine checks the function type according to C++ rules and 781/// under the assumption that the result type and parameter types have 782/// just been instantiated from a template. It therefore duplicates 783/// some of the behavior of GetTypeForDeclarator, but in a much 784/// simpler form that is only suitable for this narrow use case. 785/// 786/// \param T The return type of the function. 787/// 788/// \param ParamTypes The parameter types of the function. This array 789/// will be modified to account for adjustments to the types of the 790/// function parameters. 791/// 792/// \param NumParamTypes The number of parameter types in ParamTypes. 793/// 794/// \param Variadic Whether this is a variadic function type. 795/// 796/// \param Quals The cvr-qualifiers to be applied to the function type. 797/// 798/// \param Loc The location of the entity whose type involves this 799/// function type or, if there is no such entity, the location of the 800/// type that will have function type. 801/// 802/// \param Entity The name of the entity that involves the function 803/// type, if known. 804/// 805/// \returns A suitable function type, if there are no 806/// errors. Otherwise, returns a NULL type. 807QualType Sema::BuildFunctionType(QualType T, 808 QualType *ParamTypes, 809 unsigned NumParamTypes, 810 bool Variadic, unsigned Quals, 811 SourceLocation Loc, DeclarationName Entity) { 812 if (T->isArrayType() || T->isFunctionType()) { 813 Diag(Loc, diag::err_func_returning_array_function) 814 << T->isFunctionType() << T; 815 return QualType(); 816 } 817 818 bool Invalid = false; 819 for (unsigned Idx = 0; Idx < NumParamTypes; ++Idx) { 820 QualType ParamType = adjustParameterType(ParamTypes[Idx]); 821 if (ParamType->isVoidType()) { 822 Diag(Loc, diag::err_param_with_void_type); 823 Invalid = true; 824 } 825 826 ParamTypes[Idx] = ParamType; 827 } 828 829 if (Invalid) 830 return QualType(); 831 832 return Context.getFunctionType(T, ParamTypes, NumParamTypes, Variadic, 833 Quals, false, false, 0, 0, 834 FunctionType::ExtInfo()); 835} 836 837/// \brief Build a member pointer type \c T Class::*. 838/// 839/// \param T the type to which the member pointer refers. 840/// \param Class the class type into which the member pointer points. 841/// \param CVR Qualifiers applied to the member pointer type 842/// \param Loc the location where this type begins 843/// \param Entity the name of the entity that will have this member pointer type 844/// 845/// \returns a member pointer type, if successful, or a NULL type if there was 846/// an error. 847QualType Sema::BuildMemberPointerType(QualType T, QualType Class, 848 unsigned CVR, SourceLocation Loc, 849 DeclarationName Entity) { 850 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 851 852 // Verify that we're not building a pointer to pointer to function with 853 // exception specification. 854 if (CheckDistantExceptionSpec(T)) { 855 Diag(Loc, diag::err_distant_exception_spec); 856 857 // FIXME: If we're doing this as part of template instantiation, 858 // we should return immediately. 859 860 // Build the type anyway, but use the canonical type so that the 861 // exception specifiers are stripped off. 862 T = Context.getCanonicalType(T); 863 } 864 865 // C++ 8.3.3p3: A pointer to member shall not pointer to ... a member 866 // with reference type, or "cv void." 867 if (T->isReferenceType()) { 868 Diag(Loc, diag::err_illegal_decl_mempointer_to_reference) 869 << (Entity? Entity.getAsString() : "type name") << T; 870 return QualType(); 871 } 872 873 if (T->isVoidType()) { 874 Diag(Loc, diag::err_illegal_decl_mempointer_to_void) 875 << (Entity? Entity.getAsString() : "type name"); 876 return QualType(); 877 } 878 879 // Enforce C99 6.7.3p2: "Types other than pointer types derived from 880 // object or incomplete types shall not be restrict-qualified." 881 if (Quals.hasRestrict() && !T->isIncompleteOrObjectType()) { 882 Diag(Loc, diag::err_typecheck_invalid_restrict_invalid_pointee) 883 << T; 884 885 // FIXME: If we're doing this as part of template instantiation, 886 // we should return immediately. 887 Quals.removeRestrict(); 888 } 889 890 if (!Class->isDependentType() && !Class->isRecordType()) { 891 Diag(Loc, diag::err_mempointer_in_nonclass_type) << Class; 892 return QualType(); 893 } 894 895 return Context.getQualifiedType( 896 Context.getMemberPointerType(T, Class.getTypePtr()), Quals); 897} 898 899/// \brief Build a block pointer type. 900/// 901/// \param T The type to which we'll be building a block pointer. 902/// 903/// \param CVR The cvr-qualifiers to be applied to the block pointer type. 904/// 905/// \param Loc The location of the entity whose type involves this 906/// block pointer type or, if there is no such entity, the location of the 907/// type that will have block pointer type. 908/// 909/// \param Entity The name of the entity that involves the block pointer 910/// type, if known. 911/// 912/// \returns A suitable block pointer type, if there are no 913/// errors. Otherwise, returns a NULL type. 914QualType Sema::BuildBlockPointerType(QualType T, unsigned CVR, 915 SourceLocation Loc, 916 DeclarationName Entity) { 917 if (!T->isFunctionType()) { 918 Diag(Loc, diag::err_nonfunction_block_type); 919 return QualType(); 920 } 921 922 Qualifiers Quals = Qualifiers::fromCVRMask(CVR); 923 return Context.getQualifiedType(Context.getBlockPointerType(T), Quals); 924} 925 926QualType Sema::GetTypeFromParser(TypeTy *Ty, TypeSourceInfo **TInfo) { 927 QualType QT = QualType::getFromOpaquePtr(Ty); 928 if (QT.isNull()) { 929 if (TInfo) *TInfo = 0; 930 return QualType(); 931 } 932 933 TypeSourceInfo *DI = 0; 934 if (LocInfoType *LIT = dyn_cast<LocInfoType>(QT)) { 935 QT = LIT->getType(); 936 DI = LIT->getTypeSourceInfo(); 937 } 938 939 if (TInfo) *TInfo = DI; 940 return QT; 941} 942 943/// GetTypeForDeclarator - Convert the type for the specified 944/// declarator to Type instances. 945/// 946/// If OwnedDecl is non-NULL, and this declarator's decl-specifier-seq 947/// owns the declaration of a type (e.g., the definition of a struct 948/// type), then *OwnedDecl will receive the owned declaration. 949QualType Sema::GetTypeForDeclarator(Declarator &D, Scope *S, 950 TypeSourceInfo **TInfo, 951 TagDecl **OwnedDecl) { 952 // Determine the type of the declarator. Not all forms of declarator 953 // have a type. 954 QualType T; 955 TypeSourceInfo *ReturnTypeInfo = 0; 956 957 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromDeclSpec; 958 959 switch (D.getName().getKind()) { 960 case UnqualifiedId::IK_Identifier: 961 case UnqualifiedId::IK_OperatorFunctionId: 962 case UnqualifiedId::IK_LiteralOperatorId: 963 case UnqualifiedId::IK_TemplateId: 964 T = ConvertDeclSpecToType(*this, D, FnAttrsFromDeclSpec); 965 966 if (!D.isInvalidType() && D.getDeclSpec().isTypeSpecOwned()) { 967 TagDecl* Owned = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 968 // Owned is embedded if it was defined here, or if it is the 969 // very first (i.e., canonical) declaration of this tag type. 970 Owned->setEmbeddedInDeclarator(Owned->isDefinition() || 971 Owned->isCanonicalDecl()); 972 if (OwnedDecl) *OwnedDecl = Owned; 973 } 974 break; 975 976 case UnqualifiedId::IK_ConstructorName: 977 case UnqualifiedId::IK_ConstructorTemplateId: 978 case UnqualifiedId::IK_DestructorName: 979 // Constructors and destructors don't have return types. Use 980 // "void" instead. 981 T = Context.VoidTy; 982 983 if (TInfo) 984 ReturnTypeInfo = Context.getTrivialTypeSourceInfo(T, 985 D.getName().StartLocation); 986 break; 987 988 case UnqualifiedId::IK_ConversionFunctionId: 989 // The result type of a conversion function is the type that it 990 // converts to. 991 T = GetTypeFromParser(D.getName().ConversionFunctionId, 992 TInfo? &ReturnTypeInfo : 0); 993 break; 994 } 995 996 if (T.isNull()) 997 return T; 998 999 if (T == Context.UndeducedAutoTy) { 1000 int Error = -1; 1001 1002 switch (D.getContext()) { 1003 case Declarator::KNRTypeListContext: 1004 assert(0 && "K&R type lists aren't allowed in C++"); 1005 break; 1006 case Declarator::PrototypeContext: 1007 Error = 0; // Function prototype 1008 break; 1009 case Declarator::MemberContext: 1010 switch (cast<TagDecl>(CurContext)->getTagKind()) { 1011 case TTK_Enum: assert(0 && "unhandled tag kind"); break; 1012 case TTK_Struct: Error = 1; /* Struct member */ break; 1013 case TTK_Union: Error = 2; /* Union member */ break; 1014 case TTK_Class: Error = 3; /* Class member */ break; 1015 } 1016 break; 1017 case Declarator::CXXCatchContext: 1018 Error = 4; // Exception declaration 1019 break; 1020 case Declarator::TemplateParamContext: 1021 Error = 5; // Template parameter 1022 break; 1023 case Declarator::BlockLiteralContext: 1024 Error = 6; // Block literal 1025 break; 1026 case Declarator::FileContext: 1027 case Declarator::BlockContext: 1028 case Declarator::ForContext: 1029 case Declarator::ConditionContext: 1030 case Declarator::TypeNameContext: 1031 break; 1032 } 1033 1034 if (Error != -1) { 1035 Diag(D.getDeclSpec().getTypeSpecTypeLoc(), diag::err_auto_not_allowed) 1036 << Error; 1037 T = Context.IntTy; 1038 D.setInvalidType(true); 1039 } 1040 } 1041 1042 // The name we're declaring, if any. 1043 DeclarationName Name; 1044 if (D.getIdentifier()) 1045 Name = D.getIdentifier(); 1046 1047 llvm::SmallVector<DelayedAttribute,4> FnAttrsFromPreviousChunk; 1048 1049 // Walk the DeclTypeInfo, building the recursive type as we go. 1050 // DeclTypeInfos are ordered from the identifier out, which is 1051 // opposite of what we want :). 1052 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1053 DeclaratorChunk &DeclType = D.getTypeObject(e-i-1); 1054 switch (DeclType.Kind) { 1055 default: assert(0 && "Unknown decltype!"); 1056 case DeclaratorChunk::BlockPointer: 1057 // If blocks are disabled, emit an error. 1058 if (!LangOpts.Blocks) 1059 Diag(DeclType.Loc, diag::err_blocks_disable); 1060 1061 T = BuildBlockPointerType(T, DeclType.Cls.TypeQuals, D.getIdentifierLoc(), 1062 Name); 1063 break; 1064 case DeclaratorChunk::Pointer: 1065 // Verify that we're not building a pointer to pointer to function with 1066 // exception specification. 1067 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1068 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1069 D.setInvalidType(true); 1070 // Build the type anyway. 1071 } 1072 if (getLangOptions().ObjC1 && T->getAs<ObjCObjectType>()) { 1073 T = Context.getObjCObjectPointerType(T); 1074 T = Context.getCVRQualifiedType(T, DeclType.Ptr.TypeQuals); 1075 break; 1076 } 1077 T = BuildPointerType(T, DeclType.Ptr.TypeQuals, DeclType.Loc, Name); 1078 break; 1079 case DeclaratorChunk::Reference: { 1080 Qualifiers Quals; 1081 if (DeclType.Ref.HasRestrict) Quals.addRestrict(); 1082 1083 // Verify that we're not building a reference to pointer to function with 1084 // exception specification. 1085 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1086 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1087 D.setInvalidType(true); 1088 // Build the type anyway. 1089 } 1090 T = BuildReferenceType(T, DeclType.Ref.LValueRef, Quals, 1091 DeclType.Loc, Name); 1092 break; 1093 } 1094 case DeclaratorChunk::Array: { 1095 // Verify that we're not building an array of pointers to function with 1096 // exception specification. 1097 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1098 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1099 D.setInvalidType(true); 1100 // Build the type anyway. 1101 } 1102 DeclaratorChunk::ArrayTypeInfo &ATI = DeclType.Arr; 1103 Expr *ArraySize = static_cast<Expr*>(ATI.NumElts); 1104 ArrayType::ArraySizeModifier ASM; 1105 if (ATI.isStar) 1106 ASM = ArrayType::Star; 1107 else if (ATI.hasStatic) 1108 ASM = ArrayType::Static; 1109 else 1110 ASM = ArrayType::Normal; 1111 if (ASM == ArrayType::Star && 1112 D.getContext() != Declarator::PrototypeContext) { 1113 // FIXME: This check isn't quite right: it allows star in prototypes 1114 // for function definitions, and disallows some edge cases detailed 1115 // in http://gcc.gnu.org/ml/gcc-patches/2009-02/msg00133.html 1116 Diag(DeclType.Loc, diag::err_array_star_outside_prototype); 1117 ASM = ArrayType::Normal; 1118 D.setInvalidType(true); 1119 } 1120 T = BuildArrayType(T, ASM, ArraySize, 1121 Qualifiers::fromCVRMask(ATI.TypeQuals), 1122 SourceRange(DeclType.Loc, DeclType.EndLoc), Name); 1123 break; 1124 } 1125 case DeclaratorChunk::Function: { 1126 // If the function declarator has a prototype (i.e. it is not () and 1127 // does not have a K&R-style identifier list), then the arguments are part 1128 // of the type, otherwise the argument list is (). 1129 const DeclaratorChunk::FunctionTypeInfo &FTI = DeclType.Fun; 1130 1131 // C99 6.7.5.3p1: The return type may not be a function or array type. 1132 // For conversion functions, we'll diagnose this particular error later. 1133 if ((T->isArrayType() || T->isFunctionType()) && 1134 (D.getName().getKind() != UnqualifiedId::IK_ConversionFunctionId)) { 1135 Diag(DeclType.Loc, diag::err_func_returning_array_function) 1136 << T->isFunctionType() << T; 1137 T = Context.IntTy; 1138 D.setInvalidType(true); 1139 } 1140 1141 if (getLangOptions().CPlusPlus && D.getDeclSpec().isTypeSpecOwned()) { 1142 // C++ [dcl.fct]p6: 1143 // Types shall not be defined in return or parameter types. 1144 TagDecl *Tag = cast<TagDecl>((Decl *)D.getDeclSpec().getTypeRep()); 1145 if (Tag->isDefinition()) 1146 Diag(Tag->getLocation(), diag::err_type_defined_in_result_type) 1147 << Context.getTypeDeclType(Tag); 1148 } 1149 1150 // Exception specs are not allowed in typedefs. Complain, but add it 1151 // anyway. 1152 if (FTI.hasExceptionSpec && 1153 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) 1154 Diag(FTI.getThrowLoc(), diag::err_exception_spec_in_typedef); 1155 1156 if (FTI.NumArgs == 0) { 1157 if (getLangOptions().CPlusPlus) { 1158 // C++ 8.3.5p2: If the parameter-declaration-clause is empty, the 1159 // function takes no arguments. 1160 llvm::SmallVector<QualType, 4> Exceptions; 1161 Exceptions.reserve(FTI.NumExceptions); 1162 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1163 // FIXME: Preserve type source info. 1164 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1165 // Check that the type is valid for an exception spec, and drop it 1166 // if not. 1167 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1168 Exceptions.push_back(ET); 1169 } 1170 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, FTI.TypeQuals, 1171 FTI.hasExceptionSpec, 1172 FTI.hasAnyExceptionSpec, 1173 Exceptions.size(), Exceptions.data(), 1174 FunctionType::ExtInfo()); 1175 } else if (FTI.isVariadic) { 1176 // We allow a zero-parameter variadic function in C if the 1177 // function is marked with the "overloadable" 1178 // attribute. Scan for this attribute now. 1179 bool Overloadable = false; 1180 for (const AttributeList *Attrs = D.getAttributes(); 1181 Attrs; Attrs = Attrs->getNext()) { 1182 if (Attrs->getKind() == AttributeList::AT_overloadable) { 1183 Overloadable = true; 1184 break; 1185 } 1186 } 1187 1188 if (!Overloadable) 1189 Diag(FTI.getEllipsisLoc(), diag::err_ellipsis_first_arg); 1190 T = Context.getFunctionType(T, NULL, 0, FTI.isVariadic, 0, 1191 false, false, 0, 0, 1192 FunctionType::ExtInfo()); 1193 } else { 1194 // Simple void foo(), where the incoming T is the result type. 1195 T = Context.getFunctionNoProtoType(T); 1196 } 1197 } else if (FTI.ArgInfo[0].Param == 0) { 1198 // C99 6.7.5.3p3: Reject int(x,y,z) when it's not a function definition. 1199 Diag(FTI.ArgInfo[0].IdentLoc, diag::err_ident_list_in_fn_declaration); 1200 D.setInvalidType(true); 1201 } else { 1202 // Otherwise, we have a function with an argument list that is 1203 // potentially variadic. 1204 llvm::SmallVector<QualType, 16> ArgTys; 1205 1206 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) { 1207 ParmVarDecl *Param = 1208 cast<ParmVarDecl>(FTI.ArgInfo[i].Param.getAs<Decl>()); 1209 QualType ArgTy = Param->getType(); 1210 assert(!ArgTy.isNull() && "Couldn't parse type?"); 1211 1212 // Adjust the parameter type. 1213 assert((ArgTy == adjustParameterType(ArgTy)) && "Unadjusted type?"); 1214 1215 // Look for 'void'. void is allowed only as a single argument to a 1216 // function with no other parameters (C99 6.7.5.3p10). We record 1217 // int(void) as a FunctionProtoType with an empty argument list. 1218 if (ArgTy->isVoidType()) { 1219 // If this is something like 'float(int, void)', reject it. 'void' 1220 // is an incomplete type (C99 6.2.5p19) and function decls cannot 1221 // have arguments of incomplete type. 1222 if (FTI.NumArgs != 1 || FTI.isVariadic) { 1223 Diag(DeclType.Loc, diag::err_void_only_param); 1224 ArgTy = Context.IntTy; 1225 Param->setType(ArgTy); 1226 } else if (FTI.ArgInfo[i].Ident) { 1227 // Reject, but continue to parse 'int(void abc)'. 1228 Diag(FTI.ArgInfo[i].IdentLoc, 1229 diag::err_param_with_void_type); 1230 ArgTy = Context.IntTy; 1231 Param->setType(ArgTy); 1232 } else { 1233 // Reject, but continue to parse 'float(const void)'. 1234 if (ArgTy.hasQualifiers()) 1235 Diag(DeclType.Loc, diag::err_void_param_qualified); 1236 1237 // Do not add 'void' to the ArgTys list. 1238 break; 1239 } 1240 } else if (!FTI.hasPrototype) { 1241 if (ArgTy->isPromotableIntegerType()) { 1242 ArgTy = Context.getPromotedIntegerType(ArgTy); 1243 } else if (const BuiltinType* BTy = ArgTy->getAs<BuiltinType>()) { 1244 if (BTy->getKind() == BuiltinType::Float) 1245 ArgTy = Context.DoubleTy; 1246 } 1247 } 1248 1249 ArgTys.push_back(ArgTy); 1250 } 1251 1252 llvm::SmallVector<QualType, 4> Exceptions; 1253 Exceptions.reserve(FTI.NumExceptions); 1254 for (unsigned ei = 0, ee = FTI.NumExceptions; ei != ee; ++ei) { 1255 // FIXME: Preserve type source info. 1256 QualType ET = GetTypeFromParser(FTI.Exceptions[ei].Ty); 1257 // Check that the type is valid for an exception spec, and drop it if 1258 // not. 1259 if (!CheckSpecifiedExceptionType(ET, FTI.Exceptions[ei].Range)) 1260 Exceptions.push_back(ET); 1261 } 1262 1263 T = Context.getFunctionType(T, ArgTys.data(), ArgTys.size(), 1264 FTI.isVariadic, FTI.TypeQuals, 1265 FTI.hasExceptionSpec, 1266 FTI.hasAnyExceptionSpec, 1267 Exceptions.size(), Exceptions.data(), 1268 FunctionType::ExtInfo()); 1269 } 1270 1271 // For GCC compatibility, we allow attributes that apply only to 1272 // function types to be placed on a function's return type 1273 // instead (as long as that type doesn't happen to be function 1274 // or function-pointer itself). 1275 ProcessDelayedFnAttrs(*this, T, FnAttrsFromPreviousChunk); 1276 1277 break; 1278 } 1279 case DeclaratorChunk::MemberPointer: 1280 // Verify that we're not building a pointer to pointer to function with 1281 // exception specification. 1282 if (getLangOptions().CPlusPlus && CheckDistantExceptionSpec(T)) { 1283 Diag(D.getIdentifierLoc(), diag::err_distant_exception_spec); 1284 D.setInvalidType(true); 1285 // Build the type anyway. 1286 } 1287 // The scope spec must refer to a class, or be dependent. 1288 QualType ClsType; 1289 if (DeclType.Mem.Scope().isInvalid()) { 1290 // Avoid emitting extra errors if we already errored on the scope. 1291 D.setInvalidType(true); 1292 } else if (isDependentScopeSpecifier(DeclType.Mem.Scope()) 1293 || dyn_cast_or_null<CXXRecordDecl>( 1294 computeDeclContext(DeclType.Mem.Scope()))) { 1295 NestedNameSpecifier *NNS 1296 = (NestedNameSpecifier *)DeclType.Mem.Scope().getScopeRep(); 1297 NestedNameSpecifier *NNSPrefix = NNS->getPrefix(); 1298 switch (NNS->getKind()) { 1299 case NestedNameSpecifier::Identifier: 1300 ClsType = Context.getDependentNameType(ETK_None, NNSPrefix, 1301 NNS->getAsIdentifier()); 1302 break; 1303 1304 case NestedNameSpecifier::Namespace: 1305 case NestedNameSpecifier::Global: 1306 llvm_unreachable("Nested-name-specifier must name a type"); 1307 break; 1308 1309 case NestedNameSpecifier::TypeSpec: 1310 case NestedNameSpecifier::TypeSpecWithTemplate: 1311 ClsType = QualType(NNS->getAsType(), 0); 1312 if (NNSPrefix) 1313 ClsType = Context.getElaboratedType(ETK_None, NNSPrefix, ClsType); 1314 break; 1315 } 1316 } else { 1317 Diag(DeclType.Mem.Scope().getBeginLoc(), 1318 diag::err_illegal_decl_mempointer_in_nonclass) 1319 << (D.getIdentifier() ? D.getIdentifier()->getName() : "type name") 1320 << DeclType.Mem.Scope().getRange(); 1321 D.setInvalidType(true); 1322 } 1323 1324 if (!ClsType.isNull()) 1325 T = BuildMemberPointerType(T, ClsType, DeclType.Mem.TypeQuals, 1326 DeclType.Loc, D.getIdentifier()); 1327 if (T.isNull()) { 1328 T = Context.IntTy; 1329 D.setInvalidType(true); 1330 } 1331 break; 1332 } 1333 1334 if (T.isNull()) { 1335 D.setInvalidType(true); 1336 T = Context.IntTy; 1337 } 1338 1339 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1340 1341 // See if there are any attributes on this declarator chunk. 1342 if (const AttributeList *AL = DeclType.getAttrs()) 1343 ProcessTypeAttributeList(*this, T, false, AL, FnAttrsFromPreviousChunk); 1344 } 1345 1346 if (getLangOptions().CPlusPlus && T->isFunctionType()) { 1347 const FunctionProtoType *FnTy = T->getAs<FunctionProtoType>(); 1348 assert(FnTy && "Why oh why is there not a FunctionProtoType here?"); 1349 1350 // C++ 8.3.5p4: A cv-qualifier-seq shall only be part of the function type 1351 // for a nonstatic member function, the function type to which a pointer 1352 // to member refers, or the top-level function type of a function typedef 1353 // declaration. 1354 if (FnTy->getTypeQuals() != 0 && 1355 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef && 1356 ((D.getContext() != Declarator::MemberContext && 1357 (!D.getCXXScopeSpec().isSet() || 1358 !computeDeclContext(D.getCXXScopeSpec(), /*FIXME:*/true) 1359 ->isRecord())) || 1360 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static)) { 1361 if (D.isFunctionDeclarator()) 1362 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_function_type); 1363 else 1364 Diag(D.getIdentifierLoc(), 1365 diag::err_invalid_qualified_typedef_function_type_use); 1366 1367 // Strip the cv-quals from the type. 1368 T = Context.getFunctionType(FnTy->getResultType(), FnTy->arg_type_begin(), 1369 FnTy->getNumArgs(), FnTy->isVariadic(), 0, 1370 false, false, 0, 0, FunctionType::ExtInfo()); 1371 } 1372 } 1373 1374 // Process any function attributes we might have delayed from the 1375 // declaration-specifiers. 1376 ProcessDelayedFnAttrs(*this, T, FnAttrsFromDeclSpec); 1377 1378 // If there were any type attributes applied to the decl itself, not 1379 // the type, apply them to the result type. But don't do this for 1380 // block-literal expressions, which are parsed wierdly. 1381 if (D.getContext() != Declarator::BlockLiteralContext) 1382 if (const AttributeList *Attrs = D.getAttributes()) 1383 ProcessTypeAttributeList(*this, T, false, Attrs, 1384 FnAttrsFromPreviousChunk); 1385 1386 DiagnoseDelayedFnAttrs(*this, FnAttrsFromPreviousChunk); 1387 1388 if (TInfo) { 1389 if (D.isInvalidType()) 1390 *TInfo = 0; 1391 else 1392 *TInfo = GetTypeSourceInfoForDeclarator(D, T, ReturnTypeInfo); 1393 } 1394 1395 return T; 1396} 1397 1398namespace { 1399 class TypeSpecLocFiller : public TypeLocVisitor<TypeSpecLocFiller> { 1400 const DeclSpec &DS; 1401 1402 public: 1403 TypeSpecLocFiller(const DeclSpec &DS) : DS(DS) {} 1404 1405 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1406 Visit(TL.getUnqualifiedLoc()); 1407 } 1408 void VisitTypedefTypeLoc(TypedefTypeLoc TL) { 1409 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1410 } 1411 void VisitObjCInterfaceTypeLoc(ObjCInterfaceTypeLoc TL) { 1412 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1413 } 1414 void VisitObjCObjectTypeLoc(ObjCObjectTypeLoc TL) { 1415 // Handle the base type, which might not have been written explicitly. 1416 if (DS.getTypeSpecType() == DeclSpec::TST_unspecified) { 1417 TL.setHasBaseTypeAsWritten(false); 1418 TL.getBaseLoc().initialize(SourceLocation()); 1419 } else { 1420 TL.setHasBaseTypeAsWritten(true); 1421 Visit(TL.getBaseLoc()); 1422 } 1423 1424 // Protocol qualifiers. 1425 if (DS.getProtocolQualifiers()) { 1426 assert(TL.getNumProtocols() > 0); 1427 assert(TL.getNumProtocols() == DS.getNumProtocolQualifiers()); 1428 TL.setLAngleLoc(DS.getProtocolLAngleLoc()); 1429 TL.setRAngleLoc(DS.getSourceRange().getEnd()); 1430 for (unsigned i = 0, e = DS.getNumProtocolQualifiers(); i != e; ++i) 1431 TL.setProtocolLoc(i, DS.getProtocolLocs()[i]); 1432 } else { 1433 assert(TL.getNumProtocols() == 0); 1434 TL.setLAngleLoc(SourceLocation()); 1435 TL.setRAngleLoc(SourceLocation()); 1436 } 1437 } 1438 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1439 TL.setStarLoc(SourceLocation()); 1440 Visit(TL.getPointeeLoc()); 1441 } 1442 void VisitTemplateSpecializationTypeLoc(TemplateSpecializationTypeLoc TL) { 1443 TypeSourceInfo *TInfo = 0; 1444 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1445 1446 // If we got no declarator info from previous Sema routines, 1447 // just fill with the typespec loc. 1448 if (!TInfo) { 1449 TL.initialize(DS.getTypeSpecTypeLoc()); 1450 return; 1451 } 1452 1453 TypeLoc OldTL = TInfo->getTypeLoc(); 1454 if (TInfo->getType()->getAs<ElaboratedType>()) { 1455 ElaboratedTypeLoc ElabTL = cast<ElaboratedTypeLoc>(OldTL); 1456 TemplateSpecializationTypeLoc NamedTL = 1457 cast<TemplateSpecializationTypeLoc>(ElabTL.getNamedTypeLoc()); 1458 TL.copy(NamedTL); 1459 } 1460 else 1461 TL.copy(cast<TemplateSpecializationTypeLoc>(OldTL)); 1462 } 1463 void VisitTypeOfExprTypeLoc(TypeOfExprTypeLoc TL) { 1464 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofExpr); 1465 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1466 TL.setParensRange(DS.getTypeofParensRange()); 1467 } 1468 void VisitTypeOfTypeLoc(TypeOfTypeLoc TL) { 1469 assert(DS.getTypeSpecType() == DeclSpec::TST_typeofType); 1470 TL.setTypeofLoc(DS.getTypeSpecTypeLoc()); 1471 TL.setParensRange(DS.getTypeofParensRange()); 1472 assert(DS.getTypeRep()); 1473 TypeSourceInfo *TInfo = 0; 1474 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1475 TL.setUnderlyingTInfo(TInfo); 1476 } 1477 void VisitBuiltinTypeLoc(BuiltinTypeLoc TL) { 1478 // By default, use the source location of the type specifier. 1479 TL.setBuiltinLoc(DS.getTypeSpecTypeLoc()); 1480 if (TL.needsExtraLocalData()) { 1481 // Set info for the written builtin specifiers. 1482 TL.getWrittenBuiltinSpecs() = DS.getWrittenBuiltinSpecs(); 1483 // Try to have a meaningful source location. 1484 if (TL.getWrittenSignSpec() != TSS_unspecified) 1485 // Sign spec loc overrides the others (e.g., 'unsigned long'). 1486 TL.setBuiltinLoc(DS.getTypeSpecSignLoc()); 1487 else if (TL.getWrittenWidthSpec() != TSW_unspecified) 1488 // Width spec loc overrides type spec loc (e.g., 'short int'). 1489 TL.setBuiltinLoc(DS.getTypeSpecWidthLoc()); 1490 } 1491 } 1492 void VisitElaboratedTypeLoc(ElaboratedTypeLoc TL) { 1493 ElaboratedTypeKeyword Keyword 1494 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 1495 if (Keyword == ETK_Typename) { 1496 TypeSourceInfo *TInfo = 0; 1497 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1498 if (TInfo) { 1499 TL.copy(cast<ElaboratedTypeLoc>(TInfo->getTypeLoc())); 1500 return; 1501 } 1502 } 1503 TL.setKeywordLoc(Keyword != ETK_None 1504 ? DS.getTypeSpecTypeLoc() 1505 : SourceLocation()); 1506 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 1507 TL.setQualifierRange(SS.isEmpty() ? SourceRange(): SS.getRange()); 1508 Visit(TL.getNextTypeLoc().getUnqualifiedLoc()); 1509 } 1510 void VisitDependentNameTypeLoc(DependentNameTypeLoc TL) { 1511 ElaboratedTypeKeyword Keyword 1512 = TypeWithKeyword::getKeywordForTypeSpec(DS.getTypeSpecType()); 1513 if (Keyword == ETK_Typename) { 1514 TypeSourceInfo *TInfo = 0; 1515 Sema::GetTypeFromParser(DS.getTypeRep(), &TInfo); 1516 if (TInfo) { 1517 TL.copy(cast<DependentNameTypeLoc>(TInfo->getTypeLoc())); 1518 return; 1519 } 1520 } 1521 TL.setKeywordLoc(Keyword != ETK_None 1522 ? DS.getTypeSpecTypeLoc() 1523 : SourceLocation()); 1524 const CXXScopeSpec& SS = DS.getTypeSpecScope(); 1525 TL.setQualifierRange(SS.isEmpty() ? SourceRange() : SS.getRange()); 1526 // FIXME: load appropriate source location. 1527 TL.setNameLoc(DS.getTypeSpecTypeLoc()); 1528 } 1529 1530 void VisitTypeLoc(TypeLoc TL) { 1531 // FIXME: add other typespec types and change this to an assert. 1532 TL.initialize(DS.getTypeSpecTypeLoc()); 1533 } 1534 }; 1535 1536 class DeclaratorLocFiller : public TypeLocVisitor<DeclaratorLocFiller> { 1537 const DeclaratorChunk &Chunk; 1538 1539 public: 1540 DeclaratorLocFiller(const DeclaratorChunk &Chunk) : Chunk(Chunk) {} 1541 1542 void VisitQualifiedTypeLoc(QualifiedTypeLoc TL) { 1543 llvm_unreachable("qualified type locs not expected here!"); 1544 } 1545 1546 void VisitBlockPointerTypeLoc(BlockPointerTypeLoc TL) { 1547 assert(Chunk.Kind == DeclaratorChunk::BlockPointer); 1548 TL.setCaretLoc(Chunk.Loc); 1549 } 1550 void VisitPointerTypeLoc(PointerTypeLoc TL) { 1551 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1552 TL.setStarLoc(Chunk.Loc); 1553 } 1554 void VisitObjCObjectPointerTypeLoc(ObjCObjectPointerTypeLoc TL) { 1555 assert(Chunk.Kind == DeclaratorChunk::Pointer); 1556 TL.setStarLoc(Chunk.Loc); 1557 } 1558 void VisitMemberPointerTypeLoc(MemberPointerTypeLoc TL) { 1559 assert(Chunk.Kind == DeclaratorChunk::MemberPointer); 1560 TL.setStarLoc(Chunk.Loc); 1561 // FIXME: nested name specifier 1562 } 1563 void VisitLValueReferenceTypeLoc(LValueReferenceTypeLoc TL) { 1564 assert(Chunk.Kind == DeclaratorChunk::Reference); 1565 // 'Amp' is misleading: this might have been originally 1566 /// spelled with AmpAmp. 1567 TL.setAmpLoc(Chunk.Loc); 1568 } 1569 void VisitRValueReferenceTypeLoc(RValueReferenceTypeLoc TL) { 1570 assert(Chunk.Kind == DeclaratorChunk::Reference); 1571 assert(!Chunk.Ref.LValueRef); 1572 TL.setAmpAmpLoc(Chunk.Loc); 1573 } 1574 void VisitArrayTypeLoc(ArrayTypeLoc TL) { 1575 assert(Chunk.Kind == DeclaratorChunk::Array); 1576 TL.setLBracketLoc(Chunk.Loc); 1577 TL.setRBracketLoc(Chunk.EndLoc); 1578 TL.setSizeExpr(static_cast<Expr*>(Chunk.Arr.NumElts)); 1579 } 1580 void VisitFunctionTypeLoc(FunctionTypeLoc TL) { 1581 assert(Chunk.Kind == DeclaratorChunk::Function); 1582 TL.setLParenLoc(Chunk.Loc); 1583 TL.setRParenLoc(Chunk.EndLoc); 1584 1585 const DeclaratorChunk::FunctionTypeInfo &FTI = Chunk.Fun; 1586 for (unsigned i = 0, e = TL.getNumArgs(), tpi = 0; i != e; ++i) { 1587 ParmVarDecl *Param = FTI.ArgInfo[i].Param.getAs<ParmVarDecl>(); 1588 TL.setArg(tpi++, Param); 1589 } 1590 // FIXME: exception specs 1591 } 1592 1593 void VisitTypeLoc(TypeLoc TL) { 1594 llvm_unreachable("unsupported TypeLoc kind in declarator!"); 1595 } 1596 }; 1597} 1598 1599/// \brief Create and instantiate a TypeSourceInfo with type source information. 1600/// 1601/// \param T QualType referring to the type as written in source code. 1602/// 1603/// \param ReturnTypeInfo For declarators whose return type does not show 1604/// up in the normal place in the declaration specifiers (such as a C++ 1605/// conversion function), this pointer will refer to a type source information 1606/// for that return type. 1607TypeSourceInfo * 1608Sema::GetTypeSourceInfoForDeclarator(Declarator &D, QualType T, 1609 TypeSourceInfo *ReturnTypeInfo) { 1610 TypeSourceInfo *TInfo = Context.CreateTypeSourceInfo(T); 1611 UnqualTypeLoc CurrTL = TInfo->getTypeLoc().getUnqualifiedLoc(); 1612 1613 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) { 1614 DeclaratorLocFiller(D.getTypeObject(i)).Visit(CurrTL); 1615 CurrTL = CurrTL.getNextTypeLoc().getUnqualifiedLoc(); 1616 } 1617 1618 TypeSpecLocFiller(D.getDeclSpec()).Visit(CurrTL); 1619 1620 // We have source information for the return type that was not in the 1621 // declaration specifiers; copy that information into the current type 1622 // location so that it will be retained. This occurs, for example, with 1623 // a C++ conversion function, where the return type occurs within the 1624 // declarator-id rather than in the declaration specifiers. 1625 if (ReturnTypeInfo && D.getDeclSpec().getTypeSpecType() == TST_unspecified) { 1626 TypeLoc TL = ReturnTypeInfo->getTypeLoc(); 1627 assert(TL.getFullDataSize() == CurrTL.getFullDataSize()); 1628 memcpy(CurrTL.getOpaqueData(), TL.getOpaqueData(), TL.getFullDataSize()); 1629 } 1630 1631 return TInfo; 1632} 1633 1634/// \brief Create a LocInfoType to hold the given QualType and TypeSourceInfo. 1635QualType Sema::CreateLocInfoType(QualType T, TypeSourceInfo *TInfo) { 1636 // FIXME: LocInfoTypes are "transient", only needed for passing to/from Parser 1637 // and Sema during declaration parsing. Try deallocating/caching them when 1638 // it's appropriate, instead of allocating them and keeping them around. 1639 LocInfoType *LocT = (LocInfoType*)BumpAlloc.Allocate(sizeof(LocInfoType), 8); 1640 new (LocT) LocInfoType(T, TInfo); 1641 assert(LocT->getTypeClass() != T->getTypeClass() && 1642 "LocInfoType's TypeClass conflicts with an existing Type class"); 1643 return QualType(LocT, 0); 1644} 1645 1646void LocInfoType::getAsStringInternal(std::string &Str, 1647 const PrintingPolicy &Policy) const { 1648 assert(false && "LocInfoType leaked into the type system; an opaque TypeTy*" 1649 " was used directly instead of getting the QualType through" 1650 " GetTypeFromParser"); 1651} 1652 1653/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 1654/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 1655/// they point to and return true. If T1 and T2 aren't pointer types 1656/// or pointer-to-member types, or if they are not similar at this 1657/// level, returns false and leaves T1 and T2 unchanged. Top-level 1658/// qualifiers on T1 and T2 are ignored. This function will typically 1659/// be called in a loop that successively "unwraps" pointer and 1660/// pointer-to-member types to compare them at each level. 1661bool Sema::UnwrapSimilarPointerTypes(QualType& T1, QualType& T2) { 1662 const PointerType *T1PtrType = T1->getAs<PointerType>(), 1663 *T2PtrType = T2->getAs<PointerType>(); 1664 if (T1PtrType && T2PtrType) { 1665 T1 = T1PtrType->getPointeeType(); 1666 T2 = T2PtrType->getPointeeType(); 1667 return true; 1668 } 1669 1670 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 1671 *T2MPType = T2->getAs<MemberPointerType>(); 1672 if (T1MPType && T2MPType && 1673 Context.getCanonicalType(T1MPType->getClass()) == 1674 Context.getCanonicalType(T2MPType->getClass())) { 1675 T1 = T1MPType->getPointeeType(); 1676 T2 = T2MPType->getPointeeType(); 1677 return true; 1678 } 1679 1680 if (getLangOptions().ObjC1) { 1681 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 1682 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 1683 if (T1OPType && T2OPType) { 1684 T1 = T1OPType->getPointeeType(); 1685 T2 = T2OPType->getPointeeType(); 1686 return true; 1687 } 1688 } 1689 return false; 1690} 1691 1692Sema::TypeResult Sema::ActOnTypeName(Scope *S, Declarator &D) { 1693 // C99 6.7.6: Type names have no identifier. This is already validated by 1694 // the parser. 1695 assert(D.getIdentifier() == 0 && "Type name should have no identifier!"); 1696 1697 TypeSourceInfo *TInfo = 0; 1698 TagDecl *OwnedTag = 0; 1699 QualType T = GetTypeForDeclarator(D, S, &TInfo, &OwnedTag); 1700 if (D.isInvalidType()) 1701 return true; 1702 1703 if (getLangOptions().CPlusPlus) { 1704 // Check that there are no default arguments (C++ only). 1705 CheckExtraCXXDefaultArguments(D); 1706 1707 // C++0x [dcl.type]p3: 1708 // A type-specifier-seq shall not define a class or enumeration 1709 // unless it appears in the type-id of an alias-declaration 1710 // (7.1.3). 1711 if (OwnedTag && OwnedTag->isDefinition()) 1712 Diag(OwnedTag->getLocation(), diag::err_type_defined_in_type_specifier) 1713 << Context.getTypeDeclType(OwnedTag); 1714 } 1715 1716 if (TInfo) 1717 T = CreateLocInfoType(T, TInfo); 1718 1719 return T.getAsOpaquePtr(); 1720} 1721 1722 1723 1724//===----------------------------------------------------------------------===// 1725// Type Attribute Processing 1726//===----------------------------------------------------------------------===// 1727 1728/// HandleAddressSpaceTypeAttribute - Process an address_space attribute on the 1729/// specified type. The attribute contains 1 argument, the id of the address 1730/// space for the type. 1731static void HandleAddressSpaceTypeAttribute(QualType &Type, 1732 const AttributeList &Attr, Sema &S){ 1733 1734 // If this type is already address space qualified, reject it. 1735 // Clause 6.7.3 - Type qualifiers: "No type shall be qualified by qualifiers 1736 // for two or more different address spaces." 1737 if (Type.getAddressSpace()) { 1738 S.Diag(Attr.getLoc(), diag::err_attribute_address_multiple_qualifiers); 1739 Attr.setInvalid(); 1740 return; 1741 } 1742 1743 // Check the attribute arguments. 1744 if (Attr.getNumArgs() != 1) { 1745 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1746 Attr.setInvalid(); 1747 return; 1748 } 1749 Expr *ASArgExpr = static_cast<Expr *>(Attr.getArg(0)); 1750 llvm::APSInt addrSpace(32); 1751 if (ASArgExpr->isTypeDependent() || ASArgExpr->isValueDependent() || 1752 !ASArgExpr->isIntegerConstantExpr(addrSpace, S.Context)) { 1753 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_not_int) 1754 << ASArgExpr->getSourceRange(); 1755 Attr.setInvalid(); 1756 return; 1757 } 1758 1759 // Bounds checking. 1760 if (addrSpace.isSigned()) { 1761 if (addrSpace.isNegative()) { 1762 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_negative) 1763 << ASArgExpr->getSourceRange(); 1764 Attr.setInvalid(); 1765 return; 1766 } 1767 addrSpace.setIsSigned(false); 1768 } 1769 llvm::APSInt max(addrSpace.getBitWidth()); 1770 max = Qualifiers::MaxAddressSpace; 1771 if (addrSpace > max) { 1772 S.Diag(Attr.getLoc(), diag::err_attribute_address_space_too_high) 1773 << Qualifiers::MaxAddressSpace << ASArgExpr->getSourceRange(); 1774 Attr.setInvalid(); 1775 return; 1776 } 1777 1778 unsigned ASIdx = static_cast<unsigned>(addrSpace.getZExtValue()); 1779 Type = S.Context.getAddrSpaceQualType(Type, ASIdx); 1780} 1781 1782/// HandleObjCGCTypeAttribute - Process an objc's gc attribute on the 1783/// specified type. The attribute contains 1 argument, weak or strong. 1784static void HandleObjCGCTypeAttribute(QualType &Type, 1785 const AttributeList &Attr, Sema &S) { 1786 if (Type.getObjCGCAttr() != Qualifiers::GCNone) { 1787 S.Diag(Attr.getLoc(), diag::err_attribute_multiple_objc_gc); 1788 Attr.setInvalid(); 1789 return; 1790 } 1791 1792 // Check the attribute arguments. 1793 if (!Attr.getParameterName()) { 1794 S.Diag(Attr.getLoc(), diag::err_attribute_argument_n_not_string) 1795 << "objc_gc" << 1; 1796 Attr.setInvalid(); 1797 return; 1798 } 1799 Qualifiers::GC GCAttr; 1800 if (Attr.getNumArgs() != 0) { 1801 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1802 Attr.setInvalid(); 1803 return; 1804 } 1805 if (Attr.getParameterName()->isStr("weak")) 1806 GCAttr = Qualifiers::Weak; 1807 else if (Attr.getParameterName()->isStr("strong")) 1808 GCAttr = Qualifiers::Strong; 1809 else { 1810 S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported) 1811 << "objc_gc" << Attr.getParameterName(); 1812 Attr.setInvalid(); 1813 return; 1814 } 1815 1816 Type = S.Context.getObjCGCQualType(Type, GCAttr); 1817} 1818 1819/// Process an individual function attribute. Returns true if the 1820/// attribute does not make sense to apply to this type. 1821bool ProcessFnAttr(Sema &S, QualType &Type, const AttributeList &Attr) { 1822 if (Attr.getKind() == AttributeList::AT_noreturn) { 1823 // Complain immediately if the arg count is wrong. 1824 if (Attr.getNumArgs() != 0) { 1825 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1826 Attr.setInvalid(); 1827 return false; 1828 } 1829 1830 // Delay if this is not a function or pointer to block. 1831 if (!Type->isFunctionPointerType() 1832 && !Type->isBlockPointerType() 1833 && !Type->isFunctionType()) 1834 return true; 1835 1836 // Otherwise we can process right away. 1837 Type = S.Context.getNoReturnType(Type); 1838 return false; 1839 } 1840 1841 if (Attr.getKind() == AttributeList::AT_regparm) { 1842 // The warning is emitted elsewhere 1843 if (Attr.getNumArgs() != 1) { 1844 return false; 1845 } 1846 1847 // Delay if this is not a function or pointer to block. 1848 if (!Type->isFunctionPointerType() 1849 && !Type->isBlockPointerType() 1850 && !Type->isFunctionType()) 1851 return true; 1852 1853 // Otherwise we can process right away. 1854 Expr *NumParamsExpr = static_cast<Expr *>(Attr.getArg(0)); 1855 llvm::APSInt NumParams(32); 1856 1857 // The warning is emitted elsewhere 1858 if (NumParamsExpr->isTypeDependent() || NumParamsExpr->isValueDependent() || 1859 !NumParamsExpr->isIntegerConstantExpr(NumParams, S.Context)) 1860 return false; 1861 1862 Type = S.Context.getRegParmType(Type, NumParams.getZExtValue()); 1863 return false; 1864 } 1865 1866 // Otherwise, a calling convention. 1867 if (Attr.getNumArgs() != 0) { 1868 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 0; 1869 Attr.setInvalid(); 1870 return false; 1871 } 1872 1873 QualType T = Type; 1874 if (const PointerType *PT = Type->getAs<PointerType>()) 1875 T = PT->getPointeeType(); 1876 const FunctionType *Fn = T->getAs<FunctionType>(); 1877 1878 // Delay if the type didn't work out to a function. 1879 if (!Fn) return true; 1880 1881 // TODO: diagnose uses of these conventions on the wrong target. 1882 CallingConv CC; 1883 switch (Attr.getKind()) { 1884 case AttributeList::AT_cdecl: CC = CC_C; break; 1885 case AttributeList::AT_fastcall: CC = CC_X86FastCall; break; 1886 case AttributeList::AT_stdcall: CC = CC_X86StdCall; break; 1887 case AttributeList::AT_thiscall: CC = CC_X86ThisCall; break; 1888 default: llvm_unreachable("unexpected attribute kind"); return false; 1889 } 1890 1891 CallingConv CCOld = Fn->getCallConv(); 1892 if (S.Context.getCanonicalCallConv(CC) == 1893 S.Context.getCanonicalCallConv(CCOld)) { 1894 Attr.setInvalid(); 1895 return false; 1896 } 1897 1898 if (CCOld != CC_Default) { 1899 // Should we diagnose reapplications of the same convention? 1900 S.Diag(Attr.getLoc(), diag::err_attributes_are_not_compatible) 1901 << FunctionType::getNameForCallConv(CC) 1902 << FunctionType::getNameForCallConv(CCOld); 1903 Attr.setInvalid(); 1904 return false; 1905 } 1906 1907 // Diagnose the use of X86 fastcall on varargs or unprototyped functions. 1908 if (CC == CC_X86FastCall) { 1909 if (isa<FunctionNoProtoType>(Fn)) { 1910 S.Diag(Attr.getLoc(), diag::err_cconv_knr) 1911 << FunctionType::getNameForCallConv(CC); 1912 Attr.setInvalid(); 1913 return false; 1914 } 1915 1916 const FunctionProtoType *FnP = cast<FunctionProtoType>(Fn); 1917 if (FnP->isVariadic()) { 1918 S.Diag(Attr.getLoc(), diag::err_cconv_varargs) 1919 << FunctionType::getNameForCallConv(CC); 1920 Attr.setInvalid(); 1921 return false; 1922 } 1923 } 1924 1925 Type = S.Context.getCallConvType(Type, CC); 1926 return false; 1927} 1928 1929/// HandleVectorSizeAttribute - this attribute is only applicable to integral 1930/// and float scalars, although arrays, pointers, and function return values are 1931/// allowed in conjunction with this construct. Aggregates with this attribute 1932/// are invalid, even if they are of the same size as a corresponding scalar. 1933/// The raw attribute should contain precisely 1 argument, the vector size for 1934/// the variable, measured in bytes. If curType and rawAttr are well formed, 1935/// this routine will return a new vector type. 1936static void HandleVectorSizeAttr(QualType& CurType, const AttributeList &Attr, Sema &S) { 1937 // Check the attribute arugments. 1938 if (Attr.getNumArgs() != 1) { 1939 S.Diag(Attr.getLoc(), diag::err_attribute_wrong_number_arguments) << 1; 1940 Attr.setInvalid(); 1941 return; 1942 } 1943 Expr *sizeExpr = static_cast<Expr *>(Attr.getArg(0)); 1944 llvm::APSInt vecSize(32); 1945 if (sizeExpr->isTypeDependent() || sizeExpr->isValueDependent() || 1946 !sizeExpr->isIntegerConstantExpr(vecSize, S.Context)) { 1947 S.Diag(Attr.getLoc(), diag::err_attribute_argument_not_int) 1948 << "vector_size" << sizeExpr->getSourceRange(); 1949 Attr.setInvalid(); 1950 return; 1951 } 1952 // the base type must be integer or float, and can't already be a vector. 1953 if (CurType->isVectorType() || 1954 (!CurType->isIntegerType() && !CurType->isRealFloatingType())) { 1955 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_vector_type) << CurType; 1956 Attr.setInvalid(); 1957 return; 1958 } 1959 unsigned typeSize = static_cast<unsigned>(S.Context.getTypeSize(CurType)); 1960 // vecSize is specified in bytes - convert to bits. 1961 unsigned vectorSize = static_cast<unsigned>(vecSize.getZExtValue() * 8); 1962 1963 // the vector size needs to be an integral multiple of the type size. 1964 if (vectorSize % typeSize) { 1965 S.Diag(Attr.getLoc(), diag::err_attribute_invalid_size) 1966 << sizeExpr->getSourceRange(); 1967 Attr.setInvalid(); 1968 return; 1969 } 1970 if (vectorSize == 0) { 1971 S.Diag(Attr.getLoc(), diag::err_attribute_zero_size) 1972 << sizeExpr->getSourceRange(); 1973 Attr.setInvalid(); 1974 return; 1975 } 1976 1977 // Success! Instantiate the vector type, the number of elements is > 0, and 1978 // not required to be a power of 2, unlike GCC. 1979 CurType = S.Context.getVectorType(CurType, vectorSize/typeSize, false, false); 1980} 1981 1982void ProcessTypeAttributeList(Sema &S, QualType &Result, 1983 bool IsDeclSpec, const AttributeList *AL, 1984 DelayedAttributeSet &FnAttrs) { 1985 // Scan through and apply attributes to this type where it makes sense. Some 1986 // attributes (such as __address_space__, __vector_size__, etc) apply to the 1987 // type, but others can be present in the type specifiers even though they 1988 // apply to the decl. Here we apply type attributes and ignore the rest. 1989 for (; AL; AL = AL->getNext()) { 1990 // Skip attributes that were marked to be invalid. 1991 if (AL->isInvalid()) 1992 continue; 1993 1994 // If this is an attribute we can handle, do so now, 1995 // otherwise, add it to the FnAttrs list for rechaining. 1996 switch (AL->getKind()) { 1997 default: break; 1998 1999 case AttributeList::AT_address_space: 2000 HandleAddressSpaceTypeAttribute(Result, *AL, S); 2001 break; 2002 case AttributeList::AT_objc_gc: 2003 HandleObjCGCTypeAttribute(Result, *AL, S); 2004 break; 2005 case AttributeList::AT_vector_size: 2006 HandleVectorSizeAttr(Result, *AL, S); 2007 break; 2008 2009 case AttributeList::AT_noreturn: 2010 case AttributeList::AT_cdecl: 2011 case AttributeList::AT_fastcall: 2012 case AttributeList::AT_stdcall: 2013 case AttributeList::AT_thiscall: 2014 case AttributeList::AT_regparm: 2015 // Don't process these on the DeclSpec. 2016 if (IsDeclSpec || 2017 ProcessFnAttr(S, Result, *AL)) 2018 FnAttrs.push_back(DelayedAttribute(AL, Result)); 2019 break; 2020 } 2021 } 2022} 2023 2024/// @brief Ensure that the type T is a complete type. 2025/// 2026/// This routine checks whether the type @p T is complete in any 2027/// context where a complete type is required. If @p T is a complete 2028/// type, returns false. If @p T is a class template specialization, 2029/// this routine then attempts to perform class template 2030/// instantiation. If instantiation fails, or if @p T is incomplete 2031/// and cannot be completed, issues the diagnostic @p diag (giving it 2032/// the type @p T) and returns true. 2033/// 2034/// @param Loc The location in the source that the incomplete type 2035/// diagnostic should refer to. 2036/// 2037/// @param T The type that this routine is examining for completeness. 2038/// 2039/// @param PD The partial diagnostic that will be printed out if T is not a 2040/// complete type. 2041/// 2042/// @returns @c true if @p T is incomplete and a diagnostic was emitted, 2043/// @c false otherwise. 2044bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 2045 const PartialDiagnostic &PD, 2046 std::pair<SourceLocation, 2047 PartialDiagnostic> Note) { 2048 unsigned diag = PD.getDiagID(); 2049 2050 // FIXME: Add this assertion to make sure we always get instantiation points. 2051 // assert(!Loc.isInvalid() && "Invalid location in RequireCompleteType"); 2052 // FIXME: Add this assertion to help us flush out problems with 2053 // checking for dependent types and type-dependent expressions. 2054 // 2055 // assert(!T->isDependentType() && 2056 // "Can't ask whether a dependent type is complete"); 2057 2058 // If we have a complete type, we're done. 2059 if (!T->isIncompleteType()) 2060 return false; 2061 2062 // If we have a class template specialization or a class member of a 2063 // class template specialization, or an array with known size of such, 2064 // try to instantiate it. 2065 QualType MaybeTemplate = T; 2066 if (const ConstantArrayType *Array = Context.getAsConstantArrayType(T)) 2067 MaybeTemplate = Array->getElementType(); 2068 if (const RecordType *Record = MaybeTemplate->getAs<RecordType>()) { 2069 if (ClassTemplateSpecializationDecl *ClassTemplateSpec 2070 = dyn_cast<ClassTemplateSpecializationDecl>(Record->getDecl())) { 2071 if (ClassTemplateSpec->getSpecializationKind() == TSK_Undeclared) 2072 return InstantiateClassTemplateSpecialization(Loc, ClassTemplateSpec, 2073 TSK_ImplicitInstantiation, 2074 /*Complain=*/diag != 0); 2075 } else if (CXXRecordDecl *Rec 2076 = dyn_cast<CXXRecordDecl>(Record->getDecl())) { 2077 if (CXXRecordDecl *Pattern = Rec->getInstantiatedFromMemberClass()) { 2078 MemberSpecializationInfo *MSInfo = Rec->getMemberSpecializationInfo(); 2079 assert(MSInfo && "Missing member specialization information?"); 2080 // This record was instantiated from a class within a template. 2081 if (MSInfo->getTemplateSpecializationKind() 2082 != TSK_ExplicitSpecialization) 2083 return InstantiateClass(Loc, Rec, Pattern, 2084 getTemplateInstantiationArgs(Rec), 2085 TSK_ImplicitInstantiation, 2086 /*Complain=*/diag != 0); 2087 } 2088 } 2089 } 2090 2091 if (diag == 0) 2092 return true; 2093 2094 const TagType *Tag = 0; 2095 if (const RecordType *Record = T->getAs<RecordType>()) 2096 Tag = Record; 2097 else if (const EnumType *Enum = T->getAs<EnumType>()) 2098 Tag = Enum; 2099 2100 // Avoid diagnosing invalid decls as incomplete. 2101 if (Tag && Tag->getDecl()->isInvalidDecl()) 2102 return true; 2103 2104 // We have an incomplete type. Produce a diagnostic. 2105 Diag(Loc, PD) << T; 2106 2107 // If we have a note, produce it. 2108 if (!Note.first.isInvalid()) 2109 Diag(Note.first, Note.second); 2110 2111 // If the type was a forward declaration of a class/struct/union 2112 // type, produce a note. 2113 if (Tag && !Tag->getDecl()->isInvalidDecl()) 2114 Diag(Tag->getDecl()->getLocation(), 2115 Tag->isBeingDefined() ? diag::note_type_being_defined 2116 : diag::note_forward_declaration) 2117 << QualType(Tag, 0); 2118 2119 return true; 2120} 2121 2122bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 2123 const PartialDiagnostic &PD) { 2124 return RequireCompleteType(Loc, T, PD, 2125 std::make_pair(SourceLocation(), PDiag(0))); 2126} 2127 2128bool Sema::RequireCompleteType(SourceLocation Loc, QualType T, 2129 unsigned DiagID) { 2130 return RequireCompleteType(Loc, T, PDiag(DiagID), 2131 std::make_pair(SourceLocation(), PDiag(0))); 2132} 2133 2134/// \brief Retrieve a version of the type 'T' that is elaborated by Keyword 2135/// and qualified by the nested-name-specifier contained in SS. 2136QualType Sema::getElaboratedType(ElaboratedTypeKeyword Keyword, 2137 const CXXScopeSpec &SS, QualType T) { 2138 if (T.isNull()) 2139 return T; 2140 NestedNameSpecifier *NNS; 2141 if (SS.isValid()) 2142 NNS = static_cast<NestedNameSpecifier *>(SS.getScopeRep()); 2143 else { 2144 if (Keyword == ETK_None) 2145 return T; 2146 NNS = 0; 2147 } 2148 return Context.getElaboratedType(Keyword, NNS, T); 2149} 2150 2151QualType Sema::BuildTypeofExprType(Expr *E) { 2152 if (E->getType() == Context.OverloadTy) { 2153 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2154 // function template specialization wherever deduction cannot occur. 2155 if (FunctionDecl *Specialization 2156 = ResolveSingleFunctionTemplateSpecialization(E)) { 2157 // The access doesn't really matter in this case. 2158 DeclAccessPair Found = DeclAccessPair::make(Specialization, 2159 Specialization->getAccess()); 2160 E = FixOverloadedFunctionReference(E, Found, Specialization); 2161 if (!E) 2162 return QualType(); 2163 } else { 2164 Diag(E->getLocStart(), 2165 diag::err_cannot_determine_declared_type_of_overloaded_function) 2166 << false << E->getSourceRange(); 2167 return QualType(); 2168 } 2169 } 2170 2171 return Context.getTypeOfExprType(E); 2172} 2173 2174QualType Sema::BuildDecltypeType(Expr *E) { 2175 if (E->getType() == Context.OverloadTy) { 2176 // C++ [temp.arg.explicit]p3 allows us to resolve a template-id to a 2177 // function template specialization wherever deduction cannot occur. 2178 if (FunctionDecl *Specialization 2179 = ResolveSingleFunctionTemplateSpecialization(E)) { 2180 // The access doesn't really matter in this case. 2181 DeclAccessPair Found = DeclAccessPair::make(Specialization, 2182 Specialization->getAccess()); 2183 E = FixOverloadedFunctionReference(E, Found, Specialization); 2184 if (!E) 2185 return QualType(); 2186 } else { 2187 Diag(E->getLocStart(), 2188 diag::err_cannot_determine_declared_type_of_overloaded_function) 2189 << true << E->getSourceRange(); 2190 return QualType(); 2191 } 2192 } 2193 2194 return Context.getDecltypeType(E); 2195} 2196