clang API Documentation
00001 //===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This file implements the ASTContext interface. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 #include "clang/AST/ASTContext.h" 00015 #include "clang/AST/CharUnits.h" 00016 #include "clang/AST/DeclCXX.h" 00017 #include "clang/AST/DeclObjC.h" 00018 #include "clang/AST/DeclTemplate.h" 00019 #include "clang/AST/TypeLoc.h" 00020 #include "clang/AST/Expr.h" 00021 #include "clang/AST/ExternalASTSource.h" 00022 #include "clang/AST/RecordLayout.h" 00023 #include "clang/Basic/Builtins.h" 00024 #include "clang/Basic/SourceManager.h" 00025 #include "clang/Basic/TargetInfo.h" 00026 #include "llvm/ADT/SmallString.h" 00027 #include "llvm/ADT/StringExtras.h" 00028 #include "llvm/Support/MathExtras.h" 00029 #include "llvm/Support/raw_ostream.h" 00030 #include "RecordLayoutBuilder.h" 00031 00032 using namespace clang; 00033 00034 enum FloatingRank { 00035 FloatRank, DoubleRank, LongDoubleRank 00036 }; 00037 00038 ASTContext::ASTContext(const LangOptions& LOpts, SourceManager &SM, 00039 const TargetInfo &t, 00040 IdentifierTable &idents, SelectorTable &sels, 00041 Builtin::Context &builtins, 00042 bool FreeMem, unsigned size_reserve) : 00043 GlobalNestedNameSpecifier(0), CFConstantStringTypeDecl(0), 00044 NSConstantStringTypeDecl(0), 00045 ObjCFastEnumerationStateTypeDecl(0), FILEDecl(0), jmp_bufDecl(0), 00046 sigjmp_bufDecl(0), BlockDescriptorType(0), BlockDescriptorExtendedType(0), 00047 SourceMgr(SM), LangOpts(LOpts), FreeMemory(FreeMem), Target(t), 00048 Idents(idents), Selectors(sels), 00049 BuiltinInfo(builtins), ExternalSource(0), PrintingPolicy(LOpts), 00050 LastSDM(0, 0) { 00051 ObjCIdRedefinitionType = QualType(); 00052 ObjCClassRedefinitionType = QualType(); 00053 ObjCSelRedefinitionType = QualType(); 00054 if (size_reserve > 0) Types.reserve(size_reserve); 00055 TUDecl = TranslationUnitDecl::Create(*this); 00056 InitBuiltinTypes(); 00057 } 00058 00059 ASTContext::~ASTContext() { 00060 // Release the DenseMaps associated with DeclContext objects. 00061 // FIXME: Is this the ideal solution? 00062 ReleaseDeclContextMaps(); 00063 00064 // Release all of the memory associated with overridden C++ methods. 00065 for (llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::iterator 00066 OM = OverriddenMethods.begin(), OMEnd = OverriddenMethods.end(); 00067 OM != OMEnd; ++OM) 00068 OM->second.Destroy(); 00069 00070 if (FreeMemory) { 00071 // Deallocate all the types. 00072 while (!Types.empty()) { 00073 Types.back()->Destroy(*this); 00074 Types.pop_back(); 00075 } 00076 00077 for (llvm::FoldingSet<ExtQuals>::iterator 00078 I = ExtQualNodes.begin(), E = ExtQualNodes.end(); I != E; ) { 00079 // Increment in loop to prevent using deallocated memory. 00080 Deallocate(&*I++); 00081 } 00082 00083 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 00084 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 00085 // Increment in loop to prevent using deallocated memory. 00086 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 00087 R->Destroy(*this); 00088 } 00089 00090 for (llvm::DenseMap<const ObjCContainerDecl*, 00091 const ASTRecordLayout*>::iterator 00092 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) { 00093 // Increment in loop to prevent using deallocated memory. 00094 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 00095 R->Destroy(*this); 00096 } 00097 } 00098 00099 // Destroy nested-name-specifiers. 00100 for (llvm::FoldingSet<NestedNameSpecifier>::iterator 00101 NNS = NestedNameSpecifiers.begin(), 00102 NNSEnd = NestedNameSpecifiers.end(); 00103 NNS != NNSEnd; ) { 00104 // Increment in loop to prevent using deallocated memory. 00105 (*NNS++).Destroy(*this); 00106 } 00107 00108 if (GlobalNestedNameSpecifier) 00109 GlobalNestedNameSpecifier->Destroy(*this); 00110 00111 TUDecl->Destroy(*this); 00112 } 00113 00114 void 00115 ASTContext::setExternalSource(llvm::OwningPtr<ExternalASTSource> &Source) { 00116 ExternalSource.reset(Source.take()); 00117 } 00118 00119 void ASTContext::PrintStats() const { 00120 fprintf(stderr, "*** AST Context Stats:\n"); 00121 fprintf(stderr, " %d types total.\n", (int)Types.size()); 00122 00123 unsigned counts[] = { 00124 #define TYPE(Name, Parent) 0, 00125 #define ABSTRACT_TYPE(Name, Parent) 00126 #include "clang/AST/TypeNodes.def" 00127 0 // Extra 00128 }; 00129 00130 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 00131 Type *T = Types[i]; 00132 counts[(unsigned)T->getTypeClass()]++; 00133 } 00134 00135 unsigned Idx = 0; 00136 unsigned TotalBytes = 0; 00137 #define TYPE(Name, Parent) \ 00138 if (counts[Idx]) \ 00139 fprintf(stderr, " %d %s types\n", (int)counts[Idx], #Name); \ 00140 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 00141 ++Idx; 00142 #define ABSTRACT_TYPE(Name, Parent) 00143 #include "clang/AST/TypeNodes.def" 00144 00145 fprintf(stderr, "Total bytes = %d\n", int(TotalBytes)); 00146 00147 if (ExternalSource.get()) { 00148 fprintf(stderr, "\n"); 00149 ExternalSource->PrintStats(); 00150 } 00151 } 00152 00153 00154 void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 00155 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 00156 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 00157 Types.push_back(Ty); 00158 } 00159 00160 void ASTContext::InitBuiltinTypes() { 00161 assert(VoidTy.isNull() && "Context reinitialized?"); 00162 00163 // C99 6.2.5p19. 00164 InitBuiltinType(VoidTy, BuiltinType::Void); 00165 00166 // C99 6.2.5p2. 00167 InitBuiltinType(BoolTy, BuiltinType::Bool); 00168 // C99 6.2.5p3. 00169 if (LangOpts.CharIsSigned) 00170 InitBuiltinType(CharTy, BuiltinType::Char_S); 00171 else 00172 InitBuiltinType(CharTy, BuiltinType::Char_U); 00173 // C99 6.2.5p4. 00174 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 00175 InitBuiltinType(ShortTy, BuiltinType::Short); 00176 InitBuiltinType(IntTy, BuiltinType::Int); 00177 InitBuiltinType(LongTy, BuiltinType::Long); 00178 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 00179 00180 // C99 6.2.5p6. 00181 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 00182 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 00183 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 00184 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 00185 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 00186 00187 // C99 6.2.5p10. 00188 InitBuiltinType(FloatTy, BuiltinType::Float); 00189 InitBuiltinType(DoubleTy, BuiltinType::Double); 00190 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 00191 00192 // GNU extension, 128-bit integers. 00193 InitBuiltinType(Int128Ty, BuiltinType::Int128); 00194 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 00195 00196 if (LangOpts.CPlusPlus) // C++ 3.9.1p5 00197 InitBuiltinType(WCharTy, BuiltinType::WChar); 00198 else // C99 00199 WCharTy = getFromTargetType(Target.getWCharType()); 00200 00201 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 00202 InitBuiltinType(Char16Ty, BuiltinType::Char16); 00203 else // C99 00204 Char16Ty = getFromTargetType(Target.getChar16Type()); 00205 00206 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 00207 InitBuiltinType(Char32Ty, BuiltinType::Char32); 00208 else // C99 00209 Char32Ty = getFromTargetType(Target.getChar32Type()); 00210 00211 // Placeholder type for functions. 00212 InitBuiltinType(OverloadTy, BuiltinType::Overload); 00213 00214 // Placeholder type for type-dependent expressions whose type is 00215 // completely unknown. No code should ever check a type against 00216 // DependentTy and users should never see it; however, it is here to 00217 // help diagnose failures to properly check for type-dependent 00218 // expressions. 00219 InitBuiltinType(DependentTy, BuiltinType::Dependent); 00220 00221 // Placeholder type for C++0x auto declarations whose real type has 00222 // not yet been deduced. 00223 InitBuiltinType(UndeducedAutoTy, BuiltinType::UndeducedAuto); 00224 00225 // C99 6.2.5p11. 00226 FloatComplexTy = getComplexType(FloatTy); 00227 DoubleComplexTy = getComplexType(DoubleTy); 00228 LongDoubleComplexTy = getComplexType(LongDoubleTy); 00229 00230 BuiltinVaListType = QualType(); 00231 00232 // "Builtin" typedefs set by Sema::ActOnTranslationUnitScope(). 00233 ObjCIdTypedefType = QualType(); 00234 ObjCClassTypedefType = QualType(); 00235 ObjCSelTypedefType = QualType(); 00236 00237 // Builtin types for 'id', 'Class', and 'SEL'. 00238 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 00239 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 00240 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 00241 00242 ObjCConstantStringType = QualType(); 00243 00244 // void * type 00245 VoidPtrTy = getPointerType(VoidTy); 00246 00247 // nullptr type (C++0x 2.14.7) 00248 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 00249 } 00250 00251 MemberSpecializationInfo * 00252 ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 00253 assert(Var->isStaticDataMember() && "Not a static data member"); 00254 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 00255 = InstantiatedFromStaticDataMember.find(Var); 00256 if (Pos == InstantiatedFromStaticDataMember.end()) 00257 return 0; 00258 00259 return Pos->second; 00260 } 00261 00262 void 00263 ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 00264 TemplateSpecializationKind TSK) { 00265 assert(Inst->isStaticDataMember() && "Not a static data member"); 00266 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 00267 assert(!InstantiatedFromStaticDataMember[Inst] && 00268 "Already noted what static data member was instantiated from"); 00269 InstantiatedFromStaticDataMember[Inst] 00270 = new (*this) MemberSpecializationInfo(Tmpl, TSK); 00271 } 00272 00273 NamedDecl * 00274 ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 00275 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 00276 = InstantiatedFromUsingDecl.find(UUD); 00277 if (Pos == InstantiatedFromUsingDecl.end()) 00278 return 0; 00279 00280 return Pos->second; 00281 } 00282 00283 void 00284 ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 00285 assert((isa<UsingDecl>(Pattern) || 00286 isa<UnresolvedUsingValueDecl>(Pattern) || 00287 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 00288 "pattern decl is not a using decl"); 00289 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 00290 InstantiatedFromUsingDecl[Inst] = Pattern; 00291 } 00292 00293 UsingShadowDecl * 00294 ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 00295 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 00296 = InstantiatedFromUsingShadowDecl.find(Inst); 00297 if (Pos == InstantiatedFromUsingShadowDecl.end()) 00298 return 0; 00299 00300 return Pos->second; 00301 } 00302 00303 void 00304 ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 00305 UsingShadowDecl *Pattern) { 00306 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 00307 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 00308 } 00309 00310 FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 00311 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 00312 = InstantiatedFromUnnamedFieldDecl.find(Field); 00313 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 00314 return 0; 00315 00316 return Pos->second; 00317 } 00318 00319 void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 00320 FieldDecl *Tmpl) { 00321 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 00322 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 00323 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 00324 "Already noted what unnamed field was instantiated from"); 00325 00326 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 00327 } 00328 00329 ASTContext::overridden_cxx_method_iterator 00330 ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 00331 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 00332 = OverriddenMethods.find(Method); 00333 if (Pos == OverriddenMethods.end()) 00334 return 0; 00335 00336 return Pos->second.begin(); 00337 } 00338 00339 ASTContext::overridden_cxx_method_iterator 00340 ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 00341 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 00342 = OverriddenMethods.find(Method); 00343 if (Pos == OverriddenMethods.end()) 00344 return 0; 00345 00346 return Pos->second.end(); 00347 } 00348 00349 void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 00350 const CXXMethodDecl *Overridden) { 00351 OverriddenMethods[Method].push_back(Overridden); 00352 } 00353 00354 namespace { 00355 class BeforeInTranslationUnit 00356 : std::binary_function<SourceRange, SourceRange, bool> { 00357 SourceManager *SourceMgr; 00358 00359 public: 00360 explicit BeforeInTranslationUnit(SourceManager *SM) : SourceMgr(SM) { } 00361 00362 bool operator()(SourceRange X, SourceRange Y) { 00363 return SourceMgr->isBeforeInTranslationUnit(X.getBegin(), Y.getBegin()); 00364 } 00365 }; 00366 } 00367 00368 //===----------------------------------------------------------------------===// 00369 // Type Sizing and Analysis 00370 //===----------------------------------------------------------------------===// 00371 00372 /// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 00373 /// scalar floating point type. 00374 const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 00375 const BuiltinType *BT = T->getAs<BuiltinType>(); 00376 assert(BT && "Not a floating point type!"); 00377 switch (BT->getKind()) { 00378 default: assert(0 && "Not a floating point type!"); 00379 case BuiltinType::Float: return Target.getFloatFormat(); 00380 case BuiltinType::Double: return Target.getDoubleFormat(); 00381 case BuiltinType::LongDouble: return Target.getLongDoubleFormat(); 00382 } 00383 } 00384 00385 /// getDeclAlign - Return a conservative estimate of the alignment of the 00386 /// specified decl. Note that bitfields do not have a valid alignment, so 00387 /// this method will assert on them. 00388 /// If @p RefAsPointee, references are treated like their underlying type 00389 /// (for alignof), else they're treated like pointers (for CodeGen). 00390 CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) { 00391 unsigned Align = Target.getCharWidth(); 00392 00393 if (const AlignedAttr* AA = D->getAttr<AlignedAttr>()) 00394 Align = std::max(Align, AA->getMaxAlignment()); 00395 00396 if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 00397 QualType T = VD->getType(); 00398 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 00399 if (RefAsPointee) 00400 T = RT->getPointeeType(); 00401 else 00402 T = getPointerType(RT->getPointeeType()); 00403 } 00404 if (!T->isIncompleteType() && !T->isFunctionType()) { 00405 // Incomplete or function types default to 1. 00406 while (isa<VariableArrayType>(T) || isa<IncompleteArrayType>(T)) 00407 T = cast<ArrayType>(T)->getElementType(); 00408 00409 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 00410 } 00411 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) { 00412 // In the case of a field in a packed struct, we want the minimum 00413 // of the alignment of the field and the alignment of the struct. 00414 Align = std::min(Align, 00415 getPreferredTypeAlign(FD->getParent()->getTypeForDecl())); 00416 } 00417 } 00418 00419 return CharUnits::fromQuantity(Align / Target.getCharWidth()); 00420 } 00421 00422 /// getTypeSize - Return the size of the specified type, in bits. This method 00423 /// does not work on incomplete types. 00424 /// 00425 /// FIXME: Pointers into different addr spaces could have different sizes and 00426 /// alignment requirements: getPointerInfo should take an AddrSpace, this 00427 /// should take a QualType, &c. 00428 std::pair<uint64_t, unsigned> 00429 ASTContext::getTypeInfo(const Type *T) { 00430 uint64_t Width=0; 00431 unsigned Align=8; 00432 switch (T->getTypeClass()) { 00433 #define TYPE(Class, Base) 00434 #define ABSTRACT_TYPE(Class, Base) 00435 #define NON_CANONICAL_TYPE(Class, Base) 00436 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 00437 #include "clang/AST/TypeNodes.def" 00438 assert(false && "Should not see dependent types"); 00439 break; 00440 00441 case Type::FunctionNoProto: 00442 case Type::FunctionProto: 00443 // GCC extension: alignof(function) = 32 bits 00444 Width = 0; 00445 Align = 32; 00446 break; 00447 00448 case Type::IncompleteArray: 00449 case Type::VariableArray: 00450 Width = 0; 00451 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 00452 break; 00453 00454 case Type::ConstantArray: { 00455 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 00456 00457 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 00458 Width = EltInfo.first*CAT->getSize().getZExtValue(); 00459 Align = EltInfo.second; 00460 break; 00461 } 00462 case Type::ExtVector: 00463 case Type::Vector: { 00464 const VectorType *VT = cast<VectorType>(T); 00465 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 00466 Width = EltInfo.first*VT->getNumElements(); 00467 Align = Width; 00468 // If the alignment is not a power of 2, round up to the next power of 2. 00469 // This happens for non-power-of-2 length vectors. 00470 if (Align & (Align-1)) { 00471 Align = llvm::NextPowerOf2(Align); 00472 Width = llvm::RoundUpToAlignment(Width, Align); 00473 } 00474 break; 00475 } 00476 00477 case Type::Builtin: 00478 switch (cast<BuiltinType>(T)->getKind()) { 00479 default: assert(0 && "Unknown builtin type!"); 00480 case BuiltinType::Void: 00481 // GCC extension: alignof(void) = 8 bits. 00482 Width = 0; 00483 Align = 8; 00484 break; 00485 00486 case BuiltinType::Bool: 00487 Width = Target.getBoolWidth(); 00488 Align = Target.getBoolAlign(); 00489 break; 00490 case BuiltinType::Char_S: 00491 case BuiltinType::Char_U: 00492 case BuiltinType::UChar: 00493 case BuiltinType::SChar: 00494 Width = Target.getCharWidth(); 00495 Align = Target.getCharAlign(); 00496 break; 00497 case BuiltinType::WChar: 00498 Width = Target.getWCharWidth(); 00499 Align = Target.getWCharAlign(); 00500 break; 00501 case BuiltinType::Char16: 00502 Width = Target.getChar16Width(); 00503 Align = Target.getChar16Align(); 00504 break; 00505 case BuiltinType::Char32: 00506 Width = Target.getChar32Width(); 00507 Align = Target.getChar32Align(); 00508 break; 00509 case BuiltinType::UShort: 00510 case BuiltinType::Short: 00511 Width = Target.getShortWidth(); 00512 Align = Target.getShortAlign(); 00513 break; 00514 case BuiltinType::UInt: 00515 case BuiltinType::Int: 00516 Width = Target.getIntWidth(); 00517 Align = Target.getIntAlign(); 00518 break; 00519 case BuiltinType::ULong: 00520 case BuiltinType::Long: 00521 Width = Target.getLongWidth(); 00522 Align = Target.getLongAlign(); 00523 break; 00524 case BuiltinType::ULongLong: 00525 case BuiltinType::LongLong: 00526 Width = Target.getLongLongWidth(); 00527 Align = Target.getLongLongAlign(); 00528 break; 00529 case BuiltinType::Int128: 00530 case BuiltinType::UInt128: 00531 Width = 128; 00532 Align = 128; // int128_t is 128-bit aligned on all targets. 00533 break; 00534 case BuiltinType::Float: 00535 Width = Target.getFloatWidth(); 00536 Align = Target.getFloatAlign(); 00537 break; 00538 case BuiltinType::Double: 00539 Width = Target.getDoubleWidth(); 00540 Align = Target.getDoubleAlign(); 00541 break; 00542 case BuiltinType::LongDouble: 00543 Width = Target.getLongDoubleWidth(); 00544 Align = Target.getLongDoubleAlign(); 00545 break; 00546 case BuiltinType::NullPtr: 00547 Width = Target.getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 00548 Align = Target.getPointerAlign(0); // == sizeof(void*) 00549 break; 00550 } 00551 break; 00552 case Type::ObjCObjectPointer: 00553 Width = Target.getPointerWidth(0); 00554 Align = Target.getPointerAlign(0); 00555 break; 00556 case Type::BlockPointer: { 00557 unsigned AS = cast<BlockPointerType>(T)->getPointeeType().getAddressSpace(); 00558 Width = Target.getPointerWidth(AS); 00559 Align = Target.getPointerAlign(AS); 00560 break; 00561 } 00562 case Type::LValueReference: 00563 case Type::RValueReference: { 00564 // alignof and sizeof should never enter this code path here, so we go 00565 // the pointer route. 00566 unsigned AS = cast<ReferenceType>(T)->getPointeeType().getAddressSpace(); 00567 Width = Target.getPointerWidth(AS); 00568 Align = Target.getPointerAlign(AS); 00569 break; 00570 } 00571 case Type::Pointer: { 00572 unsigned AS = cast<PointerType>(T)->getPointeeType().getAddressSpace(); 00573 Width = Target.getPointerWidth(AS); 00574 Align = Target.getPointerAlign(AS); 00575 break; 00576 } 00577 case Type::MemberPointer: { 00578 QualType Pointee = cast<MemberPointerType>(T)->getPointeeType(); 00579 std::pair<uint64_t, unsigned> PtrDiffInfo = 00580 getTypeInfo(getPointerDiffType()); 00581 Width = PtrDiffInfo.first; 00582 if (Pointee->isFunctionType()) 00583 Width *= 2; 00584 Align = PtrDiffInfo.second; 00585 break; 00586 } 00587 case Type::Complex: { 00588 // Complex types have the same alignment as their elements, but twice the 00589 // size. 00590 std::pair<uint64_t, unsigned> EltInfo = 00591 getTypeInfo(cast<ComplexType>(T)->getElementType()); 00592 Width = EltInfo.first*2; 00593 Align = EltInfo.second; 00594 break; 00595 } 00596 case Type::ObjCInterface: { 00597 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 00598 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 00599 Width = Layout.getSize(); 00600 Align = Layout.getAlignment(); 00601 break; 00602 } 00603 case Type::Record: 00604 case Type::Enum: { 00605 const TagType *TT = cast<TagType>(T); 00606 00607 if (TT->getDecl()->isInvalidDecl()) { 00608 Width = 1; 00609 Align = 1; 00610 break; 00611 } 00612 00613 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 00614 return getTypeInfo(ET->getDecl()->getIntegerType()); 00615 00616 const RecordType *RT = cast<RecordType>(TT); 00617 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 00618 Width = Layout.getSize(); 00619 Align = Layout.getAlignment(); 00620 break; 00621 } 00622 00623 case Type::SubstTemplateTypeParm: 00624 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 00625 getReplacementType().getTypePtr()); 00626 00627 case Type::Elaborated: 00628 return getTypeInfo(cast<ElaboratedType>(T)->getUnderlyingType() 00629 .getTypePtr()); 00630 00631 case Type::Typedef: { 00632 const TypedefDecl *Typedef = cast<TypedefType>(T)->getDecl(); 00633 if (const AlignedAttr *Aligned = Typedef->getAttr<AlignedAttr>()) { 00634 Align = std::max(Aligned->getMaxAlignment(), 00635 getTypeAlign(Typedef->getUnderlyingType().getTypePtr())); 00636 Width = getTypeSize(Typedef->getUnderlyingType().getTypePtr()); 00637 } else 00638 return getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 00639 break; 00640 } 00641 00642 case Type::TypeOfExpr: 00643 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 00644 .getTypePtr()); 00645 00646 case Type::TypeOf: 00647 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 00648 00649 case Type::Decltype: 00650 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 00651 .getTypePtr()); 00652 00653 case Type::QualifiedName: 00654 return getTypeInfo(cast<QualifiedNameType>(T)->getNamedType().getTypePtr()); 00655 00656 case Type::TemplateSpecialization: 00657 assert(getCanonicalType(T) != T && 00658 "Cannot request the size of a dependent type"); 00659 // FIXME: this is likely to be wrong once we support template 00660 // aliases, since a template alias could refer to a typedef that 00661 // has an __aligned__ attribute on it. 00662 return getTypeInfo(getCanonicalType(T)); 00663 } 00664 00665 assert(Align && (Align & (Align-1)) == 0 && "Alignment must be power of 2"); 00666 return std::make_pair(Width, Align); 00667 } 00668 00669 /// getTypeSizeInChars - Return the size of the specified type, in characters. 00670 /// This method does not work on incomplete types. 00671 CharUnits ASTContext::getTypeSizeInChars(QualType T) { 00672 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 00673 } 00674 CharUnits ASTContext::getTypeSizeInChars(const Type *T) { 00675 return CharUnits::fromQuantity(getTypeSize(T) / getCharWidth()); 00676 } 00677 00678 /// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 00679 /// characters. This method does not work on incomplete types. 00680 CharUnits ASTContext::getTypeAlignInChars(QualType T) { 00681 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 00682 } 00683 CharUnits ASTContext::getTypeAlignInChars(const Type *T) { 00684 return CharUnits::fromQuantity(getTypeAlign(T) / getCharWidth()); 00685 } 00686 00687 /// getPreferredTypeAlign - Return the "preferred" alignment of the specified 00688 /// type for the current target in bits. This can be different than the ABI 00689 /// alignment in cases where it is beneficial for performance to overalign 00690 /// a data type. 00691 unsigned ASTContext::getPreferredTypeAlign(const Type *T) { 00692 unsigned ABIAlign = getTypeAlign(T); 00693 00694 // Double and long long should be naturally aligned if possible. 00695 if (const ComplexType* CT = T->getAs<ComplexType>()) 00696 T = CT->getElementType().getTypePtr(); 00697 if (T->isSpecificBuiltinType(BuiltinType::Double) || 00698 T->isSpecificBuiltinType(BuiltinType::LongLong)) 00699 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 00700 00701 return ABIAlign; 00702 } 00703 00704 static void CollectLocalObjCIvars(ASTContext *Ctx, 00705 const ObjCInterfaceDecl *OI, 00706 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 00707 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 00708 E = OI->ivar_end(); I != E; ++I) { 00709 ObjCIvarDecl *IVDecl = *I; 00710 if (!IVDecl->isInvalidDecl()) 00711 Fields.push_back(cast<FieldDecl>(IVDecl)); 00712 } 00713 } 00714 00715 void ASTContext::CollectObjCIvars(const ObjCInterfaceDecl *OI, 00716 llvm::SmallVectorImpl<FieldDecl*> &Fields) { 00717 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 00718 CollectObjCIvars(SuperClass, Fields); 00719 CollectLocalObjCIvars(this, OI, Fields); 00720 } 00721 00722 /// ShallowCollectObjCIvars - 00723 /// Collect all ivars, including those synthesized, in the current class. 00724 /// 00725 void ASTContext::ShallowCollectObjCIvars(const ObjCInterfaceDecl *OI, 00726 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 00727 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 00728 E = OI->ivar_end(); I != E; ++I) { 00729 Ivars.push_back(*I); 00730 } 00731 00732 CollectNonClassIvars(OI, Ivars); 00733 } 00734 00735 /// CollectNonClassIvars - 00736 /// This routine collects all other ivars which are not declared in the class. 00737 /// This includes synthesized ivars (via @synthesize) and those in 00738 // class's @implementation. 00739 /// 00740 void ASTContext::CollectNonClassIvars(const ObjCInterfaceDecl *OI, 00741 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) { 00742 // Find ivars declared in class extension. 00743 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) { 00744 for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(), 00745 E = CDecl->ivar_end(); I != E; ++I) { 00746 Ivars.push_back(*I); 00747 } 00748 } 00749 00750 // Also add any ivar defined in this class's implementation. This 00751 // includes synthesized ivars. 00752 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) { 00753 for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(), 00754 E = ImplDecl->ivar_end(); I != E; ++I) 00755 Ivars.push_back(*I); 00756 } 00757 } 00758 00759 /// CollectInheritedProtocols - Collect all protocols in current class and 00760 /// those inherited by it. 00761 void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 00762 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 00763 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 00764 for (ObjCInterfaceDecl::protocol_iterator P = OI->protocol_begin(), 00765 PE = OI->protocol_end(); P != PE; ++P) { 00766 ObjCProtocolDecl *Proto = (*P); 00767 Protocols.insert(Proto); 00768 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 00769 PE = Proto->protocol_end(); P != PE; ++P) { 00770 Protocols.insert(*P); 00771 CollectInheritedProtocols(*P, Protocols); 00772 } 00773 } 00774 00775 // Categories of this Interface. 00776 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 00777 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 00778 CollectInheritedProtocols(CDeclChain, Protocols); 00779 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 00780 while (SD) { 00781 CollectInheritedProtocols(SD, Protocols); 00782 SD = SD->getSuperClass(); 00783 } 00784 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 00785 for (ObjCInterfaceDecl::protocol_iterator P = OC->protocol_begin(), 00786 PE = OC->protocol_end(); P != PE; ++P) { 00787 ObjCProtocolDecl *Proto = (*P); 00788 Protocols.insert(Proto); 00789 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 00790 PE = Proto->protocol_end(); P != PE; ++P) 00791 CollectInheritedProtocols(*P, Protocols); 00792 } 00793 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 00794 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 00795 PE = OP->protocol_end(); P != PE; ++P) { 00796 ObjCProtocolDecl *Proto = (*P); 00797 Protocols.insert(Proto); 00798 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 00799 PE = Proto->protocol_end(); P != PE; ++P) 00800 CollectInheritedProtocols(*P, Protocols); 00801 } 00802 } 00803 } 00804 00805 unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) { 00806 unsigned count = 0; 00807 // Count ivars declared in class extension. 00808 if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) 00809 count += CDecl->ivar_size(); 00810 00811 // Count ivar defined in this class's implementation. This 00812 // includes synthesized ivars. 00813 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 00814 count += ImplDecl->ivar_size(); 00815 00816 return count; 00817 } 00818 00819 /// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 00820 ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 00821 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 00822 I = ObjCImpls.find(D); 00823 if (I != ObjCImpls.end()) 00824 return cast<ObjCImplementationDecl>(I->second); 00825 return 0; 00826 } 00827 /// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 00828 ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 00829 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 00830 I = ObjCImpls.find(D); 00831 if (I != ObjCImpls.end()) 00832 return cast<ObjCCategoryImplDecl>(I->second); 00833 return 0; 00834 } 00835 00836 /// \brief Set the implementation of ObjCInterfaceDecl. 00837 void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 00838 ObjCImplementationDecl *ImplD) { 00839 assert(IFaceD && ImplD && "Passed null params"); 00840 ObjCImpls[IFaceD] = ImplD; 00841 } 00842 /// \brief Set the implementation of ObjCCategoryDecl. 00843 void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 00844 ObjCCategoryImplDecl *ImplD) { 00845 assert(CatD && ImplD && "Passed null params"); 00846 ObjCImpls[CatD] = ImplD; 00847 } 00848 00849 /// \brief Allocate an uninitialized TypeSourceInfo. 00850 /// 00851 /// The caller should initialize the memory held by TypeSourceInfo using 00852 /// the TypeLoc wrappers. 00853 /// 00854 /// \param T the type that will be the basis for type source info. This type 00855 /// should refer to how the declarator was written in source code, not to 00856 /// what type semantic analysis resolved the declarator to. 00857 TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 00858 unsigned DataSize) { 00859 if (!DataSize) 00860 DataSize = TypeLoc::getFullDataSizeForType(T); 00861 else 00862 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 00863 "incorrect data size provided to CreateTypeSourceInfo!"); 00864 00865 TypeSourceInfo *TInfo = 00866 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 00867 new (TInfo) TypeSourceInfo(T); 00868 return TInfo; 00869 } 00870 00871 TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 00872 SourceLocation L) { 00873 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 00874 DI->getTypeLoc().initialize(L); 00875 return DI; 00876 } 00877 00878 /// getInterfaceLayoutImpl - Get or compute information about the 00879 /// layout of the given interface. 00880 /// 00881 /// \param Impl - If given, also include the layout of the interface's 00882 /// implementation. This may differ by including synthesized ivars. 00883 const ASTRecordLayout & 00884 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D, 00885 const ObjCImplementationDecl *Impl) { 00886 assert(!D->isForwardDecl() && "Invalid interface decl!"); 00887 00888 // Look up this layout, if already laid out, return what we have. 00889 ObjCContainerDecl *Key = 00890 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D; 00891 if (const ASTRecordLayout *Entry = ObjCLayouts[Key]) 00892 return *Entry; 00893 00894 // Add in synthesized ivar count if laying out an implementation. 00895 if (Impl) { 00896 unsigned SynthCount = CountNonClassIvars(D); 00897 // If there aren't any sythesized ivars then reuse the interface 00898 // entry. Note we can't cache this because we simply free all 00899 // entries later; however we shouldn't look up implementations 00900 // frequently. 00901 if (SynthCount == 0) 00902 return getObjCLayout(D, 0); 00903 } 00904 00905 const ASTRecordLayout *NewEntry = 00906 ASTRecordLayoutBuilder::ComputeLayout(*this, D, Impl); 00907 ObjCLayouts[Key] = NewEntry; 00908 00909 return *NewEntry; 00910 } 00911 00912 const ASTRecordLayout & 00913 ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) { 00914 return getObjCLayout(D, 0); 00915 } 00916 00917 const ASTRecordLayout & 00918 ASTContext::getASTObjCImplementationLayout(const ObjCImplementationDecl *D) { 00919 return getObjCLayout(D->getClassInterface(), D); 00920 } 00921 00922 /// getASTRecordLayout - Get or compute information about the layout of the 00923 /// specified record (struct/union/class), which indicates its size and field 00924 /// position information. 00925 const ASTRecordLayout &ASTContext::getASTRecordLayout(const RecordDecl *D) { 00926 D = D->getDefinition(); 00927 assert(D && "Cannot get layout of forward declarations!"); 00928 00929 // Look up this layout, if already laid out, return what we have. 00930 // Note that we can't save a reference to the entry because this function 00931 // is recursive. 00932 const ASTRecordLayout *Entry = ASTRecordLayouts[D]; 00933 if (Entry) return *Entry; 00934 00935 const ASTRecordLayout *NewEntry = 00936 ASTRecordLayoutBuilder::ComputeLayout(*this, D); 00937 ASTRecordLayouts[D] = NewEntry; 00938 00939 if (getLangOptions().DumpRecordLayouts) { 00940 llvm::errs() << "\n*** Dumping AST Record Layout\n"; 00941 DumpRecordLayout(D, llvm::errs()); 00942 } 00943 00944 return *NewEntry; 00945 } 00946 00947 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) { 00948 RD = cast<CXXRecordDecl>(RD->getDefinition()); 00949 assert(RD && "Cannot get key function for forward declarations!"); 00950 00951 const CXXMethodDecl *&Entry = KeyFunctions[RD]; 00952 if (!Entry) 00953 Entry = ASTRecordLayoutBuilder::ComputeKeyFunction(RD); 00954 else 00955 assert(Entry == ASTRecordLayoutBuilder::ComputeKeyFunction(RD) && 00956 "Key function changed!"); 00957 00958 return Entry; 00959 } 00960 00961 //===----------------------------------------------------------------------===// 00962 // Type creation/memoization methods 00963 //===----------------------------------------------------------------------===// 00964 00965 QualType ASTContext::getExtQualType(const Type *TypeNode, Qualifiers Quals) { 00966 unsigned Fast = Quals.getFastQualifiers(); 00967 Quals.removeFastQualifiers(); 00968 00969 // Check if we've already instantiated this type. 00970 llvm::FoldingSetNodeID ID; 00971 ExtQuals::Profile(ID, TypeNode, Quals); 00972 void *InsertPos = 0; 00973 if (ExtQuals *EQ = ExtQualNodes.FindNodeOrInsertPos(ID, InsertPos)) { 00974 assert(EQ->getQualifiers() == Quals); 00975 QualType T = QualType(EQ, Fast); 00976 return T; 00977 } 00978 00979 ExtQuals *New = new (*this, TypeAlignment) ExtQuals(*this, TypeNode, Quals); 00980 ExtQualNodes.InsertNode(New, InsertPos); 00981 QualType T = QualType(New, Fast); 00982 return T; 00983 } 00984 00985 QualType ASTContext::getVolatileType(QualType T) { 00986 QualType CanT = getCanonicalType(T); 00987 if (CanT.isVolatileQualified()) return T; 00988 00989 QualifierCollector Quals; 00990 const Type *TypeNode = Quals.strip(T); 00991 Quals.addVolatile(); 00992 00993 return getExtQualType(TypeNode, Quals); 00994 } 00995 00996 QualType ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) { 00997 QualType CanT = getCanonicalType(T); 00998 if (CanT.getAddressSpace() == AddressSpace) 00999 return T; 01000 01001 // If we are composing extended qualifiers together, merge together 01002 // into one ExtQuals node. 01003 QualifierCollector Quals; 01004 const Type *TypeNode = Quals.strip(T); 01005 01006 // If this type already has an address space specified, it cannot get 01007 // another one. 01008 assert(!Quals.hasAddressSpace() && 01009 "Type cannot be in multiple addr spaces!"); 01010 Quals.addAddressSpace(AddressSpace); 01011 01012 return getExtQualType(TypeNode, Quals); 01013 } 01014 01015 QualType ASTContext::getObjCGCQualType(QualType T, 01016 Qualifiers::GC GCAttr) { 01017 QualType CanT = getCanonicalType(T); 01018 if (CanT.getObjCGCAttr() == GCAttr) 01019 return T; 01020 01021 if (T->isPointerType()) { 01022 QualType Pointee = T->getAs<PointerType>()->getPointeeType(); 01023 if (Pointee->isAnyPointerType()) { 01024 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 01025 return getPointerType(ResultType); 01026 } 01027 } 01028 01029 // If we are composing extended qualifiers together, merge together 01030 // into one ExtQuals node. 01031 QualifierCollector Quals; 01032 const Type *TypeNode = Quals.strip(T); 01033 01034 // If this type already has an ObjCGC specified, it cannot get 01035 // another one. 01036 assert(!Quals.hasObjCGCAttr() && 01037 "Type cannot have multiple ObjCGCs!"); 01038 Quals.addObjCGCAttr(GCAttr); 01039 01040 return getExtQualType(TypeNode, Quals); 01041 } 01042 01043 static QualType getExtFunctionType(ASTContext& Context, QualType T, 01044 const FunctionType::ExtInfo &Info) { 01045 QualType ResultType; 01046 if (const PointerType *Pointer = T->getAs<PointerType>()) { 01047 QualType Pointee = Pointer->getPointeeType(); 01048 ResultType = getExtFunctionType(Context, Pointee, Info); 01049 if (ResultType == Pointee) 01050 return T; 01051 01052 ResultType = Context.getPointerType(ResultType); 01053 } else if (const BlockPointerType *BlockPointer 01054 = T->getAs<BlockPointerType>()) { 01055 QualType Pointee = BlockPointer->getPointeeType(); 01056 ResultType = getExtFunctionType(Context, Pointee, Info); 01057 if (ResultType == Pointee) 01058 return T; 01059 01060 ResultType = Context.getBlockPointerType(ResultType); 01061 } else if (const FunctionType *F = T->getAs<FunctionType>()) { 01062 if (F->getExtInfo() == Info) 01063 return T; 01064 01065 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(F)) { 01066 ResultType = Context.getFunctionNoProtoType(FNPT->getResultType(), 01067 Info); 01068 } else { 01069 const FunctionProtoType *FPT = cast<FunctionProtoType>(F); 01070 ResultType 01071 = Context.getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 01072 FPT->getNumArgs(), FPT->isVariadic(), 01073 FPT->getTypeQuals(), 01074 FPT->hasExceptionSpec(), 01075 FPT->hasAnyExceptionSpec(), 01076 FPT->getNumExceptions(), 01077 FPT->exception_begin(), 01078 Info); 01079 } 01080 } else 01081 return T; 01082 01083 return Context.getQualifiedType(ResultType, T.getLocalQualifiers()); 01084 } 01085 01086 QualType ASTContext::getNoReturnType(QualType T, bool AddNoReturn) { 01087 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 01088 return getExtFunctionType(*this, T, 01089 Info.withNoReturn(AddNoReturn)); 01090 } 01091 01092 QualType ASTContext::getCallConvType(QualType T, CallingConv CallConv) { 01093 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 01094 return getExtFunctionType(*this, T, 01095 Info.withCallingConv(CallConv)); 01096 } 01097 01098 QualType ASTContext::getRegParmType(QualType T, unsigned RegParm) { 01099 FunctionType::ExtInfo Info = getFunctionExtInfo(T); 01100 return getExtFunctionType(*this, T, 01101 Info.withRegParm(RegParm)); 01102 } 01103 01104 /// getComplexType - Return the uniqued reference to the type for a complex 01105 /// number with the specified element type. 01106 QualType ASTContext::getComplexType(QualType T) { 01107 // Unique pointers, to guarantee there is only one pointer of a particular 01108 // structure. 01109 llvm::FoldingSetNodeID ID; 01110 ComplexType::Profile(ID, T); 01111 01112 void *InsertPos = 0; 01113 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 01114 return QualType(CT, 0); 01115 01116 // If the pointee type isn't canonical, this won't be a canonical type either, 01117 // so fill in the canonical type field. 01118 QualType Canonical; 01119 if (!T.isCanonical()) { 01120 Canonical = getComplexType(getCanonicalType(T)); 01121 01122 // Get the new insert position for the node we care about. 01123 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 01124 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01125 } 01126 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 01127 Types.push_back(New); 01128 ComplexTypes.InsertNode(New, InsertPos); 01129 return QualType(New, 0); 01130 } 01131 01132 /// getPointerType - Return the uniqued reference to the type for a pointer to 01133 /// the specified type. 01134 QualType ASTContext::getPointerType(QualType T) { 01135 // Unique pointers, to guarantee there is only one pointer of a particular 01136 // structure. 01137 llvm::FoldingSetNodeID ID; 01138 PointerType::Profile(ID, T); 01139 01140 void *InsertPos = 0; 01141 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 01142 return QualType(PT, 0); 01143 01144 // If the pointee type isn't canonical, this won't be a canonical type either, 01145 // so fill in the canonical type field. 01146 QualType Canonical; 01147 if (!T.isCanonical()) { 01148 Canonical = getPointerType(getCanonicalType(T)); 01149 01150 // Get the new insert position for the node we care about. 01151 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 01152 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01153 } 01154 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 01155 Types.push_back(New); 01156 PointerTypes.InsertNode(New, InsertPos); 01157 return QualType(New, 0); 01158 } 01159 01160 /// getBlockPointerType - Return the uniqued reference to the type for 01161 /// a pointer to the specified block. 01162 QualType ASTContext::getBlockPointerType(QualType T) { 01163 assert(T->isFunctionType() && "block of function types only"); 01164 // Unique pointers, to guarantee there is only one block of a particular 01165 // structure. 01166 llvm::FoldingSetNodeID ID; 01167 BlockPointerType::Profile(ID, T); 01168 01169 void *InsertPos = 0; 01170 if (BlockPointerType *PT = 01171 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 01172 return QualType(PT, 0); 01173 01174 // If the block pointee type isn't canonical, this won't be a canonical 01175 // type either so fill in the canonical type field. 01176 QualType Canonical; 01177 if (!T.isCanonical()) { 01178 Canonical = getBlockPointerType(getCanonicalType(T)); 01179 01180 // Get the new insert position for the node we care about. 01181 BlockPointerType *NewIP = 01182 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 01183 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01184 } 01185 BlockPointerType *New 01186 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 01187 Types.push_back(New); 01188 BlockPointerTypes.InsertNode(New, InsertPos); 01189 return QualType(New, 0); 01190 } 01191 01192 /// getLValueReferenceType - Return the uniqued reference to the type for an 01193 /// lvalue reference to the specified type. 01194 QualType ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) { 01195 // Unique pointers, to guarantee there is only one pointer of a particular 01196 // structure. 01197 llvm::FoldingSetNodeID ID; 01198 ReferenceType::Profile(ID, T, SpelledAsLValue); 01199 01200 void *InsertPos = 0; 01201 if (LValueReferenceType *RT = 01202 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 01203 return QualType(RT, 0); 01204 01205 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 01206 01207 // If the referencee type isn't canonical, this won't be a canonical type 01208 // either, so fill in the canonical type field. 01209 QualType Canonical; 01210 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 01211 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 01212 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 01213 01214 // Get the new insert position for the node we care about. 01215 LValueReferenceType *NewIP = 01216 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 01217 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01218 } 01219 01220 LValueReferenceType *New 01221 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 01222 SpelledAsLValue); 01223 Types.push_back(New); 01224 LValueReferenceTypes.InsertNode(New, InsertPos); 01225 01226 return QualType(New, 0); 01227 } 01228 01229 /// getRValueReferenceType - Return the uniqued reference to the type for an 01230 /// rvalue reference to the specified type. 01231 QualType ASTContext::getRValueReferenceType(QualType T) { 01232 // Unique pointers, to guarantee there is only one pointer of a particular 01233 // structure. 01234 llvm::FoldingSetNodeID ID; 01235 ReferenceType::Profile(ID, T, false); 01236 01237 void *InsertPos = 0; 01238 if (RValueReferenceType *RT = 01239 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 01240 return QualType(RT, 0); 01241 01242 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 01243 01244 // If the referencee type isn't canonical, this won't be a canonical type 01245 // either, so fill in the canonical type field. 01246 QualType Canonical; 01247 if (InnerRef || !T.isCanonical()) { 01248 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 01249 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 01250 01251 // Get the new insert position for the node we care about. 01252 RValueReferenceType *NewIP = 01253 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 01254 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01255 } 01256 01257 RValueReferenceType *New 01258 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 01259 Types.push_back(New); 01260 RValueReferenceTypes.InsertNode(New, InsertPos); 01261 return QualType(New, 0); 01262 } 01263 01264 /// getMemberPointerType - Return the uniqued reference to the type for a 01265 /// member pointer to the specified type, in the specified class. 01266 QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) { 01267 // Unique pointers, to guarantee there is only one pointer of a particular 01268 // structure. 01269 llvm::FoldingSetNodeID ID; 01270 MemberPointerType::Profile(ID, T, Cls); 01271 01272 void *InsertPos = 0; 01273 if (MemberPointerType *PT = 01274 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 01275 return QualType(PT, 0); 01276 01277 // If the pointee or class type isn't canonical, this won't be a canonical 01278 // type either, so fill in the canonical type field. 01279 QualType Canonical; 01280 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 01281 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 01282 01283 // Get the new insert position for the node we care about. 01284 MemberPointerType *NewIP = 01285 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 01286 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01287 } 01288 MemberPointerType *New 01289 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 01290 Types.push_back(New); 01291 MemberPointerTypes.InsertNode(New, InsertPos); 01292 return QualType(New, 0); 01293 } 01294 01295 /// getConstantArrayType - Return the unique reference to the type for an 01296 /// array of the specified element type. 01297 QualType ASTContext::getConstantArrayType(QualType EltTy, 01298 const llvm::APInt &ArySizeIn, 01299 ArrayType::ArraySizeModifier ASM, 01300 unsigned EltTypeQuals) { 01301 assert((EltTy->isDependentType() || 01302 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 01303 "Constant array of VLAs is illegal!"); 01304 01305 // Convert the array size into a canonical width matching the pointer size for 01306 // the target. 01307 llvm::APInt ArySize(ArySizeIn); 01308 ArySize.zextOrTrunc(Target.getPointerWidth(EltTy.getAddressSpace())); 01309 01310 llvm::FoldingSetNodeID ID; 01311 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, EltTypeQuals); 01312 01313 void *InsertPos = 0; 01314 if (ConstantArrayType *ATP = 01315 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 01316 return QualType(ATP, 0); 01317 01318 // If the element type isn't canonical, this won't be a canonical type either, 01319 // so fill in the canonical type field. 01320 QualType Canonical; 01321 if (!EltTy.isCanonical()) { 01322 Canonical = getConstantArrayType(getCanonicalType(EltTy), ArySize, 01323 ASM, EltTypeQuals); 01324 // Get the new insert position for the node we care about. 01325 ConstantArrayType *NewIP = 01326 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 01327 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01328 } 01329 01330 ConstantArrayType *New = new(*this,TypeAlignment) 01331 ConstantArrayType(EltTy, Canonical, ArySize, ASM, EltTypeQuals); 01332 ConstantArrayTypes.InsertNode(New, InsertPos); 01333 Types.push_back(New); 01334 return QualType(New, 0); 01335 } 01336 01337 /// getVariableArrayType - Returns a non-unique reference to the type for a 01338 /// variable array of the specified element type. 01339 QualType ASTContext::getVariableArrayType(QualType EltTy, 01340 Expr *NumElts, 01341 ArrayType::ArraySizeModifier ASM, 01342 unsigned EltTypeQuals, 01343 SourceRange Brackets) { 01344 // Since we don't unique expressions, it isn't possible to unique VLA's 01345 // that have an expression provided for their size. 01346 01347 VariableArrayType *New = new(*this, TypeAlignment) 01348 VariableArrayType(EltTy, QualType(), NumElts, ASM, EltTypeQuals, Brackets); 01349 01350 VariableArrayTypes.push_back(New); 01351 Types.push_back(New); 01352 return QualType(New, 0); 01353 } 01354 01355 /// getDependentSizedArrayType - Returns a non-unique reference to 01356 /// the type for a dependently-sized array of the specified element 01357 /// type. 01358 QualType ASTContext::getDependentSizedArrayType(QualType EltTy, 01359 Expr *NumElts, 01360 ArrayType::ArraySizeModifier ASM, 01361 unsigned EltTypeQuals, 01362 SourceRange Brackets) { 01363 assert((!NumElts || NumElts->isTypeDependent() || 01364 NumElts->isValueDependent()) && 01365 "Size must be type- or value-dependent!"); 01366 01367 void *InsertPos = 0; 01368 DependentSizedArrayType *Canon = 0; 01369 llvm::FoldingSetNodeID ID; 01370 01371 if (NumElts) { 01372 // Dependently-sized array types that do not have a specified 01373 // number of elements will have their sizes deduced from an 01374 // initializer. 01375 DependentSizedArrayType::Profile(ID, *this, getCanonicalType(EltTy), ASM, 01376 EltTypeQuals, NumElts); 01377 01378 Canon = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 01379 } 01380 01381 DependentSizedArrayType *New; 01382 if (Canon) { 01383 // We already have a canonical version of this array type; use it as 01384 // the canonical type for a newly-built type. 01385 New = new (*this, TypeAlignment) 01386 DependentSizedArrayType(*this, EltTy, QualType(Canon, 0), 01387 NumElts, ASM, EltTypeQuals, Brackets); 01388 } else { 01389 QualType CanonEltTy = getCanonicalType(EltTy); 01390 if (CanonEltTy == EltTy) { 01391 New = new (*this, TypeAlignment) 01392 DependentSizedArrayType(*this, EltTy, QualType(), 01393 NumElts, ASM, EltTypeQuals, Brackets); 01394 01395 if (NumElts) { 01396 DependentSizedArrayType *CanonCheck 01397 = DependentSizedArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 01398 assert(!CanonCheck && "Dependent-sized canonical array type broken"); 01399 (void)CanonCheck; 01400 DependentSizedArrayTypes.InsertNode(New, InsertPos); 01401 } 01402 } else { 01403 QualType Canon = getDependentSizedArrayType(CanonEltTy, NumElts, 01404 ASM, EltTypeQuals, 01405 SourceRange()); 01406 New = new (*this, TypeAlignment) 01407 DependentSizedArrayType(*this, EltTy, Canon, 01408 NumElts, ASM, EltTypeQuals, Brackets); 01409 } 01410 } 01411 01412 Types.push_back(New); 01413 return QualType(New, 0); 01414 } 01415 01416 QualType ASTContext::getIncompleteArrayType(QualType EltTy, 01417 ArrayType::ArraySizeModifier ASM, 01418 unsigned EltTypeQuals) { 01419 llvm::FoldingSetNodeID ID; 01420 IncompleteArrayType::Profile(ID, EltTy, ASM, EltTypeQuals); 01421 01422 void *InsertPos = 0; 01423 if (IncompleteArrayType *ATP = 01424 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 01425 return QualType(ATP, 0); 01426 01427 // If the element type isn't canonical, this won't be a canonical type 01428 // either, so fill in the canonical type field. 01429 QualType Canonical; 01430 01431 if (!EltTy.isCanonical()) { 01432 Canonical = getIncompleteArrayType(getCanonicalType(EltTy), 01433 ASM, EltTypeQuals); 01434 01435 // Get the new insert position for the node we care about. 01436 IncompleteArrayType *NewIP = 01437 IncompleteArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 01438 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01439 } 01440 01441 IncompleteArrayType *New = new (*this, TypeAlignment) 01442 IncompleteArrayType(EltTy, Canonical, ASM, EltTypeQuals); 01443 01444 IncompleteArrayTypes.InsertNode(New, InsertPos); 01445 Types.push_back(New); 01446 return QualType(New, 0); 01447 } 01448 01449 /// getVectorType - Return the unique reference to a vector type of 01450 /// the specified element type and size. VectorType must be a built-in type. 01451 QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 01452 bool IsAltiVec, bool IsPixel) { 01453 BuiltinType *baseType; 01454 01455 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 01456 assert(baseType != 0 && "getVectorType(): Expecting a built-in type"); 01457 01458 // Check if we've already instantiated a vector of this type. 01459 llvm::FoldingSetNodeID ID; 01460 VectorType::Profile(ID, vecType, NumElts, Type::Vector, 01461 IsAltiVec, IsPixel); 01462 void *InsertPos = 0; 01463 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 01464 return QualType(VTP, 0); 01465 01466 // If the element type isn't canonical, this won't be a canonical type either, 01467 // so fill in the canonical type field. 01468 QualType Canonical; 01469 if (!vecType.isCanonical() || IsAltiVec || IsPixel) { 01470 Canonical = getVectorType(getCanonicalType(vecType), 01471 NumElts, false, false); 01472 01473 // Get the new insert position for the node we care about. 01474 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 01475 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01476 } 01477 VectorType *New = new (*this, TypeAlignment) 01478 VectorType(vecType, NumElts, Canonical, IsAltiVec, IsPixel); 01479 VectorTypes.InsertNode(New, InsertPos); 01480 Types.push_back(New); 01481 return QualType(New, 0); 01482 } 01483 01484 /// getExtVectorType - Return the unique reference to an extended vector type of 01485 /// the specified element type and size. VectorType must be a built-in type. 01486 QualType ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) { 01487 BuiltinType *baseType; 01488 01489 baseType = dyn_cast<BuiltinType>(getCanonicalType(vecType).getTypePtr()); 01490 assert(baseType != 0 && "getExtVectorType(): Expecting a built-in type"); 01491 01492 // Check if we've already instantiated a vector of this type. 01493 llvm::FoldingSetNodeID ID; 01494 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, false, false); 01495 void *InsertPos = 0; 01496 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 01497 return QualType(VTP, 0); 01498 01499 // If the element type isn't canonical, this won't be a canonical type either, 01500 // so fill in the canonical type field. 01501 QualType Canonical; 01502 if (!vecType.isCanonical()) { 01503 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 01504 01505 // Get the new insert position for the node we care about. 01506 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 01507 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01508 } 01509 ExtVectorType *New = new (*this, TypeAlignment) 01510 ExtVectorType(vecType, NumElts, Canonical); 01511 VectorTypes.InsertNode(New, InsertPos); 01512 Types.push_back(New); 01513 return QualType(New, 0); 01514 } 01515 01516 QualType ASTContext::getDependentSizedExtVectorType(QualType vecType, 01517 Expr *SizeExpr, 01518 SourceLocation AttrLoc) { 01519 llvm::FoldingSetNodeID ID; 01520 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 01521 SizeExpr); 01522 01523 void *InsertPos = 0; 01524 DependentSizedExtVectorType *Canon 01525 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 01526 DependentSizedExtVectorType *New; 01527 if (Canon) { 01528 // We already have a canonical version of this array type; use it as 01529 // the canonical type for a newly-built type. 01530 New = new (*this, TypeAlignment) 01531 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 01532 SizeExpr, AttrLoc); 01533 } else { 01534 QualType CanonVecTy = getCanonicalType(vecType); 01535 if (CanonVecTy == vecType) { 01536 New = new (*this, TypeAlignment) 01537 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 01538 AttrLoc); 01539 01540 DependentSizedExtVectorType *CanonCheck 01541 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 01542 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 01543 (void)CanonCheck; 01544 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 01545 } else { 01546 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 01547 SourceLocation()); 01548 New = new (*this, TypeAlignment) 01549 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 01550 } 01551 } 01552 01553 Types.push_back(New); 01554 return QualType(New, 0); 01555 } 01556 01557 /// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 01558 /// 01559 QualType ASTContext::getFunctionNoProtoType(QualType ResultTy, 01560 const FunctionType::ExtInfo &Info) { 01561 const CallingConv CallConv = Info.getCC(); 01562 // Unique functions, to guarantee there is only one function of a particular 01563 // structure. 01564 llvm::FoldingSetNodeID ID; 01565 FunctionNoProtoType::Profile(ID, ResultTy, Info); 01566 01567 void *InsertPos = 0; 01568 if (FunctionNoProtoType *FT = 01569 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 01570 return QualType(FT, 0); 01571 01572 QualType Canonical; 01573 if (!ResultTy.isCanonical() || 01574 getCanonicalCallConv(CallConv) != CallConv) { 01575 Canonical = 01576 getFunctionNoProtoType(getCanonicalType(ResultTy), 01577 Info.withCallingConv(getCanonicalCallConv(CallConv))); 01578 01579 // Get the new insert position for the node we care about. 01580 FunctionNoProtoType *NewIP = 01581 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 01582 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01583 } 01584 01585 FunctionNoProtoType *New = new (*this, TypeAlignment) 01586 FunctionNoProtoType(ResultTy, Canonical, Info); 01587 Types.push_back(New); 01588 FunctionNoProtoTypes.InsertNode(New, InsertPos); 01589 return QualType(New, 0); 01590 } 01591 01592 /// getFunctionType - Return a normal function type with a typed argument 01593 /// list. isVariadic indicates whether the argument list includes '...'. 01594 QualType ASTContext::getFunctionType(QualType ResultTy,const QualType *ArgArray, 01595 unsigned NumArgs, bool isVariadic, 01596 unsigned TypeQuals, bool hasExceptionSpec, 01597 bool hasAnyExceptionSpec, unsigned NumExs, 01598 const QualType *ExArray, 01599 const FunctionType::ExtInfo &Info) { 01600 const CallingConv CallConv= Info.getCC(); 01601 // Unique functions, to guarantee there is only one function of a particular 01602 // structure. 01603 llvm::FoldingSetNodeID ID; 01604 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, isVariadic, 01605 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 01606 NumExs, ExArray, Info); 01607 01608 void *InsertPos = 0; 01609 if (FunctionProtoType *FTP = 01610 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 01611 return QualType(FTP, 0); 01612 01613 // Determine whether the type being created is already canonical or not. 01614 bool isCanonical = !hasExceptionSpec && ResultTy.isCanonical(); 01615 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 01616 if (!ArgArray[i].isCanonicalAsParam()) 01617 isCanonical = false; 01618 01619 // If this type isn't canonical, get the canonical version of it. 01620 // The exception spec is not part of the canonical type. 01621 QualType Canonical; 01622 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 01623 llvm::SmallVector<QualType, 16> CanonicalArgs; 01624 CanonicalArgs.reserve(NumArgs); 01625 for (unsigned i = 0; i != NumArgs; ++i) 01626 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 01627 01628 Canonical = getFunctionType(getCanonicalType(ResultTy), 01629 CanonicalArgs.data(), NumArgs, 01630 isVariadic, TypeQuals, false, 01631 false, 0, 0, 01632 Info.withCallingConv(getCanonicalCallConv(CallConv))); 01633 01634 // Get the new insert position for the node we care about. 01635 FunctionProtoType *NewIP = 01636 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 01637 assert(NewIP == 0 && "Shouldn't be in the map!"); NewIP = NewIP; 01638 } 01639 01640 // FunctionProtoType objects are allocated with extra bytes after them 01641 // for two variable size arrays (for parameter and exception types) at the 01642 // end of them. 01643 FunctionProtoType *FTP = 01644 (FunctionProtoType*)Allocate(sizeof(FunctionProtoType) + 01645 NumArgs*sizeof(QualType) + 01646 NumExs*sizeof(QualType), TypeAlignment); 01647 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, isVariadic, 01648 TypeQuals, hasExceptionSpec, hasAnyExceptionSpec, 01649 ExArray, NumExs, Canonical, Info); 01650 Types.push_back(FTP); 01651 FunctionProtoTypes.InsertNode(FTP, InsertPos); 01652 return QualType(FTP, 0); 01653 } 01654 01655 #ifndef NDEBUG 01656 static bool NeedsInjectedClassNameType(const RecordDecl *D) { 01657 if (!isa<CXXRecordDecl>(D)) return false; 01658 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 01659 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 01660 return true; 01661 if (RD->getDescribedClassTemplate() && 01662 !isa<ClassTemplateSpecializationDecl>(RD)) 01663 return true; 01664 return false; 01665 } 01666 #endif 01667 01668 /// getInjectedClassNameType - Return the unique reference to the 01669 /// injected class name type for the specified templated declaration. 01670 QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 01671 QualType TST) { 01672 assert(NeedsInjectedClassNameType(Decl)); 01673 if (Decl->TypeForDecl) { 01674 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 01675 } else if (CXXRecordDecl *PrevDecl 01676 = cast_or_null<CXXRecordDecl>(Decl->getPreviousDeclaration())) { 01677 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 01678 Decl->TypeForDecl = PrevDecl->TypeForDecl; 01679 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 01680 } else { 01681 Decl->TypeForDecl = 01682 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 01683 Types.push_back(Decl->TypeForDecl); 01684 } 01685 return QualType(Decl->TypeForDecl, 0); 01686 } 01687 01688 /// getTypeDeclType - Return the unique reference to the type for the 01689 /// specified type declaration. 01690 QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) { 01691 assert(Decl && "Passed null for Decl param"); 01692 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 01693 01694 if (const TypedefDecl *Typedef = dyn_cast<TypedefDecl>(Decl)) 01695 return getTypedefType(Typedef); 01696 01697 if (const ObjCInterfaceDecl *ObjCInterface 01698 = dyn_cast<ObjCInterfaceDecl>(Decl)) 01699 return getObjCInterfaceType(ObjCInterface); 01700 01701 assert(!isa<TemplateTypeParmDecl>(Decl) && 01702 "Template type parameter types are always available."); 01703 01704 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 01705 assert(!Record->getPreviousDeclaration() && 01706 "struct/union has previous declaration"); 01707 assert(!NeedsInjectedClassNameType(Record)); 01708 Decl->TypeForDecl = new (*this, TypeAlignment) RecordType(Record); 01709 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 01710 assert(!Enum->getPreviousDeclaration() && 01711 "enum has previous declaration"); 01712 Decl->TypeForDecl = new (*this, TypeAlignment) EnumType(Enum); 01713 } else if (const UnresolvedUsingTypenameDecl *Using = 01714 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 01715 Decl->TypeForDecl = new (*this, TypeAlignment) UnresolvedUsingType(Using); 01716 } else 01717 llvm_unreachable("TypeDecl without a type?"); 01718 01719 Types.push_back(Decl->TypeForDecl); 01720 return QualType(Decl->TypeForDecl, 0); 01721 } 01722 01723 /// getTypedefType - Return the unique reference to the type for the 01724 /// specified typename decl. 01725 QualType ASTContext::getTypedefType(const TypedefDecl *Decl) { 01726 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 01727 01728 QualType Canonical = getCanonicalType(Decl->getUnderlyingType()); 01729 Decl->TypeForDecl = new(*this, TypeAlignment) 01730 TypedefType(Type::Typedef, Decl, Canonical); 01731 Types.push_back(Decl->TypeForDecl); 01732 return QualType(Decl->TypeForDecl, 0); 01733 } 01734 01735 /// \brief Retrieve a substitution-result type. 01736 QualType 01737 ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 01738 QualType Replacement) { 01739 assert(Replacement.isCanonical() 01740 && "replacement types must always be canonical"); 01741 01742 llvm::FoldingSetNodeID ID; 01743 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 01744 void *InsertPos = 0; 01745 SubstTemplateTypeParmType *SubstParm 01746 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 01747 01748 if (!SubstParm) { 01749 SubstParm = new (*this, TypeAlignment) 01750 SubstTemplateTypeParmType(Parm, Replacement); 01751 Types.push_back(SubstParm); 01752 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 01753 } 01754 01755 return QualType(SubstParm, 0); 01756 } 01757 01758 /// \brief Retrieve the template type parameter type for a template 01759 /// parameter or parameter pack with the given depth, index, and (optionally) 01760 /// name. 01761 QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 01762 bool ParameterPack, 01763 IdentifierInfo *Name) { 01764 llvm::FoldingSetNodeID ID; 01765 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, Name); 01766 void *InsertPos = 0; 01767 TemplateTypeParmType *TypeParm 01768 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 01769 01770 if (TypeParm) 01771 return QualType(TypeParm, 0); 01772 01773 if (Name) { 01774 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 01775 TypeParm = new (*this, TypeAlignment) 01776 TemplateTypeParmType(Depth, Index, ParameterPack, Name, Canon); 01777 01778 TemplateTypeParmType *TypeCheck 01779 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 01780 assert(!TypeCheck && "Template type parameter canonical type broken"); 01781 (void)TypeCheck; 01782 } else 01783 TypeParm = new (*this, TypeAlignment) 01784 TemplateTypeParmType(Depth, Index, ParameterPack); 01785 01786 Types.push_back(TypeParm); 01787 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 01788 01789 return QualType(TypeParm, 0); 01790 } 01791 01792 TypeSourceInfo * 01793 ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 01794 SourceLocation NameLoc, 01795 const TemplateArgumentListInfo &Args, 01796 QualType CanonType) { 01797 QualType TST = getTemplateSpecializationType(Name, Args, CanonType); 01798 01799 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 01800 TemplateSpecializationTypeLoc TL 01801 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 01802 TL.setTemplateNameLoc(NameLoc); 01803 TL.setLAngleLoc(Args.getLAngleLoc()); 01804 TL.setRAngleLoc(Args.getRAngleLoc()); 01805 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 01806 TL.setArgLocInfo(i, Args[i].getLocInfo()); 01807 return DI; 01808 } 01809 01810 QualType 01811 ASTContext::getTemplateSpecializationType(TemplateName Template, 01812 const TemplateArgumentListInfo &Args, 01813 QualType Canon, 01814 bool IsCurrentInstantiation) { 01815 unsigned NumArgs = Args.size(); 01816 01817 llvm::SmallVector<TemplateArgument, 4> ArgVec; 01818 ArgVec.reserve(NumArgs); 01819 for (unsigned i = 0; i != NumArgs; ++i) 01820 ArgVec.push_back(Args[i].getArgument()); 01821 01822 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 01823 Canon, IsCurrentInstantiation); 01824 } 01825 01826 QualType 01827 ASTContext::getTemplateSpecializationType(TemplateName Template, 01828 const TemplateArgument *Args, 01829 unsigned NumArgs, 01830 QualType Canon, 01831 bool IsCurrentInstantiation) { 01832 if (!Canon.isNull()) 01833 Canon = getCanonicalType(Canon); 01834 else { 01835 assert(!IsCurrentInstantiation && 01836 "current-instantiation specializations should always " 01837 "have a canonical type"); 01838 01839 // Build the canonical template specialization type. 01840 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 01841 llvm::SmallVector<TemplateArgument, 4> CanonArgs; 01842 CanonArgs.reserve(NumArgs); 01843 for (unsigned I = 0; I != NumArgs; ++I) 01844 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 01845 01846 // Determine whether this canonical template specialization type already 01847 // exists. 01848 llvm::FoldingSetNodeID ID; 01849 TemplateSpecializationType::Profile(ID, CanonTemplate, false, 01850 CanonArgs.data(), NumArgs, *this); 01851 01852 void *InsertPos = 0; 01853 TemplateSpecializationType *Spec 01854 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 01855 01856 if (!Spec) { 01857 // Allocate a new canonical template specialization type. 01858 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 01859 sizeof(TemplateArgument) * NumArgs), 01860 TypeAlignment); 01861 Spec = new (Mem) TemplateSpecializationType(*this, CanonTemplate, false, 01862 CanonArgs.data(), NumArgs, 01863 Canon); 01864 Types.push_back(Spec); 01865 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 01866 } 01867 01868 if (Canon.isNull()) 01869 Canon = QualType(Spec, 0); 01870 assert(Canon->isDependentType() && 01871 "Non-dependent template-id type must have a canonical type"); 01872 } 01873 01874 // Allocate the (non-canonical) template specialization type, but don't 01875 // try to unique it: these types typically have location information that 01876 // we don't unique and don't want to lose. 01877 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 01878 sizeof(TemplateArgument) * NumArgs), 01879 TypeAlignment); 01880 TemplateSpecializationType *Spec 01881 = new (Mem) TemplateSpecializationType(*this, Template, 01882 IsCurrentInstantiation, 01883 Args, NumArgs, 01884 Canon); 01885 01886 Types.push_back(Spec); 01887 return QualType(Spec, 0); 01888 } 01889 01890 QualType 01891 ASTContext::getQualifiedNameType(NestedNameSpecifier *NNS, 01892 QualType NamedType) { 01893 llvm::FoldingSetNodeID ID; 01894 QualifiedNameType::Profile(ID, NNS, NamedType); 01895 01896 void *InsertPos = 0; 01897 QualifiedNameType *T 01898 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); 01899 if (T) 01900 return QualType(T, 0); 01901 01902 QualType Canon = NamedType; 01903 if (!Canon.isCanonical()) { 01904 Canon = getCanonicalType(NamedType); 01905 QualifiedNameType *CheckT 01906 = QualifiedNameTypes.FindNodeOrInsertPos(ID, InsertPos); 01907 assert(!CheckT && "Qualified name canonical type broken"); 01908 (void)CheckT; 01909 } 01910 01911 T = new (*this) QualifiedNameType(NNS, NamedType, Canon); 01912 Types.push_back(T); 01913 QualifiedNameTypes.InsertNode(T, InsertPos); 01914 return QualType(T, 0); 01915 } 01916 01917 QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 01918 NestedNameSpecifier *NNS, 01919 const IdentifierInfo *Name, 01920 QualType Canon) { 01921 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 01922 01923 if (Canon.isNull()) { 01924 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 01925 ElaboratedTypeKeyword CanonKeyword = Keyword; 01926 if (Keyword == ETK_None) 01927 CanonKeyword = ETK_Typename; 01928 01929 if (CanonNNS != NNS || CanonKeyword != Keyword) 01930 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 01931 } 01932 01933 llvm::FoldingSetNodeID ID; 01934 DependentNameType::Profile(ID, Keyword, NNS, Name); 01935 01936 void *InsertPos = 0; 01937 DependentNameType *T 01938 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 01939 if (T) 01940 return QualType(T, 0); 01941 01942 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 01943 Types.push_back(T); 01944 DependentNameTypes.InsertNode(T, InsertPos); 01945 return QualType(T, 0); 01946 } 01947 01948 QualType 01949 ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 01950 NestedNameSpecifier *NNS, 01951 const TemplateSpecializationType *TemplateId, 01952 QualType Canon) { 01953 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 01954 01955 llvm::FoldingSetNodeID ID; 01956 DependentNameType::Profile(ID, Keyword, NNS, TemplateId); 01957 01958 void *InsertPos = 0; 01959 DependentNameType *T 01960 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 01961 if (T) 01962 return QualType(T, 0); 01963 01964 if (Canon.isNull()) { 01965 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 01966 QualType CanonType = getCanonicalType(QualType(TemplateId, 0)); 01967 ElaboratedTypeKeyword CanonKeyword = Keyword; 01968 if (Keyword == ETK_None) 01969 CanonKeyword = ETK_Typename; 01970 if (CanonNNS != NNS || CanonKeyword != Keyword || 01971 CanonType != QualType(TemplateId, 0)) { 01972 const TemplateSpecializationType *CanonTemplateId 01973 = CanonType->getAs<TemplateSpecializationType>(); 01974 assert(CanonTemplateId && 01975 "Canonical type must also be a template specialization type"); 01976 Canon = getDependentNameType(CanonKeyword, CanonNNS, CanonTemplateId); 01977 } 01978 01979 DependentNameType *CheckT 01980 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 01981 assert(!CheckT && "Typename canonical type is broken"); (void)CheckT; 01982 } 01983 01984 T = new (*this) DependentNameType(Keyword, NNS, TemplateId, Canon); 01985 Types.push_back(T); 01986 DependentNameTypes.InsertNode(T, InsertPos); 01987 return QualType(T, 0); 01988 } 01989 01990 QualType 01991 ASTContext::getElaboratedType(QualType UnderlyingType, 01992 ElaboratedType::TagKind Tag) { 01993 llvm::FoldingSetNodeID ID; 01994 ElaboratedType::Profile(ID, UnderlyingType, Tag); 01995 01996 void *InsertPos = 0; 01997 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 01998 if (T) 01999 return QualType(T, 0); 02000 02001 QualType Canon = UnderlyingType; 02002 if (!Canon.isCanonical()) { 02003 Canon = getCanonicalType(Canon); 02004 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 02005 assert(!CheckT && "Elaborated canonical type is broken"); (void)CheckT; 02006 } 02007 02008 T = new (*this) ElaboratedType(UnderlyingType, Tag, Canon); 02009 Types.push_back(T); 02010 ElaboratedTypes.InsertNode(T, InsertPos); 02011 return QualType(T, 0); 02012 } 02013 02014 /// CmpProtocolNames - Comparison predicate for sorting protocols 02015 /// alphabetically. 02016 static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 02017 const ObjCProtocolDecl *RHS) { 02018 return LHS->getDeclName() < RHS->getDeclName(); 02019 } 02020 02021 static bool areSortedAndUniqued(ObjCProtocolDecl **Protocols, 02022 unsigned NumProtocols) { 02023 if (NumProtocols == 0) return true; 02024 02025 for (unsigned i = 1; i != NumProtocols; ++i) 02026 if (!CmpProtocolNames(Protocols[i-1], Protocols[i])) 02027 return false; 02028 return true; 02029 } 02030 02031 static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 02032 unsigned &NumProtocols) { 02033 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 02034 02035 // Sort protocols, keyed by name. 02036 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 02037 02038 // Remove duplicates. 02039 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 02040 NumProtocols = ProtocolsEnd-Protocols; 02041 } 02042 02043 /// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 02044 /// the given interface decl and the conforming protocol list. 02045 QualType ASTContext::getObjCObjectPointerType(QualType InterfaceT, 02046 ObjCProtocolDecl **Protocols, 02047 unsigned NumProtocols, 02048 unsigned Quals) { 02049 llvm::FoldingSetNodeID ID; 02050 ObjCObjectPointerType::Profile(ID, InterfaceT, Protocols, NumProtocols); 02051 Qualifiers Qs = Qualifiers::fromCVRMask(Quals); 02052 02053 void *InsertPos = 0; 02054 if (ObjCObjectPointerType *QT = 02055 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 02056 return getQualifiedType(QualType(QT, 0), Qs); 02057 02058 // Sort the protocol list alphabetically to canonicalize it. 02059 QualType Canonical; 02060 if (!InterfaceT.isCanonical() || 02061 !areSortedAndUniqued(Protocols, NumProtocols)) { 02062 if (!areSortedAndUniqued(Protocols, NumProtocols)) { 02063 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 02064 Protocols + NumProtocols); 02065 unsigned UniqueCount = NumProtocols; 02066 02067 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 02068 02069 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT), 02070 &Sorted[0], UniqueCount); 02071 } else { 02072 Canonical = getObjCObjectPointerType(getCanonicalType(InterfaceT), 02073 Protocols, NumProtocols); 02074 } 02075 02076 // Regenerate InsertPos. 02077 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 02078 } 02079 02080 // No match. 02081 unsigned Size = sizeof(ObjCObjectPointerType) 02082 + NumProtocols * sizeof(ObjCProtocolDecl *); 02083 void *Mem = Allocate(Size, TypeAlignment); 02084 ObjCObjectPointerType *QType = new (Mem) ObjCObjectPointerType(Canonical, 02085 InterfaceT, 02086 Protocols, 02087 NumProtocols); 02088 02089 Types.push_back(QType); 02090 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 02091 return getQualifiedType(QualType(QType, 0), Qs); 02092 } 02093 02094 /// getObjCInterfaceType - Return the unique reference to the type for the 02095 /// specified ObjC interface decl. The list of protocols is optional. 02096 QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 02097 ObjCProtocolDecl **Protocols, unsigned NumProtocols) { 02098 llvm::FoldingSetNodeID ID; 02099 ObjCInterfaceType::Profile(ID, Decl, Protocols, NumProtocols); 02100 02101 void *InsertPos = 0; 02102 if (ObjCInterfaceType *QT = 02103 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos)) 02104 return QualType(QT, 0); 02105 02106 // Sort the protocol list alphabetically to canonicalize it. 02107 QualType Canonical; 02108 if (NumProtocols && !areSortedAndUniqued(Protocols, NumProtocols)) { 02109 llvm::SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 02110 Protocols + NumProtocols); 02111 02112 unsigned UniqueCount = NumProtocols; 02113 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 02114 02115 Canonical = getObjCInterfaceType(Decl, &Sorted[0], UniqueCount); 02116 02117 ObjCInterfaceTypes.FindNodeOrInsertPos(ID, InsertPos); 02118 } 02119 02120 unsigned Size = sizeof(ObjCInterfaceType) 02121 + NumProtocols * sizeof(ObjCProtocolDecl *); 02122 void *Mem = Allocate(Size, TypeAlignment); 02123 ObjCInterfaceType *QType = new (Mem) ObjCInterfaceType(Canonical, 02124 const_cast<ObjCInterfaceDecl*>(Decl), 02125 Protocols, 02126 NumProtocols); 02127 02128 Types.push_back(QType); 02129 ObjCInterfaceTypes.InsertNode(QType, InsertPos); 02130 return QualType(QType, 0); 02131 } 02132 02133 /// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 02134 /// TypeOfExprType AST's (since expression's are never shared). For example, 02135 /// multiple declarations that refer to "typeof(x)" all contain different 02136 /// DeclRefExpr's. This doesn't effect the type checker, since it operates 02137 /// on canonical type's (which are always unique). 02138 QualType ASTContext::getTypeOfExprType(Expr *tofExpr) { 02139 TypeOfExprType *toe; 02140 if (tofExpr->isTypeDependent()) { 02141 llvm::FoldingSetNodeID ID; 02142 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 02143 02144 void *InsertPos = 0; 02145 DependentTypeOfExprType *Canon 02146 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 02147 if (Canon) { 02148 // We already have a "canonical" version of an identical, dependent 02149 // typeof(expr) type. Use that as our canonical type. 02150 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 02151 QualType((TypeOfExprType*)Canon, 0)); 02152 } 02153 else { 02154 // Build a new, canonical typeof(expr) type. 02155 Canon 02156 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 02157 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 02158 toe = Canon; 02159 } 02160 } else { 02161 QualType Canonical = getCanonicalType(tofExpr->getType()); 02162 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 02163 } 02164 Types.push_back(toe); 02165 return QualType(toe, 0); 02166 } 02167 02168 /// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 02169 /// TypeOfType AST's. The only motivation to unique these nodes would be 02170 /// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 02171 /// an issue. This doesn't effect the type checker, since it operates 02172 /// on canonical type's (which are always unique). 02173 QualType ASTContext::getTypeOfType(QualType tofType) { 02174 QualType Canonical = getCanonicalType(tofType); 02175 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 02176 Types.push_back(tot); 02177 return QualType(tot, 0); 02178 } 02179 02180 /// getDecltypeForExpr - Given an expr, will return the decltype for that 02181 /// expression, according to the rules in C++0x [dcl.type.simple]p4 02182 static QualType getDecltypeForExpr(const Expr *e, ASTContext &Context) { 02183 if (e->isTypeDependent()) 02184 return Context.DependentTy; 02185 02186 // If e is an id expression or a class member access, decltype(e) is defined 02187 // as the type of the entity named by e. 02188 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(e)) { 02189 if (const ValueDecl *VD = dyn_cast<ValueDecl>(DRE->getDecl())) 02190 return VD->getType(); 02191 } 02192 if (const MemberExpr *ME = dyn_cast<MemberExpr>(e)) { 02193 if (const FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) 02194 return FD->getType(); 02195 } 02196 // If e is a function call or an invocation of an overloaded operator, 02197 // (parentheses around e are ignored), decltype(e) is defined as the 02198 // return type of that function. 02199 if (const CallExpr *CE = dyn_cast<CallExpr>(e->IgnoreParens())) 02200 return CE->getCallReturnType(); 02201 02202 QualType T = e->getType(); 02203 02204 // Otherwise, where T is the type of e, if e is an lvalue, decltype(e) is 02205 // defined as T&, otherwise decltype(e) is defined as T. 02206 if (e->isLvalue(Context) == Expr::LV_Valid) 02207 T = Context.getLValueReferenceType(T); 02208 02209 return T; 02210 } 02211 02212 /// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 02213 /// DecltypeType AST's. The only motivation to unique these nodes would be 02214 /// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 02215 /// an issue. This doesn't effect the type checker, since it operates 02216 /// on canonical type's (which are always unique). 02217 QualType ASTContext::getDecltypeType(Expr *e) { 02218 DecltypeType *dt; 02219 if (e->isTypeDependent()) { 02220 llvm::FoldingSetNodeID ID; 02221 DependentDecltypeType::Profile(ID, *this, e); 02222 02223 void *InsertPos = 0; 02224 DependentDecltypeType *Canon 02225 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 02226 if (Canon) { 02227 // We already have a "canonical" version of an equivalent, dependent 02228 // decltype type. Use that as our canonical type. 02229 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 02230 QualType((DecltypeType*)Canon, 0)); 02231 } 02232 else { 02233 // Build a new, canonical typeof(expr) type. 02234 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 02235 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 02236 dt = Canon; 02237 } 02238 } else { 02239 QualType T = getDecltypeForExpr(e, *this); 02240 dt = new (*this, TypeAlignment) DecltypeType(e, T, getCanonicalType(T)); 02241 } 02242 Types.push_back(dt); 02243 return QualType(dt, 0); 02244 } 02245 02246 /// getTagDeclType - Return the unique reference to the type for the 02247 /// specified TagDecl (struct/union/class/enum) decl. 02248 QualType ASTContext::getTagDeclType(const TagDecl *Decl) { 02249 assert (Decl); 02250 // FIXME: What is the design on getTagDeclType when it requires casting 02251 // away const? mutable? 02252 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 02253 } 02254 02255 /// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 02256 /// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 02257 /// needs to agree with the definition in <stddef.h>. 02258 CanQualType ASTContext::getSizeType() const { 02259 return getFromTargetType(Target.getSizeType()); 02260 } 02261 02262 /// getSignedWCharType - Return the type of "signed wchar_t". 02263 /// Used when in C++, as a GCC extension. 02264 QualType ASTContext::getSignedWCharType() const { 02265 // FIXME: derive from "Target" ? 02266 return WCharTy; 02267 } 02268 02269 /// getUnsignedWCharType - Return the type of "unsigned wchar_t". 02270 /// Used when in C++, as a GCC extension. 02271 QualType ASTContext::getUnsignedWCharType() const { 02272 // FIXME: derive from "Target" ? 02273 return UnsignedIntTy; 02274 } 02275 02276 /// getPointerDiffType - Return the unique type for "ptrdiff_t" (ref?) 02277 /// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 02278 QualType ASTContext::getPointerDiffType() const { 02279 return getFromTargetType(Target.getPtrDiffType(0)); 02280 } 02281 02282 //===----------------------------------------------------------------------===// 02283 // Type Operators 02284 //===----------------------------------------------------------------------===// 02285 02286 CanQualType ASTContext::getCanonicalParamType(QualType T) { 02287 // Push qualifiers into arrays, and then discard any remaining 02288 // qualifiers. 02289 T = getCanonicalType(T); 02290 const Type *Ty = T.getTypePtr(); 02291 02292 QualType Result; 02293 if (isa<ArrayType>(Ty)) { 02294 Result = getArrayDecayedType(QualType(Ty,0)); 02295 } else if (isa<FunctionType>(Ty)) { 02296 Result = getPointerType(QualType(Ty, 0)); 02297 } else { 02298 Result = QualType(Ty, 0); 02299 } 02300 02301 return CanQualType::CreateUnsafe(Result); 02302 } 02303 02304 /// getCanonicalType - Return the canonical (structural) type corresponding to 02305 /// the specified potentially non-canonical type. The non-canonical version 02306 /// of a type may have many "decorated" versions of types. Decorators can 02307 /// include typedefs, 'typeof' operators, etc. The returned type is guaranteed 02308 /// to be free of any of these, allowing two canonical types to be compared 02309 /// for exact equality with a simple pointer comparison. 02310 CanQualType ASTContext::getCanonicalType(QualType T) { 02311 QualifierCollector Quals; 02312 const Type *Ptr = Quals.strip(T); 02313 QualType CanType = Ptr->getCanonicalTypeInternal(); 02314 02315 // The canonical internal type will be the canonical type *except* 02316 // that we push type qualifiers down through array types. 02317 02318 // If there are no new qualifiers to push down, stop here. 02319 if (!Quals.hasQualifiers()) 02320 return CanQualType::CreateUnsafe(CanType); 02321 02322 // If the type qualifiers are on an array type, get the canonical 02323 // type of the array with the qualifiers applied to the element 02324 // type. 02325 ArrayType *AT = dyn_cast<ArrayType>(CanType); 02326 if (!AT) 02327 return CanQualType::CreateUnsafe(getQualifiedType(CanType, Quals)); 02328 02329 // Get the canonical version of the element with the extra qualifiers on it. 02330 // This can recursively sink qualifiers through multiple levels of arrays. 02331 QualType NewEltTy = getQualifiedType(AT->getElementType(), Quals); 02332 NewEltTy = getCanonicalType(NewEltTy); 02333 02334 if (ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 02335 return CanQualType::CreateUnsafe( 02336 getConstantArrayType(NewEltTy, CAT->getSize(), 02337 CAT->getSizeModifier(), 02338 CAT->getIndexTypeCVRQualifiers())); 02339 if (IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) 02340 return CanQualType::CreateUnsafe( 02341 getIncompleteArrayType(NewEltTy, IAT->getSizeModifier(), 02342 IAT->getIndexTypeCVRQualifiers())); 02343 02344 if (DependentSizedArrayType *DSAT = dyn_cast<DependentSizedArrayType>(AT)) 02345 return CanQualType::CreateUnsafe( 02346 getDependentSizedArrayType(NewEltTy, 02347 DSAT->getSizeExpr() ? 02348 DSAT->getSizeExpr()->Retain() : 0, 02349 DSAT->getSizeModifier(), 02350 DSAT->getIndexTypeCVRQualifiers(), 02351 DSAT->getBracketsRange())->getCanonicalTypeInternal()); 02352 02353 VariableArrayType *VAT = cast<VariableArrayType>(AT); 02354 return CanQualType::CreateUnsafe(getVariableArrayType(NewEltTy, 02355 VAT->getSizeExpr() ? 02356 VAT->getSizeExpr()->Retain() : 0, 02357 VAT->getSizeModifier(), 02358 VAT->getIndexTypeCVRQualifiers(), 02359 VAT->getBracketsRange())); 02360 } 02361 02362 QualType ASTContext::getUnqualifiedArrayType(QualType T, 02363 Qualifiers &Quals) { 02364 Quals = T.getQualifiers(); 02365 if (!isa<ArrayType>(T)) { 02366 return T.getUnqualifiedType(); 02367 } 02368 02369 const ArrayType *AT = cast<ArrayType>(T); 02370 QualType Elt = AT->getElementType(); 02371 QualType UnqualElt = getUnqualifiedArrayType(Elt, Quals); 02372 if (Elt == UnqualElt) 02373 return T; 02374 02375 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(T)) { 02376 return getConstantArrayType(UnqualElt, CAT->getSize(), 02377 CAT->getSizeModifier(), 0); 02378 } 02379 02380 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(T)) { 02381 return getIncompleteArrayType(UnqualElt, IAT->getSizeModifier(), 0); 02382 } 02383 02384 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(T); 02385 return getDependentSizedArrayType(UnqualElt, DSAT->getSizeExpr()->Retain(), 02386 DSAT->getSizeModifier(), 0, 02387 SourceRange()); 02388 } 02389 02390 DeclarationName ASTContext::getNameForTemplate(TemplateName Name) { 02391 if (TemplateDecl *TD = Name.getAsTemplateDecl()) 02392 return TD->getDeclName(); 02393 02394 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) { 02395 if (DTN->isIdentifier()) { 02396 return DeclarationNames.getIdentifier(DTN->getIdentifier()); 02397 } else { 02398 return DeclarationNames.getCXXOperatorName(DTN->getOperator()); 02399 } 02400 } 02401 02402 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 02403 assert(Storage); 02404 return (*Storage->begin())->getDeclName(); 02405 } 02406 02407 TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) { 02408 // If this template name refers to a template, the canonical 02409 // template name merely stores the template itself. 02410 if (TemplateDecl *Template = Name.getAsTemplateDecl()) 02411 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 02412 02413 assert(!Name.getAsOverloadedTemplate()); 02414 02415 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 02416 assert(DTN && "Non-dependent template names must refer to template decls."); 02417 return DTN->CanonicalTemplateName; 02418 } 02419 02420 bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 02421 X = getCanonicalTemplateName(X); 02422 Y = getCanonicalTemplateName(Y); 02423 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 02424 } 02425 02426 TemplateArgument 02427 ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) { 02428 switch (Arg.getKind()) { 02429 case TemplateArgument::Null: 02430 return Arg; 02431 02432 case TemplateArgument::Expression: 02433 return Arg; 02434 02435 case TemplateArgument::Declaration: 02436 return TemplateArgument(Arg.getAsDecl()->getCanonicalDecl()); 02437 02438 case TemplateArgument::Template: 02439 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 02440 02441 case TemplateArgument::Integral: 02442 return TemplateArgument(*Arg.getAsIntegral(), 02443 getCanonicalType(Arg.getIntegralType())); 02444 02445 case TemplateArgument::Type: 02446 return TemplateArgument(getCanonicalType(Arg.getAsType())); 02447 02448 case TemplateArgument::Pack: { 02449 // FIXME: Allocate in ASTContext 02450 TemplateArgument *CanonArgs = new TemplateArgument[Arg.pack_size()]; 02451 unsigned Idx = 0; 02452 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 02453 AEnd = Arg.pack_end(); 02454 A != AEnd; (void)++A, ++Idx) 02455 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 02456 02457 TemplateArgument Result; 02458 Result.setArgumentPack(CanonArgs, Arg.pack_size(), false); 02459 return Result; 02460 } 02461 } 02462 02463 // Silence GCC warning 02464 assert(false && "Unhandled template argument kind"); 02465 return TemplateArgument(); 02466 } 02467 02468 NestedNameSpecifier * 02469 ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) { 02470 if (!NNS) 02471 return 0; 02472 02473 switch (NNS->getKind()) { 02474 case NestedNameSpecifier::Identifier: 02475 // Canonicalize the prefix but keep the identifier the same. 02476 return NestedNameSpecifier::Create(*this, 02477 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 02478 NNS->getAsIdentifier()); 02479 02480 case NestedNameSpecifier::Namespace: 02481 // A namespace is canonical; build a nested-name-specifier with 02482 // this namespace and no prefix. 02483 return NestedNameSpecifier::Create(*this, 0, NNS->getAsNamespace()); 02484 02485 case NestedNameSpecifier::TypeSpec: 02486 case NestedNameSpecifier::TypeSpecWithTemplate: { 02487 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 02488 return NestedNameSpecifier::Create(*this, 0, 02489 NNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate, 02490 T.getTypePtr()); 02491 } 02492 02493 case NestedNameSpecifier::Global: 02494 // The global specifier is canonical and unique. 02495 return NNS; 02496 } 02497 02498 // Required to silence a GCC warning 02499 return 0; 02500 } 02501 02502 02503 const ArrayType *ASTContext::getAsArrayType(QualType T) { 02504 // Handle the non-qualified case efficiently. 02505 if (!T.hasLocalQualifiers()) { 02506 // Handle the common positive case fast. 02507 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 02508 return AT; 02509 } 02510 02511 // Handle the common negative case fast. 02512 QualType CType = T->getCanonicalTypeInternal(); 02513 if (!isa<ArrayType>(CType)) 02514 return 0; 02515 02516 // Apply any qualifiers from the array type to the element type. This 02517 // implements C99 6.7.3p8: "If the specification of an array type includes 02518 // any type qualifiers, the element type is so qualified, not the array type." 02519 02520 // If we get here, we either have type qualifiers on the type, or we have 02521 // sugar such as a typedef in the way. If we have type qualifiers on the type 02522 // we must propagate them down into the element type. 02523 02524 QualifierCollector Qs; 02525 const Type *Ty = Qs.strip(T.getDesugaredType()); 02526 02527 // If we have a simple case, just return now. 02528 const ArrayType *ATy = dyn_cast<ArrayType>(Ty); 02529 if (ATy == 0 || Qs.empty()) 02530 return ATy; 02531 02532 // Otherwise, we have an array and we have qualifiers on it. Push the 02533 // qualifiers into the array element type and return a new array type. 02534 // Get the canonical version of the element with the extra qualifiers on it. 02535 // This can recursively sink qualifiers through multiple levels of arrays. 02536 QualType NewEltTy = getQualifiedType(ATy->getElementType(), Qs); 02537 02538 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 02539 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 02540 CAT->getSizeModifier(), 02541 CAT->getIndexTypeCVRQualifiers())); 02542 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 02543 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 02544 IAT->getSizeModifier(), 02545 IAT->getIndexTypeCVRQualifiers())); 02546 02547 if (const DependentSizedArrayType *DSAT 02548 = dyn_cast<DependentSizedArrayType>(ATy)) 02549 return cast<ArrayType>( 02550 getDependentSizedArrayType(NewEltTy, 02551 DSAT->getSizeExpr() ? 02552 DSAT->getSizeExpr()->Retain() : 0, 02553 DSAT->getSizeModifier(), 02554 DSAT->getIndexTypeCVRQualifiers(), 02555 DSAT->getBracketsRange())); 02556 02557 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 02558 return cast<ArrayType>(getVariableArrayType(NewEltTy, 02559 VAT->getSizeExpr() ? 02560 VAT->getSizeExpr()->Retain() : 0, 02561 VAT->getSizeModifier(), 02562 VAT->getIndexTypeCVRQualifiers(), 02563 VAT->getBracketsRange())); 02564 } 02565 02566 02567 /// getArrayDecayedType - Return the properly qualified result of decaying the 02568 /// specified array type to a pointer. This operation is non-trivial when 02569 /// handling typedefs etc. The canonical type of "T" must be an array type, 02570 /// this returns a pointer to a properly qualified element of the array. 02571 /// 02572 /// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 02573 QualType ASTContext::getArrayDecayedType(QualType Ty) { 02574 // Get the element type with 'getAsArrayType' so that we don't lose any 02575 // typedefs in the element type of the array. This also handles propagation 02576 // of type qualifiers from the array type into the element type if present 02577 // (C99 6.7.3p8). 02578 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 02579 assert(PrettyArrayType && "Not an array type!"); 02580 02581 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 02582 02583 // int x[restrict 4] -> int *restrict 02584 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 02585 } 02586 02587 QualType ASTContext::getBaseElementType(QualType QT) { 02588 QualifierCollector Qs; 02589 while (const ArrayType *AT = getAsArrayType(QualType(Qs.strip(QT), 0))) 02590 QT = AT->getElementType(); 02591 return Qs.apply(QT); 02592 } 02593 02594 QualType ASTContext::getBaseElementType(const ArrayType *AT) { 02595 QualType ElemTy = AT->getElementType(); 02596 02597 if (const ArrayType *AT = getAsArrayType(ElemTy)) 02598 return getBaseElementType(AT); 02599 02600 return ElemTy; 02601 } 02602 02603 /// getConstantArrayElementCount - Returns number of constant array elements. 02604 uint64_t 02605 ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 02606 uint64_t ElementCount = 1; 02607 do { 02608 ElementCount *= CA->getSize().getZExtValue(); 02609 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 02610 } while (CA); 02611 return ElementCount; 02612 } 02613 02614 /// getFloatingRank - Return a relative rank for floating point types. 02615 /// This routine will assert if passed a built-in type that isn't a float. 02616 static FloatingRank getFloatingRank(QualType T) { 02617 if (const ComplexType *CT = T->getAs<ComplexType>()) 02618 return getFloatingRank(CT->getElementType()); 02619 02620 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 02621 switch (T->getAs<BuiltinType>()->getKind()) { 02622 default: assert(0 && "getFloatingRank(): not a floating type"); 02623 case BuiltinType::Float: return FloatRank; 02624 case BuiltinType::Double: return DoubleRank; 02625 case BuiltinType::LongDouble: return LongDoubleRank; 02626 } 02627 } 02628 02629 /// getFloatingTypeOfSizeWithinDomain - Returns a real floating 02630 /// point or a complex type (based on typeDomain/typeSize). 02631 /// 'typeDomain' is a real floating point or complex type. 02632 /// 'typeSize' is a real floating point or complex type. 02633 QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 02634 QualType Domain) const { 02635 FloatingRank EltRank = getFloatingRank(Size); 02636 if (Domain->isComplexType()) { 02637 switch (EltRank) { 02638 default: assert(0 && "getFloatingRank(): illegal value for rank"); 02639 case FloatRank: return FloatComplexTy; 02640 case DoubleRank: return DoubleComplexTy; 02641 case LongDoubleRank: return LongDoubleComplexTy; 02642 } 02643 } 02644 02645 assert(Domain->isRealFloatingType() && "Unknown domain!"); 02646 switch (EltRank) { 02647 default: assert(0 && "getFloatingRank(): illegal value for rank"); 02648 case FloatRank: return FloatTy; 02649 case DoubleRank: return DoubleTy; 02650 case LongDoubleRank: return LongDoubleTy; 02651 } 02652 } 02653 02654 /// getFloatingTypeOrder - Compare the rank of the two specified floating 02655 /// point types, ignoring the domain of the type (i.e. 'double' == 02656 /// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 02657 /// LHS < RHS, return -1. 02658 int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) { 02659 FloatingRank LHSR = getFloatingRank(LHS); 02660 FloatingRank RHSR = getFloatingRank(RHS); 02661 02662 if (LHSR == RHSR) 02663 return 0; 02664 if (LHSR > RHSR) 02665 return 1; 02666 return -1; 02667 } 02668 02669 /// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 02670 /// routine will assert if passed a built-in type that isn't an integer or enum, 02671 /// or if it is not canonicalized. 02672 unsigned ASTContext::getIntegerRank(Type *T) { 02673 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 02674 if (EnumType* ET = dyn_cast<EnumType>(T)) 02675 T = ET->getDecl()->getPromotionType().getTypePtr(); 02676 02677 if (T->isSpecificBuiltinType(BuiltinType::WChar)) 02678 T = getFromTargetType(Target.getWCharType()).getTypePtr(); 02679 02680 if (T->isSpecificBuiltinType(BuiltinType::Char16)) 02681 T = getFromTargetType(Target.getChar16Type()).getTypePtr(); 02682 02683 if (T->isSpecificBuiltinType(BuiltinType::Char32)) 02684 T = getFromTargetType(Target.getChar32Type()).getTypePtr(); 02685 02686 switch (cast<BuiltinType>(T)->getKind()) { 02687 default: assert(0 && "getIntegerRank(): not a built-in integer"); 02688 case BuiltinType::Bool: 02689 return 1 + (getIntWidth(BoolTy) << 3); 02690 case BuiltinType::Char_S: 02691 case BuiltinType::Char_U: 02692 case BuiltinType::SChar: 02693 case BuiltinType::UChar: 02694 return 2 + (getIntWidth(CharTy) << 3); 02695 case BuiltinType::Short: 02696 case BuiltinType::UShort: 02697 return 3 + (getIntWidth(ShortTy) << 3); 02698 case BuiltinType::Int: 02699 case BuiltinType::UInt: 02700 return 4 + (getIntWidth(IntTy) << 3); 02701 case BuiltinType::Long: 02702 case BuiltinType::ULong: 02703 return 5 + (getIntWidth(LongTy) << 3); 02704 case BuiltinType::LongLong: 02705 case BuiltinType::ULongLong: 02706 return 6 + (getIntWidth(LongLongTy) << 3); 02707 case BuiltinType::Int128: 02708 case BuiltinType::UInt128: 02709 return 7 + (getIntWidth(Int128Ty) << 3); 02710 } 02711 } 02712 02713 /// \brief Whether this is a promotable bitfield reference according 02714 /// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 02715 /// 02716 /// \returns the type this bit-field will promote to, or NULL if no 02717 /// promotion occurs. 02718 QualType ASTContext::isPromotableBitField(Expr *E) { 02719 FieldDecl *Field = E->getBitField(); 02720 if (!Field) 02721 return QualType(); 02722 02723 QualType FT = Field->getType(); 02724 02725 llvm::APSInt BitWidthAP = Field->getBitWidth()->EvaluateAsInt(*this); 02726 uint64_t BitWidth = BitWidthAP.getZExtValue(); 02727 uint64_t IntSize = getTypeSize(IntTy); 02728 // GCC extension compatibility: if the bit-field size is less than or equal 02729 // to the size of int, it gets promoted no matter what its type is. 02730 // For instance, unsigned long bf : 4 gets promoted to signed int. 02731 if (BitWidth < IntSize) 02732 return IntTy; 02733 02734 if (BitWidth == IntSize) 02735 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 02736 02737 // Types bigger than int are not subject to promotions, and therefore act 02738 // like the base type. 02739 // FIXME: This doesn't quite match what gcc does, but what gcc does here 02740 // is ridiculous. 02741 return QualType(); 02742 } 02743 02744 /// getPromotedIntegerType - Returns the type that Promotable will 02745 /// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 02746 /// integer type. 02747 QualType ASTContext::getPromotedIntegerType(QualType Promotable) { 02748 assert(!Promotable.isNull()); 02749 assert(Promotable->isPromotableIntegerType()); 02750 if (const EnumType *ET = Promotable->getAs<EnumType>()) 02751 return ET->getDecl()->getPromotionType(); 02752 if (Promotable->isSignedIntegerType()) 02753 return IntTy; 02754 uint64_t PromotableSize = getTypeSize(Promotable); 02755 uint64_t IntSize = getTypeSize(IntTy); 02756 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 02757 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 02758 } 02759 02760 /// getIntegerTypeOrder - Returns the highest ranked integer type: 02761 /// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 02762 /// LHS < RHS, return -1. 02763 int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) { 02764 Type *LHSC = getCanonicalType(LHS).getTypePtr(); 02765 Type *RHSC = getCanonicalType(RHS).getTypePtr(); 02766 if (LHSC == RHSC) return 0; 02767 02768 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 02769 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 02770 02771 unsigned LHSRank = getIntegerRank(LHSC); 02772 unsigned RHSRank = getIntegerRank(RHSC); 02773 02774 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 02775 if (LHSRank == RHSRank) return 0; 02776 return LHSRank > RHSRank ? 1 : -1; 02777 } 02778 02779 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 02780 if (LHSUnsigned) { 02781 // If the unsigned [LHS] type is larger, return it. 02782 if (LHSRank >= RHSRank) 02783 return 1; 02784 02785 // If the signed type can represent all values of the unsigned type, it 02786 // wins. Because we are dealing with 2's complement and types that are 02787 // powers of two larger than each other, this is always safe. 02788 return -1; 02789 } 02790 02791 // If the unsigned [RHS] type is larger, return it. 02792 if (RHSRank >= LHSRank) 02793 return -1; 02794 02795 // If the signed type can represent all values of the unsigned type, it 02796 // wins. Because we are dealing with 2's complement and types that are 02797 // powers of two larger than each other, this is always safe. 02798 return 1; 02799 } 02800 02801 static RecordDecl * 02802 CreateRecordDecl(ASTContext &Ctx, RecordDecl::TagKind TK, DeclContext *DC, 02803 SourceLocation L, IdentifierInfo *Id) { 02804 if (Ctx.getLangOptions().CPlusPlus) 02805 return CXXRecordDecl::Create(Ctx, TK, DC, L, Id); 02806 else 02807 return RecordDecl::Create(Ctx, TK, DC, L, Id); 02808 } 02809 02810 // getCFConstantStringType - Return the type used for constant CFStrings. 02811 QualType ASTContext::getCFConstantStringType() { 02812 if (!CFConstantStringTypeDecl) { 02813 CFConstantStringTypeDecl = 02814 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 02815 &Idents.get("NSConstantString")); 02816 CFConstantStringTypeDecl->startDefinition(); 02817 02818 QualType FieldTypes[4]; 02819 02820 // const int *isa; 02821 FieldTypes[0] = getPointerType(IntTy.withConst()); 02822 // int flags; 02823 FieldTypes[1] = IntTy; 02824 // const char *str; 02825 FieldTypes[2] = getPointerType(CharTy.withConst()); 02826 // long length; 02827 FieldTypes[3] = LongTy; 02828 02829 // Create fields 02830 for (unsigned i = 0; i < 4; ++i) { 02831 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 02832 SourceLocation(), 0, 02833 FieldTypes[i], /*TInfo=*/0, 02834 /*BitWidth=*/0, 02835 /*Mutable=*/false); 02836 Field->setAccess(AS_public); 02837 CFConstantStringTypeDecl->addDecl(Field); 02838 } 02839 02840 CFConstantStringTypeDecl->completeDefinition(); 02841 } 02842 02843 return getTagDeclType(CFConstantStringTypeDecl); 02844 } 02845 02846 void ASTContext::setCFConstantStringType(QualType T) { 02847 const RecordType *Rec = T->getAs<RecordType>(); 02848 assert(Rec && "Invalid CFConstantStringType"); 02849 CFConstantStringTypeDecl = Rec->getDecl(); 02850 } 02851 02852 // getNSConstantStringType - Return the type used for constant NSStrings. 02853 QualType ASTContext::getNSConstantStringType() { 02854 if (!NSConstantStringTypeDecl) { 02855 NSConstantStringTypeDecl = 02856 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 02857 &Idents.get("__builtin_NSString")); 02858 NSConstantStringTypeDecl->startDefinition(); 02859 02860 QualType FieldTypes[3]; 02861 02862 // const int *isa; 02863 FieldTypes[0] = getPointerType(IntTy.withConst()); 02864 // const char *str; 02865 FieldTypes[1] = getPointerType(CharTy.withConst()); 02866 // unsigned int length; 02867 FieldTypes[2] = UnsignedIntTy; 02868 02869 // Create fields 02870 for (unsigned i = 0; i < 3; ++i) { 02871 FieldDecl *Field = FieldDecl::Create(*this, NSConstantStringTypeDecl, 02872 SourceLocation(), 0, 02873 FieldTypes[i], /*TInfo=*/0, 02874 /*BitWidth=*/0, 02875 /*Mutable=*/false); 02876 Field->setAccess(AS_public); 02877 NSConstantStringTypeDecl->addDecl(Field); 02878 } 02879 02880 NSConstantStringTypeDecl->completeDefinition(); 02881 } 02882 02883 return getTagDeclType(NSConstantStringTypeDecl); 02884 } 02885 02886 void ASTContext::setNSConstantStringType(QualType T) { 02887 const RecordType *Rec = T->getAs<RecordType>(); 02888 assert(Rec && "Invalid NSConstantStringType"); 02889 NSConstantStringTypeDecl = Rec->getDecl(); 02890 } 02891 02892 QualType ASTContext::getObjCFastEnumerationStateType() { 02893 if (!ObjCFastEnumerationStateTypeDecl) { 02894 ObjCFastEnumerationStateTypeDecl = 02895 CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 02896 &Idents.get("__objcFastEnumerationState")); 02897 ObjCFastEnumerationStateTypeDecl->startDefinition(); 02898 02899 QualType FieldTypes[] = { 02900 UnsignedLongTy, 02901 getPointerType(ObjCIdTypedefType), 02902 getPointerType(UnsignedLongTy), 02903 getConstantArrayType(UnsignedLongTy, 02904 llvm::APInt(32, 5), ArrayType::Normal, 0) 02905 }; 02906 02907 for (size_t i = 0; i < 4; ++i) { 02908 FieldDecl *Field = FieldDecl::Create(*this, 02909 ObjCFastEnumerationStateTypeDecl, 02910 SourceLocation(), 0, 02911 FieldTypes[i], /*TInfo=*/0, 02912 /*BitWidth=*/0, 02913 /*Mutable=*/false); 02914 Field->setAccess(AS_public); 02915 ObjCFastEnumerationStateTypeDecl->addDecl(Field); 02916 } 02917 02918 ObjCFastEnumerationStateTypeDecl->completeDefinition(); 02919 } 02920 02921 return getTagDeclType(ObjCFastEnumerationStateTypeDecl); 02922 } 02923 02924 QualType ASTContext::getBlockDescriptorType() { 02925 if (BlockDescriptorType) 02926 return getTagDeclType(BlockDescriptorType); 02927 02928 RecordDecl *T; 02929 // FIXME: Needs the FlagAppleBlock bit. 02930 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 02931 &Idents.get("__block_descriptor")); 02932 T->startDefinition(); 02933 02934 QualType FieldTypes[] = { 02935 UnsignedLongTy, 02936 UnsignedLongTy, 02937 }; 02938 02939 const char *FieldNames[] = { 02940 "reserved", 02941 "Size" 02942 }; 02943 02944 for (size_t i = 0; i < 2; ++i) { 02945 FieldDecl *Field = FieldDecl::Create(*this, 02946 T, 02947 SourceLocation(), 02948 &Idents.get(FieldNames[i]), 02949 FieldTypes[i], /*TInfo=*/0, 02950 /*BitWidth=*/0, 02951 /*Mutable=*/false); 02952 Field->setAccess(AS_public); 02953 T->addDecl(Field); 02954 } 02955 02956 T->completeDefinition(); 02957 02958 BlockDescriptorType = T; 02959 02960 return getTagDeclType(BlockDescriptorType); 02961 } 02962 02963 void ASTContext::setBlockDescriptorType(QualType T) { 02964 const RecordType *Rec = T->getAs<RecordType>(); 02965 assert(Rec && "Invalid BlockDescriptorType"); 02966 BlockDescriptorType = Rec->getDecl(); 02967 } 02968 02969 QualType ASTContext::getBlockDescriptorExtendedType() { 02970 if (BlockDescriptorExtendedType) 02971 return getTagDeclType(BlockDescriptorExtendedType); 02972 02973 RecordDecl *T; 02974 // FIXME: Needs the FlagAppleBlock bit. 02975 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 02976 &Idents.get("__block_descriptor_withcopydispose")); 02977 T->startDefinition(); 02978 02979 QualType FieldTypes[] = { 02980 UnsignedLongTy, 02981 UnsignedLongTy, 02982 getPointerType(VoidPtrTy), 02983 getPointerType(VoidPtrTy) 02984 }; 02985 02986 const char *FieldNames[] = { 02987 "reserved", 02988 "Size", 02989 "CopyFuncPtr", 02990 "DestroyFuncPtr" 02991 }; 02992 02993 for (size_t i = 0; i < 4; ++i) { 02994 FieldDecl *Field = FieldDecl::Create(*this, 02995 T, 02996 SourceLocation(), 02997 &Idents.get(FieldNames[i]), 02998 FieldTypes[i], /*TInfo=*/0, 02999 /*BitWidth=*/0, 03000 /*Mutable=*/false); 03001 Field->setAccess(AS_public); 03002 T->addDecl(Field); 03003 } 03004 03005 T->completeDefinition(); 03006 03007 BlockDescriptorExtendedType = T; 03008 03009 return getTagDeclType(BlockDescriptorExtendedType); 03010 } 03011 03012 void ASTContext::setBlockDescriptorExtendedType(QualType T) { 03013 const RecordType *Rec = T->getAs<RecordType>(); 03014 assert(Rec && "Invalid BlockDescriptorType"); 03015 BlockDescriptorExtendedType = Rec->getDecl(); 03016 } 03017 03018 bool ASTContext::BlockRequiresCopying(QualType Ty) { 03019 if (Ty->isBlockPointerType()) 03020 return true; 03021 if (isObjCNSObjectType(Ty)) 03022 return true; 03023 if (Ty->isObjCObjectPointerType()) 03024 return true; 03025 return false; 03026 } 03027 03028 QualType ASTContext::BuildByRefType(const char *DeclName, QualType Ty) { 03029 // type = struct __Block_byref_1_X { 03030 // void *__isa; 03031 // struct __Block_byref_1_X *__forwarding; 03032 // unsigned int __flags; 03033 // unsigned int __size; 03034 // void *__copy_helper; // as needed 03035 // void *__destroy_help // as needed 03036 // int X; 03037 // } * 03038 03039 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 03040 03041 // FIXME: Move up 03042 static unsigned int UniqueBlockByRefTypeID = 0; 03043 llvm::SmallString<36> Name; 03044 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 03045 ++UniqueBlockByRefTypeID << '_' << DeclName; 03046 RecordDecl *T; 03047 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 03048 &Idents.get(Name.str())); 03049 T->startDefinition(); 03050 QualType Int32Ty = IntTy; 03051 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 03052 QualType FieldTypes[] = { 03053 getPointerType(VoidPtrTy), 03054 getPointerType(getTagDeclType(T)), 03055 Int32Ty, 03056 Int32Ty, 03057 getPointerType(VoidPtrTy), 03058 getPointerType(VoidPtrTy), 03059 Ty 03060 }; 03061 03062 const char *FieldNames[] = { 03063 "__isa", 03064 "__forwarding", 03065 "__flags", 03066 "__size", 03067 "__copy_helper", 03068 "__destroy_helper", 03069 DeclName, 03070 }; 03071 03072 for (size_t i = 0; i < 7; ++i) { 03073 if (!HasCopyAndDispose && i >=4 && i <= 5) 03074 continue; 03075 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 03076 &Idents.get(FieldNames[i]), 03077 FieldTypes[i], /*TInfo=*/0, 03078 /*BitWidth=*/0, /*Mutable=*/false); 03079 Field->setAccess(AS_public); 03080 T->addDecl(Field); 03081 } 03082 03083 T->completeDefinition(); 03084 03085 return getPointerType(getTagDeclType(T)); 03086 } 03087 03088 03089 QualType ASTContext::getBlockParmType( 03090 bool BlockHasCopyDispose, 03091 llvm::SmallVector<const Expr *, 8> &BlockDeclRefDecls) { 03092 // FIXME: Move up 03093 static unsigned int UniqueBlockParmTypeID = 0; 03094 llvm::SmallString<36> Name; 03095 llvm::raw_svector_ostream(Name) << "__block_literal_" 03096 << ++UniqueBlockParmTypeID; 03097 RecordDecl *T; 03098 T = CreateRecordDecl(*this, TagDecl::TK_struct, TUDecl, SourceLocation(), 03099 &Idents.get(Name.str())); 03100 T->startDefinition(); 03101 QualType FieldTypes[] = { 03102 getPointerType(VoidPtrTy), 03103 IntTy, 03104 IntTy, 03105 getPointerType(VoidPtrTy), 03106 (BlockHasCopyDispose ? 03107 getPointerType(getBlockDescriptorExtendedType()) : 03108 getPointerType(getBlockDescriptorType())) 03109 }; 03110 03111 const char *FieldNames[] = { 03112 "__isa", 03113 "__flags", 03114 "__reserved", 03115 "__FuncPtr", 03116 "__descriptor" 03117 }; 03118 03119 for (size_t i = 0; i < 5; ++i) { 03120 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 03121 &Idents.get(FieldNames[i]), 03122 FieldTypes[i], /*TInfo=*/0, 03123 /*BitWidth=*/0, /*Mutable=*/false); 03124 Field->setAccess(AS_public); 03125 T->addDecl(Field); 03126 } 03127 03128 for (size_t i = 0; i < BlockDeclRefDecls.size(); ++i) { 03129 const Expr *E = BlockDeclRefDecls[i]; 03130 const BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(E); 03131 clang::IdentifierInfo *Name = 0; 03132 if (BDRE) { 03133 const ValueDecl *D = BDRE->getDecl(); 03134 Name = &Idents.get(D->getName()); 03135 } 03136 QualType FieldType = E->getType(); 03137 03138 if (BDRE && BDRE->isByRef()) 03139 FieldType = BuildByRefType(BDRE->getDecl()->getNameAsCString(), 03140 FieldType); 03141 03142 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 03143 Name, FieldType, /*TInfo=*/0, 03144 /*BitWidth=*/0, /*Mutable=*/false); 03145 Field->setAccess(AS_public); 03146 T->addDecl(Field); 03147 } 03148 03149 T->completeDefinition(); 03150 03151 return getPointerType(getTagDeclType(T)); 03152 } 03153 03154 void ASTContext::setObjCFastEnumerationStateType(QualType T) { 03155 const RecordType *Rec = T->getAs<RecordType>(); 03156 assert(Rec && "Invalid ObjCFAstEnumerationStateType"); 03157 ObjCFastEnumerationStateTypeDecl = Rec->getDecl(); 03158 } 03159 03160 // This returns true if a type has been typedefed to BOOL: 03161 // typedef <type> BOOL; 03162 static bool isTypeTypedefedAsBOOL(QualType T) { 03163 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 03164 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 03165 return II->isStr("BOOL"); 03166 03167 return false; 03168 } 03169 03170 /// getObjCEncodingTypeSize returns size of type for objective-c encoding 03171 /// purpose. 03172 CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) { 03173 CharUnits sz = getTypeSizeInChars(type); 03174 03175 // Make all integer and enum types at least as large as an int 03176 if (sz.isPositive() && type->isIntegralType()) 03177 sz = std::max(sz, getTypeSizeInChars(IntTy)); 03178 // Treat arrays as pointers, since that's how they're passed in. 03179 else if (type->isArrayType()) 03180 sz = getTypeSizeInChars(VoidPtrTy); 03181 return sz; 03182 } 03183 03184 static inline 03185 std::string charUnitsToString(const CharUnits &CU) { 03186 return llvm::itostr(CU.getQuantity()); 03187 } 03188 03189 /// getObjCEncodingForBlockDecl - Return the encoded type for this block 03190 /// declaration. 03191 void ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr, 03192 std::string& S) { 03193 const BlockDecl *Decl = Expr->getBlockDecl(); 03194 QualType BlockTy = 03195 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 03196 // Encode result type. 03197 getObjCEncodingForType(cast<FunctionType>(BlockTy)->getResultType(), S); 03198 // Compute size of all parameters. 03199 // Start with computing size of a pointer in number of bytes. 03200 // FIXME: There might(should) be a better way of doing this computation! 03201 SourceLocation Loc; 03202 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 03203 CharUnits ParmOffset = PtrSize; 03204 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 03205 E = Decl->param_end(); PI != E; ++PI) { 03206 QualType PType = (*PI)->getType(); 03207 CharUnits sz = getObjCEncodingTypeSize(PType); 03208 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 03209 ParmOffset += sz; 03210 } 03211 // Size of the argument frame 03212 S += charUnitsToString(ParmOffset); 03213 // Block pointer and offset. 03214 S += "@?0"; 03215 ParmOffset = PtrSize; 03216 03217 // Argument types. 03218 ParmOffset = PtrSize; 03219 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 03220 Decl->param_end(); PI != E; ++PI) { 03221 ParmVarDecl *PVDecl = *PI; 03222 QualType PType = PVDecl->getOriginalType(); 03223 if (const ArrayType *AT = 03224 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 03225 // Use array's original type only if it has known number of 03226 // elements. 03227 if (!isa<ConstantArrayType>(AT)) 03228 PType = PVDecl->getType(); 03229 } else if (PType->isFunctionType()) 03230 PType = PVDecl->getType(); 03231 getObjCEncodingForType(PType, S); 03232 S += charUnitsToString(ParmOffset); 03233 ParmOffset += getObjCEncodingTypeSize(PType); 03234 } 03235 } 03236 03237 /// getObjCEncodingForMethodDecl - Return the encoded type for this method 03238 /// declaration. 03239 void ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 03240 std::string& S) { 03241 // FIXME: This is not very efficient. 03242 // Encode type qualifer, 'in', 'inout', etc. for the return type. 03243 getObjCEncodingForTypeQualifier(Decl->getObjCDeclQualifier(), S); 03244 // Encode result type. 03245 getObjCEncodingForType(Decl->getResultType(), S); 03246 // Compute size of all parameters. 03247 // Start with computing size of a pointer in number of bytes. 03248 // FIXME: There might(should) be a better way of doing this computation! 03249 SourceLocation Loc; 03250 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 03251 // The first two arguments (self and _cmd) are pointers; account for 03252 // their size. 03253 CharUnits ParmOffset = 2 * PtrSize; 03254 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 03255 E = Decl->sel_param_end(); PI != E; ++PI) { 03256 QualType PType = (*PI)->getType(); 03257 CharUnits sz = getObjCEncodingTypeSize(PType); 03258 assert (sz.isPositive() && 03259 "getObjCEncodingForMethodDecl - Incomplete param type"); 03260 ParmOffset += sz; 03261 } 03262 S += charUnitsToString(ParmOffset); 03263 S += "@0:"; 03264 S += charUnitsToString(PtrSize); 03265 03266 // Argument types. 03267 ParmOffset = 2 * PtrSize; 03268 for (ObjCMethodDecl::param_iterator PI = Decl->param_begin(), 03269 E = Decl->sel_param_end(); PI != E; ++PI) { 03270 ParmVarDecl *PVDecl = *PI; 03271 QualType PType = PVDecl->getOriginalType(); 03272 if (const ArrayType *AT = 03273 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 03274 // Use array's original type only if it has known number of 03275 // elements. 03276 if (!isa<ConstantArrayType>(AT)) 03277 PType = PVDecl->getType(); 03278 } else if (PType->isFunctionType()) 03279 PType = PVDecl->getType(); 03280 // Process argument qualifiers for user supplied arguments; such as, 03281 // 'in', 'inout', etc. 03282 getObjCEncodingForTypeQualifier(PVDecl->getObjCDeclQualifier(), S); 03283 getObjCEncodingForType(PType, S); 03284 S += charUnitsToString(ParmOffset); 03285 ParmOffset += getObjCEncodingTypeSize(PType); 03286 } 03287 } 03288 03289 /// getObjCEncodingForPropertyDecl - Return the encoded type for this 03290 /// property declaration. If non-NULL, Container must be either an 03291 /// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 03292 /// NULL when getting encodings for protocol properties. 03293 /// Property attributes are stored as a comma-delimited C string. The simple 03294 /// attributes readonly and bycopy are encoded as single characters. The 03295 /// parametrized attributes, getter=name, setter=name, and ivar=name, are 03296 /// encoded as single characters, followed by an identifier. Property types 03297 /// are also encoded as a parametrized attribute. The characters used to encode 03298 /// these attributes are defined by the following enumeration: 03299 /// @code 03300 /// enum PropertyAttributes { 03301 /// kPropertyReadOnly = 'R', // property is read-only. 03302 /// kPropertyBycopy = 'C', // property is a copy of the value last assigned 03303 /// kPropertyByref = '&', // property is a reference to the value last assigned 03304 /// kPropertyDynamic = 'D', // property is dynamic 03305 /// kPropertyGetter = 'G', // followed by getter selector name 03306 /// kPropertySetter = 'S', // followed by setter selector name 03307 /// kPropertyInstanceVariable = 'V' // followed by instance variable name 03308 /// kPropertyType = 't' // followed by old-style type encoding. 03309 /// kPropertyWeak = 'W' // 'weak' property 03310 /// kPropertyStrong = 'P' // property GC'able 03311 /// kPropertyNonAtomic = 'N' // property non-atomic 03312 /// }; 03313 /// @endcode 03314 void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 03315 const Decl *Container, 03316 std::string& S) { 03317 // Collect information from the property implementation decl(s). 03318 bool Dynamic = false; 03319 ObjCPropertyImplDecl *SynthesizePID = 0; 03320 03321 // FIXME: Duplicated code due to poor abstraction. 03322 if (Container) { 03323 if (const ObjCCategoryImplDecl *CID = 03324 dyn_cast<ObjCCategoryImplDecl>(Container)) { 03325 for (ObjCCategoryImplDecl::propimpl_iterator 03326 i = CID->propimpl_begin(), e = CID->propimpl_end(); 03327 i != e; ++i) { 03328 ObjCPropertyImplDecl *PID = *i; 03329 if (PID->getPropertyDecl() == PD) { 03330 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 03331 Dynamic = true; 03332 } else { 03333 SynthesizePID = PID; 03334 } 03335 } 03336 } 03337 } else { 03338 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 03339 for (ObjCCategoryImplDecl::propimpl_iterator 03340 i = OID->propimpl_begin(), e = OID->propimpl_end(); 03341 i != e; ++i) { 03342 ObjCPropertyImplDecl *PID = *i; 03343 if (PID->getPropertyDecl() == PD) { 03344 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 03345 Dynamic = true; 03346 } else { 03347 SynthesizePID = PID; 03348 } 03349 } 03350 } 03351 } 03352 } 03353 03354 // FIXME: This is not very efficient. 03355 S = "T"; 03356 03357 // Encode result type. 03358 // GCC has some special rules regarding encoding of properties which 03359 // closely resembles encoding of ivars. 03360 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 03361 true /* outermost type */, 03362 true /* encoding for property */); 03363 03364 if (PD->isReadOnly()) { 03365 S += ",R"; 03366 } else { 03367 switch (PD->getSetterKind()) { 03368 case ObjCPropertyDecl::Assign: break; 03369 case ObjCPropertyDecl::Copy: S += ",C"; break; 03370 case ObjCPropertyDecl::Retain: S += ",&"; break; 03371 } 03372 } 03373 03374 // It really isn't clear at all what this means, since properties 03375 // are "dynamic by default". 03376 if (Dynamic) 03377 S += ",D"; 03378 03379 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 03380 S += ",N"; 03381 03382 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 03383 S += ",G"; 03384 S += PD->getGetterName().getAsString(); 03385 } 03386 03387 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 03388 S += ",S"; 03389 S += PD->getSetterName().getAsString(); 03390 } 03391 03392 if (SynthesizePID) { 03393 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 03394 S += ",V"; 03395 S += OID->getNameAsString(); 03396 } 03397 03398 // FIXME: OBJCGC: weak & strong 03399 } 03400 03401 /// getLegacyIntegralTypeEncoding - 03402 /// Another legacy compatibility encoding: 32-bit longs are encoded as 03403 /// 'l' or 'L' , but not always. For typedefs, we need to use 03404 /// 'i' or 'I' instead if encoding a struct field, or a pointer! 03405 /// 03406 void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 03407 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 03408 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 03409 if (BT->getKind() == BuiltinType::ULong && 03410 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 03411 PointeeTy = UnsignedIntTy; 03412 else 03413 if (BT->getKind() == BuiltinType::Long && 03414 ((const_cast<ASTContext *>(this))->getIntWidth(PointeeTy) == 32)) 03415 PointeeTy = IntTy; 03416 } 03417 } 03418 } 03419 03420 void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 03421 const FieldDecl *Field) { 03422 // We follow the behavior of gcc, expanding structures which are 03423 // directly pointed to, and expanding embedded structures. Note that 03424 // these rules are sufficient to prevent recursive encoding of the 03425 // same type. 03426 getObjCEncodingForTypeImpl(T, S, true, true, Field, 03427 true /* outermost type */); 03428 } 03429 03430 static void EncodeBitField(const ASTContext *Context, std::string& S, 03431 const FieldDecl *FD) { 03432 const Expr *E = FD->getBitWidth(); 03433 assert(E && "bitfield width not there - getObjCEncodingForTypeImpl"); 03434 ASTContext *Ctx = const_cast<ASTContext*>(Context); 03435 unsigned N = E->EvaluateAsInt(*Ctx).getZExtValue(); 03436 S += 'b'; 03437 S += llvm::utostr(N); 03438 } 03439 03440 // FIXME: Use SmallString for accumulating string. 03441 void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 03442 bool ExpandPointedToStructures, 03443 bool ExpandStructures, 03444 const FieldDecl *FD, 03445 bool OutermostType, 03446 bool EncodingProperty) { 03447 if (const BuiltinType *BT = T->getAs<BuiltinType>()) { 03448 if (FD && FD->isBitField()) 03449 return EncodeBitField(this, S, FD); 03450 char encoding; 03451 switch (BT->getKind()) { 03452 default: assert(0 && "Unhandled builtin type kind"); 03453 case BuiltinType::Void: encoding = 'v'; break; 03454 case BuiltinType::Bool: encoding = 'B'; break; 03455 case BuiltinType::Char_U: 03456 case BuiltinType::UChar: encoding = 'C'; break; 03457 case BuiltinType::UShort: encoding = 'S'; break; 03458 case BuiltinType::UInt: encoding = 'I'; break; 03459 case BuiltinType::ULong: 03460 encoding = 03461 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'L' : 'Q'; 03462 break; 03463 case BuiltinType::UInt128: encoding = 'T'; break; 03464 case BuiltinType::ULongLong: encoding = 'Q'; break; 03465 case BuiltinType::Char_S: 03466 case BuiltinType::SChar: encoding = 'c'; break; 03467 case BuiltinType::Short: encoding = 's'; break; 03468 case BuiltinType::Int: encoding = 'i'; break; 03469 case BuiltinType::Long: 03470 encoding = 03471 (const_cast<ASTContext *>(this))->getIntWidth(T) == 32 ? 'l' : 'q'; 03472 break; 03473 case BuiltinType::LongLong: encoding = 'q'; break; 03474 case BuiltinType::Int128: encoding = 't'; break; 03475 case BuiltinType::Float: encoding = 'f'; break; 03476 case BuiltinType::Double: encoding = 'd'; break; 03477 case BuiltinType::LongDouble: encoding = 'd'; break; 03478 } 03479 03480 S += encoding; 03481 return; 03482 } 03483 03484 if (const ComplexType *CT = T->getAs<ComplexType>()) { 03485 S += 'j'; 03486 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 03487 false); 03488 return; 03489 } 03490 03491 // encoding for pointer or r3eference types. 03492 QualType PointeeTy; 03493 if (const PointerType *PT = T->getAs<PointerType>()) { 03494 if (PT->isObjCSelType()) { 03495 S += ':'; 03496 return; 03497 } 03498 PointeeTy = PT->getPointeeType(); 03499 } 03500 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 03501 PointeeTy = RT->getPointeeType(); 03502 if (!PointeeTy.isNull()) { 03503 bool isReadOnly = false; 03504 // For historical/compatibility reasons, the read-only qualifier of the 03505 // pointee gets emitted _before_ the '^'. The read-only qualifier of 03506 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 03507 // Also, do not emit the 'r' for anything but the outermost type! 03508 if (isa<TypedefType>(T.getTypePtr())) { 03509 if (OutermostType && T.isConstQualified()) { 03510 isReadOnly = true; 03511 S += 'r'; 03512 } 03513 } else if (OutermostType) { 03514 QualType P = PointeeTy; 03515 while (P->getAs<PointerType>()) 03516 P = P->getAs<PointerType>()->getPointeeType(); 03517 if (P.isConstQualified()) { 03518 isReadOnly = true; 03519 S += 'r'; 03520 } 03521 } 03522 if (isReadOnly) { 03523 // Another legacy compatibility encoding. Some ObjC qualifier and type 03524 // combinations need to be rearranged. 03525 // Rewrite "in const" from "nr" to "rn" 03526 if (llvm::StringRef(S).endswith("nr")) 03527 S.replace(S.end()-2, S.end(), "rn"); 03528 } 03529 03530 if (PointeeTy->isCharType()) { 03531 // char pointer types should be encoded as '*' unless it is a 03532 // type that has been typedef'd to 'BOOL'. 03533 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 03534 S += '*'; 03535 return; 03536 } 03537 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 03538 // GCC binary compat: Need to convert "struct objc_class *" to "#". 03539 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 03540 S += '#'; 03541 return; 03542 } 03543 // GCC binary compat: Need to convert "struct objc_object *" to "@". 03544 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 03545 S += '@'; 03546 return; 03547 } 03548 // fall through... 03549 } 03550 S += '^'; 03551 getLegacyIntegralTypeEncoding(PointeeTy); 03552 03553 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 03554 NULL); 03555 return; 03556 } 03557 03558 if (const ArrayType *AT = 03559 // Ignore type qualifiers etc. 03560 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 03561 if (isa<IncompleteArrayType>(AT)) { 03562 // Incomplete arrays are encoded as a pointer to the array element. 03563 S += '^'; 03564 03565 getObjCEncodingForTypeImpl(AT->getElementType(), S, 03566 false, ExpandStructures, FD); 03567 } else { 03568 S += '['; 03569 03570 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) 03571 S += llvm::utostr(CAT->getSize().getZExtValue()); 03572 else { 03573 //Variable length arrays are encoded as a regular array with 0 elements. 03574 assert(isa<VariableArrayType>(AT) && "Unknown array type!"); 03575 S += '0'; 03576 } 03577 03578 getObjCEncodingForTypeImpl(AT->getElementType(), S, 03579 false, ExpandStructures, FD); 03580 S += ']'; 03581 } 03582 return; 03583 } 03584 03585 if (T->getAs<FunctionType>()) { 03586 S += '?'; 03587 return; 03588 } 03589 03590 if (const RecordType *RTy = T->getAs<RecordType>()) { 03591 RecordDecl *RDecl = RTy->getDecl(); 03592 S += RDecl->isUnion() ? '(' : '{'; 03593 // Anonymous structures print as '?' 03594 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 03595 S += II->getName(); 03596 } else { 03597 S += '?'; 03598 } 03599 if (ExpandStructures) { 03600 S += '='; 03601 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 03602 FieldEnd = RDecl->field_end(); 03603 Field != FieldEnd; ++Field) { 03604 if (FD) { 03605 S += '"'; 03606 S += Field->getNameAsString(); 03607 S += '"'; 03608 } 03609 03610 // Special case bit-fields. 03611 if (Field->isBitField()) { 03612 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 03613 (*Field)); 03614 } else { 03615 QualType qt = Field->getType(); 03616 getLegacyIntegralTypeEncoding(qt); 03617 getObjCEncodingForTypeImpl(qt, S, false, true, 03618 FD); 03619 } 03620 } 03621 } 03622 S += RDecl->isUnion() ? ')' : '}'; 03623 return; 03624 } 03625 03626 if (T->isEnumeralType()) { 03627 if (FD && FD->isBitField()) 03628 EncodeBitField(this, S, FD); 03629 else 03630 S += 'i'; 03631 return; 03632 } 03633 03634 if (T->isBlockPointerType()) { 03635 S += "@?"; // Unlike a pointer-to-function, which is "^?". 03636 return; 03637 } 03638 03639 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 03640 // @encode(class_name) 03641 ObjCInterfaceDecl *OI = OIT->getDecl(); 03642 S += '{'; 03643 const IdentifierInfo *II = OI->getIdentifier(); 03644 S += II->getName(); 03645 S += '='; 03646 llvm::SmallVector<FieldDecl*, 32> RecFields; 03647 CollectObjCIvars(OI, RecFields); 03648 for (unsigned i = 0, e = RecFields.size(); i != e; ++i) { 03649 if (RecFields[i]->isBitField()) 03650 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 03651 RecFields[i]); 03652 else 03653 getObjCEncodingForTypeImpl(RecFields[i]->getType(), S, false, true, 03654 FD); 03655 } 03656 S += '}'; 03657 return; 03658 } 03659 03660 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 03661 if (OPT->isObjCIdType()) { 03662 S += '@'; 03663 return; 03664 } 03665 03666 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 03667 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 03668 // Since this is a binary compatibility issue, need to consult with runtime 03669 // folks. Fortunately, this is a *very* obsure construct. 03670 S += '#'; 03671 return; 03672 } 03673 03674 if (OPT->isObjCQualifiedIdType()) { 03675 getObjCEncodingForTypeImpl(getObjCIdType(), S, 03676 ExpandPointedToStructures, 03677 ExpandStructures, FD); 03678 if (FD || EncodingProperty) { 03679 // Note that we do extended encoding of protocol qualifer list 03680 // Only when doing ivar or property encoding. 03681 S += '"'; 03682 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 03683 E = OPT->qual_end(); I != E; ++I) { 03684 S += '<'; 03685 S += (*I)->getNameAsString(); 03686 S += '>'; 03687 } 03688 S += '"'; 03689 } 03690 return; 03691 } 03692 03693 QualType PointeeTy = OPT->getPointeeType(); 03694 if (!EncodingProperty && 03695 isa<TypedefType>(PointeeTy.getTypePtr())) { 03696 // Another historical/compatibility reason. 03697 // We encode the underlying type which comes out as 03698 // {...}; 03699 S += '^'; 03700 getObjCEncodingForTypeImpl(PointeeTy, S, 03701 false, ExpandPointedToStructures, 03702 NULL); 03703 return; 03704 } 03705 03706 S += '@'; 03707 if (OPT->getInterfaceDecl() && (FD || EncodingProperty)) { 03708 S += '"'; 03709 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 03710 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 03711 E = OPT->qual_end(); I != E; ++I) { 03712 S += '<'; 03713 S += (*I)->getNameAsString(); 03714 S += '>'; 03715 } 03716 S += '"'; 03717 } 03718 return; 03719 } 03720 03721 assert(0 && "@encode for type not implemented!"); 03722 } 03723 03724 void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 03725 std::string& S) const { 03726 if (QT & Decl::OBJC_TQ_In) 03727 S += 'n'; 03728 if (QT & Decl::OBJC_TQ_Inout) 03729 S += 'N'; 03730 if (QT & Decl::OBJC_TQ_Out) 03731 S += 'o'; 03732 if (QT & Decl::OBJC_TQ_Bycopy) 03733 S += 'O'; 03734 if (QT & Decl::OBJC_TQ_Byref) 03735 S += 'R'; 03736 if (QT & Decl::OBJC_TQ_Oneway) 03737 S += 'V'; 03738 } 03739 03740 void ASTContext::setBuiltinVaListType(QualType T) { 03741 assert(BuiltinVaListType.isNull() && "__builtin_va_list type already set!"); 03742 03743 BuiltinVaListType = T; 03744 } 03745 03746 void ASTContext::setObjCIdType(QualType T) { 03747 ObjCIdTypedefType = T; 03748 } 03749 03750 void ASTContext::setObjCSelType(QualType T) { 03751 ObjCSelTypedefType = T; 03752 } 03753 03754 void ASTContext::setObjCProtoType(QualType QT) { 03755 ObjCProtoType = QT; 03756 } 03757 03758 void ASTContext::setObjCClassType(QualType T) { 03759 ObjCClassTypedefType = T; 03760 } 03761 03762 void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 03763 assert(ObjCConstantStringType.isNull() && 03764 "'NSConstantString' type already set!"); 03765 03766 ObjCConstantStringType = getObjCInterfaceType(Decl); 03767 } 03768 03769 /// \brief Retrieve the template name that corresponds to a non-empty 03770 /// lookup. 03771 TemplateName ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 03772 UnresolvedSetIterator End) { 03773 unsigned size = End - Begin; 03774 assert(size > 1 && "set is not overloaded!"); 03775 03776 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 03777 size * sizeof(FunctionTemplateDecl*)); 03778 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 03779 03780 NamedDecl **Storage = OT->getStorage(); 03781 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 03782 NamedDecl *D = *I; 03783 assert(isa<FunctionTemplateDecl>(D) || 03784 (isa<UsingShadowDecl>(D) && 03785 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 03786 *Storage++ = D; 03787 } 03788 03789 return TemplateName(OT); 03790 } 03791 03792 /// \brief Retrieve the template name that represents a qualified 03793 /// template name such as \c std::vector. 03794 TemplateName ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 03795 bool TemplateKeyword, 03796 TemplateDecl *Template) { 03797 // FIXME: Canonicalization? 03798 llvm::FoldingSetNodeID ID; 03799 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 03800 03801 void *InsertPos = 0; 03802 QualifiedTemplateName *QTN = 03803 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 03804 if (!QTN) { 03805 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 03806 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 03807 } 03808 03809 return TemplateName(QTN); 03810 } 03811 03812 /// \brief Retrieve the template name that represents a dependent 03813 /// template name such as \c MetaFun::template apply. 03814 TemplateName ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 03815 const IdentifierInfo *Name) { 03816 assert((!NNS || NNS->isDependent()) && 03817 "Nested name specifier must be dependent"); 03818 03819 llvm::FoldingSetNodeID ID; 03820 DependentTemplateName::Profile(ID, NNS, Name); 03821 03822 void *InsertPos = 0; 03823 DependentTemplateName *QTN = 03824 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 03825 03826 if (QTN) 03827 return TemplateName(QTN); 03828 03829 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 03830 if (CanonNNS == NNS) { 03831 QTN = new (*this,4) DependentTemplateName(NNS, Name); 03832 } else { 03833 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 03834 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 03835 DependentTemplateName *CheckQTN = 03836 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 03837 assert(!CheckQTN && "Dependent type name canonicalization broken"); 03838 (void)CheckQTN; 03839 } 03840 03841 DependentTemplateNames.InsertNode(QTN, InsertPos); 03842 return TemplateName(QTN); 03843 } 03844 03845 /// \brief Retrieve the template name that represents a dependent 03846 /// template name such as \c MetaFun::template operator+. 03847 TemplateName 03848 ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 03849 OverloadedOperatorKind Operator) { 03850 assert((!NNS || NNS->isDependent()) && 03851 "Nested name specifier must be dependent"); 03852 03853 llvm::FoldingSetNodeID ID; 03854 DependentTemplateName::Profile(ID, NNS, Operator); 03855 03856 void *InsertPos = 0; 03857 DependentTemplateName *QTN 03858 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 03859 03860 if (QTN) 03861 return TemplateName(QTN); 03862 03863 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 03864 if (CanonNNS == NNS) { 03865 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 03866 } else { 03867 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 03868 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 03869 03870 DependentTemplateName *CheckQTN 03871 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 03872 assert(!CheckQTN && "Dependent template name canonicalization broken"); 03873 (void)CheckQTN; 03874 } 03875 03876 DependentTemplateNames.InsertNode(QTN, InsertPos); 03877 return TemplateName(QTN); 03878 } 03879 03880 /// getFromTargetType - Given one of the integer types provided by 03881 /// TargetInfo, produce the corresponding type. The unsigned @p Type 03882 /// is actually a value of type @c TargetInfo::IntType. 03883 CanQualType ASTContext::getFromTargetType(unsigned Type) const { 03884 switch (Type) { 03885 case TargetInfo::NoInt: return CanQualType(); 03886 case TargetInfo::SignedShort: return ShortTy; 03887 case TargetInfo::UnsignedShort: return UnsignedShortTy; 03888 case TargetInfo::SignedInt: return IntTy; 03889 case TargetInfo::UnsignedInt: return UnsignedIntTy; 03890 case TargetInfo::SignedLong: return LongTy; 03891 case TargetInfo::UnsignedLong: return UnsignedLongTy; 03892 case TargetInfo::SignedLongLong: return LongLongTy; 03893 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 03894 } 03895 03896 assert(false && "Unhandled TargetInfo::IntType value"); 03897 return CanQualType(); 03898 } 03899 03900 //===----------------------------------------------------------------------===// 03901 // Type Predicates. 03902 //===----------------------------------------------------------------------===// 03903 03904 /// isObjCNSObjectType - Return true if this is an NSObject object using 03905 /// NSObject attribute on a c-style pointer type. 03906 /// FIXME - Make it work directly on types. 03907 /// FIXME: Move to Type. 03908 /// 03909 bool ASTContext::isObjCNSObjectType(QualType Ty) const { 03910 if (TypedefType *TDT = dyn_cast<TypedefType>(Ty)) { 03911 if (TypedefDecl *TD = TDT->getDecl()) 03912 if (TD->getAttr<ObjCNSObjectAttr>()) 03913 return true; 03914 } 03915 return false; 03916 } 03917 03918 /// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 03919 /// garbage collection attribute. 03920 /// 03921 Qualifiers::GC ASTContext::getObjCGCAttrKind(const QualType &Ty) const { 03922 Qualifiers::GC GCAttrs = Qualifiers::GCNone; 03923 if (getLangOptions().ObjC1 && 03924 getLangOptions().getGCMode() != LangOptions::NonGC) { 03925 GCAttrs = Ty.getObjCGCAttr(); 03926 // Default behavious under objective-c's gc is for objective-c pointers 03927 // (or pointers to them) be treated as though they were declared 03928 // as __strong. 03929 if (GCAttrs == Qualifiers::GCNone) { 03930 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 03931 GCAttrs = Qualifiers::Strong; 03932 else if (Ty->isPointerType()) 03933 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 03934 } 03935 // Non-pointers have none gc'able attribute regardless of the attribute 03936 // set on them. 03937 else if (!Ty->isAnyPointerType() && !Ty->isBlockPointerType()) 03938 return Qualifiers::GCNone; 03939 } 03940 return GCAttrs; 03941 } 03942 03943 //===----------------------------------------------------------------------===// 03944 // Type Compatibility Testing 03945 //===----------------------------------------------------------------------===// 03946 03947 /// areCompatVectorTypes - Return true if the two specified vector types are 03948 /// compatible. 03949 static bool areCompatVectorTypes(const VectorType *LHS, 03950 const VectorType *RHS) { 03951 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 03952 return LHS->getElementType() == RHS->getElementType() && 03953 LHS->getNumElements() == RHS->getNumElements(); 03954 } 03955 03956 //===----------------------------------------------------------------------===// 03957 // ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 03958 //===----------------------------------------------------------------------===// 03959 03960 /// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 03961 /// inheritance hierarchy of 'rProto'. 03962 bool ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 03963 ObjCProtocolDecl *rProto) { 03964 if (lProto == rProto) 03965 return true; 03966 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 03967 E = rProto->protocol_end(); PI != E; ++PI) 03968 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 03969 return true; 03970 return false; 03971 } 03972 03973 /// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 03974 /// return true if lhs's protocols conform to rhs's protocol; false 03975 /// otherwise. 03976 bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 03977 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 03978 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 03979 return false; 03980 } 03981 03982 /// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 03983 /// ObjCQualifiedIDType. 03984 bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 03985 bool compare) { 03986 // Allow id<P..> and an 'id' or void* type in all cases. 03987 if (lhs->isVoidPointerType() || 03988 lhs->isObjCIdType() || lhs->isObjCClassType()) 03989 return true; 03990 else if (rhs->isVoidPointerType() || 03991 rhs->isObjCIdType() || rhs->isObjCClassType()) 03992 return true; 03993 03994 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 03995 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 03996 03997 if (!rhsOPT) return false; 03998 03999 if (rhsOPT->qual_empty()) { 04000 // If the RHS is a unqualified interface pointer "NSString*", 04001 // make sure we check the class hierarchy. 04002 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 04003 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 04004 E = lhsQID->qual_end(); I != E; ++I) { 04005 // when comparing an id<P> on lhs with a static type on rhs, 04006 // see if static class implements all of id's protocols, directly or 04007 // through its super class and categories. 04008 if (!rhsID->ClassImplementsProtocol(*I, true)) 04009 return false; 04010 } 04011 } 04012 // If there are no qualifiers and no interface, we have an 'id'. 04013 return true; 04014 } 04015 // Both the right and left sides have qualifiers. 04016 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 04017 E = lhsQID->qual_end(); I != E; ++I) { 04018 ObjCProtocolDecl *lhsProto = *I; 04019 bool match = false; 04020 04021 // when comparing an id<P> on lhs with a static type on rhs, 04022 // see if static class implements all of id's protocols, directly or 04023 // through its super class and categories. 04024 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 04025 E = rhsOPT->qual_end(); J != E; ++J) { 04026 ObjCProtocolDecl *rhsProto = *J; 04027 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 04028 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 04029 match = true; 04030 break; 04031 } 04032 } 04033 // If the RHS is a qualified interface pointer "NSString<P>*", 04034 // make sure we check the class hierarchy. 04035 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 04036 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 04037 E = lhsQID->qual_end(); I != E; ++I) { 04038 // when comparing an id<P> on lhs with a static type on rhs, 04039 // see if static class implements all of id's protocols, directly or 04040 // through its super class and categories. 04041 if (rhsID->ClassImplementsProtocol(*I, true)) { 04042 match = true; 04043 break; 04044 } 04045 } 04046 } 04047 if (!match) 04048 return false; 04049 } 04050 04051 return true; 04052 } 04053 04054 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 04055 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 04056 04057 if (const ObjCObjectPointerType *lhsOPT = 04058 lhs->getAsObjCInterfacePointerType()) { 04059 if (lhsOPT->qual_empty()) { 04060 bool match = false; 04061 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 04062 for (ObjCObjectPointerType::qual_iterator I = rhsQID->qual_begin(), 04063 E = rhsQID->qual_end(); I != E; ++I) { 04064 // when comparing an id<P> on lhs with a static type on rhs, 04065 // see if static class implements all of id's protocols, directly or 04066 // through its super class and categories. 04067 if (lhsID->ClassImplementsProtocol(*I, true)) { 04068 match = true; 04069 break; 04070 } 04071 } 04072 if (!match) 04073 return false; 04074 } 04075 return true; 04076 } 04077 // Both the right and left sides have qualifiers. 04078 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 04079 E = lhsOPT->qual_end(); I != E; ++I) { 04080 ObjCProtocolDecl *lhsProto = *I; 04081 bool match = false; 04082 04083 // when comparing an id<P> on lhs with a static type on rhs, 04084 // see if static class implements all of id's protocols, directly or 04085 // through its super class and categories. 04086 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 04087 E = rhsQID->qual_end(); J != E; ++J) { 04088 ObjCProtocolDecl *rhsProto = *J; 04089 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 04090 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 04091 match = true; 04092 break; 04093 } 04094 } 04095 if (!match) 04096 return false; 04097 } 04098 return true; 04099 } 04100 return false; 04101 } 04102 04103 /// canAssignObjCInterfaces - Return true if the two interface types are 04104 /// compatible for assignment from RHS to LHS. This handles validation of any 04105 /// protocol qualifiers on the LHS or RHS. 04106 /// 04107 bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 04108 const ObjCObjectPointerType *RHSOPT) { 04109 // If either type represents the built-in 'id' or 'Class' types, return true. 04110 if (LHSOPT->isObjCBuiltinType() || RHSOPT->isObjCBuiltinType()) 04111 return true; 04112 04113 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 04114 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 04115 QualType(RHSOPT,0), 04116 false); 04117 04118 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 04119 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 04120 if (LHS && RHS) // We have 2 user-defined types. 04121 return canAssignObjCInterfaces(LHS, RHS); 04122 04123 return false; 04124 } 04125 04126 /// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 04127 /// for providing type-safty for objective-c pointers used to pass/return 04128 /// arguments in block literals. When passed as arguments, passing 'A*' where 04129 /// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 04130 /// not OK. For the return type, the opposite is not OK. 04131 bool ASTContext::canAssignObjCInterfacesInBlockPointer( 04132 const ObjCObjectPointerType *LHSOPT, 04133 const ObjCObjectPointerType *RHSOPT) { 04134 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 04135 return true; 04136 04137 if (LHSOPT->isObjCBuiltinType()) { 04138 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 04139 } 04140 04141 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 04142 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 04143 QualType(RHSOPT,0), 04144 false); 04145 04146 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 04147 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 04148 if (LHS && RHS) { // We have 2 user-defined types. 04149 if (LHS != RHS) { 04150 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 04151 return false; 04152 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 04153 return true; 04154 } 04155 else 04156 return true; 04157 } 04158 return false; 04159 } 04160 04161 /// getIntersectionOfProtocols - This routine finds the intersection of set 04162 /// of protocols inherited from two distinct objective-c pointer objects. 04163 /// It is used to build composite qualifier list of the composite type of 04164 /// the conditional expression involving two objective-c pointer objects. 04165 static 04166 void getIntersectionOfProtocols(ASTContext &Context, 04167 const ObjCObjectPointerType *LHSOPT, 04168 const ObjCObjectPointerType *RHSOPT, 04169 llvm::SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 04170 04171 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 04172 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 04173 04174 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 04175 unsigned LHSNumProtocols = LHS->getNumProtocols(); 04176 if (LHSNumProtocols > 0) 04177 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 04178 else { 04179 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 04180 Context.CollectInheritedProtocols(LHS->getDecl(), LHSInheritedProtocols); 04181 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 04182 LHSInheritedProtocols.end()); 04183 } 04184 04185 unsigned RHSNumProtocols = RHS->getNumProtocols(); 04186 if (RHSNumProtocols > 0) { 04187 ObjCProtocolDecl **RHSProtocols = 04188 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 04189 for (unsigned i = 0; i < RHSNumProtocols; ++i) 04190 if (InheritedProtocolSet.count(RHSProtocols[i])) 04191 IntersectionOfProtocols.push_back(RHSProtocols[i]); 04192 } 04193 else { 04194 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 04195 Context.CollectInheritedProtocols(RHS->getDecl(), RHSInheritedProtocols); 04196 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 04197 RHSInheritedProtocols.begin(), 04198 E = RHSInheritedProtocols.end(); I != E; ++I) 04199 if (InheritedProtocolSet.count((*I))) 04200 IntersectionOfProtocols.push_back((*I)); 04201 } 04202 } 04203 04204 /// areCommonBaseCompatible - Returns common base class of the two classes if 04205 /// one found. Note that this is O'2 algorithm. But it will be called as the 04206 /// last type comparison in a ?-exp of ObjC pointer types before a 04207 /// warning is issued. So, its invokation is extremely rare. 04208 QualType ASTContext::areCommonBaseCompatible( 04209 const ObjCObjectPointerType *LHSOPT, 04210 const ObjCObjectPointerType *RHSOPT) { 04211 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 04212 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 04213 if (!LHS || !RHS) 04214 return QualType(); 04215 04216 while (const ObjCInterfaceDecl *LHSIDecl = LHS->getDecl()->getSuperClass()) { 04217 QualType LHSTy = getObjCInterfaceType(LHSIDecl); 04218 LHS = LHSTy->getAs<ObjCInterfaceType>(); 04219 if (canAssignObjCInterfaces(LHS, RHS)) { 04220 llvm::SmallVector<ObjCProtocolDecl *, 8> IntersectionOfProtocols; 04221 getIntersectionOfProtocols(*this, 04222 LHSOPT, RHSOPT, IntersectionOfProtocols); 04223 if (IntersectionOfProtocols.empty()) 04224 LHSTy = getObjCObjectPointerType(LHSTy); 04225 else 04226 LHSTy = getObjCObjectPointerType(LHSTy, &IntersectionOfProtocols[0], 04227 IntersectionOfProtocols.size()); 04228 return LHSTy; 04229 } 04230 } 04231 04232 return QualType(); 04233 } 04234 04235 bool ASTContext::canAssignObjCInterfaces(const ObjCInterfaceType *LHS, 04236 const ObjCInterfaceType *RHS) { 04237 // Verify that the base decls are compatible: the RHS must be a subclass of 04238 // the LHS. 04239 if (!LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 04240 return false; 04241 04242 // RHS must have a superset of the protocols in the LHS. If the LHS is not 04243 // protocol qualified at all, then we are good. 04244 if (LHS->getNumProtocols() == 0) 04245 return true; 04246 04247 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, then it 04248 // isn't a superset. 04249 if (RHS->getNumProtocols() == 0) 04250 return true; // FIXME: should return false! 04251 04252 for (ObjCInterfaceType::qual_iterator LHSPI = LHS->qual_begin(), 04253 LHSPE = LHS->qual_end(); 04254 LHSPI != LHSPE; LHSPI++) { 04255 bool RHSImplementsProtocol = false; 04256 04257 // If the RHS doesn't implement the protocol on the left, the types 04258 // are incompatible. 04259 for (ObjCInterfaceType::qual_iterator RHSPI = RHS->qual_begin(), 04260 RHSPE = RHS->qual_end(); 04261 RHSPI != RHSPE; RHSPI++) { 04262 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 04263 RHSImplementsProtocol = true; 04264 break; 04265 } 04266 } 04267 // FIXME: For better diagnostics, consider passing back the protocol name. 04268 if (!RHSImplementsProtocol) 04269 return false; 04270 } 04271 // The RHS implements all protocols listed on the LHS. 04272 return true; 04273 } 04274 04275 bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 04276 // get the "pointed to" types 04277 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 04278 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 04279 04280 if (!LHSOPT || !RHSOPT) 04281 return false; 04282 04283 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 04284 canAssignObjCInterfaces(RHSOPT, LHSOPT); 04285 } 04286 04287 /// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 04288 /// both shall have the identically qualified version of a compatible type. 04289 /// C99 6.2.7p1: Two types have compatible types if their types are the 04290 /// same. See 6.7.[2,3,5] for additional rules. 04291 bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS) { 04292 if (getLangOptions().CPlusPlus) 04293 return hasSameType(LHS, RHS); 04294 04295 return !mergeTypes(LHS, RHS).isNull(); 04296 } 04297 04298 bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 04299 return !mergeTypes(LHS, RHS, true).isNull(); 04300 } 04301 04302 QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 04303 bool OfBlockPointer) { 04304 const FunctionType *lbase = lhs->getAs<FunctionType>(); 04305 const FunctionType *rbase = rhs->getAs<FunctionType>(); 04306 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 04307 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 04308 bool allLTypes = true; 04309 bool allRTypes = true; 04310 04311 // Check return type 04312 QualType retType; 04313 if (OfBlockPointer) 04314 retType = mergeTypes(rbase->getResultType(), lbase->getResultType(), true); 04315 else 04316 retType = mergeTypes(lbase->getResultType(), rbase->getResultType()); 04317 if (retType.isNull()) return QualType(); 04318 if (getCanonicalType(retType) != getCanonicalType(lbase->getResultType())) 04319 allLTypes = false; 04320 if (getCanonicalType(retType) != getCanonicalType(rbase->getResultType())) 04321 allRTypes = false; 04322 // FIXME: double check this 04323 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 04324 // rbase->getRegParmAttr() != 0 && 04325 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 04326 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 04327 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 04328 unsigned RegParm = lbaseInfo.getRegParm() == 0 ? rbaseInfo.getRegParm() : 04329 lbaseInfo.getRegParm(); 04330 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 04331 if (NoReturn != lbaseInfo.getNoReturn() || 04332 RegParm != lbaseInfo.getRegParm()) 04333 allLTypes = false; 04334 if (NoReturn != rbaseInfo.getNoReturn() || 04335 RegParm != rbaseInfo.getRegParm()) 04336 allRTypes = false; 04337 CallingConv lcc = lbaseInfo.getCC(); 04338 CallingConv rcc = rbaseInfo.getCC(); 04339 // Compatible functions must have compatible calling conventions 04340 if (!isSameCallConv(lcc, rcc)) 04341 return QualType(); 04342 04343 if (lproto && rproto) { // two C99 style function prototypes 04344 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 04345 "C++ shouldn't be here"); 04346 unsigned lproto_nargs = lproto->getNumArgs(); 04347 unsigned rproto_nargs = rproto->getNumArgs(); 04348 04349 // Compatible functions must have the same number of arguments 04350 if (lproto_nargs != rproto_nargs) 04351 return QualType(); 04352 04353 // Variadic and non-variadic functions aren't compatible 04354 if (lproto->isVariadic() != rproto->isVariadic()) 04355 return QualType(); 04356 04357 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 04358 return QualType(); 04359 04360 // Check argument compatibility 04361 llvm::SmallVector<QualType, 10> types; 04362 for (unsigned i = 0; i < lproto_nargs; i++) { 04363 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 04364 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 04365 QualType argtype = mergeTypes(largtype, rargtype, OfBlockPointer); 04366 if (argtype.isNull()) return QualType(); 04367 types.push_back(argtype); 04368 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 04369 allLTypes = false; 04370 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 04371 allRTypes = false; 04372 } 04373 if (allLTypes) return lhs; 04374 if (allRTypes) return rhs; 04375 return getFunctionType(retType, types.begin(), types.size(), 04376 lproto->isVariadic(), lproto->getTypeQuals(), 04377 false, false, 0, 0, 04378 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 04379 } 04380 04381 if (lproto) allRTypes = false; 04382 if (rproto) allLTypes = false; 04383 04384 const FunctionProtoType *proto = lproto ? lproto : rproto; 04385 if (proto) { 04386 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 04387 if (proto->isVariadic()) return QualType(); 04388 // Check that the types are compatible with the types that 04389 // would result from default argument promotions (C99 6.7.5.3p15). 04390 // The only types actually affected are promotable integer 04391 // types and floats, which would be passed as a different 04392 // type depending on whether the prototype is visible. 04393 unsigned proto_nargs = proto->getNumArgs(); 04394 for (unsigned i = 0; i < proto_nargs; ++i) { 04395 QualType argTy = proto->getArgType(i); 04396 04397 // Look at the promotion type of enum types, since that is the type used 04398 // to pass enum values. 04399 if (const EnumType *Enum = argTy->getAs<EnumType>()) 04400 argTy = Enum->getDecl()->getPromotionType(); 04401 04402 if (argTy->isPromotableIntegerType() || 04403 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 04404 return QualType(); 04405 } 04406 04407 if (allLTypes) return lhs; 04408 if (allRTypes) return rhs; 04409 return getFunctionType(retType, proto->arg_type_begin(), 04410 proto->getNumArgs(), proto->isVariadic(), 04411 proto->getTypeQuals(), 04412 false, false, 0, 0, 04413 FunctionType::ExtInfo(NoReturn, RegParm, lcc)); 04414 } 04415 04416 if (allLTypes) return lhs; 04417 if (allRTypes) return rhs; 04418 FunctionType::ExtInfo Info(NoReturn, RegParm, lcc); 04419 return getFunctionNoProtoType(retType, Info); 04420 } 04421 04422 QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 04423 bool OfBlockPointer) { 04424 // C++ [expr]: If an expression initially has the type "reference to T", the 04425 // type is adjusted to "T" prior to any further analysis, the expression 04426 // designates the object or function denoted by the reference, and the 04427 // expression is an lvalue unless the reference is an rvalue reference and 04428 // the expression is a function call (possibly inside parentheses). 04429 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 04430 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 04431 04432 QualType LHSCan = getCanonicalType(LHS), 04433 RHSCan = getCanonicalType(RHS); 04434 04435 // If two types are identical, they are compatible. 04436 if (LHSCan == RHSCan) 04437 return LHS; 04438 04439 // If the qualifiers are different, the types aren't compatible... mostly. 04440 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 04441 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 04442 if (LQuals != RQuals) { 04443 // If any of these qualifiers are different, we have a type 04444 // mismatch. 04445 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 04446 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 04447 return QualType(); 04448 04449 // Exactly one GC qualifier difference is allowed: __strong is 04450 // okay if the other type has no GC qualifier but is an Objective 04451 // C object pointer (i.e. implicitly strong by default). We fix 04452 // this by pretending that the unqualified type was actually 04453 // qualified __strong. 04454 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 04455 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 04456 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 04457 04458 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 04459 return QualType(); 04460 04461 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 04462 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 04463 } 04464 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 04465 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 04466 } 04467 return QualType(); 04468 } 04469 04470 // Okay, qualifiers are equal. 04471 04472 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 04473 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 04474 04475 // We want to consider the two function types to be the same for these 04476 // comparisons, just force one to the other. 04477 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 04478 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 04479 04480 // Same as above for arrays 04481 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 04482 LHSClass = Type::ConstantArray; 04483 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 04484 RHSClass = Type::ConstantArray; 04485 04486 // Canonicalize ExtVector -> Vector. 04487 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 04488 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 04489 04490 // If the canonical type classes don't match. 04491 if (LHSClass != RHSClass) { 04492 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 04493 // a signed integer type, or an unsigned integer type. 04494 // Compatibility is based on the underlying type, not the promotion 04495 // type. 04496 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 04497 if (ETy->getDecl()->getIntegerType() == RHSCan.getUnqualifiedType()) 04498 return RHS; 04499 } 04500 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 04501 if (ETy->getDecl()->getIntegerType() == LHSCan.getUnqualifiedType()) 04502 return LHS; 04503 } 04504 04505 return QualType(); 04506 } 04507 04508 // The canonical type classes match. 04509 switch (LHSClass) { 04510 #define TYPE(Class, Base) 04511 #define ABSTRACT_TYPE(Class, Base) 04512 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 04513 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 04514 #define DEPENDENT_TYPE(Class, Base) case Type::Class: 04515 #include "clang/AST/TypeNodes.def" 04516 assert(false && "Non-canonical and dependent types shouldn't get here"); 04517 return QualType(); 04518 04519 case Type::LValueReference: 04520 case Type::RValueReference: 04521 case Type::MemberPointer: 04522 assert(false && "C++ should never be in mergeTypes"); 04523 return QualType(); 04524 04525 case Type::IncompleteArray: 04526 case Type::VariableArray: 04527 case Type::FunctionProto: 04528 case Type::ExtVector: 04529 assert(false && "Types are eliminated above"); 04530 return QualType(); 04531 04532 case Type::Pointer: 04533 { 04534 // Merge two pointer types, while trying to preserve typedef info 04535 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 04536 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 04537 QualType ResultType = mergeTypes(LHSPointee, RHSPointee); 04538 if (ResultType.isNull()) return QualType(); 04539 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 04540 return LHS; 04541 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 04542 return RHS; 04543 return getPointerType(ResultType); 04544 } 04545 case Type::BlockPointer: 04546 { 04547 // Merge two block pointer types, while trying to preserve typedef info 04548 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 04549 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 04550 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer); 04551 if (ResultType.isNull()) return QualType(); 04552 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 04553 return LHS; 04554 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 04555 return RHS; 04556 return getBlockPointerType(ResultType); 04557 } 04558 case Type::ConstantArray: 04559 { 04560 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 04561 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 04562 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 04563 return QualType(); 04564 04565 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 04566 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 04567 QualType ResultType = mergeTypes(LHSElem, RHSElem); 04568 if (ResultType.isNull()) return QualType(); 04569 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 04570 return LHS; 04571 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 04572 return RHS; 04573 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 04574 ArrayType::ArraySizeModifier(), 0); 04575 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 04576 ArrayType::ArraySizeModifier(), 0); 04577 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 04578 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 04579 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 04580 return LHS; 04581 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 04582 return RHS; 04583 if (LVAT) { 04584 // FIXME: This isn't correct! But tricky to implement because 04585 // the array's size has to be the size of LHS, but the type 04586 // has to be different. 04587 return LHS; 04588 } 04589 if (RVAT) { 04590 // FIXME: This isn't correct! But tricky to implement because 04591 // the array's size has to be the size of RHS, but the type 04592 // has to be different. 04593 return RHS; 04594 } 04595 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 04596 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 04597 return getIncompleteArrayType(ResultType, 04598 ArrayType::ArraySizeModifier(), 0); 04599 } 04600 case Type::FunctionNoProto: 04601 return mergeFunctionTypes(LHS, RHS, OfBlockPointer); 04602 case Type::Record: 04603 case Type::Enum: 04604 return QualType(); 04605 case Type::Builtin: 04606 // Only exactly equal builtin types are compatible, which is tested above. 04607 return QualType(); 04608 case Type::Complex: 04609 // Distinct complex types are incompatible. 04610 return QualType(); 04611 case Type::Vector: 04612 // FIXME: The merged type should be an ExtVector! 04613 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 04614 RHSCan->getAs<VectorType>())) 04615 return LHS; 04616 return QualType(); 04617 case Type::ObjCInterface: { 04618 // Check if the interfaces are assignment compatible. 04619 // FIXME: This should be type compatibility, e.g. whether 04620 // "LHS x; RHS x;" at global scope is legal. 04621 const ObjCInterfaceType* LHSIface = LHS->getAs<ObjCInterfaceType>(); 04622 const ObjCInterfaceType* RHSIface = RHS->getAs<ObjCInterfaceType>(); 04623 if (LHSIface && RHSIface && 04624 canAssignObjCInterfaces(LHSIface, RHSIface)) 04625 return LHS; 04626 04627 return QualType(); 04628 } 04629 case Type::ObjCObjectPointer: { 04630 if (OfBlockPointer) { 04631 if (canAssignObjCInterfacesInBlockPointer( 04632 LHS->getAs<ObjCObjectPointerType>(), 04633 RHS->getAs<ObjCObjectPointerType>())) 04634 return LHS; 04635 return QualType(); 04636 } 04637 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 04638 RHS->getAs<ObjCObjectPointerType>())) 04639 return LHS; 04640 04641 return QualType(); 04642 } 04643 } 04644 04645 return QualType(); 04646 } 04647 04648 //===----------------------------------------------------------------------===// 04649 // Integer Predicates 04650 //===----------------------------------------------------------------------===// 04651 04652 unsigned ASTContext::getIntWidth(QualType T) { 04653 if (T->isBooleanType()) 04654 return 1; 04655 if (EnumType *ET = dyn_cast<EnumType>(T)) 04656 T = ET->getDecl()->getIntegerType(); 04657 // For builtin types, just use the standard type sizing method 04658 return (unsigned)getTypeSize(T); 04659 } 04660 04661 QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 04662 assert(T->isSignedIntegerType() && "Unexpected type"); 04663 04664 // Turn <4 x signed int> -> <4 x unsigned int> 04665 if (const VectorType *VTy = T->getAs<VectorType>()) 04666 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 04667 VTy->getNumElements(), VTy->isAltiVec(), VTy->isPixel()); 04668 04669 // For enums, we return the unsigned version of the base type. 04670 if (const EnumType *ETy = T->getAs<EnumType>()) 04671 T = ETy->getDecl()->getIntegerType(); 04672 04673 const BuiltinType *BTy = T->getAs<BuiltinType>(); 04674 assert(BTy && "Unexpected signed integer type"); 04675 switch (BTy->getKind()) { 04676 case BuiltinType::Char_S: 04677 case BuiltinType::SChar: 04678 return UnsignedCharTy; 04679 case BuiltinType::Short: 04680 return UnsignedShortTy; 04681 case BuiltinType::Int: 04682 return UnsignedIntTy; 04683 case BuiltinType::Long: 04684 return UnsignedLongTy; 04685 case BuiltinType::LongLong: 04686 return UnsignedLongLongTy; 04687 case BuiltinType::Int128: 04688 return UnsignedInt128Ty; 04689 default: 04690 assert(0 && "Unexpected signed integer type"); 04691 return QualType(); 04692 } 04693 } 04694 04695 ExternalASTSource::~ExternalASTSource() { } 04696 04697 void ExternalASTSource::PrintStats() { } 04698 04699 04700 //===----------------------------------------------------------------------===// 04701 // Builtin Type Computation 04702 //===----------------------------------------------------------------------===// 04703 04704 /// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 04705 /// pointer over the consumed characters. This returns the resultant type. 04706 static QualType DecodeTypeFromStr(const char *&Str, ASTContext &Context, 04707 ASTContext::GetBuiltinTypeError &Error, 04708 bool AllowTypeModifiers = true) { 04709 // Modifiers. 04710 int HowLong = 0; 04711 bool Signed = false, Unsigned = false; 04712 04713 // Read the modifiers first. 04714 bool Done = false; 04715 while (!Done) { 04716 switch (*Str++) { 04717 default: Done = true; --Str; break; 04718 case 'S': 04719 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 04720 assert(!Signed && "Can't use 'S' modifier multiple times!"); 04721 Signed = true; 04722 break; 04723 case 'U': 04724 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 04725 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 04726 Unsigned = true; 04727 break; 04728 case 'L': 04729 assert(HowLong <= 2 && "Can't have LLLL modifier"); 04730 ++HowLong; 04731 break; 04732 } 04733 } 04734 04735 QualType Type; 04736 04737 // Read the base type. 04738 switch (*Str++) { 04739 default: assert(0 && "Unknown builtin type letter!"); 04740 case 'v': 04741 assert(HowLong == 0 && !Signed && !Unsigned && 04742 "Bad modifiers used with 'v'!"); 04743 Type = Context.VoidTy; 04744 break; 04745 case 'f': 04746 assert(HowLong == 0 && !Signed && !Unsigned && 04747 "Bad modifiers used with 'f'!"); 04748 Type = Context.FloatTy; 04749 break; 04750 case 'd': 04751 assert(HowLong < 2 && !Signed && !Unsigned && 04752 "Bad modifiers used with 'd'!"); 04753 if (HowLong) 04754 Type = Context.LongDoubleTy; 04755 else 04756 Type = Context.DoubleTy; 04757 break; 04758 case 's': 04759 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 04760 if (Unsigned) 04761 Type = Context.UnsignedShortTy; 04762 else 04763 Type = Context.ShortTy; 04764 break; 04765 case 'i': 04766 if (HowLong == 3) 04767 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 04768 else if (HowLong == 2) 04769 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 04770 else if (HowLong == 1) 04771 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 04772 else 04773 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 04774 break; 04775 case 'c': 04776 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 04777 if (Signed) 04778 Type = Context.SignedCharTy; 04779 else if (Unsigned) 04780 Type = Context.UnsignedCharTy; 04781 else 04782 Type = Context.CharTy; 04783 break; 04784 case 'b': // boolean 04785 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 04786 Type = Context.BoolTy; 04787 break; 04788 case 'z': // size_t. 04789 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 04790 Type = Context.getSizeType(); 04791 break; 04792 case 'F': 04793 Type = Context.getCFConstantStringType(); 04794 break; 04795 case 'a': 04796 Type = Context.getBuiltinVaListType(); 04797 assert(!Type.isNull() && "builtin va list type not initialized!"); 04798 break; 04799 case 'A': 04800 // This is a "reference" to a va_list; however, what exactly 04801 // this means depends on how va_list is defined. There are two 04802 // different kinds of va_list: ones passed by value, and ones 04803 // passed by reference. An example of a by-value va_list is 04804 // x86, where va_list is a char*. An example of by-ref va_list 04805 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 04806 // we want this argument to be a char*&; for x86-64, we want 04807 // it to be a __va_list_tag*. 04808 Type = Context.getBuiltinVaListType(); 04809 assert(!Type.isNull() && "builtin va list type not initialized!"); 04810 if (Type->isArrayType()) { 04811 Type = Context.getArrayDecayedType(Type); 04812 } else { 04813 Type = Context.getLValueReferenceType(Type); 04814 } 04815 break; 04816 case 'V': { 04817 char *End; 04818 unsigned NumElements = strtoul(Str, &End, 10); 04819 assert(End != Str && "Missing vector size"); 04820 04821 Str = End; 04822 04823 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 04824 // FIXME: Don't know what to do about AltiVec. 04825 Type = Context.getVectorType(ElementType, NumElements, false, false); 04826 break; 04827 } 04828 case 'X': { 04829 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, false); 04830 Type = Context.getComplexType(ElementType); 04831 break; 04832 } 04833 case 'P': 04834 Type = Context.getFILEType(); 04835 if (Type.isNull()) { 04836 Error = ASTContext::GE_Missing_stdio; 04837 return QualType(); 04838 } 04839 break; 04840 case 'J': 04841 if (Signed) 04842 Type = Context.getsigjmp_bufType(); 04843 else 04844 Type = Context.getjmp_bufType(); 04845 04846 if (Type.isNull()) { 04847 Error = ASTContext::GE_Missing_setjmp; 04848 return QualType(); 04849 } 04850 break; 04851 } 04852 04853 if (!AllowTypeModifiers) 04854 return Type; 04855 04856 Done = false; 04857 while (!Done) { 04858 switch (char c = *Str++) { 04859 default: Done = true; --Str; break; 04860 case '*': 04861 case '&': 04862 { 04863 // Both pointers and references can have their pointee types 04864 // qualified with an address space. 04865 char *End; 04866 unsigned AddrSpace = strtoul(Str, &End, 10); 04867 if (End != Str && AddrSpace != 0) { 04868 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 04869 Str = End; 04870 } 04871 } 04872 if (c == '*') 04873 Type = Context.getPointerType(Type); 04874 else 04875 Type = Context.getLValueReferenceType(Type); 04876 break; 04877 // FIXME: There's no way to have a built-in with an rvalue ref arg. 04878 case 'C': 04879 Type = Type.withConst(); 04880 break; 04881 case 'D': 04882 Type = Context.getVolatileType(Type); 04883 break; 04884 } 04885 } 04886 04887 return Type; 04888 } 04889 04890 /// GetBuiltinType - Return the type for the specified builtin. 04891 QualType ASTContext::GetBuiltinType(unsigned id, 04892 GetBuiltinTypeError &Error) { 04893 const char *TypeStr = BuiltinInfo.GetTypeString(id); 04894 04895 llvm::SmallVector<QualType, 8> ArgTypes; 04896 04897 Error = GE_None; 04898 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error); 04899 if (Error != GE_None) 04900 return QualType(); 04901 while (TypeStr[0] && TypeStr[0] != '.') { 04902 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error); 04903 if (Error != GE_None) 04904 return QualType(); 04905 04906 // Do array -> pointer decay. The builtin should use the decayed type. 04907 if (Ty->isArrayType()) 04908 Ty = getArrayDecayedType(Ty); 04909 04910 ArgTypes.push_back(Ty); 04911 } 04912 04913 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 04914 "'.' should only occur at end of builtin type list!"); 04915 04916 // handle untyped/variadic arguments "T c99Style();" or "T cppStyle(...);". 04917 if (ArgTypes.size() == 0 && TypeStr[0] == '.') 04918 return getFunctionNoProtoType(ResType); 04919 04920 // FIXME: Should we create noreturn types? 04921 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), 04922 TypeStr[0] == '.', 0, false, false, 0, 0, 04923 FunctionType::ExtInfo()); 04924 } 04925 04926 QualType 04927 ASTContext::UsualArithmeticConversionsType(QualType lhs, QualType rhs) { 04928 // Perform the usual unary conversions. We do this early so that 04929 // integral promotions to "int" can allow us to exit early, in the 04930 // lhs == rhs check. Also, for conversion purposes, we ignore any 04931 // qualifiers. For example, "const float" and "float" are 04932 // equivalent. 04933 if (lhs->isPromotableIntegerType()) 04934 lhs = getPromotedIntegerType(lhs); 04935 else 04936 lhs = lhs.getUnqualifiedType(); 04937 if (rhs->isPromotableIntegerType()) 04938 rhs = getPromotedIntegerType(rhs); 04939 else 04940 rhs = rhs.getUnqualifiedType(); 04941 04942 // If both types are identical, no conversion is needed. 04943 if (lhs == rhs) 04944 return lhs; 04945 04946 // If either side is a non-arithmetic type (e.g. a pointer), we are done. 04947 // The caller can deal with this (e.g. pointer + int). 04948 if (!lhs->isArithmeticType() || !rhs->isArithmeticType()) 04949 return lhs; 04950 04951 // At this point, we have two different arithmetic types. 04952 04953 // Handle complex types first (C99 6.3.1.8p1). 04954 if (lhs->isComplexType() || rhs->isComplexType()) { 04955 // if we have an integer operand, the result is the complex type. 04956 if (rhs->isIntegerType() || rhs->isComplexIntegerType()) { 04957 // convert the rhs to the lhs complex type. 04958 return lhs; 04959 } 04960 if (lhs->isIntegerType() || lhs->isComplexIntegerType()) { 04961 // convert the lhs to the rhs complex type. 04962 return rhs; 04963 } 04964 // This handles complex/complex, complex/float, or float/complex. 04965 // When both operands are complex, the shorter operand is converted to the 04966 // type of the longer, and that is the type of the result. This corresponds 04967 // to what is done when combining two real floating-point operands. 04968 // The fun begins when size promotion occur across type domains. 04969 // From H&S 6.3.4: When one operand is complex and the other is a real 04970 // floating-point type, the less precise type is converted, within it's 04971 // real or complex domain, to the precision of the other type. For example, 04972 // when combining a "long double" with a "double _Complex", the 04973 // "double _Complex" is promoted to "long double _Complex". 04974 int result = getFloatingTypeOrder(lhs, rhs); 04975 04976 if (result > 0) { // The left side is bigger, convert rhs. 04977 rhs = getFloatingTypeOfSizeWithinDomain(lhs, rhs); 04978 } else if (result < 0) { // The right side is bigger, convert lhs. 04979 lhs = getFloatingTypeOfSizeWithinDomain(rhs, lhs); 04980 } 04981 // At this point, lhs and rhs have the same rank/size. Now, make sure the 04982 // domains match. This is a requirement for our implementation, C99 04983 // does not require this promotion. 04984 if (lhs != rhs) { // Domains don't match, we have complex/float mix. 04985 if (lhs->isRealFloatingType()) { // handle "double, _Complex double". 04986 return rhs; 04987 } else { // handle "_Complex double, double". 04988 return lhs; 04989 } 04990 } 04991 return lhs; // The domain/size match exactly. 04992 } 04993 // Now handle "real" floating types (i.e. float, double, long double). 04994 if (lhs->isRealFloatingType() || rhs->isRealFloatingType()) { 04995 // if we have an integer operand, the result is the real floating type. 04996 if (rhs->isIntegerType()) { 04997 // convert rhs to the lhs floating point type. 04998 return lhs; 04999 } 05000 if (rhs->isComplexIntegerType()) { 05001 // convert rhs to the complex floating point type. 05002 return getComplexType(lhs); 05003 } 05004 if (lhs->isIntegerType()) { 05005 // convert lhs to the rhs floating point type. 05006 return rhs; 05007 } 05008 if (lhs->isComplexIntegerType()) { 05009 // convert lhs to the complex floating point type. 05010 return getComplexType(rhs); 05011 } 05012 // We have two real floating types, float/complex combos were handled above. 05013 // Convert the smaller operand to the bigger result. 05014 int result = getFloatingTypeOrder(lhs, rhs); 05015 if (result > 0) // convert the rhs 05016 return lhs; 05017 assert(result < 0 && "illegal float comparison"); 05018 return rhs; // convert the lhs 05019 } 05020 if (lhs->isComplexIntegerType() || rhs->isComplexIntegerType()) { 05021 // Handle GCC complex int extension. 05022 const ComplexType *lhsComplexInt = lhs->getAsComplexIntegerType(); 05023 const ComplexType *rhsComplexInt = rhs->getAsComplexIntegerType(); 05024 05025 if (lhsComplexInt && rhsComplexInt) { 05026 if (getIntegerTypeOrder(lhsComplexInt->getElementType(), 05027 rhsComplexInt->getElementType()) >= 0) 05028 return lhs; // convert the rhs 05029 return rhs; 05030 } else if (lhsComplexInt && rhs->isIntegerType()) { 05031 // convert the rhs to the lhs complex type. 05032 return lhs; 05033 } else if (rhsComplexInt && lhs->isIntegerType()) { 05034 // convert the lhs to the rhs complex type. 05035 return rhs; 05036 } 05037 } 05038 // Finally, we have two differing integer types. 05039 // The rules for this case are in C99 6.3.1.8 05040 int compare = getIntegerTypeOrder(lhs, rhs); 05041 bool lhsSigned = lhs->isSignedIntegerType(), 05042 rhsSigned = rhs->isSignedIntegerType(); 05043 QualType destType; 05044 if (lhsSigned == rhsSigned) { 05045 // Same signedness; use the higher-ranked type 05046 destType = compare >= 0 ? lhs : rhs; 05047 } else if (compare != (lhsSigned ? 1 : -1)) { 05048 // The unsigned type has greater than or equal rank to the 05049 // signed type, so use the unsigned type 05050 destType = lhsSigned ? rhs : lhs; 05051 } else if (getIntWidth(lhs) != getIntWidth(rhs)) { 05052 // The two types are different widths; if we are here, that 05053 // means the signed type is larger than the unsigned type, so 05054 // use the signed type. 05055 destType = lhsSigned ? lhs : rhs; 05056 } else { 05057 // The signed type is higher-ranked than the unsigned type, 05058 // but isn't actually any bigger (like unsigned int and long 05059 // on most 32-bit systems). Use the unsigned type corresponding 05060 // to the signed type. 05061 destType = getCorrespondingUnsignedType(lhsSigned ? lhs : rhs); 05062 } 05063 return destType; 05064 }