ASTContext.cpp revision 5bfe232d1f07a6fd160fcf82c277c055a412a1c0
1//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 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 the ASTContext interface. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/ASTContext.h" 15#include "clang/AST/CharUnits.h" 16#include "clang/AST/DeclCXX.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/DeclTemplate.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/Expr.h" 21#include "clang/AST/ExprCXX.h" 22#include "clang/AST/ExternalASTSource.h" 23#include "clang/AST/ASTMutationListener.h" 24#include "clang/AST/RecordLayout.h" 25#include "clang/Basic/Builtins.h" 26#include "clang/Basic/SourceManager.h" 27#include "clang/Basic/TargetInfo.h" 28#include "llvm/ADT/SmallString.h" 29#include "llvm/ADT/StringExtras.h" 30#include "llvm/Support/MathExtras.h" 31#include "llvm/Support/raw_ostream.h" 32#include "CXXABI.h" 33 34using namespace clang; 35 36unsigned ASTContext::NumImplicitDefaultConstructors; 37unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 38unsigned ASTContext::NumImplicitCopyConstructors; 39unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 40unsigned ASTContext::NumImplicitCopyAssignmentOperators; 41unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 42unsigned ASTContext::NumImplicitDestructors; 43unsigned ASTContext::NumImplicitDestructorsDeclared; 44 45enum FloatingRank { 46 FloatRank, DoubleRank, LongDoubleRank 47}; 48 49void 50ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 51 TemplateTemplateParmDecl *Parm) { 52 ID.AddInteger(Parm->getDepth()); 53 ID.AddInteger(Parm->getPosition()); 54 // FIXME: Parameter pack 55 56 TemplateParameterList *Params = Parm->getTemplateParameters(); 57 ID.AddInteger(Params->size()); 58 for (TemplateParameterList::const_iterator P = Params->begin(), 59 PEnd = Params->end(); 60 P != PEnd; ++P) { 61 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 62 ID.AddInteger(0); 63 ID.AddBoolean(TTP->isParameterPack()); 64 continue; 65 } 66 67 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 68 ID.AddInteger(1); 69 // FIXME: Parameter pack 70 ID.AddPointer(NTTP->getType().getAsOpaquePtr()); 71 continue; 72 } 73 74 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 75 ID.AddInteger(2); 76 Profile(ID, TTP); 77 } 78} 79 80TemplateTemplateParmDecl * 81ASTContext::getCanonicalTemplateTemplateParmDecl( 82 TemplateTemplateParmDecl *TTP) { 83 // Check if we already have a canonical template template parameter. 84 llvm::FoldingSetNodeID ID; 85 CanonicalTemplateTemplateParm::Profile(ID, TTP); 86 void *InsertPos = 0; 87 CanonicalTemplateTemplateParm *Canonical 88 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 89 if (Canonical) 90 return Canonical->getParam(); 91 92 // Build a canonical template parameter list. 93 TemplateParameterList *Params = TTP->getTemplateParameters(); 94 llvm::SmallVector<NamedDecl *, 4> CanonParams; 95 CanonParams.reserve(Params->size()); 96 for (TemplateParameterList::const_iterator P = Params->begin(), 97 PEnd = Params->end(); 98 P != PEnd; ++P) { 99 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 100 CanonParams.push_back( 101 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 102 SourceLocation(), TTP->getDepth(), 103 TTP->getIndex(), 0, false, 104 TTP->isParameterPack())); 105 else if (NonTypeTemplateParmDecl *NTTP 106 = dyn_cast<NonTypeTemplateParmDecl>(*P)) 107 CanonParams.push_back( 108 NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 109 SourceLocation(), NTTP->getDepth(), 110 NTTP->getPosition(), 0, 111 getCanonicalType(NTTP->getType()), 112 0)); 113 else 114 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 115 cast<TemplateTemplateParmDecl>(*P))); 116 } 117 118 TemplateTemplateParmDecl *CanonTTP 119 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 120 SourceLocation(), TTP->getDepth(), 121 TTP->getPosition(), 0, 122 TemplateParameterList::Create(*this, SourceLocation(), 123 SourceLocation(), 124 CanonParams.data(), 125 CanonParams.size(), 126 SourceLocation())); 127 128 // Get the new insert position for the node we care about. 129 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 130 assert(Canonical == 0 && "Shouldn't be in the map!"); 131 (void)Canonical; 132 133 // Create the canonical template template parameter entry. 134 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 135 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 136 return CanonTTP; 137} 138 139CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 140 if (!LangOpts.CPlusPlus) return 0; 141 142 switch (T.getCXXABI()) { 143 case CXXABI_ARM: 144 return CreateARMCXXABI(*this); 145 case CXXABI_Itanium: 146 return CreateItaniumCXXABI(*this); 147 case CXXABI_Microsoft: 148 return CreateMicrosoftCXXABI(*this); 149 } 150 return 0; 151} 152 153ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 154 const TargetInfo &t, 155 IdentifierTable &idents, SelectorTable &sels, 156 Builtin::Context &builtins, 157 unsigned size_reserve) : 158 TemplateSpecializationTypes(this_()), 159 DependentTemplateSpecializationTypes(this_()), 160 GlobalNestedNameSpecifier(0), IsInt128Installed(false), 161 CFConstantStringTypeDecl(0), NSConstantStringTypeDecl(0), 162 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0), 163 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0), 164 NullTypeSourceInfo(QualType()), 165 SourceMgr(SM), LangOpts(LOpts), ABI(createCXXABI(t)), Target(t), 166 Idents(idents), Selectors(sels), 167 BuiltinInfo(builtins), 168 DeclarationNames(*this), 169 ExternalSource(0), Listener(0), PrintingPolicy(LOpts), 170 LastSDM(0, 0), 171 UniqueBlockByRefTypeID(0), UniqueBlockParmTypeID(0) { 172 ObjCIdRedefinitionType = QualType(); 173 ObjCClassRedefinitionType = QualType(); 174 ObjCSelRedefinitionType = QualType(); 175 if (size_reserve > 0) Types.reserve(size_reserve); 176 TUDecl = TranslationUnitDecl::Create(*this); 177 InitBuiltinTypes(); 178} 179 180ASTContext::~ASTContext() { 181 // Release the DenseMaps associated with DeclContext objects. 182 // FIXME: Is this the ideal solution? 183 ReleaseDeclContextMaps(); 184 185 // Call all of the deallocation functions. 186 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 187 Deallocations[I].first(Deallocations[I].second); 188 189 // Release all of the memory associated with overridden C++ methods. 190 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator 191 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end(); 192 OM != OMEnd; ++OM) 193 OM->second.Destroy(); 194 195 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 196 // because they can contain DenseMaps. 197 for (llvm::DenseMap<const ObjCContainerDecl*, 198 const ASTRecordLayout*>::iterator 199 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 200 // Increment in loop to prevent using deallocated memory. 201 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 202 R->Destroy(*this); 203 204 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 205 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 206 // Increment in loop to prevent using deallocated memory. 207 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 208 R->Destroy(*this); 209 } 210 211 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 212 AEnd = DeclAttrs.end(); 213 A != AEnd; ++A) 214 A->second->~AttrVec(); 215} 216 217void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 218 Deallocations.push_back(std::make_pair(Callback, Data)); 219} 220 221void 222ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 223 ExternalSource.reset(Source.take()); 224} 225 226void ASTContext::PrintStats() const { 227 fprintf(stderr, "*** AST Context Stats:\n"); 228 fprintf(stderr, " %d types total.\n", (int)Types.size()); 229 230 unsigned counts[] = { 231#define TYPE(Name, Parent) 0, 232#define ABSTRACT_TYPE(Name, Parent) 233#include "clang/AST/TypeNodes.def" 234 0 // Extra 235 }; 236 237 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 238 Type *T = Types[i]; 239 counts[(unsigned)T->getTypeClass()]++; 240 } 241 242 unsigned Idx = 0; 243 unsigned TotalBytes = 0; 244#define TYPE(Name, Parent) \ 245 if (counts[Idx]) \ 246 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 247 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 248 ++Idx; 249#define ABSTRACT_TYPE(Name, Parent) 250#include "clang/AST/TypeNodes.def" 251 252 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 253 254 // Implicit special member functions. 255 fprintf(stderr, " %u/%u implicit default constructors created\n", 256 NumImplicitDefaultConstructorsDeclared, 257 NumImplicitDefaultConstructors); 258 fprintf(stderr, " %u/%u implicit copy constructors created\n", 259 NumImplicitCopyConstructorsDeclared, 260 NumImplicitCopyConstructors); 261 fprintf(stderr, " %u/%u implicit copy assignment operators created\n", 262 NumImplicitCopyAssignmentOperatorsDeclared, 263 NumImplicitCopyAssignmentOperators); 264 fprintf(stderr, " %u/%u implicit destructors created\n", 265 NumImplicitDestructorsDeclared, NumImplicitDestructors); 266 267 if (ExternalSource.get()) { 268 fprintf(stderr, "\n"); 269 ExternalSource->PrintStats(); 270 } 271 272 BumpAlloc.PrintStats(); 273} 274 275 276void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 277 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 278 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 279 Types.push_back(Ty); 280} 281 282void ASTContext::InitBuiltinTypes() { 283 assert(VoidTy.isNull() && "Context reinitialized?"); 284 285 // C99 6.2.5p19. 286 InitBuiltinType(VoidTy, BuiltinType::Void); 287 288 // C99 6.2.5p2. 289 InitBuiltinType(BoolTy, BuiltinType::Bool); 290 // C99 6.2.5p3. 291 if (LangOpts.CharIsSigned) 292 InitBuiltinType(CharTy, BuiltinType::Char_S); 293 else 294 InitBuiltinType(CharTy, BuiltinType::Char_U); 295 // C99 6.2.5p4. 296 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 297 InitBuiltinType(ShortTy, BuiltinType::Short); 298 InitBuiltinType(IntTy, BuiltinType::Int); 299 InitBuiltinType(LongTy, BuiltinType::Long); 300 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 301 302 // C99 6.2.5p6. 303 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 304 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 305 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 306 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 307 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 308 309 // C99 6.2.5p10. 310 InitBuiltinType(FloatTy, BuiltinType::Float); 311 InitBuiltinType(DoubleTy, BuiltinType::Double); 312 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 313 314 // GNU extension, 128-bit integers. 315 InitBuiltinType(Int128Ty, BuiltinType::Int128); 316 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 317 318 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 319 InitBuiltinType(WCharTy, BuiltinType::WChar); 320 else // C99 321 WCharTy = getFromTargetType(Target.getWCharType()); 322 323 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 324 InitBuiltinType(Char16Ty, BuiltinType::Char16); 325 else // C99 326 Char16Ty = getFromTargetType(Target.getChar16Type()); 327 328 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 329 InitBuiltinType(Char32Ty, BuiltinType::Char32); 330 else // C99 331 Char32Ty = getFromTargetType(Target.getChar32Type()); 332 333 // Placeholder type for type-dependent expressions whose type is 334 // completely unknown. No code should ever check a type against 335 // DependentTy and users should never see it; however, it is here to 336 // help diagnose failures to properly check for type-dependent 337 // expressions. 338 InitBuiltinType(DependentTy, BuiltinType::Dependent); 339 340 // Placeholder type for functions. 341 InitBuiltinType(OverloadTy, BuiltinType::Overload); 342 343 // Placeholder type for C++0x auto declarations whose real type has 344 // not yet been deduced. 345 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); 346 347 // C99 6.2.5p11. 348 FloatComplexTy = getComplexType(FloatTy); 349 DoubleComplexTy = getComplexType(DoubleTy); 350 LongDoubleComplexTy = getComplexType(LongDoubleTy); 351 352 BuiltinVaListType = QualType(); 353 354 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope(). 355 ObjCIdTypedefType = QualType(); 356 ObjCClassTypedefType = QualType(); 357 ObjCSelTypedefType = QualType(); 358 359 // Builtin types for 'id', 'Class', and 'SEL'. 360 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 361 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 362 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 363 364 ObjCConstantStringType = QualType(); 365 366 // void * type 367 VoidPtrTy = getPointerType(VoidTy); 368 369 // nullptr type (C++0x 2.14.7) 370 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 371} 372 373Diagnostic &ASTContext::getDiagnostics() const { 374 return SourceMgr.getDiagnostics(); 375} 376 377AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 378 AttrVec *&Result = DeclAttrs[D]; 379 if (!Result) { 380 void *Mem = Allocate(sizeof(AttrVec)); 381 Result = new (Mem) AttrVec; 382 } 383 384 return *Result; 385} 386 387/// \brief Erase the attributes corresponding to the given declaration. 388void ASTContext::eraseDeclAttrs(const Decl *D) { 389 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 390 if (Pos != DeclAttrs.end()) { 391 Pos->second->~AttrVec(); 392 DeclAttrs.erase(Pos); 393 } 394} 395 396 397MemberSpecializationInfo * 398ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 399 assert(Var->isStaticDataMember() && "Not a static data member"); 400 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 401 = InstantiatedFromStaticDataMember.find(Var); 402 if (Pos == InstantiatedFromStaticDataMember.end()) 403 return 0; 404 405 return Pos->second; 406} 407 408void 409ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 410 TemplateSpecializationKind TSK, 411 SourceLocation PointOfInstantiation) { 412 assert(Inst->isStaticDataMember() && "Not a static data member"); 413 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 414 assert(!InstantiatedFromStaticDataMember[Inst] && 415 "Already noted what static data member was instantiated from"); 416 InstantiatedFromStaticDataMember[Inst] 417 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 418} 419 420NamedDecl * 421ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 422 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 423 = InstantiatedFromUsingDecl.find(UUD); 424 if (Pos == InstantiatedFromUsingDecl.end()) 425 return 0; 426 427 return Pos->second; 428} 429 430void 431ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 432 assert((isa<UsingDecl>(Pattern) || 433 isa<UnresolvedUsingValueDecl>(Pattern) || 434 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 435 "pattern decl is not a using decl"); 436 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 437 InstantiatedFromUsingDecl[Inst] = Pattern; 438} 439 440UsingShadowDecl * 441ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 442 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 443 = InstantiatedFromUsingShadowDecl.find(Inst); 444 if (Pos == InstantiatedFromUsingShadowDecl.end()) 445 return 0; 446 447 return Pos->second; 448} 449 450void 451ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 452 UsingShadowDecl *Pattern) { 453 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 454 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 455} 456 457FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 458 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 459 = InstantiatedFromUnnamedFieldDecl.find(Field); 460 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 461 return 0; 462 463 return Pos->second; 464} 465 466void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 467 FieldDecl *Tmpl) { 468 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 469 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 470 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 471 "Already noted what unnamed field was instantiated from"); 472 473 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 474} 475 476ASTContext::overridden_cxx_method_iterator 477ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 478 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 479 = OverriddenMethods.find(Method); 480 if (Pos == OverriddenMethods.end()) 481 return 0; 482 483 return Pos->second.begin(); 484} 485 486ASTContext::overridden_cxx_method_iterator 487ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 488 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 489 = OverriddenMethods.find(Method); 490 if (Pos == OverriddenMethods.end()) 491 return 0; 492 493 return Pos->second.end(); 494} 495 496unsigned 497ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 498 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 499 = OverriddenMethods.find(Method); 500 if (Pos == OverriddenMethods.end()) 501 return 0; 502 503 return Pos->second.size(); 504} 505 506void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 507 const CXXMethodDecl *Overridden) { 508 OverriddenMethods[Method].push_back(Overridden); 509} 510 511//===----------------------------------------------------------------------===// 512// Type Sizing and Analysis 513//===----------------------------------------------------------------------===// 514 515/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 516/// scalar floating point type. 517const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 518 const BuiltinType *BT = T->getAs<BuiltinType>(); 519 assert(BT && "Not a floating point type!"); 520 switch (BT->getKind()) { 521 default: assert(0 && "Not a floating point type!"); 522 case BuiltinType::Float: return Target.getFloatFormat(); 523 case BuiltinType::Double: return Target.getDoubleFormat(); 524 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 525 } 526} 527 528/// getDeclAlign - Return a conservative estimate of the alignment of the 529/// specified decl. Note that bitfields do not have a valid alignment, so 530/// this method will assert on them. 531/// If @p RefAsPointee, references are treated like their underlying type 532/// (for alignof), else they're treated like pointers (for CodeGen). 533CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) { 534 unsigned Align = Target.getCharWidth(); 535 536 bool UseAlignAttrOnly = false; 537 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 538 Align = AlignFromAttr; 539 540 // __attribute__((aligned)) can increase or decrease alignment 541 // *except* on a struct or struct member, where it only increases 542 // alignment unless 'packed' is also specified. 543 // 544 // It is an error for [[align]] to decrease alignment, so we can 545 // ignore that possibility; Sema should diagnose it. 546 if (isa<FieldDecl>(D)) { 547 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 548 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 549 } else { 550 UseAlignAttrOnly = true; 551 } 552 } 553 554 if (UseAlignAttrOnly) { 555 // ignore type of value 556 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 557 QualType T = VD->getType(); 558 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 559 if (RefAsPointee) 560 T = RT->getPointeeType(); 561 else 562 T = getPointerType(RT->getPointeeType()); 563 } 564 if (!T->isIncompleteType() && !T->isFunctionType()) { 565 unsigned MinWidth = Target.getLargeArrayMinWidth(); 566 unsigned ArrayAlign = Target.getLargeArrayAlign(); 567 if (isa<VariableArrayType>(T) && MinWidth != 0) 568 Align = std::max(Align, ArrayAlign); 569 if (ConstantArrayType *CT = dyn_cast<ConstantArrayType>(T)) { 570 unsigned Size = getTypeSize(CT); 571 if (MinWidth != 0 && MinWidth <= Size) 572 Align = std::max(Align, ArrayAlign); 573 } 574 // Incomplete or function types default to 1. 575 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 576 T = cast<ArrayType>(T)->getElementType(); 577 578 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 579 } 580 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 581 // In the case of a field in a packed struct, we want the minimum 582 // of the alignment of the field and the alignment of the struct. 583 Align = std::min(Align, 584 getPreferredTypeAlign(FD->getParent()->getTypeForDecl())); 585 } 586 } 587 588 return CharUnits::fromQuantity(Align / Target.getCharWidth()); 589} 590 591std::pair<CharUnits, CharUnits> 592ASTContext::getTypeInfoInChars(const Type *T) { 593 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 594 return std::make_pair(CharUnits::fromQuantity(Info.first / getCharWidth()), 595 CharUnits::fromQuantity(Info.second / getCharWidth())); 596} 597 598std::pair<CharUnits, CharUnits> 599ASTContext::getTypeInfoInChars(QualType T) { 600 return getTypeInfoInChars(T.getTypePtr()); 601} 602 603/// getTypeSize - Return the size of the specified type, in bits. This method 604/// does not work on incomplete types. 605/// 606/// FIXME: Pointers into different addr spaces could have different sizes and 607/// alignment requirements: getPointerInfo should take an AddrSpace, this 608/// should take a QualType, &c. 609std::pair<uint64_t, unsigned> 610ASTContext::getTypeInfo(const Type *T) { 611 uint64_t Width=0; 612 unsigned Align=8; 613 switch (T->getTypeClass()) { 614#define TYPE(Class, Base) 615#define ABSTRACT_TYPE(Class, Base) 616#define NON_CANONICAL_TYPE(Class, Base) 617#define DEPENDENT_TYPE(Class, Base) case Type::Class: 618#include "clang/AST/TypeNodes.def" 619 assert(false && "Should not see dependent types"); 620 break; 621 622 case Type::FunctionNoProto: 623 case Type::FunctionProto: 624 // GCC extension: alignof(function) = 32 bits 625 Width = 0; 626 Align = 32; 627 break; 628 629 case Type::IncompleteArray: 630 case Type::VariableArray: 631 Width = 0; 632 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 633 break; 634 635 case Type::ConstantArray: { 636 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 637 638 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 639 Width = EltInfo.first*CAT->getSize().getZExtValue(); 640 Align = EltInfo.second; 641 break; 642 } 643 case Type::ExtVector: 644 case Type::Vector: { 645 const VectorType *VT = cast<VectorType>(T); 646 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 647 Width = EltInfo.first*VT->getNumElements(); 648 Align = Width; 649 // If the alignment is not a power of 2, round up to the next power of 2. 650 // This happens for non-power-of-2 length vectors. 651 if (Align & (Align-1)) { 652 Align = llvm::NextPowerOf2(Align); 653 Width = llvm::RoundUpToAlignment(Width, Align); 654 } 655 break; 656 } 657 658 case Type::Builtin: 659 switch (cast<BuiltinType>(T)->getKind()) { 660 default: assert(0 && "Unknown builtin type!"); 661 case BuiltinType::Void: 662 // GCC extension: alignof(void) = 8 bits. 663 Width = 0; 664 Align = 8; 665 break; 666 667 case BuiltinType::Bool: 668 Width = Target.getBoolWidth(); 669 Align = Target.getBoolAlign(); 670 break; 671 case BuiltinType::Char_S: 672 case BuiltinType::Char_U: 673 case BuiltinType::UChar: 674 case BuiltinType::SChar: 675 Width = Target.getCharWidth(); 676 Align = Target.getCharAlign(); 677 break; 678 case BuiltinType::WChar: 679 Width = Target.getWCharWidth(); 680 Align = Target.getWCharAlign(); 681 break; 682 case BuiltinType::Char16: 683 Width = Target.getChar16Width(); 684 Align = Target.getChar16Align(); 685 break; 686 case BuiltinType::Char32: 687 Width = Target.getChar32Width(); 688 Align = Target.getChar32Align(); 689 break; 690 case BuiltinType::UShort: 691 case BuiltinType::Short: 692 Width = Target.getShortWidth(); 693 Align = Target.getShortAlign(); 694 break; 695 case BuiltinType::UInt: 696 case BuiltinType::Int: 697 Width = Target.getIntWidth(); 698 Align = Target.getIntAlign(); 699 break; 700 case BuiltinType::ULong: 701 case BuiltinType::Long: 702 Width = Target.getLongWidth(); 703 Align = Target.getLongAlign(); 704 break; 705 case BuiltinType::ULongLong: 706 case BuiltinType::LongLong: 707 Width = Target.getLongLongWidth(); 708 Align = Target.getLongLongAlign(); 709 break; 710 case BuiltinType::Int128: 711 case BuiltinType::UInt128: 712 Width = 128; 713 Align = 128; // int128_t is 128-bit aligned on all targets. 714 break; 715 case BuiltinType::Float: 716 Width = Target.getFloatWidth(); 717 Align = Target.getFloatAlign(); 718 break; 719 case BuiltinType::Double: 720 Width = Target.getDoubleWidth(); 721 Align = Target.getDoubleAlign(); 722 break; 723 case BuiltinType::LongDouble: 724 Width = Target.getLongDoubleWidth(); 725 Align = Target.getLongDoubleAlign(); 726 break; 727 case BuiltinType::NullPtr: 728 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 729 Align = Target.getPointerAlign(0); // == sizeof(void*) 730 break; 731 case BuiltinType::ObjCId: 732 case BuiltinType::ObjCClass: 733 case BuiltinType::ObjCSel: 734 Width = Target.getPointerWidth(0); 735 Align = Target.getPointerAlign(0); 736 break; 737 } 738 break; 739 case Type::ObjCObjectPointer: 740 Width = Target.getPointerWidth(0); 741 Align = Target.getPointerAlign(0); 742 break; 743 case Type::BlockPointer: { 744 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 745 Width = Target.getPointerWidth(AS); 746 Align = Target.getPointerAlign(AS); 747 break; 748 } 749 case Type::LValueReference: 750 case Type::RValueReference: { 751 // alignof and sizeof should never enter this code path here, so we go 752 // the pointer route. 753 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace(); 754 Width = Target.getPointerWidth(AS); 755 Align = Target.getPointerAlign(AS); 756 break; 757 } 758 case Type::Pointer: { 759 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 760 Width = Target.getPointerWidth(AS); 761 Align = Target.getPointerAlign(AS); 762 break; 763 } 764 case Type::MemberPointer: { 765 const MemberPointerType *MPT = cast<MemberPointerType>(T); 766 std::pair<uint64_t, unsigned> PtrDiffInfo = 767 getTypeInfo(getPointerDiffType()); 768 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 769 Align = PtrDiffInfo.second; 770 break; 771 } 772 case Type::Complex: { 773 // Complex types have the same alignment as their elements, but twice the 774 // size. 775 std::pair<uint64_t, unsigned> EltInfo = 776 getTypeInfo(cast<ComplexType>(T)->getElementType()); 777 Width = EltInfo.first*2; 778 Align = EltInfo.second; 779 break; 780 } 781 case Type::ObjCObject: 782 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 783 case Type::ObjCInterface: { 784 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 785 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 786 Width = Layout.getSize(); 787 Align = Layout.getAlignment(); 788 break; 789 } 790 case Type::Record: 791 case Type::Enum: { 792 const TagType *TT = cast<TagType>(T); 793 794 if (TT->getDecl()->isInvalidDecl()) { 795 Width = 1; 796 Align = 1; 797 break; 798 } 799 800 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 801 return getTypeInfo(ET->getDecl()->getIntegerType()); 802 803 const RecordType *RT = cast<RecordType>(TT); 804 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 805 Width = Layout.getSize(); 806 Align = Layout.getAlignment(); 807 break; 808 } 809 810 case Type::SubstTemplateTypeParm: 811 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 812 getReplacementType().getTypePtr()); 813 814 case Type::Paren: 815 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 816 817 case Type::Typedef: { 818 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 819 std::pair<uint64_t, unsigned> Info 820 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 821 Align = std::max(Typedef->getMaxAlignment(), Info.second); 822 Width = Info.first; 823 break; 824 } 825 826 case Type::TypeOfExpr: 827 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 828 .getTypePtr()); 829 830 case Type::TypeOf: 831 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 832 833 case Type::Decltype: 834 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 835 .getTypePtr()); 836 837 case Type::Elaborated: 838 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 839 840 case Type::TemplateSpecialization: 841 assert(getCanonicalType(T) != T && 842 "Cannot request the size of a dependent type"); 843 // FIXME: this is likely to be wrong once we support template 844 // aliases, since a template alias could refer to a typedef that 845 // has an __aligned__ attribute on it. 846 return getTypeInfo(getCanonicalType(T)); 847 } 848 849 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 850 return std::make_pair(Width, Align); 851} 852 853/// getTypeSizeInChars - Return the size of the specified type, in characters. 854/// This method does not work on incomplete types. 855CharUnits ASTContext::getTypeSizeInChars(QualType T) { 856 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 857} 858CharUnits ASTContext::getTypeSizeInChars(const Type *T) { 859 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 860} 861 862/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 863/// characters. This method does not work on incomplete types. 864CharUnits ASTContext::getTypeAlignInChars(QualType T) { 865 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 866} 867CharUnits ASTContext::getTypeAlignInChars(const Type *T) { 868 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 869} 870 871/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 872/// type for the current target in bits. This can be different than the ABI 873/// alignment in cases where it is beneficial for performance to overalign 874/// a data type. 875unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 876 unsigned ABIAlign = getTypeAlign(T); 877 878 // Double and long long should be naturally aligned if possible. 879 if (const ComplexType* CT = T->getAs<ComplexType>()) 880 T = CT->getElementType().getTypePtr(); 881 if (T->isSpecificBuiltinType(BuiltinType::Double) || 882 T->isSpecificBuiltinType(BuiltinType::LongLong)) 883 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 884 885 return ABIAlign; 886} 887 888/// ShallowCollectObjCIvars - 889/// Collect all ivars, including those synthesized, in the current class. 890/// 891void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 892 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 893 // FIXME. This need be removed but there are two many places which 894 // assume const-ness of ObjCInterfaceDecl 895 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 896 for (ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 897 Iv= Iv->getNextIvar()) 898 Ivars.push_back(Iv); 899} 900 901/// DeepCollectObjCIvars - 902/// This routine first collects all declared, but not synthesized, ivars in 903/// super class and then collects all ivars, including those synthesized for 904/// current class. This routine is used for implementation of current class 905/// when all ivars, declared and synthesized are known. 906/// 907void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 908 bool leafClass, 909 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 910 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 911 DeepCollectObjCIvars(SuperClass, false, Ivars); 912 if (!leafClass) { 913 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 914 E = OI->ivar_end(); I != E; ++I) 915 Ivars.push_back(*I); 916 } 917 else 918 ShallowCollectObjCIvars(OI, Ivars); 919} 920 921/// CollectInheritedProtocols - Collect all protocols in current class and 922/// those inherited by it. 923void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 924 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 925 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 926 // We can use protocol_iterator here instead of 927 // all_referenced_protocol_iterator since we are walking all categories. 928 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 929 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 930 ObjCProtocolDecl *Proto = (*P); 931 Protocols.insert(Proto); 932 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 933 PE = Proto->protocol_end(); P != PE; ++P) { 934 Protocols.insert(*P); 935 CollectInheritedProtocols(*P, Protocols); 936 } 937 } 938 939 // Categories of this Interface. 940 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 941 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 942 CollectInheritedProtocols(CDeclChain, Protocols); 943 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 944 while (SD) { 945 CollectInheritedProtocols(SD, Protocols); 946 SD = SD->getSuperClass(); 947 } 948 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 949 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 950 PE = OC->protocol_end(); P != PE; ++P) { 951 ObjCProtocolDecl *Proto = (*P); 952 Protocols.insert(Proto); 953 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 954 PE = Proto->protocol_end(); P != PE; ++P) 955 CollectInheritedProtocols(*P, Protocols); 956 } 957 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 958 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 959 PE = OP->protocol_end(); P != PE; ++P) { 960 ObjCProtocolDecl *Proto = (*P); 961 Protocols.insert(Proto); 962 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 963 PE = Proto->protocol_end(); P != PE; ++P) 964 CollectInheritedProtocols(*P, Protocols); 965 } 966 } 967} 968 969unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) { 970 unsigned count = 0; 971 // Count ivars declared in class extension. 972 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 973 CDecl = CDecl->getNextClassExtension()) 974 count += CDecl->ivar_size(); 975 976 // Count ivar defined in this class's implementation. This 977 // includes synthesized ivars. 978 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 979 count += ImplDecl->ivar_size(); 980 981 return count; 982} 983 984/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 985ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 986 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 987 I = ObjCImpls.find(D); 988 if (I != ObjCImpls.end()) 989 return cast<ObjCImplementationDecl>(I->second); 990 return 0; 991} 992/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 993ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 994 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 995 I = ObjCImpls.find(D); 996 if (I != ObjCImpls.end()) 997 return cast<ObjCCategoryImplDecl>(I->second); 998 return 0; 999} 1000 1001/// \brief Set the implementation of ObjCInterfaceDecl. 1002void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1003 ObjCImplementationDecl *ImplD) { 1004 assert(IFaceD && ImplD && "Passed null params"); 1005 ObjCImpls[IFaceD] = ImplD; 1006} 1007/// \brief Set the implementation of ObjCCategoryDecl. 1008void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1009 ObjCCategoryImplDecl *ImplD) { 1010 assert(CatD && ImplD && "Passed null params"); 1011 ObjCImpls[CatD] = ImplD; 1012} 1013 1014/// \brief Get the copy initialization expression of VarDecl,or NULL if 1015/// none exists. 1016Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1017 assert(VD && "Passed null params"); 1018 assert(VD->hasAttr<BlocksAttr>() && 1019 "getBlockVarCopyInits - not __block var"); 1020 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1021 I = BlockVarCopyInits.find(VD); 1022 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1023} 1024 1025/// \brief Set the copy inialization expression of a block var decl. 1026void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1027 assert(VD && Init && "Passed null params"); 1028 assert(VD->hasAttr<BlocksAttr>() && 1029 "setBlockVarCopyInits - not __block var"); 1030 BlockVarCopyInits[VD] = Init; 1031} 1032 1033/// \brief Allocate an uninitialized TypeSourceInfo. 1034/// 1035/// The caller should initialize the memory held by TypeSourceInfo using 1036/// the TypeLoc wrappers. 1037/// 1038/// \param T the type that will be the basis for type source info. This type 1039/// should refer to how the declarator was written in source code, not to 1040/// what type semantic analysis resolved the declarator to. 1041TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1042 unsigned DataSize) { 1043 if (!DataSize) 1044 DataSize = TypeLoc::getFullDataSizeForType(T); 1045 else 1046 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1047 "incorrect data size provided to CreateTypeSourceInfo!"); 1048 1049 TypeSourceInfo *TInfo = 1050 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1051 new (TInfo) TypeSourceInfo(T); 1052 return TInfo; 1053} 1054 1055TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1056 SourceLocation L) { 1057 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1058 DI->getTypeLoc().initialize(L); 1059 return DI; 1060} 1061 1062const ASTRecordLayout & 1063ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 1064 return getObjCLayout(D, 0); 1065} 1066 1067const ASTRecordLayout & 1068ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 1069 return getObjCLayout(D->getClassInterface(), D); 1070} 1071 1072//===----------------------------------------------------------------------===// 1073// Type creation/memoization methods 1074//===----------------------------------------------------------------------===// 1075 1076QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) { 1077 unsigned Fast = Quals.getFastQualifiers(); 1078 Quals.removeFastQualifiers(); 1079 1080 // Check if we've already instantiated this type. 1081 llvm::FoldingSetNodeID ID; 1082 ExtQuals::Profile(ID, TypeNode, Quals); 1083 void *InsertPos = 0; 1084 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) { 1085 assert(EQ->getQualifiers() == Quals); 1086 QualType T = QualType(EQ, Fast); 1087 return T; 1088 } 1089 1090 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(TypeNode, Quals); 1091 ExtQualNodes.InsertNode(New, InsertPos); 1092 QualType T = QualType(New, Fast); 1093 return T; 1094} 1095 1096QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 1097 QualType CanT = getCanonicalType(T); 1098 if (CanT.getAddressSpace() == AddressSpace) 1099 return T; 1100 1101 // If we are composing extended qualifiers together, merge together 1102 // into one ExtQuals node. 1103 QualifierCollector Quals; 1104 const Type *TypeNode = Quals.strip(T); 1105 1106 // If this type already has an address space specified, it cannot get 1107 // another one. 1108 assert(!Quals.hasAddressSpace() && 1109 "Type cannot be in multiple addr spaces!"); 1110 Quals.addAddressSpace(AddressSpace); 1111 1112 return getExtQualType(TypeNode, Quals); 1113} 1114 1115QualType ASTContext::getObjCGCQualType(QualType T, 1116 Qualifiers::GC GCAttr) { 1117 QualType CanT = getCanonicalType(T); 1118 if (CanT.getObjCGCAttr() == GCAttr) 1119 return T; 1120 1121 if (T->isPointerType()) { 1122 QualType Pointee = T->getAs<PointerType>()->getPointeeType(); 1123 if (Pointee->isAnyPointerType()) { 1124 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1125 return getPointerType(ResultType); 1126 } 1127 } 1128 1129 // If we are composing extended qualifiers together, merge together 1130 // into one ExtQuals node. 1131 QualifierCollector Quals; 1132 const Type *TypeNode = Quals.strip(T); 1133 1134 // If this type already has an ObjCGC specified, it cannot get 1135 // another one. 1136 assert(!Quals.hasObjCGCAttr() && 1137 "Type cannot have multiple ObjCGCs!"); 1138 Quals.addObjCGCAttr(GCAttr); 1139 1140 return getExtQualType(TypeNode, Quals); 1141} 1142 1143static QualType getExtFunctionType(ASTContext& Context, QualType T, 1144 const FunctionType::ExtInfo &Info) { 1145 QualType ResultType; 1146 if (const PointerType *Pointer = T->getAs<PointerType>()) { 1147 QualType Pointee = Pointer->getPointeeType(); 1148 ResultType = getExtFunctionType(Context, Pointee, Info); 1149 if (ResultType == Pointee) 1150 return T; 1151 1152 ResultType = Context.getPointerType(ResultType); 1153 } else if (const ParenType *Paren = T->getAs<ParenType>()) { 1154 QualType Inner = Paren->getInnerType(); 1155 ResultType = getExtFunctionType(Context, Inner, Info); 1156 if (ResultType == Inner) 1157 return T; 1158 1159 ResultType = Context.getParenType(ResultType); 1160 } else if (const BlockPointerType *BlockPointer 1161 = T->getAs<BlockPointerType>()) { 1162 QualType Pointee = BlockPointer->getPointeeType(); 1163 ResultType = getExtFunctionType(Context, Pointee, Info); 1164 if (ResultType == Pointee) 1165 return T; 1166 1167 ResultType = Context.getBlockPointerType(ResultType); 1168 } else if (const MemberPointerType *MemberPointer 1169 = T->getAs<MemberPointerType>()) { 1170 QualType Pointee = MemberPointer->getPointeeType(); 1171 ResultType = getExtFunctionType(Context, Pointee, Info); 1172 if (ResultType == Pointee) 1173 return T; 1174 1175 ResultType = Context.getMemberPointerType(ResultType, 1176 MemberPointer->getClass()); 1177 } else if (const FunctionType *F = T->getAs<FunctionType>()) { 1178 if (F->getExtInfo() == Info) 1179 return T; 1180 1181 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) { 1182 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(), 1183 Info); 1184 } else { 1185 const FunctionProtoType *FPT = cast<FunctionProtoType>(F); 1186 ResultType 1187 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1188 FPT->getNumArgs(), FPT->isVariadic(), 1189 FPT->getTypeQuals(), 1190 FPT->hasExceptionSpec(), 1191 FPT->hasAnyExceptionSpec(), 1192 FPT->getNumExceptions(), 1193 FPT->exception_begin(), 1194 Info); 1195 } 1196 } else 1197 return T; 1198 1199 return Context.getQualifiedType(ResultType, T.getLocalQualifiers()); 1200} 1201 1202QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) { 1203 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1204 return getExtFunctionType(*this, T, 1205 Info.withNoReturn(AddNoReturn)); 1206} 1207 1208QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) { 1209 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1210 return getExtFunctionType(*this, T, 1211 Info.withCallingConv(CallConv)); 1212} 1213 1214QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) { 1215 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 1216 return getExtFunctionType(*this, T, 1217 Info.withRegParm(RegParm)); 1218} 1219 1220/// getComplexType - Return the uniqued reference to the type for a complex 1221/// number with the specified element type. 1222QualType ASTContext::getComplexType(QualType T) { 1223 // Unique pointers, to guarantee there is only one pointer of a particular 1224 // structure. 1225 llvm::FoldingSetNodeID ID; 1226 ComplexType::Profile(ID, T); 1227 1228 void *InsertPos = 0; 1229 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1230 return QualType(CT, 0); 1231 1232 // If the pointee type isn't canonical, this won't be a canonical type either, 1233 // so fill in the canonical type field. 1234 QualType Canonical; 1235 if (!T.isCanonical()) { 1236 Canonical = getComplexType(getCanonicalType(T)); 1237 1238 // Get the new insert position for the node we care about. 1239 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1240 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1241 } 1242 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1243 Types.push_back(New); 1244 ComplexTypes.InsertNode(New, InsertPos); 1245 return QualType(New, 0); 1246} 1247 1248/// getPointerType - Return the uniqued reference to the type for a pointer to 1249/// the specified type. 1250QualType ASTContext::getPointerType(QualType T) { 1251 // Unique pointers, to guarantee there is only one pointer of a particular 1252 // structure. 1253 llvm::FoldingSetNodeID ID; 1254 PointerType::Profile(ID, T); 1255 1256 void *InsertPos = 0; 1257 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1258 return QualType(PT, 0); 1259 1260 // If the pointee type isn't canonical, this won't be a canonical type either, 1261 // so fill in the canonical type field. 1262 QualType Canonical; 1263 if (!T.isCanonical()) { 1264 Canonical = getPointerType(getCanonicalType(T)); 1265 1266 // Get the new insert position for the node we care about. 1267 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1268 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1269 } 1270 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1271 Types.push_back(New); 1272 PointerTypes.InsertNode(New, InsertPos); 1273 return QualType(New, 0); 1274} 1275 1276/// getBlockPointerType - Return the uniqued reference to the type for 1277/// a pointer to the specified block. 1278QualType ASTContext::getBlockPointerType(QualType T) { 1279 assert(T->isFunctionType() && "block of function types only"); 1280 // Unique pointers, to guarantee there is only one block of a particular 1281 // structure. 1282 llvm::FoldingSetNodeID ID; 1283 BlockPointerType::Profile(ID, T); 1284 1285 void *InsertPos = 0; 1286 if (BlockPointerType *PT = 1287 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1288 return QualType(PT, 0); 1289 1290 // If the block pointee type isn't canonical, this won't be a canonical 1291 // type either so fill in the canonical type field. 1292 QualType Canonical; 1293 if (!T.isCanonical()) { 1294 Canonical = getBlockPointerType(getCanonicalType(T)); 1295 1296 // Get the new insert position for the node we care about. 1297 BlockPointerType *NewIP = 1298 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1299 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1300 } 1301 BlockPointerType *New 1302 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1303 Types.push_back(New); 1304 BlockPointerTypes.InsertNode(New, InsertPos); 1305 return QualType(New, 0); 1306} 1307 1308/// getLValueReferenceType - Return the uniqued reference to the type for an 1309/// lvalue reference to the specified type. 1310QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) { 1311 // Unique pointers, to guarantee there is only one pointer of a particular 1312 // structure. 1313 llvm::FoldingSetNodeID ID; 1314 ReferenceType::Profile(ID, T, SpelledAsLValue); 1315 1316 void *InsertPos = 0; 1317 if (LValueReferenceType *RT = 1318 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1319 return QualType(RT, 0); 1320 1321 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1322 1323 // If the referencee type isn't canonical, this won't be a canonical type 1324 // either, so fill in the canonical type field. 1325 QualType Canonical; 1326 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1327 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1328 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1329 1330 // Get the new insert position for the node we care about. 1331 LValueReferenceType *NewIP = 1332 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1333 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1334 } 1335 1336 LValueReferenceType *New 1337 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1338 SpelledAsLValue); 1339 Types.push_back(New); 1340 LValueReferenceTypes.InsertNode(New, InsertPos); 1341 1342 return QualType(New, 0); 1343} 1344 1345/// getRValueReferenceType - Return the uniqued reference to the type for an 1346/// rvalue reference to the specified type. 1347QualType ASTContext::getRValueReferenceType(QualType T) { 1348 // Unique pointers, to guarantee there is only one pointer of a particular 1349 // structure. 1350 llvm::FoldingSetNodeID ID; 1351 ReferenceType::Profile(ID, T, false); 1352 1353 void *InsertPos = 0; 1354 if (RValueReferenceType *RT = 1355 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1356 return QualType(RT, 0); 1357 1358 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1359 1360 // If the referencee type isn't canonical, this won't be a canonical type 1361 // either, so fill in the canonical type field. 1362 QualType Canonical; 1363 if (InnerRef || !T.isCanonical()) { 1364 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1365 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1366 1367 // Get the new insert position for the node we care about. 1368 RValueReferenceType *NewIP = 1369 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1370 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1371 } 1372 1373 RValueReferenceType *New 1374 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1375 Types.push_back(New); 1376 RValueReferenceTypes.InsertNode(New, InsertPos); 1377 return QualType(New, 0); 1378} 1379 1380/// getMemberPointerType - Return the uniqued reference to the type for a 1381/// member pointer to the specified type, in the specified class. 1382QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) { 1383 // Unique pointers, to guarantee there is only one pointer of a particular 1384 // structure. 1385 llvm::FoldingSetNodeID ID; 1386 MemberPointerType::Profile(ID, T, Cls); 1387 1388 void *InsertPos = 0; 1389 if (MemberPointerType *PT = 1390 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1391 return QualType(PT, 0); 1392 1393 // If the pointee or class type isn't canonical, this won't be a canonical 1394 // type either, so fill in the canonical type field. 1395 QualType Canonical; 1396 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1397 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1398 1399 // Get the new insert position for the node we care about. 1400 MemberPointerType *NewIP = 1401 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1402 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1403 } 1404 MemberPointerType *New 1405 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1406 Types.push_back(New); 1407 MemberPointerTypes.InsertNode(New, InsertPos); 1408 return QualType(New, 0); 1409} 1410 1411/// getConstantArrayType - Return the unique reference to the type for an 1412/// array of the specified element type. 1413QualType ASTContext::getConstantArrayType(QualType EltTy, 1414 const llvm::APInt &ArySizeIn, 1415 ArrayType::ArraySizeModifier ASM, 1416 unsigned EltTypeQuals) { 1417 assert((EltTy->isDependentType() || 1418 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1419 "Constant array of VLAs is illegal!"); 1420 1421 // Convert the array size into a canonical width matching the pointer size for 1422 // the target. 1423 llvm::APInt ArySize(ArySizeIn); 1424 ArySize = 1425 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 1426 1427 llvm::FoldingSetNodeID ID; 1428 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 1429 1430 void *InsertPos = 0; 1431 if (ConstantArrayType *ATP = 1432 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1433 return QualType(ATP, 0); 1434 1435 // If the element type isn't canonical, this won't be a canonical type either, 1436 // so fill in the canonical type field. 1437 QualType Canonical; 1438 if (!EltTy.isCanonical()) { 1439 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 1440 ASM, EltTypeQuals); 1441 // Get the new insert position for the node we care about. 1442 ConstantArrayType *NewIP = 1443 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1444 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1445 } 1446 1447 ConstantArrayType *New = new(*this,TypeAlignment) 1448 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 1449 ConstantArrayTypes.InsertNode(New, InsertPos); 1450 Types.push_back(New); 1451 return QualType(New, 0); 1452} 1453 1454/// getIncompleteArrayType - Returns a unique reference to the type for a 1455/// incomplete array of the specified element type. 1456QualType ASTContext::getUnknownSizeVariableArrayType(QualType Ty) { 1457 QualType ElemTy = getBaseElementType(Ty); 1458 DeclarationName Name; 1459 llvm::SmallVector<QualType, 8> ATypes; 1460 QualType ATy = Ty; 1461 while (const ArrayType *AT = getAsArrayType(ATy)) { 1462 ATypes.push_back(ATy); 1463 ATy = AT->getElementType(); 1464 } 1465 for (int i = ATypes.size() - 1; i >= 0; i--) { 1466 if (const VariableArrayType *VAT = getAsVariableArrayType(ATypes[i])) { 1467 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Star, 1468 0, VAT->getBracketsRange()); 1469 } 1470 else if (const ConstantArrayType *CAT = getAsConstantArrayType(ATypes[i])) { 1471 llvm::APSInt ConstVal(CAT->getSize()); 1472 ElemTy = getConstantArrayType(ElemTy, ConstVal, ArrayType::Normal, 0); 1473 } 1474 else if (getAsIncompleteArrayType(ATypes[i])) { 1475 ElemTy = getVariableArrayType(ElemTy, /*ArraySize*/0, ArrayType::Normal, 1476 0, SourceRange()); 1477 } 1478 else 1479 assert(false && "DependentArrayType is seen"); 1480 } 1481 return ElemTy; 1482} 1483 1484/// getVariableArrayDecayedType - Returns a vla type where known sizes 1485/// are replaced with [*] 1486QualType ASTContext::getVariableArrayDecayedType(QualType Ty) { 1487 if (Ty->isPointerType()) { 1488 QualType BaseType = Ty->getAs<PointerType>()->getPointeeType(); 1489 if (isa<VariableArrayType>(BaseType)) { 1490 ArrayType *AT = dyn_cast<ArrayType>(BaseType); 1491 VariableArrayType *VAT = cast<VariableArrayType>(AT); 1492 if (VAT->getSizeExpr()) { 1493 Ty = getUnknownSizeVariableArrayType(BaseType); 1494 Ty = getPointerType(Ty); 1495 } 1496 } 1497 } 1498 return Ty; 1499} 1500 1501 1502/// getVariableArrayType - Returns a non-unique reference to the type for a 1503/// variable array of the specified element type. 1504QualType ASTContext::getVariableArrayType(QualType EltTy, 1505 Expr *NumElts, 1506 ArrayType::ArraySizeModifier ASM, 1507 unsigned EltTypeQuals, 1508 SourceRange Brackets) { 1509 // Since we don't unique expressions, it isn't possible to unique VLA's 1510 // that have an expression provided for their size. 1511 QualType CanonType; 1512 1513 if (!EltTy.isCanonical()) { 1514 CanonType = getVariableArrayType(getCanonicalType(EltTy), NumElts, ASM, 1515 EltTypeQuals, Brackets); 1516 } 1517 1518 VariableArrayType *New = new(*this, TypeAlignment) 1519 VariableArrayType(EltTy, CanonType, NumElts, ASM, EltTypeQuals, Brackets); 1520 1521 VariableArrayTypes.push_back(New); 1522 Types.push_back(New); 1523 return QualType(New, 0); 1524} 1525 1526/// getDependentSizedArrayType - Returns a non-unique reference to 1527/// the type for a dependently-sized array of the specified element 1528/// type. 1529QualType ASTContext::getDependentSizedArrayType(QualType EltTy, 1530 Expr *NumElts, 1531 ArrayType::ArraySizeModifier ASM, 1532 unsigned EltTypeQuals, 1533 SourceRange Brackets) { 1534 assert((!NumElts || NumElts->isTypeDependent() || 1535 NumElts->isValueDependent()) && 1536 "Size must be type- or value-dependent!"); 1537 1538 void *InsertPos = 0; 1539 DependentSizedArrayType *Canon = 0; 1540 llvm::FoldingSetNodeID ID; 1541 1542 QualType CanonicalEltTy = getCanonicalType(EltTy); 1543 if (NumElts) { 1544 // Dependently-sized array types that do not have a specified 1545 // number of elements will have their sizes deduced from an 1546 // initializer. 1547 DependentSizedArrayType::Profile(ID, *this, CanonicalEltTy, ASM, 1548 EltTypeQuals, NumElts); 1549 1550 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1551 } 1552 1553 DependentSizedArrayType *New; 1554 if (Canon) { 1555 // We already have a canonical version of this array type; use it as 1556 // the canonical type for a newly-built type. 1557 New = new (*this, TypeAlignment) 1558 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0), 1559 NumElts, ASM, EltTypeQuals, Brackets); 1560 } else if (CanonicalEltTy == EltTy) { 1561 // This is a canonical type. Record it. 1562 New = new (*this, TypeAlignment) 1563 DependentSizedArrayType(*this, EltTy, QualType(), 1564 NumElts, ASM, EltTypeQuals, Brackets); 1565 1566 if (NumElts) { 1567#ifndef NDEBUG 1568 DependentSizedArrayType *CanonCheck 1569 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1570 assert(!CanonCheck && "Dependent-sized canonical array type broken"); 1571 (void)CanonCheck; 1572#endif 1573 DependentSizedArrayTypes.InsertNode(New, InsertPos); 1574 } 1575 } else { 1576 QualType Canon = getDependentSizedArrayType(CanonicalEltTy, NumElts, 1577 ASM, EltTypeQuals, 1578 SourceRange()); 1579 New = new (*this, TypeAlignment) 1580 DependentSizedArrayType(*this, EltTy, Canon, 1581 NumElts, ASM, EltTypeQuals, Brackets); 1582 } 1583 1584 Types.push_back(New); 1585 return QualType(New, 0); 1586} 1587 1588QualType ASTContext::getIncompleteArrayType(QualType EltTy, 1589 ArrayType::ArraySizeModifier ASM, 1590 unsigned EltTypeQuals) { 1591 llvm::FoldingSetNodeID ID; 1592 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 1593 1594 void *InsertPos = 0; 1595 if (IncompleteArrayType *ATP = 1596 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1597 return QualType(ATP, 0); 1598 1599 // If the element type isn't canonical, this won't be a canonical type 1600 // either, so fill in the canonical type field. 1601 QualType Canonical; 1602 1603 if (!EltTy.isCanonical()) { 1604 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 1605 ASM, EltTypeQuals); 1606 1607 // Get the new insert position for the node we care about. 1608 IncompleteArrayType *NewIP = 1609 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1610 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1611 } 1612 1613 IncompleteArrayType *New = new (*this, TypeAlignment) 1614 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals); 1615 1616 IncompleteArrayTypes.InsertNode(New, InsertPos); 1617 Types.push_back(New); 1618 return QualType(New, 0); 1619} 1620 1621/// getVectorType - Return the unique reference to a vector type of 1622/// the specified element type and size. VectorType must be a built-in type. 1623QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 1624 VectorType::VectorKind VecKind) { 1625 BuiltinType *BaseType; 1626 1627 BaseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1628 assert(BaseType != 0 && "getVectorType(): Expecting a built-in type"); 1629 1630 // Check if we've already instantiated a vector of this type. 1631 llvm::FoldingSetNodeID ID; 1632 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 1633 1634 void *InsertPos = 0; 1635 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1636 return QualType(VTP, 0); 1637 1638 // If the element type isn't canonical, this won't be a canonical type either, 1639 // so fill in the canonical type field. 1640 QualType Canonical; 1641 if (!vecType.isCanonical()) { 1642 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 1643 1644 // Get the new insert position for the node we care about. 1645 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1646 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1647 } 1648 VectorType *New = new (*this, TypeAlignment) 1649 VectorType(vecType, NumElts, Canonical, VecKind); 1650 VectorTypes.InsertNode(New, InsertPos); 1651 Types.push_back(New); 1652 return QualType(New, 0); 1653} 1654 1655/// getExtVectorType - Return the unique reference to an extended vector type of 1656/// the specified element type and size. VectorType must be a built-in type. 1657QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 1658 BuiltinType *baseType; 1659 1660 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 1661 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 1662 1663 // Check if we've already instantiated a vector of this type. 1664 llvm::FoldingSetNodeID ID; 1665 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 1666 VectorType::GenericVector); 1667 void *InsertPos = 0; 1668 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 1669 return QualType(VTP, 0); 1670 1671 // If the element type isn't canonical, this won't be a canonical type either, 1672 // so fill in the canonical type field. 1673 QualType Canonical; 1674 if (!vecType.isCanonical()) { 1675 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 1676 1677 // Get the new insert position for the node we care about. 1678 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1679 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1680 } 1681 ExtVectorType *New = new (*this, TypeAlignment) 1682 ExtVectorType(vecType, NumElts, Canonical); 1683 VectorTypes.InsertNode(New, InsertPos); 1684 Types.push_back(New); 1685 return QualType(New, 0); 1686} 1687 1688QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, 1689 Expr *SizeExpr, 1690 SourceLocation AttrLoc) { 1691 llvm::FoldingSetNodeID ID; 1692 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 1693 SizeExpr); 1694 1695 void *InsertPos = 0; 1696 DependentSizedExtVectorType *Canon 1697 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1698 DependentSizedExtVectorType *New; 1699 if (Canon) { 1700 // We already have a canonical version of this array type; use it as 1701 // the canonical type for a newly-built type. 1702 New = new (*this, TypeAlignment) 1703 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 1704 SizeExpr, AttrLoc); 1705 } else { 1706 QualType CanonVecTy = getCanonicalType(vecType); 1707 if (CanonVecTy == vecType) { 1708 New = new (*this, TypeAlignment) 1709 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 1710 AttrLoc); 1711 1712 DependentSizedExtVectorType *CanonCheck 1713 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 1714 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 1715 (void)CanonCheck; 1716 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 1717 } else { 1718 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 1719 SourceLocation()); 1720 New = new (*this, TypeAlignment) 1721 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 1722 } 1723 } 1724 1725 Types.push_back(New); 1726 return QualType(New, 0); 1727} 1728 1729/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 1730/// 1731QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, 1732 const FunctionType::ExtInfo &Info) { 1733 const CallingConv CallConv = Info.getCC(); 1734 // Unique functions, to guarantee there is only one function of a particular 1735 // structure. 1736 llvm::FoldingSetNodeID ID; 1737 FunctionNoProtoType::Profile(ID, ResultTy, Info); 1738 1739 void *InsertPos = 0; 1740 if (FunctionNoProtoType *FT = 1741 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1742 return QualType(FT, 0); 1743 1744 QualType Canonical; 1745 if (!ResultTy.isCanonical() || 1746 getCanonicalCallConv(CallConv) != CallConv) { 1747 Canonical = 1748 getFunctionNoProtoType(getCanonicalType(ResultTy), 1749 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1750 1751 // Get the new insert position for the node we care about. 1752 FunctionNoProtoType *NewIP = 1753 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1754 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1755 } 1756 1757 FunctionNoProtoType *New = new (*this, TypeAlignment) 1758 FunctionNoProtoType(ResultTy, Canonical, Info); 1759 Types.push_back(New); 1760 FunctionNoProtoTypes.InsertNode(New, InsertPos); 1761 return QualType(New, 0); 1762} 1763 1764/// getFunctionType - Return a normal function type with a typed argument 1765/// list. isVariadic indicates whether the argument list includes '...'. 1766QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 1767 unsigned NumArgs, bool isVariadic, 1768 unsigned TypeQuals, bool hasExceptionSpec, 1769 bool hasAnyExceptionSpec, unsigned NumExs, 1770 const QualType *ExArray, 1771 const FunctionType::ExtInfo &Info) { 1772 1773 const CallingConv CallConv= Info.getCC(); 1774 // Unique functions, to guarantee there is only one function of a particular 1775 // structure. 1776 llvm::FoldingSetNodeID ID; 1777 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 1778 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1779 NumExs, ExArray, Info); 1780 1781 void *InsertPos = 0; 1782 if (FunctionProtoType *FTP = 1783 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 1784 return QualType(FTP, 0); 1785 1786 // Determine whether the type being created is already canonical or not. 1787 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical(); 1788 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 1789 if (!ArgArray[i].isCanonicalAsParam()) 1790 isCanonical = false; 1791 1792 // If this type isn't canonical, get the canonical version of it. 1793 // The exception spec is not part of the canonical type. 1794 QualType Canonical; 1795 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 1796 llvm::SmallVector<QualType, 16> CanonicalArgs; 1797 CanonicalArgs.reserve(NumArgs); 1798 for (unsigned i = 0; i != NumArgs; ++i) 1799 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 1800 1801 Canonical = getFunctionType(getCanonicalType(ResultTy), 1802 CanonicalArgs.data(), NumArgs, 1803 isVariadic, TypeQuals, false, 1804 false, 0, 0, 1805 Info.withCallingConv(getCanonicalCallConv(CallConv))); 1806 1807 // Get the new insert position for the node we care about. 1808 FunctionProtoType *NewIP = 1809 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 1810 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 1811 } 1812 1813 // FunctionProtoType objects are allocated with extra bytes after them 1814 // for two variable size arrays (for parameter and exception types) at the 1815 // end of them. 1816 FunctionProtoType *FTP = 1817 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 1818 NumArgs*sizeof(QualType) + 1819 NumExs*sizeof(QualType), TypeAlignment); 1820 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 1821 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 1822 ExArray, NumExs, Canonical, Info); 1823 Types.push_back(FTP); 1824 FunctionProtoTypes.InsertNode(FTP, InsertPos); 1825 return QualType(FTP, 0); 1826} 1827 1828#ifndef NDEBUG 1829static bool NeedsInjectedClassNameType(const RecordDecl *D) { 1830 if (!isa<CXXRecordDecl>(D)) return false; 1831 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 1832 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 1833 return true; 1834 if (RD->getDescribedClassTemplate() && 1835 !isa<ClassTemplateSpecializationDecl>(RD)) 1836 return true; 1837 return false; 1838} 1839#endif 1840 1841/// getInjectedClassNameType - Return the unique reference to the 1842/// injected class name type for the specified templated declaration. 1843QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 1844 QualType TST) { 1845 assert(NeedsInjectedClassNameType(Decl)); 1846 if (Decl->TypeForDecl) { 1847 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1848 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDeclaration()) { 1849 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 1850 Decl->TypeForDecl = PrevDecl->TypeForDecl; 1851 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 1852 } else { 1853 Decl->TypeForDecl = 1854 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 1855 Types.push_back(Decl->TypeForDecl); 1856 } 1857 return QualType(Decl->TypeForDecl, 0); 1858} 1859 1860/// getTypeDeclType - Return the unique reference to the type for the 1861/// specified type declaration. 1862QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) { 1863 assert(Decl && "Passed null for Decl param"); 1864 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 1865 1866 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 1867 return getTypedefType(Typedef); 1868 1869 assert(!isa<TemplateTypeParmDecl>(Decl) && 1870 "Template type parameter types are always available."); 1871 1872 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 1873 assert(!Record->getPreviousDeclaration() && 1874 "struct/union has previous declaration"); 1875 assert(!NeedsInjectedClassNameType(Record)); 1876 return getRecordType(Record); 1877 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 1878 assert(!Enum->getPreviousDeclaration() && 1879 "enum has previous declaration"); 1880 return getEnumType(Enum); 1881 } else if (const UnresolvedUsingTypenameDecl *Using = 1882 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 1883 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using); 1884 } else 1885 llvm_unreachable("TypeDecl without a type?"); 1886 1887 Types.push_back(Decl->TypeForDecl); 1888 return QualType(Decl->TypeForDecl, 0); 1889} 1890 1891/// getTypedefType - Return the unique reference to the type for the 1892/// specified typename decl. 1893QualType 1894ASTContext::getTypedefType(const TypedefDecl *Decl, QualType Canonical) { 1895 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1896 1897 if (Canonical.isNull()) 1898 Canonical = getCanonicalType(Decl->getUnderlyingType()); 1899 Decl->TypeForDecl = new(*this, TypeAlignment) 1900 TypedefType(Type::Typedef, Decl, Canonical); 1901 Types.push_back(Decl->TypeForDecl); 1902 return QualType(Decl->TypeForDecl, 0); 1903} 1904 1905QualType ASTContext::getRecordType(const RecordDecl *Decl) { 1906 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1907 1908 if (const RecordDecl *PrevDecl = Decl->getPreviousDeclaration()) 1909 if (PrevDecl->TypeForDecl) 1910 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 1911 1912 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Decl); 1913 Types.push_back(Decl->TypeForDecl); 1914 return QualType(Decl->TypeForDecl, 0); 1915} 1916 1917QualType ASTContext::getEnumType(const EnumDecl *Decl) { 1918 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 1919 1920 if (const EnumDecl *PrevDecl = Decl->getPreviousDeclaration()) 1921 if (PrevDecl->TypeForDecl) 1922 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 1923 1924 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Decl); 1925 Types.push_back(Decl->TypeForDecl); 1926 return QualType(Decl->TypeForDecl, 0); 1927} 1928 1929/// \brief Retrieve a substitution-result type. 1930QualType 1931ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 1932 QualType Replacement) { 1933 assert(Replacement.isCanonical() 1934 && "replacement types must always be canonical"); 1935 1936 llvm::FoldingSetNodeID ID; 1937 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 1938 void *InsertPos = 0; 1939 SubstTemplateTypeParmType *SubstParm 1940 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1941 1942 if (!SubstParm) { 1943 SubstParm = new (*this, TypeAlignment) 1944 SubstTemplateTypeParmType(Parm, Replacement); 1945 Types.push_back(SubstParm); 1946 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 1947 } 1948 1949 return QualType(SubstParm, 0); 1950} 1951 1952/// \brief Retrieve the template type parameter type for a template 1953/// parameter or parameter pack with the given depth, index, and (optionally) 1954/// name. 1955QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 1956 bool ParameterPack, 1957 IdentifierInfo *Name) { 1958 llvm::FoldingSetNodeID ID; 1959 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); 1960 void *InsertPos = 0; 1961 TemplateTypeParmType *TypeParm 1962 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1963 1964 if (TypeParm) 1965 return QualType(TypeParm, 0); 1966 1967 if (Name) { 1968 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 1969 TypeParm = new (*this, TypeAlignment) 1970 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon); 1971 1972 TemplateTypeParmType *TypeCheck 1973 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 1974 assert(!TypeCheck && "Template type parameter canonical type broken"); 1975 (void)TypeCheck; 1976 } else 1977 TypeParm = new (*this, TypeAlignment) 1978 TemplateTypeParmType(Depth, Index, ParameterPack); 1979 1980 Types.push_back(TypeParm); 1981 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 1982 1983 return QualType(TypeParm, 0); 1984} 1985 1986TypeSourceInfo * 1987ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 1988 SourceLocation NameLoc, 1989 const TemplateArgumentListInfo &Args, 1990 QualType CanonType) { 1991 QualType TST = getTemplateSpecializationType(Name, Args, CanonType); 1992 1993 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 1994 TemplateSpecializationTypeLoc TL 1995 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 1996 TL.setTemplateNameLoc(NameLoc); 1997 TL.setLAngleLoc(Args.getLAngleLoc()); 1998 TL.setRAngleLoc(Args.getRAngleLoc()); 1999 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 2000 TL.setArgLocInfo(i, Args[i].getLocInfo()); 2001 return DI; 2002} 2003 2004QualType 2005ASTContext::getTemplateSpecializationType(TemplateName Template, 2006 const TemplateArgumentListInfo &Args, 2007 QualType Canon) { 2008 unsigned NumArgs = Args.size(); 2009 2010 llvm::SmallVector<TemplateArgument, 4> ArgVec; 2011 ArgVec.reserve(NumArgs); 2012 for (unsigned i = 0; i != NumArgs; ++i) 2013 ArgVec.push_back(Args[i].getArgument()); 2014 2015 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 2016 Canon); 2017} 2018 2019QualType 2020ASTContext::getTemplateSpecializationType(TemplateName Template, 2021 const TemplateArgument *Args, 2022 unsigned NumArgs, 2023 QualType Canon) { 2024 if (!Canon.isNull()) 2025 Canon = getCanonicalType(Canon); 2026 else 2027 Canon = getCanonicalTemplateSpecializationType(Template, Args, NumArgs); 2028 2029 // Allocate the (non-canonical) template specialization type, but don't 2030 // try to unique it: these types typically have location information that 2031 // we don't unique and don't want to lose. 2032 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2033 sizeof(TemplateArgument) * NumArgs), 2034 TypeAlignment); 2035 TemplateSpecializationType *Spec 2036 = new (Mem) TemplateSpecializationType(Template, 2037 Args, NumArgs, 2038 Canon); 2039 2040 Types.push_back(Spec); 2041 return QualType(Spec, 0); 2042} 2043 2044QualType 2045ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2046 const TemplateArgument *Args, 2047 unsigned NumArgs) { 2048 // Build the canonical template specialization type. 2049 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2050 llvm::SmallVector<TemplateArgument, 4> CanonArgs; 2051 CanonArgs.reserve(NumArgs); 2052 for (unsigned I = 0; I != NumArgs; ++I) 2053 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2054 2055 // Determine whether this canonical template specialization type already 2056 // exists. 2057 llvm::FoldingSetNodeID ID; 2058 TemplateSpecializationType::Profile(ID, CanonTemplate, 2059 CanonArgs.data(), NumArgs, *this); 2060 2061 void *InsertPos = 0; 2062 TemplateSpecializationType *Spec 2063 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2064 2065 if (!Spec) { 2066 // Allocate a new canonical template specialization type. 2067 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2068 sizeof(TemplateArgument) * NumArgs), 2069 TypeAlignment); 2070 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2071 CanonArgs.data(), NumArgs, 2072 QualType()); 2073 Types.push_back(Spec); 2074 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2075 } 2076 2077 assert(Spec->isDependentType() && 2078 "Non-dependent template-id type must have a canonical type"); 2079 return QualType(Spec, 0); 2080} 2081 2082QualType 2083ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2084 NestedNameSpecifier *NNS, 2085 QualType NamedType) { 2086 llvm::FoldingSetNodeID ID; 2087 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2088 2089 void *InsertPos = 0; 2090 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2091 if (T) 2092 return QualType(T, 0); 2093 2094 QualType Canon = NamedType; 2095 if (!Canon.isCanonical()) { 2096 Canon = getCanonicalType(NamedType); 2097 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2098 assert(!CheckT && "Elaborated canonical type broken"); 2099 (void)CheckT; 2100 } 2101 2102 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2103 Types.push_back(T); 2104 ElaboratedTypes.InsertNode(T, InsertPos); 2105 return QualType(T, 0); 2106} 2107 2108QualType 2109ASTContext::getParenType(QualType InnerType) { 2110 llvm::FoldingSetNodeID ID; 2111 ParenType::Profile(ID, InnerType); 2112 2113 void *InsertPos = 0; 2114 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2115 if (T) 2116 return QualType(T, 0); 2117 2118 QualType Canon = InnerType; 2119 if (!Canon.isCanonical()) { 2120 Canon = getCanonicalType(InnerType); 2121 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2122 assert(!CheckT && "Paren canonical type broken"); 2123 (void)CheckT; 2124 } 2125 2126 T = new (*this) ParenType(InnerType, Canon); 2127 Types.push_back(T); 2128 ParenTypes.InsertNode(T, InsertPos); 2129 return QualType(T, 0); 2130} 2131 2132QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2133 NestedNameSpecifier *NNS, 2134 const IdentifierInfo *Name, 2135 QualType Canon) { 2136 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2137 2138 if (Canon.isNull()) { 2139 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2140 ElaboratedTypeKeyword CanonKeyword = Keyword; 2141 if (Keyword == ETK_None) 2142 CanonKeyword = ETK_Typename; 2143 2144 if (CanonNNS != NNS || CanonKeyword != Keyword) 2145 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2146 } 2147 2148 llvm::FoldingSetNodeID ID; 2149 DependentNameType::Profile(ID, Keyword, NNS, Name); 2150 2151 void *InsertPos = 0; 2152 DependentNameType *T 2153 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2154 if (T) 2155 return QualType(T, 0); 2156 2157 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2158 Types.push_back(T); 2159 DependentNameTypes.InsertNode(T, InsertPos); 2160 return QualType(T, 0); 2161} 2162 2163QualType 2164ASTContext::getDependentTemplateSpecializationType( 2165 ElaboratedTypeKeyword Keyword, 2166 NestedNameSpecifier *NNS, 2167 const IdentifierInfo *Name, 2168 const TemplateArgumentListInfo &Args) { 2169 // TODO: avoid this copy 2170 llvm::SmallVector<TemplateArgument, 16> ArgCopy; 2171 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2172 ArgCopy.push_back(Args[I].getArgument()); 2173 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2174 ArgCopy.size(), 2175 ArgCopy.data()); 2176} 2177 2178QualType 2179ASTContext::getDependentTemplateSpecializationType( 2180 ElaboratedTypeKeyword Keyword, 2181 NestedNameSpecifier *NNS, 2182 const IdentifierInfo *Name, 2183 unsigned NumArgs, 2184 const TemplateArgument *Args) { 2185 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2186 2187 llvm::FoldingSetNodeID ID; 2188 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2189 Name, NumArgs, Args); 2190 2191 void *InsertPos = 0; 2192 DependentTemplateSpecializationType *T 2193 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2194 if (T) 2195 return QualType(T, 0); 2196 2197 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2198 2199 ElaboratedTypeKeyword CanonKeyword = Keyword; 2200 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2201 2202 bool AnyNonCanonArgs = false; 2203 llvm::SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2204 for (unsigned I = 0; I != NumArgs; ++I) { 2205 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2206 if (!CanonArgs[I].structurallyEquals(Args[I])) 2207 AnyNonCanonArgs = true; 2208 } 2209 2210 QualType Canon; 2211 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2212 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2213 Name, NumArgs, 2214 CanonArgs.data()); 2215 2216 // Find the insert position again. 2217 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2218 } 2219 2220 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2221 sizeof(TemplateArgument) * NumArgs), 2222 TypeAlignment); 2223 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2224 Name, NumArgs, Args, Canon); 2225 Types.push_back(T); 2226 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2227 return QualType(T, 0); 2228} 2229 2230/// CmpProtocolNames - Comparison predicate for sorting protocols 2231/// alphabetically. 2232static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2233 const ObjCProtocolDecl *RHS) { 2234 return LHS->getDeclName() < RHS->getDeclName(); 2235} 2236 2237static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2238 unsigned NumProtocols) { 2239 if (NumProtocols == 0) return true; 2240 2241 for (unsigned i = 1; i != NumProtocols; ++i) 2242 if (!CmpProtocolNames(Protocols[i-1], Protocols[i])) 2243 return false; 2244 return true; 2245} 2246 2247static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2248 unsigned &NumProtocols) { 2249 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2250 2251 // Sort protocols, keyed by name. 2252 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2253 2254 // Remove duplicates. 2255 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2256 NumProtocols = ProtocolsEnd-Protocols; 2257} 2258 2259QualType ASTContext::getObjCObjectType(QualType BaseType, 2260 ObjCProtocolDecl * const *Protocols, 2261 unsigned NumProtocols) { 2262 // If the base type is an interface and there aren't any protocols 2263 // to add, then the interface type will do just fine. 2264 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 2265 return BaseType; 2266 2267 // Look in the folding set for an existing type. 2268 llvm::FoldingSetNodeID ID; 2269 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 2270 void *InsertPos = 0; 2271 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 2272 return QualType(QT, 0); 2273 2274 // Build the canonical type, which has the canonical base type and 2275 // a sorted-and-uniqued list of protocols. 2276 QualType Canonical; 2277 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 2278 if (!ProtocolsSorted || !BaseType.isCanonical()) { 2279 if (!ProtocolsSorted) { 2280 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 2281 Protocols + NumProtocols); 2282 unsigned UniqueCount = NumProtocols; 2283 2284 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 2285 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2286 &Sorted[0], UniqueCount); 2287 } else { 2288 Canonical = getObjCObjectType(getCanonicalType(BaseType), 2289 Protocols, NumProtocols); 2290 } 2291 2292 // Regenerate InsertPos. 2293 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 2294 } 2295 2296 unsigned Size = sizeof(ObjCObjectTypeImpl); 2297 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 2298 void *Mem = Allocate(Size, TypeAlignment); 2299 ObjCObjectTypeImpl *T = 2300 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 2301 2302 Types.push_back(T); 2303 ObjCObjectTypes.InsertNode(T, InsertPos); 2304 return QualType(T, 0); 2305} 2306 2307/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 2308/// the given object type. 2309QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) { 2310 llvm::FoldingSetNodeID ID; 2311 ObjCObjectPointerType::Profile(ID, ObjectT); 2312 2313 void *InsertPos = 0; 2314 if (ObjCObjectPointerType *QT = 2315 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 2316 return QualType(QT, 0); 2317 2318 // Find the canonical object type. 2319 QualType Canonical; 2320 if (!ObjectT.isCanonical()) { 2321 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 2322 2323 // Regenerate InsertPos. 2324 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 2325 } 2326 2327 // No match. 2328 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 2329 ObjCObjectPointerType *QType = 2330 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 2331 2332 Types.push_back(QType); 2333 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 2334 return QualType(QType, 0); 2335} 2336 2337/// getObjCInterfaceType - Return the unique reference to the type for the 2338/// specified ObjC interface decl. The list of protocols is optional. 2339QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl) { 2340 if (Decl->TypeForDecl) 2341 return QualType(Decl->TypeForDecl, 0); 2342 2343 // FIXME: redeclarations? 2344 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 2345 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 2346 Decl->TypeForDecl = T; 2347 Types.push_back(T); 2348 return QualType(T, 0); 2349} 2350 2351/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 2352/// TypeOfExprType AST's (since expression's are never shared). For example, 2353/// multiple declarations that refer to "typeof(x)" all contain different 2354/// DeclRefExpr's. This doesn't effect the type checker, since it operates 2355/// on canonical type's (which are always unique). 2356QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 2357 TypeOfExprType *toe; 2358 if (tofExpr->isTypeDependent()) { 2359 llvm::FoldingSetNodeID ID; 2360 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 2361 2362 void *InsertPos = 0; 2363 DependentTypeOfExprType *Canon 2364 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 2365 if (Canon) { 2366 // We already have a "canonical" version of an identical, dependent 2367 // typeof(expr) type. Use that as our canonical type. 2368 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 2369 QualType((TypeOfExprType*)Canon, 0)); 2370 } 2371 else { 2372 // Build a new, canonical typeof(expr) type. 2373 Canon 2374 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 2375 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 2376 toe = Canon; 2377 } 2378 } else { 2379 QualType Canonical = getCanonicalType(tofExpr->getType()); 2380 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 2381 } 2382 Types.push_back(toe); 2383 return QualType(toe, 0); 2384} 2385 2386/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 2387/// TypeOfType AST's. The only motivation to unique these nodes would be 2388/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 2389/// an issue. This doesn't effect the type checker, since it operates 2390/// on canonical type's (which are always unique). 2391QualType ASTContext::getTypeOfType(QualType tofType) { 2392 QualType Canonical = getCanonicalType(tofType); 2393 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 2394 Types.push_back(tot); 2395 return QualType(tot, 0); 2396} 2397 2398/// getDecltypeForExpr - Given an expr, will return the decltype for that 2399/// expression, according to the rules in C++0x [dcl.type.simple]p4 2400static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { 2401 if (e->isTypeDependent()) 2402 return Context.DependentTy; 2403 2404 // If e is an id expression or a class member access, decltype(e) is defined 2405 // as the type of the entity named by e. 2406 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 2407 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 2408 return VD->getType(); 2409 } 2410 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 2411 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 2412 return FD->getType(); 2413 } 2414 // If e is a function call or an invocation of an overloaded operator, 2415 // (parentheses around e are ignored), decltype(e) is defined as the 2416 // return type of that function. 2417 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 2418 return CE->getCallReturnType(); 2419 2420 QualType T = e->getType(); 2421 2422 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 2423 // defined as T&, otherwise decltype(e) is defined as T. 2424 if (e->isLValue()) 2425 T = Context.getLValueReferenceType(T); 2426 2427 return T; 2428} 2429 2430/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 2431/// DecltypeType AST's. The only motivation to unique these nodes would be 2432/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 2433/// an issue. This doesn't effect the type checker, since it operates 2434/// on canonical type's (which are always unique). 2435QualType ASTContext::getDecltypeType(Expr *e) { 2436 DecltypeType *dt; 2437 if (e->isTypeDependent()) { 2438 llvm::FoldingSetNodeID ID; 2439 DependentDecltypeType::Profile(ID, *this, e); 2440 2441 void *InsertPos = 0; 2442 DependentDecltypeType *Canon 2443 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 2444 if (Canon) { 2445 // We already have a "canonical" version of an equivalent, dependent 2446 // decltype type. Use that as our canonical type. 2447 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 2448 QualType((DecltypeType*)Canon, 0)); 2449 } 2450 else { 2451 // Build a new, canonical typeof(expr) type. 2452 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 2453 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 2454 dt = Canon; 2455 } 2456 } else { 2457 QualType T = getDecltypeForExpr(e, *this); 2458 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T)); 2459 } 2460 Types.push_back(dt); 2461 return QualType(dt, 0); 2462} 2463 2464/// getTagDeclType - Return the unique reference to the type for the 2465/// specified TagDecl (struct/union/class/enum) decl. 2466QualType ASTContext::getTagDeclType(const TagDecl *Decl) { 2467 assert (Decl); 2468 // FIXME: What is the design on getTagDeclType when it requires casting 2469 // away const? mutable? 2470 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 2471} 2472 2473/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 2474/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 2475/// needs to agree with the definition in <stddef.h>. 2476CanQualType ASTContext::getSizeType() const { 2477 return getFromTargetType(Target.getSizeType()); 2478} 2479 2480/// getSignedWCharType - Return the type of "signed wchar_t". 2481/// Used when in C++, as a GCC extension. 2482QualType ASTContext::getSignedWCharType() const { 2483 // FIXME: derive from "Target" ? 2484 return WCharTy; 2485} 2486 2487/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 2488/// Used when in C++, as a GCC extension. 2489QualType ASTContext::getUnsignedWCharType() const { 2490 // FIXME: derive from "Target" ? 2491 return UnsignedIntTy; 2492} 2493 2494/// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 2495/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 2496QualType ASTContext::getPointerDiffType() const { 2497 return getFromTargetType(Target.getPtrDiffType(0)); 2498} 2499 2500//===----------------------------------------------------------------------===// 2501// Type Operators 2502//===----------------------------------------------------------------------===// 2503 2504CanQualType ASTContext::getCanonicalParamType(QualType T) { 2505 // Push qualifiers into arrays, and then discard any remaining 2506 // qualifiers. 2507 T = getCanonicalType(T); 2508 T = getVariableArrayDecayedType(T); 2509 const Type *Ty = T.getTypePtr(); 2510 QualType Result; 2511 if (isa<ArrayType>(Ty)) { 2512 Result = getArrayDecayedType(QualType(Ty,0)); 2513 } else if (isa<FunctionType>(Ty)) { 2514 Result = getPointerType(QualType(Ty, 0)); 2515 } else { 2516 Result = QualType(Ty, 0); 2517 } 2518 2519 return CanQualType::CreateUnsafe(Result); 2520} 2521 2522/// getCanonicalType - Return the canonical (structural) type corresponding to 2523/// the specified potentially non-canonical type. The non-canonical version 2524/// of a type may have many "decorated" versions of types. Decorators can 2525/// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 2526/// to be free of any of these, allowing two canonical types to be compared 2527/// for exact equality with a simple pointer comparison. 2528CanQualType ASTContext::getCanonicalType(QualType T) { 2529 QualifierCollector Quals; 2530 const Type *Ptr = Quals.strip(T); 2531 QualType CanType = Ptr->getCanonicalTypeInternal(); 2532 2533 // The canonical internal type will be the canonical type *except* 2534 // that we push type qualifiers down through array types. 2535 2536 // If there are no new qualifiers to push down, stop here. 2537 if (!Quals.hasQualifiers()) 2538 return CanQualType::CreateUnsafe(CanType); 2539 2540 // If the type qualifiers are on an array type, get the canonical 2541 // type of the array with the qualifiers applied to the element 2542 // type. 2543 ArrayType *AT = dyn_cast<ArrayType>(CanType); 2544 if (!AT) 2545 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals)); 2546 2547 // Get the canonical version of the element with the extra qualifiers on it. 2548 // This can recursively sink qualifiers through multiple levels of arrays. 2549 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals); 2550 NewEltTy = getCanonicalType(NewEltTy); 2551 2552 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 2553 return CanQualType::CreateUnsafe( 2554 getConstantArrayType(NewEltTy, CAT->getSize(), 2555 CAT->getSizeModifier(), 2556 CAT->getIndexTypeCVRQualifiers())); 2557 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 2558 return CanQualType::CreateUnsafe( 2559 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 2560 IAT->getIndexTypeCVRQualifiers())); 2561 2562 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 2563 return CanQualType::CreateUnsafe( 2564 getDependentSizedArrayType(NewEltTy, 2565 DSAT->getSizeExpr(), 2566 DSAT->getSizeModifier(), 2567 DSAT->getIndexTypeCVRQualifiers(), 2568 DSAT->getBracketsRange())->getCanonicalTypeInternal()); 2569 2570 VariableArrayType *VAT = cast<VariableArrayType>(AT); 2571 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy, 2572 VAT->getSizeExpr(), 2573 VAT->getSizeModifier(), 2574 VAT->getIndexTypeCVRQualifiers(), 2575 VAT->getBracketsRange())); 2576} 2577 2578QualType ASTContext::getUnqualifiedArrayType(QualType T, 2579 Qualifiers &Quals) { 2580 Quals = T.getQualifiers(); 2581 const ArrayType *AT = getAsArrayType(T); 2582 if (!AT) { 2583 return T.getUnqualifiedType(); 2584 } 2585 2586 QualType Elt = AT->getElementType(); 2587 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals); 2588 if (Elt == UnqualElt) 2589 return T; 2590 2591 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 2592 return getConstantArrayType(UnqualElt, CAT->getSize(), 2593 CAT->getSizeModifier(), 0); 2594 } 2595 2596 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 2597 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0); 2598 } 2599 2600 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 2601 return getVariableArrayType(UnqualElt, 2602 VAT->getSizeExpr(), 2603 VAT->getSizeModifier(), 2604 VAT->getIndexTypeCVRQualifiers(), 2605 VAT->getBracketsRange()); 2606 } 2607 2608 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 2609 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr(), 2610 DSAT->getSizeModifier(), 0, 2611 SourceRange()); 2612} 2613 2614/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 2615/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 2616/// they point to and return true. If T1 and T2 aren't pointer types 2617/// or pointer-to-member types, or if they are not similar at this 2618/// level, returns false and leaves T1 and T2 unchanged. Top-level 2619/// qualifiers on T1 and T2 are ignored. This function will typically 2620/// be called in a loop that successively "unwraps" pointer and 2621/// pointer-to-member types to compare them at each level. 2622bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 2623 const PointerType *T1PtrType = T1->getAs<PointerType>(), 2624 *T2PtrType = T2->getAs<PointerType>(); 2625 if (T1PtrType && T2PtrType) { 2626 T1 = T1PtrType->getPointeeType(); 2627 T2 = T2PtrType->getPointeeType(); 2628 return true; 2629 } 2630 2631 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 2632 *T2MPType = T2->getAs<MemberPointerType>(); 2633 if (T1MPType && T2MPType && 2634 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 2635 QualType(T2MPType->getClass(), 0))) { 2636 T1 = T1MPType->getPointeeType(); 2637 T2 = T2MPType->getPointeeType(); 2638 return true; 2639 } 2640 2641 if (getLangOptions().ObjC1) { 2642 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 2643 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 2644 if (T1OPType && T2OPType) { 2645 T1 = T1OPType->getPointeeType(); 2646 T2 = T2OPType->getPointeeType(); 2647 return true; 2648 } 2649 } 2650 2651 // FIXME: Block pointers, too? 2652 2653 return false; 2654} 2655 2656DeclarationNameInfo ASTContext::getNameForTemplate(TemplateName Name, 2657 SourceLocation NameLoc) { 2658 if (TemplateDecl *TD = Name.getAsTemplateDecl()) 2659 // DNInfo work in progress: CHECKME: what about DNLoc? 2660 return DeclarationNameInfo(TD->getDeclName(), NameLoc); 2661 2662 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { 2663 DeclarationName DName; 2664 if (DTN->isIdentifier()) { 2665 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 2666 return DeclarationNameInfo(DName, NameLoc); 2667 } else { 2668 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 2669 // DNInfo work in progress: FIXME: source locations? 2670 DeclarationNameLoc DNLoc; 2671 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 2672 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 2673 return DeclarationNameInfo(DName, NameLoc, DNLoc); 2674 } 2675 } 2676 2677 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 2678 assert(Storage); 2679 // DNInfo work in progress: CHECKME: what about DNLoc? 2680 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 2681} 2682 2683TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 2684 if (TemplateDecl *Template = Name.getAsTemplateDecl()) { 2685 if (TemplateTemplateParmDecl *TTP 2686 = dyn_cast<TemplateTemplateParmDecl>(Template)) 2687 Template = getCanonicalTemplateTemplateParmDecl(TTP); 2688 2689 // The canonical template name is the canonical template declaration. 2690 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 2691 } 2692 2693 assert(!Name.getAsOverloadedTemplate()); 2694 2695 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 2696 assert(DTN && "Non-dependent template names must refer to template decls."); 2697 return DTN->CanonicalTemplateName; 2698} 2699 2700bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 2701 X = getCanonicalTemplateName(X); 2702 Y = getCanonicalTemplateName(Y); 2703 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 2704} 2705 2706TemplateArgument 2707ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { 2708 switch (Arg.getKind()) { 2709 case TemplateArgument::Null: 2710 return Arg; 2711 2712 case TemplateArgument::Expression: 2713 return Arg; 2714 2715 case TemplateArgument::Declaration: 2716 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl()); 2717 2718 case TemplateArgument::Template: 2719 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 2720 2721 case TemplateArgument::Integral: 2722 return TemplateArgument(*Arg.getAsIntegral(), 2723 getCanonicalType(Arg.getIntegralType())); 2724 2725 case TemplateArgument::Type: 2726 return TemplateArgument(getCanonicalType(Arg.getAsType())); 2727 2728 case TemplateArgument::Pack: { 2729 TemplateArgument *CanonArgs 2730 = new (*this) TemplateArgument[Arg.pack_size()]; 2731 unsigned Idx = 0; 2732 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 2733 AEnd = Arg.pack_end(); 2734 A != AEnd; (void)++A, ++Idx) 2735 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 2736 2737 return TemplateArgument(CanonArgs, Arg.pack_size()); 2738 } 2739 } 2740 2741 // Silence GCC warning 2742 assert(false && "Unhandled template argument kind"); 2743 return TemplateArgument(); 2744} 2745 2746NestedNameSpecifier * 2747ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 2748 if (!NNS) 2749 return 0; 2750 2751 switch (NNS->getKind()) { 2752 case NestedNameSpecifier::Identifier: 2753 // Canonicalize the prefix but keep the identifier the same. 2754 return NestedNameSpecifier::Create(*this, 2755 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 2756 NNS->getAsIdentifier()); 2757 2758 case NestedNameSpecifier::Namespace: 2759 // A namespace is canonical; build a nested-name-specifier with 2760 // this namespace and no prefix. 2761 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 2762 2763 case NestedNameSpecifier::TypeSpec: 2764 case NestedNameSpecifier::TypeSpecWithTemplate: { 2765 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 2766 2767 // If we have some kind of dependent-named type (e.g., "typename T::type"), 2768 // break it apart into its prefix and identifier, then reconsititute those 2769 // as the canonical nested-name-specifier. This is required to canonicalize 2770 // a dependent nested-name-specifier involving typedefs of dependent-name 2771 // types, e.g., 2772 // typedef typename T::type T1; 2773 // typedef typename T1::type T2; 2774 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) { 2775 NestedNameSpecifier *Prefix 2776 = getCanonicalNestedNameSpecifier(DNT->getQualifier()); 2777 return NestedNameSpecifier::Create(*this, Prefix, 2778 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 2779 } 2780 2781 // Do the same thing as above, but with dependent-named specializations. 2782 if (const DependentTemplateSpecializationType *DTST 2783 = T->getAs<DependentTemplateSpecializationType>()) { 2784 NestedNameSpecifier *Prefix 2785 = getCanonicalNestedNameSpecifier(DTST->getQualifier()); 2786 TemplateName Name 2787 = getDependentTemplateName(Prefix, DTST->getIdentifier()); 2788 T = getTemplateSpecializationType(Name, 2789 DTST->getArgs(), DTST->getNumArgs()); 2790 T = getCanonicalType(T); 2791 } 2792 2793 return NestedNameSpecifier::Create(*this, 0, false, T.getTypePtr()); 2794 } 2795 2796 case NestedNameSpecifier::Global: 2797 // The global specifier is canonical and unique. 2798 return NNS; 2799 } 2800 2801 // Required to silence a GCC warning 2802 return 0; 2803} 2804 2805 2806const ArrayType *ASTContext::getAsArrayType(QualType T) { 2807 // Handle the non-qualified case efficiently. 2808 if (!T.hasLocalQualifiers()) { 2809 // Handle the common positive case fast. 2810 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 2811 return AT; 2812 } 2813 2814 // Handle the common negative case fast. 2815 QualType CType = T->getCanonicalTypeInternal(); 2816 if (!isa<ArrayType>(CType)) 2817 return 0; 2818 2819 // Apply any qualifiers from the array type to the element type. This 2820 // implements C99 6.7.3p8: "If the specification of an array type includes 2821 // any type qualifiers, the element type is so qualified, not the array type." 2822 2823 // If we get here, we either have type qualifiers on the type, or we have 2824 // sugar such as a typedef in the way. If we have type qualifiers on the type 2825 // we must propagate them down into the element type. 2826 2827 QualifierCollector Qs; 2828 const Type *Ty = Qs.strip(T.getDesugaredType(*this)); 2829 2830 // If we have a simple case, just return now. 2831 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 2832 if (ATy == 0 || Qs.empty()) 2833 return ATy; 2834 2835 // Otherwise, we have an array and we have qualifiers on it. Push the 2836 // qualifiers into the array element type and return a new array type. 2837 // Get the canonical version of the element with the extra qualifiers on it. 2838 // This can recursively sink qualifiers through multiple levels of arrays. 2839 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs); 2840 2841 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 2842 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 2843 CAT->getSizeModifier(), 2844 CAT->getIndexTypeCVRQualifiers())); 2845 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 2846 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 2847 IAT->getSizeModifier(), 2848 IAT->getIndexTypeCVRQualifiers())); 2849 2850 if (const DependentSizedArrayType *DSAT 2851 = dyn_cast<DependentSizedArrayType>(ATy)) 2852 return cast<ArrayType>( 2853 getDependentSizedArrayType(NewEltTy, 2854 DSAT->getSizeExpr(), 2855 DSAT->getSizeModifier(), 2856 DSAT->getIndexTypeCVRQualifiers(), 2857 DSAT->getBracketsRange())); 2858 2859 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 2860 return cast<ArrayType>(getVariableArrayType(NewEltTy, 2861 VAT->getSizeExpr(), 2862 VAT->getSizeModifier(), 2863 VAT->getIndexTypeCVRQualifiers(), 2864 VAT->getBracketsRange())); 2865} 2866 2867/// getArrayDecayedType - Return the properly qualified result of decaying the 2868/// specified array type to a pointer. This operation is non-trivial when 2869/// handling typedefs etc. The canonical type of "T" must be an array type, 2870/// this returns a pointer to a properly qualified element of the array. 2871/// 2872/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 2873QualType ASTContext::getArrayDecayedType(QualType Ty) { 2874 // Get the element type with 'getAsArrayType' so that we don't lose any 2875 // typedefs in the element type of the array. This also handles propagation 2876 // of type qualifiers from the array type into the element type if present 2877 // (C99 6.7.3p8). 2878 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 2879 assert(PrettyArrayType && "Not an array type!"); 2880 2881 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 2882 2883 // int x[restrict 4] -> int *restrict 2884 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 2885} 2886 2887QualType ASTContext::getBaseElementType(QualType QT) { 2888 QualifierCollector Qs; 2889 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0))) 2890 QT = AT->getElementType(); 2891 return Qs.apply(*this, QT); 2892} 2893 2894QualType ASTContext::getBaseElementType(const ArrayType *AT) { 2895 QualType ElemTy = AT->getElementType(); 2896 2897 if (const ArrayType *AT = getAsArrayType(ElemTy)) 2898 return getBaseElementType(AT); 2899 2900 return ElemTy; 2901} 2902 2903/// getConstantArrayElementCount - Returns number of constant array elements. 2904uint64_t 2905ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 2906 uint64_t ElementCount = 1; 2907 do { 2908 ElementCount *= CA->getSize().getZExtValue(); 2909 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 2910 } while (CA); 2911 return ElementCount; 2912} 2913 2914/// getFloatingRank - Return a relative rank for floating point types. 2915/// This routine will assert if passed a built-in type that isn't a float. 2916static FloatingRank getFloatingRank(QualType T) { 2917 if (const ComplexType *CT = T->getAs<ComplexType>()) 2918 return getFloatingRank(CT->getElementType()); 2919 2920 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 2921 switch (T->getAs<BuiltinType>()->getKind()) { 2922 default: assert(0 && "getFloatingRank(): not a floating type"); 2923 case BuiltinType::Float: return FloatRank; 2924 case BuiltinType::Double: return DoubleRank; 2925 case BuiltinType::LongDouble: return LongDoubleRank; 2926 } 2927} 2928 2929/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 2930/// point or a complex type (based on typeDomain/typeSize). 2931/// 'typeDomain' is a real floating point or complex type. 2932/// 'typeSize' is a real floating point or complex type. 2933QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 2934 QualType Domain) const { 2935 FloatingRank EltRank = getFloatingRank(Size); 2936 if (Domain->isComplexType()) { 2937 switch (EltRank) { 2938 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2939 case FloatRank: return FloatComplexTy; 2940 case DoubleRank: return DoubleComplexTy; 2941 case LongDoubleRank: return LongDoubleComplexTy; 2942 } 2943 } 2944 2945 assert(Domain->isRealFloatingType() && "Unknown domain!"); 2946 switch (EltRank) { 2947 default: assert(0 && "getFloatingRank(): illegal value for rank"); 2948 case FloatRank: return FloatTy; 2949 case DoubleRank: return DoubleTy; 2950 case LongDoubleRank: return LongDoubleTy; 2951 } 2952} 2953 2954/// getFloatingTypeOrder - Compare the rank of the two specified floating 2955/// point types, ignoring the domain of the type (i.e. 'double' == 2956/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 2957/// LHS < RHS, return -1. 2958int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 2959 FloatingRank LHSR = getFloatingRank(LHS); 2960 FloatingRank RHSR = getFloatingRank(RHS); 2961 2962 if (LHSR == RHSR) 2963 return 0; 2964 if (LHSR > RHSR) 2965 return 1; 2966 return -1; 2967} 2968 2969/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 2970/// routine will assert if passed a built-in type that isn't an integer or enum, 2971/// or if it is not canonicalized. 2972unsigned ASTContext::getIntegerRank(Type *T) { 2973 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 2974 if (EnumType* ET = dyn_cast<EnumType>(T)) 2975 T = ET->getDecl()->getPromotionType().getTypePtr(); 2976 2977 if (T->isSpecificBuiltinType(BuiltinType::WChar)) 2978 T = getFromTargetType(Target.getWCharType()).getTypePtr(); 2979 2980 if (T->isSpecificBuiltinType(BuiltinType::Char16)) 2981 T = getFromTargetType(Target.getChar16Type()).getTypePtr(); 2982 2983 if (T->isSpecificBuiltinType(BuiltinType::Char32)) 2984 T = getFromTargetType(Target.getChar32Type()).getTypePtr(); 2985 2986 switch (cast<BuiltinType>(T)->getKind()) { 2987 default: assert(0 && "getIntegerRank(): not a built-in integer"); 2988 case BuiltinType::Bool: 2989 return 1 + (getIntWidth(BoolTy) << 3); 2990 case BuiltinType::Char_S: 2991 case BuiltinType::Char_U: 2992 case BuiltinType::SChar: 2993 case BuiltinType::UChar: 2994 return 2 + (getIntWidth(CharTy) << 3); 2995 case BuiltinType::Short: 2996 case BuiltinType::UShort: 2997 return 3 + (getIntWidth(ShortTy) << 3); 2998 case BuiltinType::Int: 2999 case BuiltinType::UInt: 3000 return 4 + (getIntWidth(IntTy) << 3); 3001 case BuiltinType::Long: 3002 case BuiltinType::ULong: 3003 return 5 + (getIntWidth(LongTy) << 3); 3004 case BuiltinType::LongLong: 3005 case BuiltinType::ULongLong: 3006 return 6 + (getIntWidth(LongLongTy) << 3); 3007 case BuiltinType::Int128: 3008 case BuiltinType::UInt128: 3009 return 7 + (getIntWidth(Int128Ty) << 3); 3010 } 3011} 3012 3013/// \brief Whether this is a promotable bitfield reference according 3014/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3015/// 3016/// \returns the type this bit-field will promote to, or NULL if no 3017/// promotion occurs. 3018QualType ASTContext::isPromotableBitField(Expr *E) { 3019 if (E->isTypeDependent() || E->isValueDependent()) 3020 return QualType(); 3021 3022 FieldDecl *Field = E->getBitField(); 3023 if (!Field) 3024 return QualType(); 3025 3026 QualType FT = Field->getType(); 3027 3028 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this); 3029 uint64_t BitWidth = BitWidthAP.getZExtValue(); 3030 uint64_t IntSize = getTypeSize(IntTy); 3031 // GCC extension compatibility: if the bit-field size is less than or equal 3032 // to the size of int, it gets promoted no matter what its type is. 3033 // For instance, unsigned long bf : 4 gets promoted to signed int. 3034 if (BitWidth < IntSize) 3035 return IntTy; 3036 3037 if (BitWidth == IntSize) 3038 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3039 3040 // Types bigger than int are not subject to promotions, and therefore act 3041 // like the base type. 3042 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3043 // is ridiculous. 3044 return QualType(); 3045} 3046 3047/// getPromotedIntegerType - Returns the type that Promotable will 3048/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3049/// integer type. 3050QualType ASTContext::getPromotedIntegerType(QualType Promotable) { 3051 assert(!Promotable.isNull()); 3052 assert(Promotable->isPromotableIntegerType()); 3053 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3054 return ET->getDecl()->getPromotionType(); 3055 if (Promotable->isSignedIntegerType()) 3056 return IntTy; 3057 uint64_t PromotableSize = getTypeSize(Promotable); 3058 uint64_t IntSize = getTypeSize(IntTy); 3059 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 3060 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 3061} 3062 3063/// getIntegerTypeOrder - Returns the highest ranked integer type: 3064/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 3065/// LHS < RHS, return -1. 3066int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 3067 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 3068 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 3069 if (LHSC == RHSC) return 0; 3070 3071 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 3072 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 3073 3074 unsigned LHSRank = getIntegerRank(LHSC); 3075 unsigned RHSRank = getIntegerRank(RHSC); 3076 3077 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 3078 if (LHSRank == RHSRank) return 0; 3079 return LHSRank > RHSRank ? 1 : -1; 3080 } 3081 3082 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3083 if (LHSUnsigned) { 3084 // If the unsigned [LHS] type is larger, return it. 3085 if (LHSRank >= RHSRank) 3086 return 1; 3087 3088 // If the signed type can represent all values of the unsigned type, it 3089 // wins. Because we are dealing with 2's complement and types that are 3090 // powers of two larger than each other, this is always safe. 3091 return -1; 3092 } 3093 3094 // If the unsigned [RHS] type is larger, return it. 3095 if (RHSRank >= LHSRank) 3096 return -1; 3097 3098 // If the signed type can represent all values of the unsigned type, it 3099 // wins. Because we are dealing with 2's complement and types that are 3100 // powers of two larger than each other, this is always safe. 3101 return 1; 3102} 3103 3104static RecordDecl * 3105CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC, 3106 SourceLocation L, IdentifierInfo *Id) { 3107 if (Ctx.getLangOptions().CPlusPlus) 3108 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id); 3109 else 3110 return RecordDecl::Create(Ctx, TK, DC, L, Id); 3111} 3112 3113// getCFConstantStringType - Return the type used for constant CFStrings. 3114QualType ASTContext::getCFConstantStringType() { 3115 if (!CFConstantStringTypeDecl) { 3116 CFConstantStringTypeDecl = 3117 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3118 &Idents.get("NSConstantString")); 3119 CFConstantStringTypeDecl->startDefinition(); 3120 3121 QualType FieldTypes[4]; 3122 3123 // const int *isa; 3124 FieldTypes[0] = getPointerType(IntTy.withConst()); 3125 // int flags; 3126 FieldTypes[1] = IntTy; 3127 // const char *str; 3128 FieldTypes[2] = getPointerType(CharTy.withConst()); 3129 // long length; 3130 FieldTypes[3] = LongTy; 3131 3132 // Create fields 3133 for (unsigned i = 0; i < 4; ++i) { 3134 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 3135 SourceLocation(), 0, 3136 FieldTypes[i], /*TInfo=*/0, 3137 /*BitWidth=*/0, 3138 /*Mutable=*/false); 3139 Field->setAccess(AS_public); 3140 CFConstantStringTypeDecl->addDecl(Field); 3141 } 3142 3143 CFConstantStringTypeDecl->completeDefinition(); 3144 } 3145 3146 return getTagDeclType(CFConstantStringTypeDecl); 3147} 3148 3149void ASTContext::setCFConstantStringType(QualType T) { 3150 const RecordType *Rec = T->getAs<RecordType>(); 3151 assert(Rec && "Invalid CFConstantStringType"); 3152 CFConstantStringTypeDecl = Rec->getDecl(); 3153} 3154 3155// getNSConstantStringType - Return the type used for constant NSStrings. 3156QualType ASTContext::getNSConstantStringType() { 3157 if (!NSConstantStringTypeDecl) { 3158 NSConstantStringTypeDecl = 3159 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3160 &Idents.get("__builtin_NSString")); 3161 NSConstantStringTypeDecl->startDefinition(); 3162 3163 QualType FieldTypes[3]; 3164 3165 // const int *isa; 3166 FieldTypes[0] = getPointerType(IntTy.withConst()); 3167 // const char *str; 3168 FieldTypes[1] = getPointerType(CharTy.withConst()); 3169 // unsigned int length; 3170 FieldTypes[2] = UnsignedIntTy; 3171 3172 // Create fields 3173 for (unsigned i = 0; i < 3; ++i) { 3174 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl, 3175 SourceLocation(), 0, 3176 FieldTypes[i], /*TInfo=*/0, 3177 /*BitWidth=*/0, 3178 /*Mutable=*/false); 3179 Field->setAccess(AS_public); 3180 NSConstantStringTypeDecl->addDecl(Field); 3181 } 3182 3183 NSConstantStringTypeDecl->completeDefinition(); 3184 } 3185 3186 return getTagDeclType(NSConstantStringTypeDecl); 3187} 3188 3189void ASTContext::setNSConstantStringType(QualType T) { 3190 const RecordType *Rec = T->getAs<RecordType>(); 3191 assert(Rec && "Invalid NSConstantStringType"); 3192 NSConstantStringTypeDecl = Rec->getDecl(); 3193} 3194 3195QualType ASTContext::getObjCFastEnumerationStateType() { 3196 if (!ObjCFastEnumerationStateTypeDecl) { 3197 ObjCFastEnumerationStateTypeDecl = 3198 CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3199 &Idents.get("__objcFastEnumerationState")); 3200 ObjCFastEnumerationStateTypeDecl->startDefinition(); 3201 3202 QualType FieldTypes[] = { 3203 UnsignedLongTy, 3204 getPointerType(ObjCIdTypedefType), 3205 getPointerType(UnsignedLongTy), 3206 getConstantArrayType(UnsignedLongTy, 3207 llvm::APInt(32, 5), ArrayType::Normal, 0) 3208 }; 3209 3210 for (size_t i = 0; i < 4; ++i) { 3211 FieldDecl *Field = FieldDecl::Create(*this, 3212 ObjCFastEnumerationStateTypeDecl, 3213 SourceLocation(), 0, 3214 FieldTypes[i], /*TInfo=*/0, 3215 /*BitWidth=*/0, 3216 /*Mutable=*/false); 3217 Field->setAccess(AS_public); 3218 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 3219 } 3220 3221 ObjCFastEnumerationStateTypeDecl->completeDefinition(); 3222 } 3223 3224 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 3225} 3226 3227QualType ASTContext::getBlockDescriptorType() { 3228 if (BlockDescriptorType) 3229 return getTagDeclType(BlockDescriptorType); 3230 3231 RecordDecl *T; 3232 // FIXME: Needs the FlagAppleBlock bit. 3233 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3234 &Idents.get("__block_descriptor")); 3235 T->startDefinition(); 3236 3237 QualType FieldTypes[] = { 3238 UnsignedLongTy, 3239 UnsignedLongTy, 3240 }; 3241 3242 const char *FieldNames[] = { 3243 "reserved", 3244 "Size" 3245 }; 3246 3247 for (size_t i = 0; i < 2; ++i) { 3248 FieldDecl *Field = FieldDecl::Create(*this, 3249 T, 3250 SourceLocation(), 3251 &Idents.get(FieldNames[i]), 3252 FieldTypes[i], /*TInfo=*/0, 3253 /*BitWidth=*/0, 3254 /*Mutable=*/false); 3255 Field->setAccess(AS_public); 3256 T->addDecl(Field); 3257 } 3258 3259 T->completeDefinition(); 3260 3261 BlockDescriptorType = T; 3262 3263 return getTagDeclType(BlockDescriptorType); 3264} 3265 3266void ASTContext::setBlockDescriptorType(QualType T) { 3267 const RecordType *Rec = T->getAs<RecordType>(); 3268 assert(Rec && "Invalid BlockDescriptorType"); 3269 BlockDescriptorType = Rec->getDecl(); 3270} 3271 3272QualType ASTContext::getBlockDescriptorExtendedType() { 3273 if (BlockDescriptorExtendedType) 3274 return getTagDeclType(BlockDescriptorExtendedType); 3275 3276 RecordDecl *T; 3277 // FIXME: Needs the FlagAppleBlock bit. 3278 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3279 &Idents.get("__block_descriptor_withcopydispose")); 3280 T->startDefinition(); 3281 3282 QualType FieldTypes[] = { 3283 UnsignedLongTy, 3284 UnsignedLongTy, 3285 getPointerType(VoidPtrTy), 3286 getPointerType(VoidPtrTy) 3287 }; 3288 3289 const char *FieldNames[] = { 3290 "reserved", 3291 "Size", 3292 "CopyFuncPtr", 3293 "DestroyFuncPtr" 3294 }; 3295 3296 for (size_t i = 0; i < 4; ++i) { 3297 FieldDecl *Field = FieldDecl::Create(*this, 3298 T, 3299 SourceLocation(), 3300 &Idents.get(FieldNames[i]), 3301 FieldTypes[i], /*TInfo=*/0, 3302 /*BitWidth=*/0, 3303 /*Mutable=*/false); 3304 Field->setAccess(AS_public); 3305 T->addDecl(Field); 3306 } 3307 3308 T->completeDefinition(); 3309 3310 BlockDescriptorExtendedType = T; 3311 3312 return getTagDeclType(BlockDescriptorExtendedType); 3313} 3314 3315void ASTContext::setBlockDescriptorExtendedType(QualType T) { 3316 const RecordType *Rec = T->getAs<RecordType>(); 3317 assert(Rec && "Invalid BlockDescriptorType"); 3318 BlockDescriptorExtendedType = Rec->getDecl(); 3319} 3320 3321bool ASTContext::BlockRequiresCopying(QualType Ty) { 3322 if (Ty->isBlockPointerType()) 3323 return true; 3324 if (isObjCNSObjectType(Ty)) 3325 return true; 3326 if (Ty->isObjCObjectPointerType()) 3327 return true; 3328 if (getLangOptions().CPlusPlus) { 3329 if (const RecordType *RT = Ty->getAs<RecordType>()) { 3330 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 3331 return RD->hasConstCopyConstructor(*this); 3332 3333 } 3334 } 3335 return false; 3336} 3337 3338QualType ASTContext::BuildByRefType(llvm::StringRef DeclName, QualType Ty) { 3339 // type = struct __Block_byref_1_X { 3340 // void *__isa; 3341 // struct __Block_byref_1_X *__forwarding; 3342 // unsigned int __flags; 3343 // unsigned int __size; 3344 // void *__copy_helper; // as needed 3345 // void *__destroy_help // as needed 3346 // int X; 3347 // } * 3348 3349 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 3350 3351 // FIXME: Move up 3352 llvm::SmallString<36> Name; 3353 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 3354 ++UniqueBlockByRefTypeID << '_' << DeclName; 3355 RecordDecl *T; 3356 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3357 &Idents.get(Name.str())); 3358 T->startDefinition(); 3359 QualType Int32Ty = IntTy; 3360 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 3361 QualType FieldTypes[] = { 3362 getPointerType(VoidPtrTy), 3363 getPointerType(getTagDeclType(T)), 3364 Int32Ty, 3365 Int32Ty, 3366 getPointerType(VoidPtrTy), 3367 getPointerType(VoidPtrTy), 3368 Ty 3369 }; 3370 3371 llvm::StringRef FieldNames[] = { 3372 "__isa", 3373 "__forwarding", 3374 "__flags", 3375 "__size", 3376 "__copy_helper", 3377 "__destroy_helper", 3378 DeclName, 3379 }; 3380 3381 for (size_t i = 0; i < 7; ++i) { 3382 if (!HasCopyAndDispose && i >=4 && i <= 5) 3383 continue; 3384 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3385 &Idents.get(FieldNames[i]), 3386 FieldTypes[i], /*TInfo=*/0, 3387 /*BitWidth=*/0, /*Mutable=*/false); 3388 Field->setAccess(AS_public); 3389 T->addDecl(Field); 3390 } 3391 3392 T->completeDefinition(); 3393 3394 return getPointerType(getTagDeclType(T)); 3395} 3396 3397 3398QualType ASTContext::getBlockParmType( 3399 bool BlockHasCopyDispose, 3400 llvm::SmallVectorImpl<const Expr *> &Layout) { 3401 3402 // FIXME: Move up 3403 llvm::SmallString<36> Name; 3404 llvm::raw_svector_ostream(Name) << "__block_literal_" 3405 << ++UniqueBlockParmTypeID; 3406 RecordDecl *T; 3407 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, SourceLocation(), 3408 &Idents.get(Name.str())); 3409 T->startDefinition(); 3410 QualType FieldTypes[] = { 3411 getPointerType(VoidPtrTy), 3412 IntTy, 3413 IntTy, 3414 getPointerType(VoidPtrTy), 3415 (BlockHasCopyDispose ? 3416 getPointerType(getBlockDescriptorExtendedType()) : 3417 getPointerType(getBlockDescriptorType())) 3418 }; 3419 3420 const char *FieldNames[] = { 3421 "__isa", 3422 "__flags", 3423 "__reserved", 3424 "__FuncPtr", 3425 "__descriptor" 3426 }; 3427 3428 for (size_t i = 0; i < 5; ++i) { 3429 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3430 &Idents.get(FieldNames[i]), 3431 FieldTypes[i], /*TInfo=*/0, 3432 /*BitWidth=*/0, /*Mutable=*/false); 3433 Field->setAccess(AS_public); 3434 T->addDecl(Field); 3435 } 3436 3437 for (unsigned i = 0; i < Layout.size(); ++i) { 3438 const Expr *E = Layout[i]; 3439 3440 QualType FieldType = E->getType(); 3441 IdentifierInfo *FieldName = 0; 3442 if (isa<CXXThisExpr>(E)) { 3443 FieldName = &Idents.get("this"); 3444 } else if (const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E)) { 3445 const ValueDecl *D = BDRE->getDecl(); 3446 FieldName = D->getIdentifier(); 3447 if (BDRE->isByRef()) 3448 FieldType = BuildByRefType(D->getName(), FieldType); 3449 } else { 3450 // Padding. 3451 assert(isa<ConstantArrayType>(FieldType) && 3452 isa<DeclRefExpr>(E) && 3453 !cast<DeclRefExpr>(E)->getDecl()->getDeclName() && 3454 "doesn't match characteristics of padding decl"); 3455 } 3456 3457 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 3458 FieldName, FieldType, /*TInfo=*/0, 3459 /*BitWidth=*/0, /*Mutable=*/false); 3460 Field->setAccess(AS_public); 3461 T->addDecl(Field); 3462 } 3463 3464 T->completeDefinition(); 3465 3466 return getPointerType(getTagDeclType(T)); 3467} 3468 3469void ASTContext::setObjCFastEnumerationStateType(QualType T) { 3470 const RecordType *Rec = T->getAs<RecordType>(); 3471 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 3472 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 3473} 3474 3475// This returns true if a type has been typedefed to BOOL: 3476// typedef <type> BOOL; 3477static bool isTypeTypedefedAsBOOL(QualType T) { 3478 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 3479 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 3480 return II->isStr("BOOL"); 3481 3482 return false; 3483} 3484 3485/// getObjCEncodingTypeSize returns size of type for objective-c encoding 3486/// purpose. 3487CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) { 3488 CharUnits sz = getTypeSizeInChars(type); 3489 3490 // Make all integer and enum types at least as large as an int 3491 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 3492 sz = std::max(sz, getTypeSizeInChars(IntTy)); 3493 // Treat arrays as pointers, since that's how they're passed in. 3494 else if (type->isArrayType()) 3495 sz = getTypeSizeInChars(VoidPtrTy); 3496 return sz; 3497} 3498 3499static inline 3500std::string charUnitsToString(const CharUnits &CU) { 3501 return llvm::itostr(CU.getQuantity()); 3502} 3503 3504/// getObjCEncodingForBlockDecl - Return the encoded type for this block 3505/// declaration. 3506void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr, 3507 std::string& S) { 3508 const BlockDecl *Decl = Expr->getBlockDecl(); 3509 QualType BlockTy = 3510 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 3511 // Encode result type. 3512 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 3513 // Compute size of all parameters. 3514 // Start with computing size of a pointer in number of bytes. 3515 // FIXME: There might(should) be a better way of doing this computation! 3516 SourceLocation Loc; 3517 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3518 CharUnits ParmOffset = PtrSize; 3519 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 3520 E = Decl->param_end(); PI != E; ++PI) { 3521 QualType PType = (*PI)->getType(); 3522 CharUnits sz = getObjCEncodingTypeSize(PType); 3523 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 3524 ParmOffset += sz; 3525 } 3526 // Size of the argument frame 3527 S += charUnitsToString(ParmOffset); 3528 // Block pointer and offset. 3529 S += "@?0"; 3530 ParmOffset = PtrSize; 3531 3532 // Argument types. 3533 ParmOffset = PtrSize; 3534 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 3535 Decl->param_end(); PI != E; ++PI) { 3536 ParmVarDecl *PVDecl = *PI; 3537 QualType PType = PVDecl->getOriginalType(); 3538 if (const ArrayType *AT = 3539 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3540 // Use array's original type only if it has known number of 3541 // elements. 3542 if (!isa<ConstantArrayType>(AT)) 3543 PType = PVDecl->getType(); 3544 } else if (PType->isFunctionType()) 3545 PType = PVDecl->getType(); 3546 getObjCEncodingForType(PType, S); 3547 S += charUnitsToString(ParmOffset); 3548 ParmOffset += getObjCEncodingTypeSize(PType); 3549 } 3550} 3551 3552/// getObjCEncodingForMethodDecl - Return the encoded type for this method 3553/// declaration. 3554void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 3555 std::string& S) { 3556 // FIXME: This is not very efficient. 3557 // Encode type qualifer, 'in', 'inout', etc. for the return type. 3558 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 3559 // Encode result type. 3560 getObjCEncodingForType(Decl->getResultType(), S); 3561 // Compute size of all parameters. 3562 // Start with computing size of a pointer in number of bytes. 3563 // FIXME: There might(should) be a better way of doing this computation! 3564 SourceLocation Loc; 3565 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 3566 // The first two arguments (self and _cmd) are pointers; account for 3567 // their size. 3568 CharUnits ParmOffset = 2 * PtrSize; 3569 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3570 E = Decl->sel_param_end(); PI != E; ++PI) { 3571 QualType PType = (*PI)->getType(); 3572 CharUnits sz = getObjCEncodingTypeSize(PType); 3573 assert (sz.isPositive() && 3574 "getObjCEncodingForMethodDecl - Incomplete param type"); 3575 ParmOffset += sz; 3576 } 3577 S += charUnitsToString(ParmOffset); 3578 S += "@0:"; 3579 S += charUnitsToString(PtrSize); 3580 3581 // Argument types. 3582 ParmOffset = 2 * PtrSize; 3583 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 3584 E = Decl->sel_param_end(); PI != E; ++PI) { 3585 ParmVarDecl *PVDecl = *PI; 3586 QualType PType = PVDecl->getOriginalType(); 3587 if (const ArrayType *AT = 3588 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 3589 // Use array's original type only if it has known number of 3590 // elements. 3591 if (!isa<ConstantArrayType>(AT)) 3592 PType = PVDecl->getType(); 3593 } else if (PType->isFunctionType()) 3594 PType = PVDecl->getType(); 3595 // Process argument qualifiers for user supplied arguments; such as, 3596 // 'in', 'inout', etc. 3597 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 3598 getObjCEncodingForType(PType, S); 3599 S += charUnitsToString(ParmOffset); 3600 ParmOffset += getObjCEncodingTypeSize(PType); 3601 } 3602} 3603 3604/// getObjCEncodingForPropertyDecl - Return the encoded type for this 3605/// property declaration. If non-NULL, Container must be either an 3606/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 3607/// NULL when getting encodings for protocol properties. 3608/// Property attributes are stored as a comma-delimited C string. The simple 3609/// attributes readonly and bycopy are encoded as single characters. The 3610/// parametrized attributes, getter=name, setter=name, and ivar=name, are 3611/// encoded as single characters, followed by an identifier. Property types 3612/// are also encoded as a parametrized attribute. The characters used to encode 3613/// these attributes are defined by the following enumeration: 3614/// @code 3615/// enum PropertyAttributes { 3616/// kPropertyReadOnly = 'R', // property is read-only. 3617/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 3618/// kPropertyByref = '&', // property is a reference to the value last assigned 3619/// kPropertyDynamic = 'D', // property is dynamic 3620/// kPropertyGetter = 'G', // followed by getter selector name 3621/// kPropertySetter = 'S', // followed by setter selector name 3622/// kPropertyInstanceVariable = 'V' // followed by instance variable name 3623/// kPropertyType = 't' // followed by old-style type encoding. 3624/// kPropertyWeak = 'W' // 'weak' property 3625/// kPropertyStrong = 'P' // property GC'able 3626/// kPropertyNonAtomic = 'N' // property non-atomic 3627/// }; 3628/// @endcode 3629void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 3630 const Decl *Container, 3631 std::string& S) { 3632 // Collect information from the property implementation decl(s). 3633 bool Dynamic = false; 3634 ObjCPropertyImplDecl *SynthesizePID = 0; 3635 3636 // FIXME: Duplicated code due to poor abstraction. 3637 if (Container) { 3638 if (const ObjCCategoryImplDecl *CID = 3639 dyn_cast<ObjCCategoryImplDecl>(Container)) { 3640 for (ObjCCategoryImplDecl::propimpl_iterator 3641 i = CID->propimpl_begin(), e = CID->propimpl_end(); 3642 i != e; ++i) { 3643 ObjCPropertyImplDecl *PID = *i; 3644 if (PID->getPropertyDecl() == PD) { 3645 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3646 Dynamic = true; 3647 } else { 3648 SynthesizePID = PID; 3649 } 3650 } 3651 } 3652 } else { 3653 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 3654 for (ObjCCategoryImplDecl::propimpl_iterator 3655 i = OID->propimpl_begin(), e = OID->propimpl_end(); 3656 i != e; ++i) { 3657 ObjCPropertyImplDecl *PID = *i; 3658 if (PID->getPropertyDecl() == PD) { 3659 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 3660 Dynamic = true; 3661 } else { 3662 SynthesizePID = PID; 3663 } 3664 } 3665 } 3666 } 3667 } 3668 3669 // FIXME: This is not very efficient. 3670 S = "T"; 3671 3672 // Encode result type. 3673 // GCC has some special rules regarding encoding of properties which 3674 // closely resembles encoding of ivars. 3675 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 3676 true /* outermost type */, 3677 true /* encoding for property */); 3678 3679 if (PD->isReadOnly()) { 3680 S += ",R"; 3681 } else { 3682 switch (PD->getSetterKind()) { 3683 case ObjCPropertyDecl::Assign: break; 3684 case ObjCPropertyDecl::Copy: S += ",C"; break; 3685 case ObjCPropertyDecl::Retain: S += ",&"; break; 3686 } 3687 } 3688 3689 // It really isn't clear at all what this means, since properties 3690 // are "dynamic by default". 3691 if (Dynamic) 3692 S += ",D"; 3693 3694 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 3695 S += ",N"; 3696 3697 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 3698 S += ",G"; 3699 S += PD->getGetterName().getAsString(); 3700 } 3701 3702 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 3703 S += ",S"; 3704 S += PD->getSetterName().getAsString(); 3705 } 3706 3707 if (SynthesizePID) { 3708 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 3709 S += ",V"; 3710 S += OID->getNameAsString(); 3711 } 3712 3713 // FIXME: OBJCGC: weak & strong 3714} 3715 3716/// getLegacyIntegralTypeEncoding - 3717/// Another legacy compatibility encoding: 32-bit longs are encoded as 3718/// 'l' or 'L' , but not always. For typedefs, we need to use 3719/// 'i' or 'I' instead if encoding a struct field, or a pointer! 3720/// 3721void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 3722 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 3723 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 3724 if (BT->getKind() == BuiltinType::ULong && 3725 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3726 PointeeTy = UnsignedIntTy; 3727 else 3728 if (BT->getKind() == BuiltinType::Long && 3729 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 3730 PointeeTy = IntTy; 3731 } 3732 } 3733} 3734 3735void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 3736 const FieldDecl *Field) { 3737 // We follow the behavior of gcc, expanding structures which are 3738 // directly pointed to, and expanding embedded structures. Note that 3739 // these rules are sufficient to prevent recursive encoding of the 3740 // same type. 3741 getObjCEncodingForTypeImpl(T, S, true, true, Field, 3742 true /* outermost type */); 3743} 3744 3745static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 3746 switch (T->getAs<BuiltinType>()->getKind()) { 3747 default: assert(0 && "Unhandled builtin type kind"); 3748 case BuiltinType::Void: return 'v'; 3749 case BuiltinType::Bool: return 'B'; 3750 case BuiltinType::Char_U: 3751 case BuiltinType::UChar: return 'C'; 3752 case BuiltinType::UShort: return 'S'; 3753 case BuiltinType::UInt: return 'I'; 3754 case BuiltinType::ULong: 3755 return 3756 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'L' : 'Q'; 3757 case BuiltinType::UInt128: return 'T'; 3758 case BuiltinType::ULongLong: return 'Q'; 3759 case BuiltinType::Char_S: 3760 case BuiltinType::SChar: return 'c'; 3761 case BuiltinType::Short: return 's'; 3762 case BuiltinType::WChar: 3763 case BuiltinType::Int: return 'i'; 3764 case BuiltinType::Long: 3765 return 3766 (const_cast<ASTContext *>(C))->getIntWidth(T) == 32 ? 'l' : 'q'; 3767 case BuiltinType::LongLong: return 'q'; 3768 case BuiltinType::Int128: return 't'; 3769 case BuiltinType::Float: return 'f'; 3770 case BuiltinType::Double: return 'd'; 3771 case BuiltinType::LongDouble: return 'D'; 3772 } 3773} 3774 3775static void EncodeBitField(const ASTContext *Context, std::string& S, 3776 QualType T, const FieldDecl *FD) { 3777 const Expr *E = FD->getBitWidth(); 3778 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 3779 ASTContext *Ctx = const_cast<ASTContext*>(Context); 3780 S += 'b'; 3781 // The NeXT runtime encodes bit fields as b followed by the number of bits. 3782 // The GNU runtime requires more information; bitfields are encoded as b, 3783 // then the offset (in bits) of the first element, then the type of the 3784 // bitfield, then the size in bits. For example, in this structure: 3785 // 3786 // struct 3787 // { 3788 // int integer; 3789 // int flags:2; 3790 // }; 3791 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 3792 // runtime, but b32i2 for the GNU runtime. The reason for this extra 3793 // information is not especially sensible, but we're stuck with it for 3794 // compatibility with GCC, although providing it breaks anything that 3795 // actually uses runtime introspection and wants to work on both runtimes... 3796 if (!Ctx->getLangOptions().NeXTRuntime) { 3797 const RecordDecl *RD = FD->getParent(); 3798 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 3799 // FIXME: This same linear search is also used in ExprConstant - it might 3800 // be better if the FieldDecl stored its offset. We'd be increasing the 3801 // size of the object slightly, but saving some time every time it is used. 3802 unsigned i = 0; 3803 for (RecordDecl::field_iterator Field = RD->field_begin(), 3804 FieldEnd = RD->field_end(); 3805 Field != FieldEnd; (void)++Field, ++i) { 3806 if (*Field == FD) 3807 break; 3808 } 3809 S += llvm::utostr(RL.getFieldOffset(i)); 3810 S += ObjCEncodingForPrimitiveKind(Context, T); 3811 } 3812 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 3813 S += llvm::utostr(N); 3814} 3815 3816// FIXME: Use SmallString for accumulating string. 3817void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 3818 bool ExpandPointedToStructures, 3819 bool ExpandStructures, 3820 const FieldDecl *FD, 3821 bool OutermostType, 3822 bool EncodingProperty) { 3823 if (T->getAs<BuiltinType>()) { 3824 if (FD && FD->isBitField()) 3825 return EncodeBitField(this, S, T, FD); 3826 S += ObjCEncodingForPrimitiveKind(this, T); 3827 return; 3828 } 3829 3830 if (const ComplexType *CT = T->getAs<ComplexType>()) { 3831 S += 'j'; 3832 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 3833 false); 3834 return; 3835 } 3836 3837 // encoding for pointer or r3eference types. 3838 QualType PointeeTy; 3839 if (const PointerType *PT = T->getAs<PointerType>()) { 3840 if (PT->isObjCSelType()) { 3841 S += ':'; 3842 return; 3843 } 3844 PointeeTy = PT->getPointeeType(); 3845 } 3846 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3847 PointeeTy = RT->getPointeeType(); 3848 if (!PointeeTy.isNull()) { 3849 bool isReadOnly = false; 3850 // For historical/compatibility reasons, the read-only qualifier of the 3851 // pointee gets emitted _before_ the '^'. The read-only qualifier of 3852 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 3853 // Also, do not emit the 'r' for anything but the outermost type! 3854 if (isa<TypedefType>(T.getTypePtr())) { 3855 if (OutermostType && T.isConstQualified()) { 3856 isReadOnly = true; 3857 S += 'r'; 3858 } 3859 } else if (OutermostType) { 3860 QualType P = PointeeTy; 3861 while (P->getAs<PointerType>()) 3862 P = P->getAs<PointerType>()->getPointeeType(); 3863 if (P.isConstQualified()) { 3864 isReadOnly = true; 3865 S += 'r'; 3866 } 3867 } 3868 if (isReadOnly) { 3869 // Another legacy compatibility encoding. Some ObjC qualifier and type 3870 // combinations need to be rearranged. 3871 // Rewrite "in const" from "nr" to "rn" 3872 if (llvm::StringRef(S).endswith("nr")) 3873 S.replace(S.end()-2, S.end(), "rn"); 3874 } 3875 3876 if (PointeeTy->isCharType()) { 3877 // char pointer types should be encoded as '*' unless it is a 3878 // type that has been typedef'd to 'BOOL'. 3879 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 3880 S += '*'; 3881 return; 3882 } 3883 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 3884 // GCC binary compat: Need to convert "struct objc_class *" to "#". 3885 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 3886 S += '#'; 3887 return; 3888 } 3889 // GCC binary compat: Need to convert "struct objc_object *" to "@". 3890 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 3891 S += '@'; 3892 return; 3893 } 3894 // fall through... 3895 } 3896 S += '^'; 3897 getLegacyIntegralTypeEncoding(PointeeTy); 3898 3899 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 3900 NULL); 3901 return; 3902 } 3903 3904 if (const ArrayType *AT = 3905 // Ignore type qualifiers etc. 3906 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 3907 if (isa<IncompleteArrayType>(AT)) { 3908 // Incomplete arrays are encoded as a pointer to the array element. 3909 S += '^'; 3910 3911 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3912 false, ExpandStructures, FD); 3913 } else { 3914 S += '['; 3915 3916 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 3917 S += llvm::utostr(CAT->getSize().getZExtValue()); 3918 else { 3919 //Variable length arrays are encoded as a regular array with 0 elements. 3920 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 3921 S += '0'; 3922 } 3923 3924 getObjCEncodingForTypeImpl(AT->getElementType(), S, 3925 false, ExpandStructures, FD); 3926 S += ']'; 3927 } 3928 return; 3929 } 3930 3931 if (T->getAs<FunctionType>()) { 3932 S += '?'; 3933 return; 3934 } 3935 3936 if (const RecordType *RTy = T->getAs<RecordType>()) { 3937 RecordDecl *RDecl = RTy->getDecl(); 3938 S += RDecl->isUnion() ? '(' : '{'; 3939 // Anonymous structures print as '?' 3940 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 3941 S += II->getName(); 3942 if (ClassTemplateSpecializationDecl *Spec 3943 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 3944 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 3945 std::string TemplateArgsStr 3946 = TemplateSpecializationType::PrintTemplateArgumentList( 3947 TemplateArgs.data(), 3948 TemplateArgs.size(), 3949 (*this).PrintingPolicy); 3950 3951 S += TemplateArgsStr; 3952 } 3953 } else { 3954 S += '?'; 3955 } 3956 if (ExpandStructures) { 3957 S += '='; 3958 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 3959 FieldEnd = RDecl->field_end(); 3960 Field != FieldEnd; ++Field) { 3961 if (FD) { 3962 S += '"'; 3963 S += Field->getNameAsString(); 3964 S += '"'; 3965 } 3966 3967 // Special case bit-fields. 3968 if (Field->isBitField()) { 3969 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 3970 (*Field)); 3971 } else { 3972 QualType qt = Field->getType(); 3973 getLegacyIntegralTypeEncoding(qt); 3974 getObjCEncodingForTypeImpl(qt, S, false, true, 3975 FD); 3976 } 3977 } 3978 } 3979 S += RDecl->isUnion() ? ')' : '}'; 3980 return; 3981 } 3982 3983 if (T->isEnumeralType()) { 3984 if (FD && FD->isBitField()) 3985 EncodeBitField(this, S, T, FD); 3986 else 3987 S += 'i'; 3988 return; 3989 } 3990 3991 if (T->isBlockPointerType()) { 3992 S += "@?"; // Unlike a pointer-to-function, which is "^?". 3993 return; 3994 } 3995 3996 // Ignore protocol qualifiers when mangling at this level. 3997 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 3998 T = OT->getBaseType(); 3999 4000 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4001 // @encode(class_name) 4002 ObjCInterfaceDecl *OI = OIT->getDecl(); 4003 S += '{'; 4004 const IdentifierInfo *II = OI->getIdentifier(); 4005 S += II->getName(); 4006 S += '='; 4007 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars; 4008 DeepCollectObjCIvars(OI, true, Ivars); 4009 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4010 FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4011 if (Field->isBitField()) 4012 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4013 else 4014 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4015 } 4016 S += '}'; 4017 return; 4018 } 4019 4020 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4021 if (OPT->isObjCIdType()) { 4022 S += '@'; 4023 return; 4024 } 4025 4026 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4027 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4028 // Since this is a binary compatibility issue, need to consult with runtime 4029 // folks. Fortunately, this is a *very* obsure construct. 4030 S += '#'; 4031 return; 4032 } 4033 4034 if (OPT->isObjCQualifiedIdType()) { 4035 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4036 ExpandPointedToStructures, 4037 ExpandStructures, FD); 4038 if (FD || EncodingProperty) { 4039 // Note that we do extended encoding of protocol qualifer list 4040 // Only when doing ivar or property encoding. 4041 S += '"'; 4042 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4043 E = OPT->qual_end(); I != E; ++I) { 4044 S += '<'; 4045 S += (*I)->getNameAsString(); 4046 S += '>'; 4047 } 4048 S += '"'; 4049 } 4050 return; 4051 } 4052 4053 QualType PointeeTy = OPT->getPointeeType(); 4054 if (!EncodingProperty && 4055 isa<TypedefType>(PointeeTy.getTypePtr())) { 4056 // Another historical/compatibility reason. 4057 // We encode the underlying type which comes out as 4058 // {...}; 4059 S += '^'; 4060 getObjCEncodingForTypeImpl(PointeeTy, S, 4061 false, ExpandPointedToStructures, 4062 NULL); 4063 return; 4064 } 4065 4066 S += '@'; 4067 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) { 4068 S += '"'; 4069 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 4070 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4071 E = OPT->qual_end(); I != E; ++I) { 4072 S += '<'; 4073 S += (*I)->getNameAsString(); 4074 S += '>'; 4075 } 4076 S += '"'; 4077 } 4078 return; 4079 } 4080 4081 // gcc just blithely ignores member pointers. 4082 // TODO: maybe there should be a mangling for these 4083 if (T->getAs<MemberPointerType>()) 4084 return; 4085 4086 if (T->isVectorType()) { 4087 // This matches gcc's encoding, even though technically it is 4088 // insufficient. 4089 // FIXME. We should do a better job than gcc. 4090 return; 4091 } 4092 4093 assert(0 && "@encode for type not implemented!"); 4094} 4095 4096void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 4097 std::string& S) const { 4098 if (QT & Decl::OBJC_TQ_In) 4099 S += 'n'; 4100 if (QT & Decl::OBJC_TQ_Inout) 4101 S += 'N'; 4102 if (QT & Decl::OBJC_TQ_Out) 4103 S += 'o'; 4104 if (QT & Decl::OBJC_TQ_Bycopy) 4105 S += 'O'; 4106 if (QT & Decl::OBJC_TQ_Byref) 4107 S += 'R'; 4108 if (QT & Decl::OBJC_TQ_Oneway) 4109 S += 'V'; 4110} 4111 4112void ASTContext::setBuiltinVaListType(QualType T) { 4113 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 4114 4115 BuiltinVaListType = T; 4116} 4117 4118void ASTContext::setObjCIdType(QualType T) { 4119 ObjCIdTypedefType = T; 4120} 4121 4122void ASTContext::setObjCSelType(QualType T) { 4123 ObjCSelTypedefType = T; 4124} 4125 4126void ASTContext::setObjCProtoType(QualType QT) { 4127 ObjCProtoType = QT; 4128} 4129 4130void ASTContext::setObjCClassType(QualType T) { 4131 ObjCClassTypedefType = T; 4132} 4133 4134void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 4135 assert(ObjCConstantStringType.isNull() && 4136 "'NSConstantString' type already set!"); 4137 4138 ObjCConstantStringType = getObjCInterfaceType(Decl); 4139} 4140 4141/// \brief Retrieve the template name that corresponds to a non-empty 4142/// lookup. 4143TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 4144 UnresolvedSetIterator End) { 4145 unsigned size = End - Begin; 4146 assert(size > 1 && "set is not overloaded!"); 4147 4148 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 4149 size * sizeof(FunctionTemplateDecl*)); 4150 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 4151 4152 NamedDecl **Storage = OT->getStorage(); 4153 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 4154 NamedDecl *D = *I; 4155 assert(isa<FunctionTemplateDecl>(D) || 4156 (isa<UsingShadowDecl>(D) && 4157 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 4158 *Storage++ = D; 4159 } 4160 4161 return TemplateName(OT); 4162} 4163 4164/// \brief Retrieve the template name that represents a qualified 4165/// template name such as \c std::vector. 4166TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 4167 bool TemplateKeyword, 4168 TemplateDecl *Template) { 4169 // FIXME: Canonicalization? 4170 llvm::FoldingSetNodeID ID; 4171 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 4172 4173 void *InsertPos = 0; 4174 QualifiedTemplateName *QTN = 4175 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4176 if (!QTN) { 4177 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 4178 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 4179 } 4180 4181 return TemplateName(QTN); 4182} 4183 4184/// \brief Retrieve the template name that represents a dependent 4185/// template name such as \c MetaFun::template apply. 4186TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4187 const IdentifierInfo *Name) { 4188 assert((!NNS || NNS->isDependent()) && 4189 "Nested name specifier must be dependent"); 4190 4191 llvm::FoldingSetNodeID ID; 4192 DependentTemplateName::Profile(ID, NNS, Name); 4193 4194 void *InsertPos = 0; 4195 DependentTemplateName *QTN = 4196 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4197 4198 if (QTN) 4199 return TemplateName(QTN); 4200 4201 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4202 if (CanonNNS == NNS) { 4203 QTN = new (*this,4) DependentTemplateName(NNS, Name); 4204 } else { 4205 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 4206 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 4207 DependentTemplateName *CheckQTN = 4208 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4209 assert(!CheckQTN && "Dependent type name canonicalization broken"); 4210 (void)CheckQTN; 4211 } 4212 4213 DependentTemplateNames.InsertNode(QTN, InsertPos); 4214 return TemplateName(QTN); 4215} 4216 4217/// \brief Retrieve the template name that represents a dependent 4218/// template name such as \c MetaFun::template operator+. 4219TemplateName 4220ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 4221 OverloadedOperatorKind Operator) { 4222 assert((!NNS || NNS->isDependent()) && 4223 "Nested name specifier must be dependent"); 4224 4225 llvm::FoldingSetNodeID ID; 4226 DependentTemplateName::Profile(ID, NNS, Operator); 4227 4228 void *InsertPos = 0; 4229 DependentTemplateName *QTN 4230 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4231 4232 if (QTN) 4233 return TemplateName(QTN); 4234 4235 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 4236 if (CanonNNS == NNS) { 4237 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 4238 } else { 4239 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 4240 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 4241 4242 DependentTemplateName *CheckQTN 4243 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 4244 assert(!CheckQTN && "Dependent template name canonicalization broken"); 4245 (void)CheckQTN; 4246 } 4247 4248 DependentTemplateNames.InsertNode(QTN, InsertPos); 4249 return TemplateName(QTN); 4250} 4251 4252/// getFromTargetType - Given one of the integer types provided by 4253/// TargetInfo, produce the corresponding type. The unsigned @p Type 4254/// is actually a value of type @c TargetInfo::IntType. 4255CanQualType ASTContext::getFromTargetType(unsigned Type) const { 4256 switch (Type) { 4257 case TargetInfo::NoInt: return CanQualType(); 4258 case TargetInfo::SignedShort: return ShortTy; 4259 case TargetInfo::UnsignedShort: return UnsignedShortTy; 4260 case TargetInfo::SignedInt: return IntTy; 4261 case TargetInfo::UnsignedInt: return UnsignedIntTy; 4262 case TargetInfo::SignedLong: return LongTy; 4263 case TargetInfo::UnsignedLong: return UnsignedLongTy; 4264 case TargetInfo::SignedLongLong: return LongLongTy; 4265 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 4266 } 4267 4268 assert(false && "Unhandled TargetInfo::IntType value"); 4269 return CanQualType(); 4270} 4271 4272//===----------------------------------------------------------------------===// 4273// Type Predicates. 4274//===----------------------------------------------------------------------===// 4275 4276/// isObjCNSObjectType - Return true if this is an NSObject object using 4277/// NSObject attribute on a c-style pointer type. 4278/// FIXME - Make it work directly on types. 4279/// FIXME: Move to Type. 4280/// 4281bool ASTContext::isObjCNSObjectType(QualType Ty) const { 4282 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 4283 if (TypedefDecl *TD = TDT->getDecl()) 4284 if (TD->getAttr<ObjCNSObjectAttr>()) 4285 return true; 4286 } 4287 return false; 4288} 4289 4290/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 4291/// garbage collection attribute. 4292/// 4293Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 4294 Qualifiers::GC GCAttrs = Qualifiers::GCNone; 4295 if (getLangOptions().ObjC1 && 4296 getLangOptions().getGCMode() != LangOptions::NonGC) { 4297 GCAttrs = Ty.getObjCGCAttr(); 4298 // Default behavious under objective-c's gc is for objective-c pointers 4299 // (or pointers to them) be treated as though they were declared 4300 // as __strong. 4301 if (GCAttrs == Qualifiers::GCNone) { 4302 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 4303 GCAttrs = Qualifiers::Strong; 4304 else if (Ty->isPointerType()) 4305 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 4306 } 4307 // Non-pointers have none gc'able attribute regardless of the attribute 4308 // set on them. 4309 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType()) 4310 return Qualifiers::GCNone; 4311 } 4312 return GCAttrs; 4313} 4314 4315//===----------------------------------------------------------------------===// 4316// Type Compatibility Testing 4317//===----------------------------------------------------------------------===// 4318 4319/// areCompatVectorTypes - Return true if the two specified vector types are 4320/// compatible. 4321static bool areCompatVectorTypes(const VectorType *LHS, 4322 const VectorType *RHS) { 4323 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 4324 return LHS->getElementType() == RHS->getElementType() && 4325 LHS->getNumElements() == RHS->getNumElements(); 4326} 4327 4328bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 4329 QualType SecondVec) { 4330 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 4331 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 4332 4333 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 4334 return true; 4335 4336 // Treat Neon vector types and most AltiVec vector types as if they are the 4337 // equivalent GCC vector types. 4338 const VectorType *First = FirstVec->getAs<VectorType>(); 4339 const VectorType *Second = SecondVec->getAs<VectorType>(); 4340 if (First->getNumElements() == Second->getNumElements() && 4341 hasSameType(First->getElementType(), Second->getElementType()) && 4342 First->getVectorKind() != VectorType::AltiVecPixel && 4343 First->getVectorKind() != VectorType::AltiVecBool && 4344 Second->getVectorKind() != VectorType::AltiVecPixel && 4345 Second->getVectorKind() != VectorType::AltiVecBool) 4346 return true; 4347 4348 return false; 4349} 4350 4351//===----------------------------------------------------------------------===// 4352// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 4353//===----------------------------------------------------------------------===// 4354 4355/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 4356/// inheritance hierarchy of 'rProto'. 4357bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 4358 ObjCProtocolDecl *rProto) { 4359 if (lProto == rProto) 4360 return true; 4361 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 4362 E = rProto->protocol_end(); PI != E; ++PI) 4363 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 4364 return true; 4365 return false; 4366} 4367 4368/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 4369/// return true if lhs's protocols conform to rhs's protocol; false 4370/// otherwise. 4371bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 4372 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 4373 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 4374 return false; 4375} 4376 4377/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 4378/// Class<p1, ...>. 4379bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 4380 QualType rhs) { 4381 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 4382 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 4383 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 4384 4385 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4386 E = lhsQID->qual_end(); I != E; ++I) { 4387 bool match = false; 4388 ObjCProtocolDecl *lhsProto = *I; 4389 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 4390 E = rhsOPT->qual_end(); J != E; ++J) { 4391 ObjCProtocolDecl *rhsProto = *J; 4392 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 4393 match = true; 4394 break; 4395 } 4396 } 4397 if (!match) 4398 return false; 4399 } 4400 return true; 4401} 4402 4403/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 4404/// ObjCQualifiedIDType. 4405bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 4406 bool compare) { 4407 // Allow id<P..> and an 'id' or void* type in all cases. 4408 if (lhs->isVoidPointerType() || 4409 lhs->isObjCIdType() || lhs->isObjCClassType()) 4410 return true; 4411 else if (rhs->isVoidPointerType() || 4412 rhs->isObjCIdType() || rhs->isObjCClassType()) 4413 return true; 4414 4415 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 4416 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 4417 4418 if (!rhsOPT) return false; 4419 4420 if (rhsOPT->qual_empty()) { 4421 // If the RHS is a unqualified interface pointer "NSString*", 4422 // make sure we check the class hierarchy. 4423 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4424 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4425 E = lhsQID->qual_end(); I != E; ++I) { 4426 // when comparing an id<P> on lhs with a static type on rhs, 4427 // see if static class implements all of id's protocols, directly or 4428 // through its super class and categories. 4429 if (!rhsID->ClassImplementsProtocol(*I, true)) 4430 return false; 4431 } 4432 } 4433 // If there are no qualifiers and no interface, we have an 'id'. 4434 return true; 4435 } 4436 // Both the right and left sides have qualifiers. 4437 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4438 E = lhsQID->qual_end(); I != E; ++I) { 4439 ObjCProtocolDecl *lhsProto = *I; 4440 bool match = false; 4441 4442 // when comparing an id<P> on lhs with a static type on rhs, 4443 // see if static class implements all of id's protocols, directly or 4444 // through its super class and categories. 4445 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 4446 E = rhsOPT->qual_end(); J != E; ++J) { 4447 ObjCProtocolDecl *rhsProto = *J; 4448 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4449 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4450 match = true; 4451 break; 4452 } 4453 } 4454 // If the RHS is a qualified interface pointer "NSString<P>*", 4455 // make sure we check the class hierarchy. 4456 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 4457 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 4458 E = lhsQID->qual_end(); I != E; ++I) { 4459 // when comparing an id<P> on lhs with a static type on rhs, 4460 // see if static class implements all of id's protocols, directly or 4461 // through its super class and categories. 4462 if (rhsID->ClassImplementsProtocol(*I, true)) { 4463 match = true; 4464 break; 4465 } 4466 } 4467 } 4468 if (!match) 4469 return false; 4470 } 4471 4472 return true; 4473 } 4474 4475 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 4476 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 4477 4478 if (const ObjCObjectPointerType *lhsOPT = 4479 lhs->getAsObjCInterfacePointerType()) { 4480 // If both the right and left sides have qualifiers. 4481 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 4482 E = lhsOPT->qual_end(); I != E; ++I) { 4483 ObjCProtocolDecl *lhsProto = *I; 4484 bool match = false; 4485 4486 // when comparing an id<P> on rhs with a static type on lhs, 4487 // see if static class implements all of id's protocols, directly or 4488 // through its super class and categories. 4489 // First, lhs protocols in the qualifier list must be found, direct 4490 // or indirect in rhs's qualifier list or it is a mismatch. 4491 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 4492 E = rhsQID->qual_end(); J != E; ++J) { 4493 ObjCProtocolDecl *rhsProto = *J; 4494 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4495 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4496 match = true; 4497 break; 4498 } 4499 } 4500 if (!match) 4501 return false; 4502 } 4503 4504 // Static class's protocols, or its super class or category protocols 4505 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 4506 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 4507 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 4508 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 4509 // This is rather dubious but matches gcc's behavior. If lhs has 4510 // no type qualifier and its class has no static protocol(s) 4511 // assume that it is mismatch. 4512 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 4513 return false; 4514 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 4515 LHSInheritedProtocols.begin(), 4516 E = LHSInheritedProtocols.end(); I != E; ++I) { 4517 bool match = false; 4518 ObjCProtocolDecl *lhsProto = (*I); 4519 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 4520 E = rhsQID->qual_end(); J != E; ++J) { 4521 ObjCProtocolDecl *rhsProto = *J; 4522 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 4523 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 4524 match = true; 4525 break; 4526 } 4527 } 4528 if (!match) 4529 return false; 4530 } 4531 } 4532 return true; 4533 } 4534 return false; 4535} 4536 4537/// canAssignObjCInterfaces - Return true if the two interface types are 4538/// compatible for assignment from RHS to LHS. This handles validation of any 4539/// protocol qualifiers on the LHS or RHS. 4540/// 4541bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 4542 const ObjCObjectPointerType *RHSOPT) { 4543 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4544 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4545 4546 // If either type represents the built-in 'id' or 'Class' types, return true. 4547 if (LHS->isObjCUnqualifiedIdOrClass() || 4548 RHS->isObjCUnqualifiedIdOrClass()) 4549 return true; 4550 4551 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 4552 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4553 QualType(RHSOPT,0), 4554 false); 4555 4556 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 4557 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 4558 QualType(RHSOPT,0)); 4559 4560 // If we have 2 user-defined types, fall into that path. 4561 if (LHS->getInterface() && RHS->getInterface()) 4562 return canAssignObjCInterfaces(LHS, RHS); 4563 4564 return false; 4565} 4566 4567/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 4568/// for providing type-safty for objective-c pointers used to pass/return 4569/// arguments in block literals. When passed as arguments, passing 'A*' where 4570/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 4571/// not OK. For the return type, the opposite is not OK. 4572bool ASTContext::canAssignObjCInterfacesInBlockPointer( 4573 const ObjCObjectPointerType *LHSOPT, 4574 const ObjCObjectPointerType *RHSOPT) { 4575 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 4576 return true; 4577 4578 if (LHSOPT->isObjCBuiltinType()) { 4579 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 4580 } 4581 4582 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 4583 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 4584 QualType(RHSOPT,0), 4585 false); 4586 4587 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 4588 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 4589 if (LHS && RHS) { // We have 2 user-defined types. 4590 if (LHS != RHS) { 4591 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 4592 return false; 4593 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 4594 return true; 4595 } 4596 else 4597 return true; 4598 } 4599 return false; 4600} 4601 4602/// getIntersectionOfProtocols - This routine finds the intersection of set 4603/// of protocols inherited from two distinct objective-c pointer objects. 4604/// It is used to build composite qualifier list of the composite type of 4605/// the conditional expression involving two objective-c pointer objects. 4606static 4607void getIntersectionOfProtocols(ASTContext &Context, 4608 const ObjCObjectPointerType *LHSOPT, 4609 const ObjCObjectPointerType *RHSOPT, 4610 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 4611 4612 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 4613 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 4614 assert(LHS->getInterface() && "LHS must have an interface base"); 4615 assert(RHS->getInterface() && "RHS must have an interface base"); 4616 4617 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 4618 unsigned LHSNumProtocols = LHS->getNumProtocols(); 4619 if (LHSNumProtocols > 0) 4620 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 4621 else { 4622 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 4623 Context.CollectInheritedProtocols(LHS->getInterface(), 4624 LHSInheritedProtocols); 4625 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 4626 LHSInheritedProtocols.end()); 4627 } 4628 4629 unsigned RHSNumProtocols = RHS->getNumProtocols(); 4630 if (RHSNumProtocols > 0) { 4631 ObjCProtocolDecl **RHSProtocols = 4632 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 4633 for (unsigned i = 0; i < RHSNumProtocols; ++i) 4634 if (InheritedProtocolSet.count(RHSProtocols[i])) 4635 IntersectionOfProtocols.push_back(RHSProtocols[i]); 4636 } 4637 else { 4638 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 4639 Context.CollectInheritedProtocols(RHS->getInterface(), 4640 RHSInheritedProtocols); 4641 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 4642 RHSInheritedProtocols.begin(), 4643 E = RHSInheritedProtocols.end(); I != E; ++I) 4644 if (InheritedProtocolSet.count((*I))) 4645 IntersectionOfProtocols.push_back((*I)); 4646 } 4647} 4648 4649/// areCommonBaseCompatible - Returns common base class of the two classes if 4650/// one found. Note that this is O'2 algorithm. But it will be called as the 4651/// last type comparison in a ?-exp of ObjC pointer types before a 4652/// warning is issued. So, its invokation is extremely rare. 4653QualType ASTContext::areCommonBaseCompatible( 4654 const ObjCObjectPointerType *Lptr, 4655 const ObjCObjectPointerType *Rptr) { 4656 const ObjCObjectType *LHS = Lptr->getObjectType(); 4657 const ObjCObjectType *RHS = Rptr->getObjectType(); 4658 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 4659 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 4660 if (!LDecl || !RDecl) 4661 return QualType(); 4662 4663 while ((LDecl = LDecl->getSuperClass())) { 4664 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 4665 if (canAssignObjCInterfaces(LHS, RHS)) { 4666 llvm::SmallVector<ObjCProtocolDecl *, 8> Protocols; 4667 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 4668 4669 QualType Result = QualType(LHS, 0); 4670 if (!Protocols.empty()) 4671 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 4672 Result = getObjCObjectPointerType(Result); 4673 return Result; 4674 } 4675 } 4676 4677 return QualType(); 4678} 4679 4680bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 4681 const ObjCObjectType *RHS) { 4682 assert(LHS->getInterface() && "LHS is not an interface type"); 4683 assert(RHS->getInterface() && "RHS is not an interface type"); 4684 4685 // Verify that the base decls are compatible: the RHS must be a subclass of 4686 // the LHS. 4687 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 4688 return false; 4689 4690 // RHS must have a superset of the protocols in the LHS. If the LHS is not 4691 // protocol qualified at all, then we are good. 4692 if (LHS->getNumProtocols() == 0) 4693 return true; 4694 4695 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 4696 // isn't a superset. 4697 if (RHS->getNumProtocols() == 0) 4698 return true; // FIXME: should return false! 4699 4700 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 4701 LHSPE = LHS->qual_end(); 4702 LHSPI != LHSPE; LHSPI++) { 4703 bool RHSImplementsProtocol = false; 4704 4705 // If the RHS doesn't implement the protocol on the left, the types 4706 // are incompatible. 4707 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 4708 RHSPE = RHS->qual_end(); 4709 RHSPI != RHSPE; RHSPI++) { 4710 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 4711 RHSImplementsProtocol = true; 4712 break; 4713 } 4714 } 4715 // FIXME: For better diagnostics, consider passing back the protocol name. 4716 if (!RHSImplementsProtocol) 4717 return false; 4718 } 4719 // The RHS implements all protocols listed on the LHS. 4720 return true; 4721} 4722 4723bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 4724 // get the "pointed to" types 4725 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 4726 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 4727 4728 if (!LHSOPT || !RHSOPT) 4729 return false; 4730 4731 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 4732 canAssignObjCInterfaces(RHSOPT, LHSOPT); 4733} 4734 4735bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 4736 return canAssignObjCInterfaces( 4737 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 4738 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 4739} 4740 4741/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 4742/// both shall have the identically qualified version of a compatible type. 4743/// C99 6.2.7p1: Two types have compatible types if their types are the 4744/// same. See 6.7.[2,3,5] for additional rules. 4745bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 4746 bool CompareUnqualified) { 4747 if (getLangOptions().CPlusPlus) 4748 return hasSameType(LHS, RHS); 4749 4750 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 4751} 4752 4753bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 4754 return !mergeTypes(LHS, RHS, true).isNull(); 4755} 4756 4757/// mergeTransparentUnionType - if T is a transparent union type and a member 4758/// of T is compatible with SubType, return the merged type, else return 4759/// QualType() 4760QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 4761 bool OfBlockPointer, 4762 bool Unqualified) { 4763 if (const RecordType *UT = T->getAsUnionType()) { 4764 RecordDecl *UD = UT->getDecl(); 4765 if (UD->hasAttr<TransparentUnionAttr>()) { 4766 for (RecordDecl::field_iterator it = UD->field_begin(), 4767 itend = UD->field_end(); it != itend; ++it) { 4768 QualType ET = it->getType().getUnqualifiedType(); 4769 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 4770 if (!MT.isNull()) 4771 return MT; 4772 } 4773 } 4774 } 4775 4776 return QualType(); 4777} 4778 4779/// mergeFunctionArgumentTypes - merge two types which appear as function 4780/// argument types 4781QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 4782 bool OfBlockPointer, 4783 bool Unqualified) { 4784 // GNU extension: two types are compatible if they appear as a function 4785 // argument, one of the types is a transparent union type and the other 4786 // type is compatible with a union member 4787 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 4788 Unqualified); 4789 if (!lmerge.isNull()) 4790 return lmerge; 4791 4792 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 4793 Unqualified); 4794 if (!rmerge.isNull()) 4795 return rmerge; 4796 4797 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 4798} 4799 4800QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 4801 bool OfBlockPointer, 4802 bool Unqualified) { 4803 const FunctionType *lbase = lhs->getAs<FunctionType>(); 4804 const FunctionType *rbase = rhs->getAs<FunctionType>(); 4805 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 4806 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 4807 bool allLTypes = true; 4808 bool allRTypes = true; 4809 4810 // Check return type 4811 QualType retType; 4812 if (OfBlockPointer) 4813 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true, 4814 Unqualified); 4815 else 4816 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), 4817 false, Unqualified); 4818 if (retType.isNull()) return QualType(); 4819 4820 if (Unqualified) 4821 retType = retType.getUnqualifiedType(); 4822 4823 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 4824 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 4825 if (Unqualified) { 4826 LRetType = LRetType.getUnqualifiedType(); 4827 RRetType = RRetType.getUnqualifiedType(); 4828 } 4829 4830 if (getCanonicalType(retType) != LRetType) 4831 allLTypes = false; 4832 if (getCanonicalType(retType) != RRetType) 4833 allRTypes = false; 4834 // FIXME: double check this 4835 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 4836 // rbase->getRegParmAttr() != 0 && 4837 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 4838 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 4839 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 4840 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() : 4841 lbaseInfo.getRegParm(); 4842 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 4843 if (NoReturn != lbaseInfo.getNoReturn() || 4844 RegParm != lbaseInfo.getRegParm()) 4845 allLTypes = false; 4846 if (NoReturn != rbaseInfo.getNoReturn() || 4847 RegParm != rbaseInfo.getRegParm()) 4848 allRTypes = false; 4849 CallingConv lcc = lbaseInfo.getCC(); 4850 CallingConv rcc = rbaseInfo.getCC(); 4851 // Compatible functions must have compatible calling conventions 4852 if (!isSameCallConv(lcc, rcc)) 4853 return QualType(); 4854 4855 if (lproto && rproto) { // two C99 style function prototypes 4856 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 4857 "C++ shouldn't be here"); 4858 unsigned lproto_nargs = lproto->getNumArgs(); 4859 unsigned rproto_nargs = rproto->getNumArgs(); 4860 4861 // Compatible functions must have the same number of arguments 4862 if (lproto_nargs != rproto_nargs) 4863 return QualType(); 4864 4865 // Variadic and non-variadic functions aren't compatible 4866 if (lproto->isVariadic() != rproto->isVariadic()) 4867 return QualType(); 4868 4869 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 4870 return QualType(); 4871 4872 // Check argument compatibility 4873 llvm::SmallVector<QualType, 10> types; 4874 for (unsigned i = 0; i < lproto_nargs; i++) { 4875 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 4876 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 4877 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 4878 OfBlockPointer, 4879 Unqualified); 4880 if (argtype.isNull()) return QualType(); 4881 4882 if (Unqualified) 4883 argtype = argtype.getUnqualifiedType(); 4884 4885 types.push_back(argtype); 4886 if (Unqualified) { 4887 largtype = largtype.getUnqualifiedType(); 4888 rargtype = rargtype.getUnqualifiedType(); 4889 } 4890 4891 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 4892 allLTypes = false; 4893 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 4894 allRTypes = false; 4895 } 4896 if (allLTypes) return lhs; 4897 if (allRTypes) return rhs; 4898 return getFunctionType(retType, types.begin(), types.size(), 4899 lproto->isVariadic(), lproto->getTypeQuals(), 4900 false, false, 0, 0, 4901 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4902 } 4903 4904 if (lproto) allRTypes = false; 4905 if (rproto) allLTypes = false; 4906 4907 const FunctionProtoType *proto = lproto ? lproto : rproto; 4908 if (proto) { 4909 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 4910 if (proto->isVariadic()) return QualType(); 4911 // Check that the types are compatible with the types that 4912 // would result from default argument promotions (C99 6.7.5.3p15). 4913 // The only types actually affected are promotable integer 4914 // types and floats, which would be passed as a different 4915 // type depending on whether the prototype is visible. 4916 unsigned proto_nargs = proto->getNumArgs(); 4917 for (unsigned i = 0; i < proto_nargs; ++i) { 4918 QualType argTy = proto->getArgType(i); 4919 4920 // Look at the promotion type of enum types, since that is the type used 4921 // to pass enum values. 4922 if (const EnumType *Enum = argTy->getAs<EnumType>()) 4923 argTy = Enum->getDecl()->getPromotionType(); 4924 4925 if (argTy->isPromotableIntegerType() || 4926 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 4927 return QualType(); 4928 } 4929 4930 if (allLTypes) return lhs; 4931 if (allRTypes) return rhs; 4932 return getFunctionType(retType, proto->arg_type_begin(), 4933 proto->getNumArgs(), proto->isVariadic(), 4934 proto->getTypeQuals(), 4935 false, false, 0, 0, 4936 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 4937 } 4938 4939 if (allLTypes) return lhs; 4940 if (allRTypes) return rhs; 4941 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc); 4942 return getFunctionNoProtoType(retType, Info); 4943} 4944 4945QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 4946 bool OfBlockPointer, 4947 bool Unqualified) { 4948 // C++ [expr]: If an expression initially has the type "reference to T", the 4949 // type is adjusted to "T" prior to any further analysis, the expression 4950 // designates the object or function denoted by the reference, and the 4951 // expression is an lvalue unless the reference is an rvalue reference and 4952 // the expression is a function call (possibly inside parentheses). 4953 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 4954 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 4955 4956 if (Unqualified) { 4957 LHS = LHS.getUnqualifiedType(); 4958 RHS = RHS.getUnqualifiedType(); 4959 } 4960 4961 QualType LHSCan = getCanonicalType(LHS), 4962 RHSCan = getCanonicalType(RHS); 4963 4964 // If two types are identical, they are compatible. 4965 if (LHSCan == RHSCan) 4966 return LHS; 4967 4968 // If the qualifiers are different, the types aren't compatible... mostly. 4969 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 4970 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 4971 if (LQuals != RQuals) { 4972 // If any of these qualifiers are different, we have a type 4973 // mismatch. 4974 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 4975 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 4976 return QualType(); 4977 4978 // Exactly one GC qualifier difference is allowed: __strong is 4979 // okay if the other type has no GC qualifier but is an Objective 4980 // C object pointer (i.e. implicitly strong by default). We fix 4981 // this by pretending that the unqualified type was actually 4982 // qualified __strong. 4983 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 4984 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 4985 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 4986 4987 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 4988 return QualType(); 4989 4990 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 4991 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 4992 } 4993 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 4994 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 4995 } 4996 return QualType(); 4997 } 4998 4999 // Okay, qualifiers are equal. 5000 5001 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 5002 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 5003 5004 // We want to consider the two function types to be the same for these 5005 // comparisons, just force one to the other. 5006 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 5007 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 5008 5009 // Same as above for arrays 5010 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 5011 LHSClass = Type::ConstantArray; 5012 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 5013 RHSClass = Type::ConstantArray; 5014 5015 // ObjCInterfaces are just specialized ObjCObjects. 5016 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 5017 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 5018 5019 // Canonicalize ExtVector -> Vector. 5020 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 5021 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 5022 5023 // If the canonical type classes don't match. 5024 if (LHSClass != RHSClass) { 5025 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 5026 // a signed integer type, or an unsigned integer type. 5027 // Compatibility is based on the underlying type, not the promotion 5028 // type. 5029 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 5030 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 5031 return RHS; 5032 } 5033 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 5034 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 5035 return LHS; 5036 } 5037 5038 return QualType(); 5039 } 5040 5041 // The canonical type classes match. 5042 switch (LHSClass) { 5043#define TYPE(Class, Base) 5044#define ABSTRACT_TYPE(Class, Base) 5045#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 5046#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 5047#define DEPENDENT_TYPE(Class, Base) case Type::Class: 5048#include "clang/AST/TypeNodes.def" 5049 assert(false && "Non-canonical and dependent types shouldn't get here"); 5050 return QualType(); 5051 5052 case Type::LValueReference: 5053 case Type::RValueReference: 5054 case Type::MemberPointer: 5055 assert(false && "C++ should never be in mergeTypes"); 5056 return QualType(); 5057 5058 case Type::ObjCInterface: 5059 case Type::IncompleteArray: 5060 case Type::VariableArray: 5061 case Type::FunctionProto: 5062 case Type::ExtVector: 5063 assert(false && "Types are eliminated above"); 5064 return QualType(); 5065 5066 case Type::Pointer: 5067 { 5068 // Merge two pointer types, while trying to preserve typedef info 5069 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 5070 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 5071 if (Unqualified) { 5072 LHSPointee = LHSPointee.getUnqualifiedType(); 5073 RHSPointee = RHSPointee.getUnqualifiedType(); 5074 } 5075 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 5076 Unqualified); 5077 if (ResultType.isNull()) return QualType(); 5078 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 5079 return LHS; 5080 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 5081 return RHS; 5082 return getPointerType(ResultType); 5083 } 5084 case Type::BlockPointer: 5085 { 5086 // Merge two block pointer types, while trying to preserve typedef info 5087 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 5088 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 5089 if (Unqualified) { 5090 LHSPointee = LHSPointee.getUnqualifiedType(); 5091 RHSPointee = RHSPointee.getUnqualifiedType(); 5092 } 5093 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 5094 Unqualified); 5095 if (ResultType.isNull()) return QualType(); 5096 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 5097 return LHS; 5098 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 5099 return RHS; 5100 return getBlockPointerType(ResultType); 5101 } 5102 case Type::ConstantArray: 5103 { 5104 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 5105 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 5106 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 5107 return QualType(); 5108 5109 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 5110 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 5111 if (Unqualified) { 5112 LHSElem = LHSElem.getUnqualifiedType(); 5113 RHSElem = RHSElem.getUnqualifiedType(); 5114 } 5115 5116 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 5117 if (ResultType.isNull()) return QualType(); 5118 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 5119 return LHS; 5120 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 5121 return RHS; 5122 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 5123 ArrayType::ArraySizeModifier(), 0); 5124 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 5125 ArrayType::ArraySizeModifier(), 0); 5126 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 5127 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 5128 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 5129 return LHS; 5130 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 5131 return RHS; 5132 if (LVAT) { 5133 // FIXME: This isn't correct! But tricky to implement because 5134 // the array's size has to be the size of LHS, but the type 5135 // has to be different. 5136 return LHS; 5137 } 5138 if (RVAT) { 5139 // FIXME: This isn't correct! But tricky to implement because 5140 // the array's size has to be the size of RHS, but the type 5141 // has to be different. 5142 return RHS; 5143 } 5144 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 5145 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 5146 return getIncompleteArrayType(ResultType, 5147 ArrayType::ArraySizeModifier(), 0); 5148 } 5149 case Type::FunctionNoProto: 5150 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 5151 case Type::Record: 5152 case Type::Enum: 5153 return QualType(); 5154 case Type::Builtin: 5155 // Only exactly equal builtin types are compatible, which is tested above. 5156 return QualType(); 5157 case Type::Complex: 5158 // Distinct complex types are incompatible. 5159 return QualType(); 5160 case Type::Vector: 5161 // FIXME: The merged type should be an ExtVector! 5162 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 5163 RHSCan->getAs<VectorType>())) 5164 return LHS; 5165 return QualType(); 5166 case Type::ObjCObject: { 5167 // Check if the types are assignment compatible. 5168 // FIXME: This should be type compatibility, e.g. whether 5169 // "LHS x; RHS x;" at global scope is legal. 5170 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 5171 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 5172 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 5173 return LHS; 5174 5175 return QualType(); 5176 } 5177 case Type::ObjCObjectPointer: { 5178 if (OfBlockPointer) { 5179 if (canAssignObjCInterfacesInBlockPointer( 5180 LHS->getAs<ObjCObjectPointerType>(), 5181 RHS->getAs<ObjCObjectPointerType>())) 5182 return LHS; 5183 return QualType(); 5184 } 5185 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 5186 RHS->getAs<ObjCObjectPointerType>())) 5187 return LHS; 5188 5189 return QualType(); 5190 } 5191 } 5192 5193 return QualType(); 5194} 5195 5196/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 5197/// 'RHS' attributes and returns the merged version; including for function 5198/// return types. 5199QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 5200 QualType LHSCan = getCanonicalType(LHS), 5201 RHSCan = getCanonicalType(RHS); 5202 // If two types are identical, they are compatible. 5203 if (LHSCan == RHSCan) 5204 return LHS; 5205 if (RHSCan->isFunctionType()) { 5206 if (!LHSCan->isFunctionType()) 5207 return QualType(); 5208 QualType OldReturnType = 5209 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 5210 QualType NewReturnType = 5211 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 5212 QualType ResReturnType = 5213 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 5214 if (ResReturnType.isNull()) 5215 return QualType(); 5216 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 5217 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 5218 // In either case, use OldReturnType to build the new function type. 5219 const FunctionType *F = LHS->getAs<FunctionType>(); 5220 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 5221 FunctionType::ExtInfo Info = getFunctionExtInfo(LHS); 5222 QualType ResultType 5223 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 5224 FPT->getNumArgs(), FPT->isVariadic(), 5225 FPT->getTypeQuals(), 5226 FPT->hasExceptionSpec(), 5227 FPT->hasAnyExceptionSpec(), 5228 FPT->getNumExceptions(), 5229 FPT->exception_begin(), 5230 Info); 5231 return ResultType; 5232 } 5233 } 5234 return QualType(); 5235 } 5236 5237 // If the qualifiers are different, the types can still be merged. 5238 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 5239 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 5240 if (LQuals != RQuals) { 5241 // If any of these qualifiers are different, we have a type mismatch. 5242 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 5243 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 5244 return QualType(); 5245 5246 // Exactly one GC qualifier difference is allowed: __strong is 5247 // okay if the other type has no GC qualifier but is an Objective 5248 // C object pointer (i.e. implicitly strong by default). We fix 5249 // this by pretending that the unqualified type was actually 5250 // qualified __strong. 5251 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 5252 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 5253 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 5254 5255 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 5256 return QualType(); 5257 5258 if (GC_L == Qualifiers::Strong) 5259 return LHS; 5260 if (GC_R == Qualifiers::Strong) 5261 return RHS; 5262 return QualType(); 5263 } 5264 5265 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 5266 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 5267 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 5268 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 5269 if (ResQT == LHSBaseQT) 5270 return LHS; 5271 if (ResQT == RHSBaseQT) 5272 return RHS; 5273 } 5274 return QualType(); 5275} 5276 5277//===----------------------------------------------------------------------===// 5278// Integer Predicates 5279//===----------------------------------------------------------------------===// 5280 5281unsigned ASTContext::getIntWidth(QualType T) { 5282 if (EnumType *ET = dyn_cast<EnumType>(T)) 5283 T = ET->getDecl()->getIntegerType(); 5284 if (T->isBooleanType()) 5285 return 1; 5286 // For builtin types, just use the standard type sizing method 5287 return (unsigned)getTypeSize(T); 5288} 5289 5290QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 5291 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 5292 5293 // Turn <4 x signed int> -> <4 x unsigned int> 5294 if (const VectorType *VTy = T->getAs<VectorType>()) 5295 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 5296 VTy->getNumElements(), VTy->getVectorKind()); 5297 5298 // For enums, we return the unsigned version of the base type. 5299 if (const EnumType *ETy = T->getAs<EnumType>()) 5300 T = ETy->getDecl()->getIntegerType(); 5301 5302 const BuiltinType *BTy = T->getAs<BuiltinType>(); 5303 assert(BTy && "Unexpected signed integer type"); 5304 switch (BTy->getKind()) { 5305 case BuiltinType::Char_S: 5306 case BuiltinType::SChar: 5307 return UnsignedCharTy; 5308 case BuiltinType::Short: 5309 return UnsignedShortTy; 5310 case BuiltinType::Int: 5311 return UnsignedIntTy; 5312 case BuiltinType::Long: 5313 return UnsignedLongTy; 5314 case BuiltinType::LongLong: 5315 return UnsignedLongLongTy; 5316 case BuiltinType::Int128: 5317 return UnsignedInt128Ty; 5318 default: 5319 assert(0 && "Unexpected signed integer type"); 5320 return QualType(); 5321 } 5322} 5323 5324ExternalASTSource::~ExternalASTSource() { } 5325 5326void ExternalASTSource::PrintStats() { } 5327 5328ASTMutationListener::~ASTMutationListener() { } 5329 5330 5331//===----------------------------------------------------------------------===// 5332// Builtin Type Computation 5333//===----------------------------------------------------------------------===// 5334 5335/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 5336/// pointer over the consumed characters. This returns the resultant type. If 5337/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 5338/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 5339/// a vector of "i*". 5340/// 5341/// RequiresICE is filled in on return to indicate whether the value is required 5342/// to be an Integer Constant Expression. 5343static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, 5344 ASTContext::GetBuiltinTypeError &Error, 5345 bool &RequiresICE, 5346 bool AllowTypeModifiers) { 5347 // Modifiers. 5348 int HowLong = 0; 5349 bool Signed = false, Unsigned = false; 5350 RequiresICE = false; 5351 5352 // Read the prefixed modifiers first. 5353 bool Done = false; 5354 while (!Done) { 5355 switch (*Str++) { 5356 default: Done = true; --Str; break; 5357 case 'I': 5358 RequiresICE = true; 5359 break; 5360 case 'S': 5361 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 5362 assert(!Signed && "Can't use 'S' modifier multiple times!"); 5363 Signed = true; 5364 break; 5365 case 'U': 5366 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 5367 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 5368 Unsigned = true; 5369 break; 5370 case 'L': 5371 assert(HowLong <= 2 && "Can't have LLLL modifier"); 5372 ++HowLong; 5373 break; 5374 } 5375 } 5376 5377 QualType Type; 5378 5379 // Read the base type. 5380 switch (*Str++) { 5381 default: assert(0 && "Unknown builtin type letter!"); 5382 case 'v': 5383 assert(HowLong == 0 && !Signed && !Unsigned && 5384 "Bad modifiers used with 'v'!"); 5385 Type = Context.VoidTy; 5386 break; 5387 case 'f': 5388 assert(HowLong == 0 && !Signed && !Unsigned && 5389 "Bad modifiers used with 'f'!"); 5390 Type = Context.FloatTy; 5391 break; 5392 case 'd': 5393 assert(HowLong < 2 && !Signed && !Unsigned && 5394 "Bad modifiers used with 'd'!"); 5395 if (HowLong) 5396 Type = Context.LongDoubleTy; 5397 else 5398 Type = Context.DoubleTy; 5399 break; 5400 case 's': 5401 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 5402 if (Unsigned) 5403 Type = Context.UnsignedShortTy; 5404 else 5405 Type = Context.ShortTy; 5406 break; 5407 case 'i': 5408 if (HowLong == 3) 5409 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 5410 else if (HowLong == 2) 5411 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 5412 else if (HowLong == 1) 5413 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 5414 else 5415 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 5416 break; 5417 case 'c': 5418 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 5419 if (Signed) 5420 Type = Context.SignedCharTy; 5421 else if (Unsigned) 5422 Type = Context.UnsignedCharTy; 5423 else 5424 Type = Context.CharTy; 5425 break; 5426 case 'b': // boolean 5427 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 5428 Type = Context.BoolTy; 5429 break; 5430 case 'z': // size_t. 5431 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 5432 Type = Context.getSizeType(); 5433 break; 5434 case 'F': 5435 Type = Context.getCFConstantStringType(); 5436 break; 5437 case 'G': 5438 Type = Context.getObjCIdType(); 5439 break; 5440 case 'H': 5441 Type = Context.getObjCSelType(); 5442 break; 5443 case 'a': 5444 Type = Context.getBuiltinVaListType(); 5445 assert(!Type.isNull() && "builtin va list type not initialized!"); 5446 break; 5447 case 'A': 5448 // This is a "reference" to a va_list; however, what exactly 5449 // this means depends on how va_list is defined. There are two 5450 // different kinds of va_list: ones passed by value, and ones 5451 // passed by reference. An example of a by-value va_list is 5452 // x86, where va_list is a char*. An example of by-ref va_list 5453 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 5454 // we want this argument to be a char*&; for x86-64, we want 5455 // it to be a __va_list_tag*. 5456 Type = Context.getBuiltinVaListType(); 5457 assert(!Type.isNull() && "builtin va list type not initialized!"); 5458 if (Type->isArrayType()) 5459 Type = Context.getArrayDecayedType(Type); 5460 else 5461 Type = Context.getLValueReferenceType(Type); 5462 break; 5463 case 'V': { 5464 char *End; 5465 unsigned NumElements = strtoul(Str, &End, 10); 5466 assert(End != Str && "Missing vector size"); 5467 Str = End; 5468 5469 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 5470 RequiresICE, false); 5471 assert(!RequiresICE && "Can't require vector ICE"); 5472 5473 // TODO: No way to make AltiVec vectors in builtins yet. 5474 Type = Context.getVectorType(ElementType, NumElements, 5475 VectorType::GenericVector); 5476 break; 5477 } 5478 case 'X': { 5479 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 5480 false); 5481 assert(!RequiresICE && "Can't require complex ICE"); 5482 Type = Context.getComplexType(ElementType); 5483 break; 5484 } 5485 case 'P': 5486 Type = Context.getFILEType(); 5487 if (Type.isNull()) { 5488 Error = ASTContext::GE_Missing_stdio; 5489 return QualType(); 5490 } 5491 break; 5492 case 'J': 5493 if (Signed) 5494 Type = Context.getsigjmp_bufType(); 5495 else 5496 Type = Context.getjmp_bufType(); 5497 5498 if (Type.isNull()) { 5499 Error = ASTContext::GE_Missing_setjmp; 5500 return QualType(); 5501 } 5502 break; 5503 } 5504 5505 // If there are modifiers and if we're allowed to parse them, go for it. 5506 Done = !AllowTypeModifiers; 5507 while (!Done) { 5508 switch (char c = *Str++) { 5509 default: Done = true; --Str; break; 5510 case '*': 5511 case '&': { 5512 // Both pointers and references can have their pointee types 5513 // qualified with an address space. 5514 char *End; 5515 unsigned AddrSpace = strtoul(Str, &End, 10); 5516 if (End != Str && AddrSpace != 0) { 5517 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 5518 Str = End; 5519 } 5520 if (c == '*') 5521 Type = Context.getPointerType(Type); 5522 else 5523 Type = Context.getLValueReferenceType(Type); 5524 break; 5525 } 5526 // FIXME: There's no way to have a built-in with an rvalue ref arg. 5527 case 'C': 5528 Type = Type.withConst(); 5529 break; 5530 case 'D': 5531 Type = Context.getVolatileType(Type); 5532 break; 5533 } 5534 } 5535 5536 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 5537 "Integer constant 'I' type must be an integer"); 5538 5539 return Type; 5540} 5541 5542/// GetBuiltinType - Return the type for the specified builtin. 5543QualType ASTContext::GetBuiltinType(unsigned Id, 5544 GetBuiltinTypeError &Error, 5545 unsigned *IntegerConstantArgs) { 5546 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 5547 5548 llvm::SmallVector<QualType, 8> ArgTypes; 5549 5550 bool RequiresICE = false; 5551 Error = GE_None; 5552 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 5553 RequiresICE, true); 5554 if (Error != GE_None) 5555 return QualType(); 5556 5557 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 5558 5559 while (TypeStr[0] && TypeStr[0] != '.') { 5560 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 5561 if (Error != GE_None) 5562 return QualType(); 5563 5564 // If this argument is required to be an IntegerConstantExpression and the 5565 // caller cares, fill in the bitmask we return. 5566 if (RequiresICE && IntegerConstantArgs) 5567 *IntegerConstantArgs |= 1 << ArgTypes.size(); 5568 5569 // Do array -> pointer decay. The builtin should use the decayed type. 5570 if (Ty->isArrayType()) 5571 Ty = getArrayDecayedType(Ty); 5572 5573 ArgTypes.push_back(Ty); 5574 } 5575 5576 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 5577 "'.' should only occur at end of builtin type list!"); 5578 5579 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". 5580 if (ArgTypes.size() == 0 && TypeStr[0] == '.') 5581 return getFunctionNoProtoType(ResType); 5582 5583 // FIXME: Should we create noreturn types? 5584 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), 5585 TypeStr[0] == '.', 0, false, false, 0, 0, 5586 FunctionType::ExtInfo()); 5587} 5588 5589GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 5590 GVALinkage External = GVA_StrongExternal; 5591 5592 Linkage L = FD->getLinkage(); 5593 if (L == ExternalLinkage && getLangOptions().CPlusPlus && 5594 FD->getType()->getLinkage() == UniqueExternalLinkage) 5595 L = UniqueExternalLinkage; 5596 5597 switch (L) { 5598 case NoLinkage: 5599 case InternalLinkage: 5600 case UniqueExternalLinkage: 5601 return GVA_Internal; 5602 5603 case ExternalLinkage: 5604 switch (FD->getTemplateSpecializationKind()) { 5605 case TSK_Undeclared: 5606 case TSK_ExplicitSpecialization: 5607 External = GVA_StrongExternal; 5608 break; 5609 5610 case TSK_ExplicitInstantiationDefinition: 5611 return GVA_ExplicitTemplateInstantiation; 5612 5613 case TSK_ExplicitInstantiationDeclaration: 5614 case TSK_ImplicitInstantiation: 5615 External = GVA_TemplateInstantiation; 5616 break; 5617 } 5618 } 5619 5620 if (!FD->isInlined()) 5621 return External; 5622 5623 if (!getLangOptions().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 5624 // GNU or C99 inline semantics. Determine whether this symbol should be 5625 // externally visible. 5626 if (FD->isInlineDefinitionExternallyVisible()) 5627 return External; 5628 5629 // C99 inline semantics, where the symbol is not externally visible. 5630 return GVA_C99Inline; 5631 } 5632 5633 // C++0x [temp.explicit]p9: 5634 // [ Note: The intent is that an inline function that is the subject of 5635 // an explicit instantiation declaration will still be implicitly 5636 // instantiated when used so that the body can be considered for 5637 // inlining, but that no out-of-line copy of the inline function would be 5638 // generated in the translation unit. -- end note ] 5639 if (FD->getTemplateSpecializationKind() 5640 == TSK_ExplicitInstantiationDeclaration) 5641 return GVA_C99Inline; 5642 5643 return GVA_CXXInline; 5644} 5645 5646GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 5647 // If this is a static data member, compute the kind of template 5648 // specialization. Otherwise, this variable is not part of a 5649 // template. 5650 TemplateSpecializationKind TSK = TSK_Undeclared; 5651 if (VD->isStaticDataMember()) 5652 TSK = VD->getTemplateSpecializationKind(); 5653 5654 Linkage L = VD->getLinkage(); 5655 if (L == ExternalLinkage && getLangOptions().CPlusPlus && 5656 VD->getType()->getLinkage() == UniqueExternalLinkage) 5657 L = UniqueExternalLinkage; 5658 5659 switch (L) { 5660 case NoLinkage: 5661 case InternalLinkage: 5662 case UniqueExternalLinkage: 5663 return GVA_Internal; 5664 5665 case ExternalLinkage: 5666 switch (TSK) { 5667 case TSK_Undeclared: 5668 case TSK_ExplicitSpecialization: 5669 return GVA_StrongExternal; 5670 5671 case TSK_ExplicitInstantiationDeclaration: 5672 llvm_unreachable("Variable should not be instantiated"); 5673 // Fall through to treat this like any other instantiation. 5674 5675 case TSK_ExplicitInstantiationDefinition: 5676 return GVA_ExplicitTemplateInstantiation; 5677 5678 case TSK_ImplicitInstantiation: 5679 return GVA_TemplateInstantiation; 5680 } 5681 } 5682 5683 return GVA_StrongExternal; 5684} 5685 5686bool ASTContext::DeclMustBeEmitted(const Decl *D) { 5687 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 5688 if (!VD->isFileVarDecl()) 5689 return false; 5690 } else if (!isa<FunctionDecl>(D)) 5691 return false; 5692 5693 // Weak references don't produce any output by themselves. 5694 if (D->hasAttr<WeakRefAttr>()) 5695 return false; 5696 5697 // Aliases and used decls are required. 5698 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 5699 return true; 5700 5701 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 5702 // Forward declarations aren't required. 5703 if (!FD->isThisDeclarationADefinition()) 5704 return false; 5705 5706 // Constructors and destructors are required. 5707 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 5708 return true; 5709 5710 // The key function for a class is required. 5711 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 5712 const CXXRecordDecl *RD = MD->getParent(); 5713 if (MD->isOutOfLine() && RD->isDynamicClass()) { 5714 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 5715 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 5716 return true; 5717 } 5718 } 5719 5720 GVALinkage Linkage = GetGVALinkageForFunction(FD); 5721 5722 // static, static inline, always_inline, and extern inline functions can 5723 // always be deferred. Normal inline functions can be deferred in C99/C++. 5724 // Implicit template instantiations can also be deferred in C++. 5725 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 5726 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 5727 return false; 5728 return true; 5729 } 5730 5731 const VarDecl *VD = cast<VarDecl>(D); 5732 assert(VD->isFileVarDecl() && "Expected file scoped var"); 5733 5734 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 5735 return false; 5736 5737 // Structs that have non-trivial constructors or destructors are required. 5738 5739 // FIXME: Handle references. 5740 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 5741 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 5742 if (RD->hasDefinition() && 5743 (!RD->hasTrivialConstructor() || !RD->hasTrivialDestructor())) 5744 return true; 5745 } 5746 } 5747 5748 GVALinkage L = GetGVALinkageForVariable(VD); 5749 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 5750 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 5751 return false; 5752 } 5753 5754 return true; 5755} 5756 5757CallingConv ASTContext::getDefaultMethodCallConv() { 5758 // Pass through to the C++ ABI object 5759 return ABI->getDefaultMethodCallConv(); 5760} 5761 5762bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) { 5763 // Pass through to the C++ ABI object 5764 return ABI->isNearlyEmpty(RD); 5765} 5766 5767CXXABI::~CXXABI() {} 5768