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