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