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