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