ASTContext.cpp revision f50555eedef33fd5a67d369aa0ae8a6f1d201543
15d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===--- ASTContext.cpp - Context to hold long-lived AST nodes ------------===// 25d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// 35d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// The LLVM Compiler Infrastructure 45d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// 55d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// This file is distributed under the University of Illinois Open Source 65d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// License. See LICENSE.TXT for details. 75d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// 85d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)//===----------------------------------------------------------------------===// 95d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// 105d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)// This file implements the ASTContext interface. 11a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// 12a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)//===----------------------------------------------------------------------===// 135d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 145d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/ASTContext.h" 155d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/CharUnits.h" 16a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/CommentCommandTraits.h" 17a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclCXX.h" 18a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclObjC.h" 19a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/DeclTemplate.h" 205d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/TypeLoc.h" 215d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/Expr.h" 225d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/ExprCXX.h" 23a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/ExternalASTSource.h" 24a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/ASTMutationListener.h" 25a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/AST/RecordLayout.h" 265d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/AST/Mangle.h" 27f8ee788a64d60abd8f2d742a5fdedde054ecd910Torne (Richard Coles)#include "clang/Basic/Builtins.h" 285d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "clang/Basic/SourceManager.h" 29a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "clang/Basic/TargetInfo.h" 305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "llvm/ADT/SmallString.h" 315d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "llvm/ADT/StringExtras.h" 325d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "llvm/Support/MathExtras.h" 33a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/Support/raw_ostream.h" 34a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "llvm/Support/Capacity.h" 355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "CXXABI.h" 365d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include <map> 375d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 385d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)using namespace clang; 395d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 405d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitDefaultConstructors; 415d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitDefaultConstructorsDeclared; 42a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)unsigned ASTContext::NumImplicitCopyConstructors; 43a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)unsigned ASTContext::NumImplicitCopyConstructorsDeclared; 445d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitMoveConstructors; 455d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitMoveConstructorsDeclared; 465d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitCopyAssignmentOperators; 475d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitCopyAssignmentOperatorsDeclared; 485d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitMoveAssignmentOperators; 495d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitMoveAssignmentOperatorsDeclared; 505d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitDestructors; 515d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)unsigned ASTContext::NumImplicitDestructorsDeclared; 525d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 535d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)enum FloatingRank { 54a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) HalfRank, FloatRank, DoubleRank, LongDoubleRank 55a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}; 56a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 575d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const { 585d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) if (!CommentsLoaded && ExternalSource) { 595d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) ExternalSource->ReadComments(); 605d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) CommentsLoaded = true; 61a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) } 62a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 635d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) assert(D); 645d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 65a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) // User can not attach documentation to implicit declarations. 66a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) if (D->isImplicit()) 67a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) return NULL; 68a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) 69a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles) // TODO: handle comments for function parameters properly. 705d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) if (isa<ParmVarDecl>(D)) 715d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) return NULL; 725d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) 735d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // TODO: we could look up template parameter documentation in the template 745d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles) // documentation. 75 if (isa<TemplateTypeParmDecl>(D) || 76 isa<NonTypeTemplateParmDecl>(D) || 77 isa<TemplateTemplateParmDecl>(D)) 78 return NULL; 79 80 ArrayRef<RawComment *> RawComments = Comments.getComments(); 81 82 // If there are no comments anywhere, we won't find anything. 83 if (RawComments.empty()) 84 return NULL; 85 86 // Find declaration location. 87 // For Objective-C declarations we generally don't expect to have multiple 88 // declarators, thus use declaration starting location as the "declaration 89 // location". 90 // For all other declarations multiple declarators are used quite frequently, 91 // so we use the location of the identifier as the "declaration location". 92 SourceLocation DeclLoc; 93 if (isa<ObjCMethodDecl>(D) || isa<ObjCContainerDecl>(D) || 94 isa<ObjCPropertyDecl>(D) || 95 isa<RedeclarableTemplateDecl>(D) || 96 isa<ClassTemplateSpecializationDecl>(D)) 97 DeclLoc = D->getLocStart(); 98 else 99 DeclLoc = D->getLocation(); 100 101 // If the declaration doesn't map directly to a location in a file, we 102 // can't find the comment. 103 if (DeclLoc.isInvalid() || !DeclLoc.isFileID()) 104 return NULL; 105 106 // Find the comment that occurs just after this declaration. 107 ArrayRef<RawComment *>::iterator Comment; 108 { 109 // When searching for comments during parsing, the comment we are looking 110 // for is usually among the last two comments we parsed -- check them 111 // first. 112 RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc)); 113 BeforeThanCompare<RawComment> Compare(SourceMgr); 114 ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1; 115 bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 116 if (!Found && RawComments.size() >= 2) { 117 MaybeBeforeDecl--; 118 Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc); 119 } 120 121 if (Found) { 122 Comment = MaybeBeforeDecl + 1; 123 assert(Comment == std::lower_bound(RawComments.begin(), RawComments.end(), 124 &CommentAtDeclLoc, Compare)); 125 } else { 126 // Slow path. 127 Comment = std::lower_bound(RawComments.begin(), RawComments.end(), 128 &CommentAtDeclLoc, Compare); 129 } 130 } 131 132 // Decompose the location for the declaration and find the beginning of the 133 // file buffer. 134 std::pair<FileID, unsigned> DeclLocDecomp = SourceMgr.getDecomposedLoc(DeclLoc); 135 136 // First check whether we have a trailing comment. 137 if (Comment != RawComments.end() && 138 (*Comment)->isDocumentation() && (*Comment)->isTrailingComment() && 139 (isa<FieldDecl>(D) || isa<EnumConstantDecl>(D) || isa<VarDecl>(D))) { 140 std::pair<FileID, unsigned> CommentBeginDecomp 141 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getBegin()); 142 // Check that Doxygen trailing comment comes after the declaration, starts 143 // on the same line and in the same file as the declaration. 144 if (DeclLocDecomp.first == CommentBeginDecomp.first && 145 SourceMgr.getLineNumber(DeclLocDecomp.first, DeclLocDecomp.second) 146 == SourceMgr.getLineNumber(CommentBeginDecomp.first, 147 CommentBeginDecomp.second)) { 148 (*Comment)->setDecl(D); 149 return *Comment; 150 } 151 } 152 153 // The comment just after the declaration was not a trailing comment. 154 // Let's look at the previous comment. 155 if (Comment == RawComments.begin()) 156 return NULL; 157 --Comment; 158 159 // Check that we actually have a non-member Doxygen comment. 160 if (!(*Comment)->isDocumentation() || (*Comment)->isTrailingComment()) 161 return NULL; 162 163 // Decompose the end of the comment. 164 std::pair<FileID, unsigned> CommentEndDecomp 165 = SourceMgr.getDecomposedLoc((*Comment)->getSourceRange().getEnd()); 166 167 // If the comment and the declaration aren't in the same file, then they 168 // aren't related. 169 if (DeclLocDecomp.first != CommentEndDecomp.first) 170 return NULL; 171 172 // Get the corresponding buffer. 173 bool Invalid = false; 174 const char *Buffer = SourceMgr.getBufferData(DeclLocDecomp.first, 175 &Invalid).data(); 176 if (Invalid) 177 return NULL; 178 179 // Extract text between the comment and declaration. 180 StringRef Text(Buffer + CommentEndDecomp.second, 181 DeclLocDecomp.second - CommentEndDecomp.second); 182 183 // There should be no other declarations or preprocessor directives between 184 // comment and declaration. 185 if (Text.find_first_of(",;{}#@") != StringRef::npos) 186 return NULL; 187 188 (*Comment)->setDecl(D); 189 return *Comment; 190} 191 192const RawComment *ASTContext::getRawCommentForAnyRedecl(const Decl *D) const { 193 // Check whether we have cached a comment for this declaration already. 194 { 195 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 196 RedeclComments.find(D); 197 if (Pos != RedeclComments.end()) { 198 const RawCommentAndCacheFlags &Raw = Pos->second; 199 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) 200 return Raw.getRaw(); 201 } 202 } 203 204 // Search for comments attached to declarations in the redeclaration chain. 205 const RawComment *RC = NULL; 206 for (Decl::redecl_iterator I = D->redecls_begin(), 207 E = D->redecls_end(); 208 I != E; ++I) { 209 llvm::DenseMap<const Decl *, RawCommentAndCacheFlags>::iterator Pos = 210 RedeclComments.find(*I); 211 if (Pos != RedeclComments.end()) { 212 const RawCommentAndCacheFlags &Raw = Pos->second; 213 if (Raw.getKind() != RawCommentAndCacheFlags::NoCommentInDecl) { 214 RC = Raw.getRaw(); 215 break; 216 } 217 } else { 218 RC = getRawCommentForDeclNoCache(*I); 219 RawCommentAndCacheFlags Raw; 220 if (RC) { 221 Raw.setRaw(RC); 222 Raw.setKind(RawCommentAndCacheFlags::FromDecl); 223 } else 224 Raw.setKind(RawCommentAndCacheFlags::NoCommentInDecl); 225 RedeclComments[*I] = Raw; 226 if (RC) 227 break; 228 } 229 } 230 231 // If we found a comment, it should be a documentation comment. 232 assert(!RC || RC->isDocumentation()); 233 234 // Update cache for every declaration in the redeclaration chain. 235 RawCommentAndCacheFlags Raw; 236 Raw.setRaw(RC); 237 Raw.setKind(RawCommentAndCacheFlags::FromRedecl); 238 239 for (Decl::redecl_iterator I = D->redecls_begin(), 240 E = D->redecls_end(); 241 I != E; ++I) { 242 RawCommentAndCacheFlags &R = RedeclComments[*I]; 243 if (R.getKind() == RawCommentAndCacheFlags::NoCommentInDecl) 244 R = Raw; 245 } 246 247 return RC; 248} 249 250comments::FullComment *ASTContext::getCommentForDecl(const Decl *D) const { 251 const RawComment *RC = getRawCommentForAnyRedecl(D); 252 if (!RC) 253 return NULL; 254 255 return RC->getParsed(*this); 256} 257 258void 259ASTContext::CanonicalTemplateTemplateParm::Profile(llvm::FoldingSetNodeID &ID, 260 TemplateTemplateParmDecl *Parm) { 261 ID.AddInteger(Parm->getDepth()); 262 ID.AddInteger(Parm->getPosition()); 263 ID.AddBoolean(Parm->isParameterPack()); 264 265 TemplateParameterList *Params = Parm->getTemplateParameters(); 266 ID.AddInteger(Params->size()); 267 for (TemplateParameterList::const_iterator P = Params->begin(), 268 PEnd = Params->end(); 269 P != PEnd; ++P) { 270 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) { 271 ID.AddInteger(0); 272 ID.AddBoolean(TTP->isParameterPack()); 273 continue; 274 } 275 276 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 277 ID.AddInteger(1); 278 ID.AddBoolean(NTTP->isParameterPack()); 279 ID.AddPointer(NTTP->getType().getCanonicalType().getAsOpaquePtr()); 280 if (NTTP->isExpandedParameterPack()) { 281 ID.AddBoolean(true); 282 ID.AddInteger(NTTP->getNumExpansionTypes()); 283 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 284 QualType T = NTTP->getExpansionType(I); 285 ID.AddPointer(T.getCanonicalType().getAsOpaquePtr()); 286 } 287 } else 288 ID.AddBoolean(false); 289 continue; 290 } 291 292 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 293 ID.AddInteger(2); 294 Profile(ID, TTP); 295 } 296} 297 298TemplateTemplateParmDecl * 299ASTContext::getCanonicalTemplateTemplateParmDecl( 300 TemplateTemplateParmDecl *TTP) const { 301 // Check if we already have a canonical template template parameter. 302 llvm::FoldingSetNodeID ID; 303 CanonicalTemplateTemplateParm::Profile(ID, TTP); 304 void *InsertPos = 0; 305 CanonicalTemplateTemplateParm *Canonical 306 = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 307 if (Canonical) 308 return Canonical->getParam(); 309 310 // Build a canonical template parameter list. 311 TemplateParameterList *Params = TTP->getTemplateParameters(); 312 SmallVector<NamedDecl *, 4> CanonParams; 313 CanonParams.reserve(Params->size()); 314 for (TemplateParameterList::const_iterator P = Params->begin(), 315 PEnd = Params->end(); 316 P != PEnd; ++P) { 317 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(*P)) 318 CanonParams.push_back( 319 TemplateTypeParmDecl::Create(*this, getTranslationUnitDecl(), 320 SourceLocation(), 321 SourceLocation(), 322 TTP->getDepth(), 323 TTP->getIndex(), 0, false, 324 TTP->isParameterPack())); 325 else if (NonTypeTemplateParmDecl *NTTP 326 = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 327 QualType T = getCanonicalType(NTTP->getType()); 328 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(T); 329 NonTypeTemplateParmDecl *Param; 330 if (NTTP->isExpandedParameterPack()) { 331 SmallVector<QualType, 2> ExpandedTypes; 332 SmallVector<TypeSourceInfo *, 2> ExpandedTInfos; 333 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 334 ExpandedTypes.push_back(getCanonicalType(NTTP->getExpansionType(I))); 335 ExpandedTInfos.push_back( 336 getTrivialTypeSourceInfo(ExpandedTypes.back())); 337 } 338 339 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 340 SourceLocation(), 341 SourceLocation(), 342 NTTP->getDepth(), 343 NTTP->getPosition(), 0, 344 T, 345 TInfo, 346 ExpandedTypes.data(), 347 ExpandedTypes.size(), 348 ExpandedTInfos.data()); 349 } else { 350 Param = NonTypeTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 351 SourceLocation(), 352 SourceLocation(), 353 NTTP->getDepth(), 354 NTTP->getPosition(), 0, 355 T, 356 NTTP->isParameterPack(), 357 TInfo); 358 } 359 CanonParams.push_back(Param); 360 361 } else 362 CanonParams.push_back(getCanonicalTemplateTemplateParmDecl( 363 cast<TemplateTemplateParmDecl>(*P))); 364 } 365 366 TemplateTemplateParmDecl *CanonTTP 367 = TemplateTemplateParmDecl::Create(*this, getTranslationUnitDecl(), 368 SourceLocation(), TTP->getDepth(), 369 TTP->getPosition(), 370 TTP->isParameterPack(), 371 0, 372 TemplateParameterList::Create(*this, SourceLocation(), 373 SourceLocation(), 374 CanonParams.data(), 375 CanonParams.size(), 376 SourceLocation())); 377 378 // Get the new insert position for the node we care about. 379 Canonical = CanonTemplateTemplateParms.FindNodeOrInsertPos(ID, InsertPos); 380 assert(Canonical == 0 && "Shouldn't be in the map!"); 381 (void)Canonical; 382 383 // Create the canonical template template parameter entry. 384 Canonical = new (*this) CanonicalTemplateTemplateParm(CanonTTP); 385 CanonTemplateTemplateParms.InsertNode(Canonical, InsertPos); 386 return CanonTTP; 387} 388 389CXXABI *ASTContext::createCXXABI(const TargetInfo &T) { 390 if (!LangOpts.CPlusPlus) return 0; 391 392 switch (T.getCXXABI()) { 393 case CXXABI_ARM: 394 return CreateARMCXXABI(*this); 395 case CXXABI_Itanium: 396 return CreateItaniumCXXABI(*this); 397 case CXXABI_Microsoft: 398 return CreateMicrosoftCXXABI(*this); 399 } 400 llvm_unreachable("Invalid CXXABI type!"); 401} 402 403static const LangAS::Map *getAddressSpaceMap(const TargetInfo &T, 404 const LangOptions &LOpts) { 405 if (LOpts.FakeAddressSpaceMap) { 406 // The fake address space map must have a distinct entry for each 407 // language-specific address space. 408 static const unsigned FakeAddrSpaceMap[] = { 409 1, // opencl_global 410 2, // opencl_local 411 3, // opencl_constant 412 4, // cuda_device 413 5, // cuda_constant 414 6 // cuda_shared 415 }; 416 return &FakeAddrSpaceMap; 417 } else { 418 return &T.getAddressSpaceMap(); 419 } 420} 421 422ASTContext::ASTContext(LangOptions& LOpts, SourceManager &SM, 423 const TargetInfo *t, 424 IdentifierTable &idents, SelectorTable &sels, 425 Builtin::Context &builtins, 426 unsigned size_reserve, 427 bool DelayInitialization) 428 : FunctionProtoTypes(this_()), 429 TemplateSpecializationTypes(this_()), 430 DependentTemplateSpecializationTypes(this_()), 431 SubstTemplateTemplateParmPacks(this_()), 432 GlobalNestedNameSpecifier(0), 433 Int128Decl(0), UInt128Decl(0), 434 BuiltinVaListDecl(0), 435 ObjCIdDecl(0), ObjCSelDecl(0), ObjCClassDecl(0), ObjCProtocolClassDecl(0), 436 CFConstantStringTypeDecl(0), ObjCInstanceTypeDecl(0), 437 FILEDecl(0), 438 jmp_bufDecl(0), sigjmp_bufDecl(0), ucontext_tDecl(0), 439 BlockDescriptorType(0), BlockDescriptorExtendedType(0), 440 cudaConfigureCallDecl(0), 441 NullTypeSourceInfo(QualType()), 442 FirstLocalImport(), LastLocalImport(), 443 SourceMgr(SM), LangOpts(LOpts), 444 AddrSpaceMap(0), Target(t), PrintingPolicy(LOpts), 445 Idents(idents), Selectors(sels), 446 BuiltinInfo(builtins), 447 DeclarationNames(*this), 448 ExternalSource(0), Listener(0), 449 Comments(SM), CommentsLoaded(false), 450 LastSDM(0, 0), 451 UniqueBlockByRefTypeID(0) 452{ 453 if (size_reserve > 0) Types.reserve(size_reserve); 454 TUDecl = TranslationUnitDecl::Create(*this); 455 456 if (!DelayInitialization) { 457 assert(t && "No target supplied for ASTContext initialization"); 458 InitBuiltinTypes(*t); 459 } 460} 461 462ASTContext::~ASTContext() { 463 // Release the DenseMaps associated with DeclContext objects. 464 // FIXME: Is this the ideal solution? 465 ReleaseDeclContextMaps(); 466 467 // Call all of the deallocation functions. 468 for (unsigned I = 0, N = Deallocations.size(); I != N; ++I) 469 Deallocations[I].first(Deallocations[I].second); 470 471 // ASTRecordLayout objects in ASTRecordLayouts must always be destroyed 472 // because they can contain DenseMaps. 473 for (llvm::DenseMap<const ObjCContainerDecl*, 474 const ASTRecordLayout*>::iterator 475 I = ObjCLayouts.begin(), E = ObjCLayouts.end(); I != E; ) 476 // Increment in loop to prevent using deallocated memory. 477 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 478 R->Destroy(*this); 479 480 for (llvm::DenseMap<const RecordDecl*, const ASTRecordLayout*>::iterator 481 I = ASTRecordLayouts.begin(), E = ASTRecordLayouts.end(); I != E; ) { 482 // Increment in loop to prevent using deallocated memory. 483 if (ASTRecordLayout *R = const_cast<ASTRecordLayout*>((I++)->second)) 484 R->Destroy(*this); 485 } 486 487 for (llvm::DenseMap<const Decl*, AttrVec*>::iterator A = DeclAttrs.begin(), 488 AEnd = DeclAttrs.end(); 489 A != AEnd; ++A) 490 A->second->~AttrVec(); 491} 492 493void ASTContext::AddDeallocation(void (*Callback)(void*), void *Data) { 494 Deallocations.push_back(std::make_pair(Callback, Data)); 495} 496 497void 498ASTContext::setExternalSource(OwningPtr<ExternalASTSource> &Source) { 499 ExternalSource.reset(Source.take()); 500} 501 502void ASTContext::PrintStats() const { 503 llvm::errs() << "\n*** AST Context Stats:\n"; 504 llvm::errs() << " " << Types.size() << " types total.\n"; 505 506 unsigned counts[] = { 507#define TYPE(Name, Parent) 0, 508#define ABSTRACT_TYPE(Name, Parent) 509#include "clang/AST/TypeNodes.def" 510 0 // Extra 511 }; 512 513 for (unsigned i = 0, e = Types.size(); i != e; ++i) { 514 Type *T = Types[i]; 515 counts[(unsigned)T->getTypeClass()]++; 516 } 517 518 unsigned Idx = 0; 519 unsigned TotalBytes = 0; 520#define TYPE(Name, Parent) \ 521 if (counts[Idx]) \ 522 llvm::errs() << " " << counts[Idx] << " " << #Name \ 523 << " types\n"; \ 524 TotalBytes += counts[Idx] * sizeof(Name##Type); \ 525 ++Idx; 526#define ABSTRACT_TYPE(Name, Parent) 527#include "clang/AST/TypeNodes.def" 528 529 llvm::errs() << "Total bytes = " << TotalBytes << "\n"; 530 531 // Implicit special member functions. 532 llvm::errs() << NumImplicitDefaultConstructorsDeclared << "/" 533 << NumImplicitDefaultConstructors 534 << " implicit default constructors created\n"; 535 llvm::errs() << NumImplicitCopyConstructorsDeclared << "/" 536 << NumImplicitCopyConstructors 537 << " implicit copy constructors created\n"; 538 if (getLangOpts().CPlusPlus) 539 llvm::errs() << NumImplicitMoveConstructorsDeclared << "/" 540 << NumImplicitMoveConstructors 541 << " implicit move constructors created\n"; 542 llvm::errs() << NumImplicitCopyAssignmentOperatorsDeclared << "/" 543 << NumImplicitCopyAssignmentOperators 544 << " implicit copy assignment operators created\n"; 545 if (getLangOpts().CPlusPlus) 546 llvm::errs() << NumImplicitMoveAssignmentOperatorsDeclared << "/" 547 << NumImplicitMoveAssignmentOperators 548 << " implicit move assignment operators created\n"; 549 llvm::errs() << NumImplicitDestructorsDeclared << "/" 550 << NumImplicitDestructors 551 << " implicit destructors created\n"; 552 553 if (ExternalSource.get()) { 554 llvm::errs() << "\n"; 555 ExternalSource->PrintStats(); 556 } 557 558 BumpAlloc.PrintStats(); 559} 560 561TypedefDecl *ASTContext::getInt128Decl() const { 562 if (!Int128Decl) { 563 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(Int128Ty); 564 Int128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 565 getTranslationUnitDecl(), 566 SourceLocation(), 567 SourceLocation(), 568 &Idents.get("__int128_t"), 569 TInfo); 570 } 571 572 return Int128Decl; 573} 574 575TypedefDecl *ASTContext::getUInt128Decl() const { 576 if (!UInt128Decl) { 577 TypeSourceInfo *TInfo = getTrivialTypeSourceInfo(UnsignedInt128Ty); 578 UInt128Decl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 579 getTranslationUnitDecl(), 580 SourceLocation(), 581 SourceLocation(), 582 &Idents.get("__uint128_t"), 583 TInfo); 584 } 585 586 return UInt128Decl; 587} 588 589void ASTContext::InitBuiltinType(CanQualType &R, BuiltinType::Kind K) { 590 BuiltinType *Ty = new (*this, TypeAlignment) BuiltinType(K); 591 R = CanQualType::CreateUnsafe(QualType(Ty, 0)); 592 Types.push_back(Ty); 593} 594 595void ASTContext::InitBuiltinTypes(const TargetInfo &Target) { 596 assert((!this->Target || this->Target == &Target) && 597 "Incorrect target reinitialization"); 598 assert(VoidTy.isNull() && "Context reinitialized?"); 599 600 this->Target = &Target; 601 602 ABI.reset(createCXXABI(Target)); 603 AddrSpaceMap = getAddressSpaceMap(Target, LangOpts); 604 605 // C99 6.2.5p19. 606 InitBuiltinType(VoidTy, BuiltinType::Void); 607 608 // C99 6.2.5p2. 609 InitBuiltinType(BoolTy, BuiltinType::Bool); 610 // C99 6.2.5p3. 611 if (LangOpts.CharIsSigned) 612 InitBuiltinType(CharTy, BuiltinType::Char_S); 613 else 614 InitBuiltinType(CharTy, BuiltinType::Char_U); 615 // C99 6.2.5p4. 616 InitBuiltinType(SignedCharTy, BuiltinType::SChar); 617 InitBuiltinType(ShortTy, BuiltinType::Short); 618 InitBuiltinType(IntTy, BuiltinType::Int); 619 InitBuiltinType(LongTy, BuiltinType::Long); 620 InitBuiltinType(LongLongTy, BuiltinType::LongLong); 621 622 // C99 6.2.5p6. 623 InitBuiltinType(UnsignedCharTy, BuiltinType::UChar); 624 InitBuiltinType(UnsignedShortTy, BuiltinType::UShort); 625 InitBuiltinType(UnsignedIntTy, BuiltinType::UInt); 626 InitBuiltinType(UnsignedLongTy, BuiltinType::ULong); 627 InitBuiltinType(UnsignedLongLongTy, BuiltinType::ULongLong); 628 629 // C99 6.2.5p10. 630 InitBuiltinType(FloatTy, BuiltinType::Float); 631 InitBuiltinType(DoubleTy, BuiltinType::Double); 632 InitBuiltinType(LongDoubleTy, BuiltinType::LongDouble); 633 634 // GNU extension, 128-bit integers. 635 InitBuiltinType(Int128Ty, BuiltinType::Int128); 636 InitBuiltinType(UnsignedInt128Ty, BuiltinType::UInt128); 637 638 if (LangOpts.CPlusPlus) { // C++ 3.9.1p5 639 if (TargetInfo::isTypeSigned(Target.getWCharType())) 640 InitBuiltinType(WCharTy, BuiltinType::WChar_S); 641 else // -fshort-wchar makes wchar_t be unsigned. 642 InitBuiltinType(WCharTy, BuiltinType::WChar_U); 643 } else // C99 644 WCharTy = getFromTargetType(Target.getWCharType()); 645 646 WIntTy = getFromTargetType(Target.getWIntType()); 647 648 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 649 InitBuiltinType(Char16Ty, BuiltinType::Char16); 650 else // C99 651 Char16Ty = getFromTargetType(Target.getChar16Type()); 652 653 if (LangOpts.CPlusPlus) // C++0x 3.9.1p5, extension for C++ 654 InitBuiltinType(Char32Ty, BuiltinType::Char32); 655 else // C99 656 Char32Ty = getFromTargetType(Target.getChar32Type()); 657 658 // Placeholder type for type-dependent expressions whose type is 659 // completely unknown. No code should ever check a type against 660 // DependentTy and users should never see it; however, it is here to 661 // help diagnose failures to properly check for type-dependent 662 // expressions. 663 InitBuiltinType(DependentTy, BuiltinType::Dependent); 664 665 // Placeholder type for functions. 666 InitBuiltinType(OverloadTy, BuiltinType::Overload); 667 668 // Placeholder type for bound members. 669 InitBuiltinType(BoundMemberTy, BuiltinType::BoundMember); 670 671 // Placeholder type for pseudo-objects. 672 InitBuiltinType(PseudoObjectTy, BuiltinType::PseudoObject); 673 674 // "any" type; useful for debugger-like clients. 675 InitBuiltinType(UnknownAnyTy, BuiltinType::UnknownAny); 676 677 // Placeholder type for unbridged ARC casts. 678 InitBuiltinType(ARCUnbridgedCastTy, BuiltinType::ARCUnbridgedCast); 679 680 // C99 6.2.5p11. 681 FloatComplexTy = getComplexType(FloatTy); 682 DoubleComplexTy = getComplexType(DoubleTy); 683 LongDoubleComplexTy = getComplexType(LongDoubleTy); 684 685 // Builtin types for 'id', 'Class', and 'SEL'. 686 InitBuiltinType(ObjCBuiltinIdTy, BuiltinType::ObjCId); 687 InitBuiltinType(ObjCBuiltinClassTy, BuiltinType::ObjCClass); 688 InitBuiltinType(ObjCBuiltinSelTy, BuiltinType::ObjCSel); 689 690 // Builtin type for __objc_yes and __objc_no 691 ObjCBuiltinBoolTy = (Target.useSignedCharForObjCBool() ? 692 SignedCharTy : BoolTy); 693 694 ObjCConstantStringType = QualType(); 695 696 // void * type 697 VoidPtrTy = getPointerType(VoidTy); 698 699 // nullptr type (C++0x 2.14.7) 700 InitBuiltinType(NullPtrTy, BuiltinType::NullPtr); 701 702 // half type (OpenCL 6.1.1.1) / ARM NEON __fp16 703 InitBuiltinType(HalfTy, BuiltinType::Half); 704 705 // Builtin type used to help define __builtin_va_list. 706 VaListTagTy = QualType(); 707} 708 709DiagnosticsEngine &ASTContext::getDiagnostics() const { 710 return SourceMgr.getDiagnostics(); 711} 712 713AttrVec& ASTContext::getDeclAttrs(const Decl *D) { 714 AttrVec *&Result = DeclAttrs[D]; 715 if (!Result) { 716 void *Mem = Allocate(sizeof(AttrVec)); 717 Result = new (Mem) AttrVec; 718 } 719 720 return *Result; 721} 722 723/// \brief Erase the attributes corresponding to the given declaration. 724void ASTContext::eraseDeclAttrs(const Decl *D) { 725 llvm::DenseMap<const Decl*, AttrVec*>::iterator Pos = DeclAttrs.find(D); 726 if (Pos != DeclAttrs.end()) { 727 Pos->second->~AttrVec(); 728 DeclAttrs.erase(Pos); 729 } 730} 731 732MemberSpecializationInfo * 733ASTContext::getInstantiatedFromStaticDataMember(const VarDecl *Var) { 734 assert(Var->isStaticDataMember() && "Not a static data member"); 735 llvm::DenseMap<const VarDecl *, MemberSpecializationInfo *>::iterator Pos 736 = InstantiatedFromStaticDataMember.find(Var); 737 if (Pos == InstantiatedFromStaticDataMember.end()) 738 return 0; 739 740 return Pos->second; 741} 742 743void 744ASTContext::setInstantiatedFromStaticDataMember(VarDecl *Inst, VarDecl *Tmpl, 745 TemplateSpecializationKind TSK, 746 SourceLocation PointOfInstantiation) { 747 assert(Inst->isStaticDataMember() && "Not a static data member"); 748 assert(Tmpl->isStaticDataMember() && "Not a static data member"); 749 assert(!InstantiatedFromStaticDataMember[Inst] && 750 "Already noted what static data member was instantiated from"); 751 InstantiatedFromStaticDataMember[Inst] 752 = new (*this) MemberSpecializationInfo(Tmpl, TSK, PointOfInstantiation); 753} 754 755FunctionDecl *ASTContext::getClassScopeSpecializationPattern( 756 const FunctionDecl *FD){ 757 assert(FD && "Specialization is 0"); 758 llvm::DenseMap<const FunctionDecl*, FunctionDecl *>::const_iterator Pos 759 = ClassScopeSpecializationPattern.find(FD); 760 if (Pos == ClassScopeSpecializationPattern.end()) 761 return 0; 762 763 return Pos->second; 764} 765 766void ASTContext::setClassScopeSpecializationPattern(FunctionDecl *FD, 767 FunctionDecl *Pattern) { 768 assert(FD && "Specialization is 0"); 769 assert(Pattern && "Class scope specialization pattern is 0"); 770 ClassScopeSpecializationPattern[FD] = Pattern; 771} 772 773NamedDecl * 774ASTContext::getInstantiatedFromUsingDecl(UsingDecl *UUD) { 775 llvm::DenseMap<UsingDecl *, NamedDecl *>::const_iterator Pos 776 = InstantiatedFromUsingDecl.find(UUD); 777 if (Pos == InstantiatedFromUsingDecl.end()) 778 return 0; 779 780 return Pos->second; 781} 782 783void 784ASTContext::setInstantiatedFromUsingDecl(UsingDecl *Inst, NamedDecl *Pattern) { 785 assert((isa<UsingDecl>(Pattern) || 786 isa<UnresolvedUsingValueDecl>(Pattern) || 787 isa<UnresolvedUsingTypenameDecl>(Pattern)) && 788 "pattern decl is not a using decl"); 789 assert(!InstantiatedFromUsingDecl[Inst] && "pattern already exists"); 790 InstantiatedFromUsingDecl[Inst] = Pattern; 791} 792 793UsingShadowDecl * 794ASTContext::getInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst) { 795 llvm::DenseMap<UsingShadowDecl*, UsingShadowDecl*>::const_iterator Pos 796 = InstantiatedFromUsingShadowDecl.find(Inst); 797 if (Pos == InstantiatedFromUsingShadowDecl.end()) 798 return 0; 799 800 return Pos->second; 801} 802 803void 804ASTContext::setInstantiatedFromUsingShadowDecl(UsingShadowDecl *Inst, 805 UsingShadowDecl *Pattern) { 806 assert(!InstantiatedFromUsingShadowDecl[Inst] && "pattern already exists"); 807 InstantiatedFromUsingShadowDecl[Inst] = Pattern; 808} 809 810FieldDecl *ASTContext::getInstantiatedFromUnnamedFieldDecl(FieldDecl *Field) { 811 llvm::DenseMap<FieldDecl *, FieldDecl *>::iterator Pos 812 = InstantiatedFromUnnamedFieldDecl.find(Field); 813 if (Pos == InstantiatedFromUnnamedFieldDecl.end()) 814 return 0; 815 816 return Pos->second; 817} 818 819void ASTContext::setInstantiatedFromUnnamedFieldDecl(FieldDecl *Inst, 820 FieldDecl *Tmpl) { 821 assert(!Inst->getDeclName() && "Instantiated field decl is not unnamed"); 822 assert(!Tmpl->getDeclName() && "Template field decl is not unnamed"); 823 assert(!InstantiatedFromUnnamedFieldDecl[Inst] && 824 "Already noted what unnamed field was instantiated from"); 825 826 InstantiatedFromUnnamedFieldDecl[Inst] = Tmpl; 827} 828 829bool ASTContext::ZeroBitfieldFollowsNonBitfield(const FieldDecl *FD, 830 const FieldDecl *LastFD) const { 831 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 832 FD->getBitWidthValue(*this) == 0); 833} 834 835bool ASTContext::ZeroBitfieldFollowsBitfield(const FieldDecl *FD, 836 const FieldDecl *LastFD) const { 837 return (FD->isBitField() && LastFD && LastFD->isBitField() && 838 FD->getBitWidthValue(*this) == 0 && 839 LastFD->getBitWidthValue(*this) != 0); 840} 841 842bool ASTContext::BitfieldFollowsBitfield(const FieldDecl *FD, 843 const FieldDecl *LastFD) const { 844 return (FD->isBitField() && LastFD && LastFD->isBitField() && 845 FD->getBitWidthValue(*this) && 846 LastFD->getBitWidthValue(*this)); 847} 848 849bool ASTContext::NonBitfieldFollowsBitfield(const FieldDecl *FD, 850 const FieldDecl *LastFD) const { 851 return (!FD->isBitField() && LastFD && LastFD->isBitField() && 852 LastFD->getBitWidthValue(*this)); 853} 854 855bool ASTContext::BitfieldFollowsNonBitfield(const FieldDecl *FD, 856 const FieldDecl *LastFD) const { 857 return (FD->isBitField() && LastFD && !LastFD->isBitField() && 858 FD->getBitWidthValue(*this)); 859} 860 861ASTContext::overridden_cxx_method_iterator 862ASTContext::overridden_methods_begin(const CXXMethodDecl *Method) const { 863 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 864 = OverriddenMethods.find(Method); 865 if (Pos == OverriddenMethods.end()) 866 return 0; 867 868 return Pos->second.begin(); 869} 870 871ASTContext::overridden_cxx_method_iterator 872ASTContext::overridden_methods_end(const CXXMethodDecl *Method) const { 873 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 874 = OverriddenMethods.find(Method); 875 if (Pos == OverriddenMethods.end()) 876 return 0; 877 878 return Pos->second.end(); 879} 880 881unsigned 882ASTContext::overridden_methods_size(const CXXMethodDecl *Method) const { 883 llvm::DenseMap<const CXXMethodDecl *, CXXMethodVector>::const_iterator Pos 884 = OverriddenMethods.find(Method); 885 if (Pos == OverriddenMethods.end()) 886 return 0; 887 888 return Pos->second.size(); 889} 890 891void ASTContext::addOverriddenMethod(const CXXMethodDecl *Method, 892 const CXXMethodDecl *Overridden) { 893 OverriddenMethods[Method].push_back(Overridden); 894} 895 896void ASTContext::addedLocalImportDecl(ImportDecl *Import) { 897 assert(!Import->NextLocalImport && "Import declaration already in the chain"); 898 assert(!Import->isFromASTFile() && "Non-local import declaration"); 899 if (!FirstLocalImport) { 900 FirstLocalImport = Import; 901 LastLocalImport = Import; 902 return; 903 } 904 905 LastLocalImport->NextLocalImport = Import; 906 LastLocalImport = Import; 907} 908 909//===----------------------------------------------------------------------===// 910// Type Sizing and Analysis 911//===----------------------------------------------------------------------===// 912 913/// getFloatTypeSemantics - Return the APFloat 'semantics' for the specified 914/// scalar floating point type. 915const llvm::fltSemantics &ASTContext::getFloatTypeSemantics(QualType T) const { 916 const BuiltinType *BT = T->getAs<BuiltinType>(); 917 assert(BT && "Not a floating point type!"); 918 switch (BT->getKind()) { 919 default: llvm_unreachable("Not a floating point type!"); 920 case BuiltinType::Half: return Target->getHalfFormat(); 921 case BuiltinType::Float: return Target->getFloatFormat(); 922 case BuiltinType::Double: return Target->getDoubleFormat(); 923 case BuiltinType::LongDouble: return Target->getLongDoubleFormat(); 924 } 925} 926 927/// getDeclAlign - Return a conservative estimate of the alignment of the 928/// specified decl. Note that bitfields do not have a valid alignment, so 929/// this method will assert on them. 930/// If @p RefAsPointee, references are treated like their underlying type 931/// (for alignof), else they're treated like pointers (for CodeGen). 932CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const { 933 unsigned Align = Target->getCharWidth(); 934 935 bool UseAlignAttrOnly = false; 936 if (unsigned AlignFromAttr = D->getMaxAlignment()) { 937 Align = AlignFromAttr; 938 939 // __attribute__((aligned)) can increase or decrease alignment 940 // *except* on a struct or struct member, where it only increases 941 // alignment unless 'packed' is also specified. 942 // 943 // It is an error for alignas to decrease alignment, so we can 944 // ignore that possibility; Sema should diagnose it. 945 if (isa<FieldDecl>(D)) { 946 UseAlignAttrOnly = D->hasAttr<PackedAttr>() || 947 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 948 } else { 949 UseAlignAttrOnly = true; 950 } 951 } 952 else if (isa<FieldDecl>(D)) 953 UseAlignAttrOnly = 954 D->hasAttr<PackedAttr>() || 955 cast<FieldDecl>(D)->getParent()->hasAttr<PackedAttr>(); 956 957 // If we're using the align attribute only, just ignore everything 958 // else about the declaration and its type. 959 if (UseAlignAttrOnly) { 960 // do nothing 961 962 } else if (const ValueDecl *VD = dyn_cast<ValueDecl>(D)) { 963 QualType T = VD->getType(); 964 if (const ReferenceType* RT = T->getAs<ReferenceType>()) { 965 if (RefAsPointee) 966 T = RT->getPointeeType(); 967 else 968 T = getPointerType(RT->getPointeeType()); 969 } 970 if (!T->isIncompleteType() && !T->isFunctionType()) { 971 // Adjust alignments of declarations with array type by the 972 // large-array alignment on the target. 973 unsigned MinWidth = Target->getLargeArrayMinWidth(); 974 const ArrayType *arrayType; 975 if (MinWidth && (arrayType = getAsArrayType(T))) { 976 if (isa<VariableArrayType>(arrayType)) 977 Align = std::max(Align, Target->getLargeArrayAlign()); 978 else if (isa<ConstantArrayType>(arrayType) && 979 MinWidth <= getTypeSize(cast<ConstantArrayType>(arrayType))) 980 Align = std::max(Align, Target->getLargeArrayAlign()); 981 982 // Walk through any array types while we're at it. 983 T = getBaseElementType(arrayType); 984 } 985 Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr())); 986 } 987 988 // Fields can be subject to extra alignment constraints, like if 989 // the field is packed, the struct is packed, or the struct has a 990 // a max-field-alignment constraint (#pragma pack). So calculate 991 // the actual alignment of the field within the struct, and then 992 // (as we're expected to) constrain that by the alignment of the type. 993 if (const FieldDecl *field = dyn_cast<FieldDecl>(VD)) { 994 // So calculate the alignment of the field. 995 const ASTRecordLayout &layout = getASTRecordLayout(field->getParent()); 996 997 // Start with the record's overall alignment. 998 unsigned fieldAlign = toBits(layout.getAlignment()); 999 1000 // Use the GCD of that and the offset within the record. 1001 uint64_t offset = layout.getFieldOffset(field->getFieldIndex()); 1002 if (offset > 0) { 1003 // Alignment is always a power of 2, so the GCD will be a power of 2, 1004 // which means we get to do this crazy thing instead of Euclid's. 1005 uint64_t lowBitOfOffset = offset & (~offset + 1); 1006 if (lowBitOfOffset < fieldAlign) 1007 fieldAlign = static_cast<unsigned>(lowBitOfOffset); 1008 } 1009 1010 Align = std::min(Align, fieldAlign); 1011 } 1012 } 1013 1014 return toCharUnitsFromBits(Align); 1015} 1016 1017std::pair<CharUnits, CharUnits> 1018ASTContext::getTypeInfoInChars(const Type *T) const { 1019 std::pair<uint64_t, unsigned> Info = getTypeInfo(T); 1020 return std::make_pair(toCharUnitsFromBits(Info.first), 1021 toCharUnitsFromBits(Info.second)); 1022} 1023 1024std::pair<CharUnits, CharUnits> 1025ASTContext::getTypeInfoInChars(QualType T) const { 1026 return getTypeInfoInChars(T.getTypePtr()); 1027} 1028 1029std::pair<uint64_t, unsigned> ASTContext::getTypeInfo(const Type *T) const { 1030 TypeInfoMap::iterator it = MemoizedTypeInfo.find(T); 1031 if (it != MemoizedTypeInfo.end()) 1032 return it->second; 1033 1034 std::pair<uint64_t, unsigned> Info = getTypeInfoImpl(T); 1035 MemoizedTypeInfo.insert(std::make_pair(T, Info)); 1036 return Info; 1037} 1038 1039/// getTypeInfoImpl - Return the size of the specified type, in bits. This 1040/// method does not work on incomplete types. 1041/// 1042/// FIXME: Pointers into different addr spaces could have different sizes and 1043/// alignment requirements: getPointerInfo should take an AddrSpace, this 1044/// should take a QualType, &c. 1045std::pair<uint64_t, unsigned> 1046ASTContext::getTypeInfoImpl(const Type *T) const { 1047 uint64_t Width=0; 1048 unsigned Align=8; 1049 switch (T->getTypeClass()) { 1050#define TYPE(Class, Base) 1051#define ABSTRACT_TYPE(Class, Base) 1052#define NON_CANONICAL_TYPE(Class, Base) 1053#define DEPENDENT_TYPE(Class, Base) case Type::Class: 1054#include "clang/AST/TypeNodes.def" 1055 llvm_unreachable("Should not see dependent types"); 1056 1057 case Type::FunctionNoProto: 1058 case Type::FunctionProto: 1059 // GCC extension: alignof(function) = 32 bits 1060 Width = 0; 1061 Align = 32; 1062 break; 1063 1064 case Type::IncompleteArray: 1065 case Type::VariableArray: 1066 Width = 0; 1067 Align = getTypeAlign(cast<ArrayType>(T)->getElementType()); 1068 break; 1069 1070 case Type::ConstantArray: { 1071 const ConstantArrayType *CAT = cast<ConstantArrayType>(T); 1072 1073 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(CAT->getElementType()); 1074 uint64_t Size = CAT->getSize().getZExtValue(); 1075 assert((Size == 0 || EltInfo.first <= (uint64_t)(-1)/Size) && 1076 "Overflow in array type bit size evaluation"); 1077 Width = EltInfo.first*Size; 1078 Align = EltInfo.second; 1079 Width = llvm::RoundUpToAlignment(Width, Align); 1080 break; 1081 } 1082 case Type::ExtVector: 1083 case Type::Vector: { 1084 const VectorType *VT = cast<VectorType>(T); 1085 std::pair<uint64_t, unsigned> EltInfo = getTypeInfo(VT->getElementType()); 1086 Width = EltInfo.first*VT->getNumElements(); 1087 Align = Width; 1088 // If the alignment is not a power of 2, round up to the next power of 2. 1089 // This happens for non-power-of-2 length vectors. 1090 if (Align & (Align-1)) { 1091 Align = llvm::NextPowerOf2(Align); 1092 Width = llvm::RoundUpToAlignment(Width, Align); 1093 } 1094 // Adjust the alignment based on the target max. 1095 uint64_t TargetVectorAlign = Target->getMaxVectorAlign(); 1096 if (TargetVectorAlign && TargetVectorAlign < Align) 1097 Align = TargetVectorAlign; 1098 break; 1099 } 1100 1101 case Type::Builtin: 1102 switch (cast<BuiltinType>(T)->getKind()) { 1103 default: llvm_unreachable("Unknown builtin type!"); 1104 case BuiltinType::Void: 1105 // GCC extension: alignof(void) = 8 bits. 1106 Width = 0; 1107 Align = 8; 1108 break; 1109 1110 case BuiltinType::Bool: 1111 Width = Target->getBoolWidth(); 1112 Align = Target->getBoolAlign(); 1113 break; 1114 case BuiltinType::Char_S: 1115 case BuiltinType::Char_U: 1116 case BuiltinType::UChar: 1117 case BuiltinType::SChar: 1118 Width = Target->getCharWidth(); 1119 Align = Target->getCharAlign(); 1120 break; 1121 case BuiltinType::WChar_S: 1122 case BuiltinType::WChar_U: 1123 Width = Target->getWCharWidth(); 1124 Align = Target->getWCharAlign(); 1125 break; 1126 case BuiltinType::Char16: 1127 Width = Target->getChar16Width(); 1128 Align = Target->getChar16Align(); 1129 break; 1130 case BuiltinType::Char32: 1131 Width = Target->getChar32Width(); 1132 Align = Target->getChar32Align(); 1133 break; 1134 case BuiltinType::UShort: 1135 case BuiltinType::Short: 1136 Width = Target->getShortWidth(); 1137 Align = Target->getShortAlign(); 1138 break; 1139 case BuiltinType::UInt: 1140 case BuiltinType::Int: 1141 Width = Target->getIntWidth(); 1142 Align = Target->getIntAlign(); 1143 break; 1144 case BuiltinType::ULong: 1145 case BuiltinType::Long: 1146 Width = Target->getLongWidth(); 1147 Align = Target->getLongAlign(); 1148 break; 1149 case BuiltinType::ULongLong: 1150 case BuiltinType::LongLong: 1151 Width = Target->getLongLongWidth(); 1152 Align = Target->getLongLongAlign(); 1153 break; 1154 case BuiltinType::Int128: 1155 case BuiltinType::UInt128: 1156 Width = 128; 1157 Align = 128; // int128_t is 128-bit aligned on all targets. 1158 break; 1159 case BuiltinType::Half: 1160 Width = Target->getHalfWidth(); 1161 Align = Target->getHalfAlign(); 1162 break; 1163 case BuiltinType::Float: 1164 Width = Target->getFloatWidth(); 1165 Align = Target->getFloatAlign(); 1166 break; 1167 case BuiltinType::Double: 1168 Width = Target->getDoubleWidth(); 1169 Align = Target->getDoubleAlign(); 1170 break; 1171 case BuiltinType::LongDouble: 1172 Width = Target->getLongDoubleWidth(); 1173 Align = Target->getLongDoubleAlign(); 1174 break; 1175 case BuiltinType::NullPtr: 1176 Width = Target->getPointerWidth(0); // C++ 3.9.1p11: sizeof(nullptr_t) 1177 Align = Target->getPointerAlign(0); // == sizeof(void*) 1178 break; 1179 case BuiltinType::ObjCId: 1180 case BuiltinType::ObjCClass: 1181 case BuiltinType::ObjCSel: 1182 Width = Target->getPointerWidth(0); 1183 Align = Target->getPointerAlign(0); 1184 break; 1185 } 1186 break; 1187 case Type::ObjCObjectPointer: 1188 Width = Target->getPointerWidth(0); 1189 Align = Target->getPointerAlign(0); 1190 break; 1191 case Type::BlockPointer: { 1192 unsigned AS = getTargetAddressSpace( 1193 cast<BlockPointerType>(T)->getPointeeType()); 1194 Width = Target->getPointerWidth(AS); 1195 Align = Target->getPointerAlign(AS); 1196 break; 1197 } 1198 case Type::LValueReference: 1199 case Type::RValueReference: { 1200 // alignof and sizeof should never enter this code path here, so we go 1201 // the pointer route. 1202 unsigned AS = getTargetAddressSpace( 1203 cast<ReferenceType>(T)->getPointeeType()); 1204 Width = Target->getPointerWidth(AS); 1205 Align = Target->getPointerAlign(AS); 1206 break; 1207 } 1208 case Type::Pointer: { 1209 unsigned AS = getTargetAddressSpace(cast<PointerType>(T)->getPointeeType()); 1210 Width = Target->getPointerWidth(AS); 1211 Align = Target->getPointerAlign(AS); 1212 break; 1213 } 1214 case Type::MemberPointer: { 1215 const MemberPointerType *MPT = cast<MemberPointerType>(T); 1216 std::pair<uint64_t, unsigned> PtrDiffInfo = 1217 getTypeInfo(getPointerDiffType()); 1218 Width = PtrDiffInfo.first * ABI->getMemberPointerSize(MPT); 1219 Align = PtrDiffInfo.second; 1220 break; 1221 } 1222 case Type::Complex: { 1223 // Complex types have the same alignment as their elements, but twice the 1224 // size. 1225 std::pair<uint64_t, unsigned> EltInfo = 1226 getTypeInfo(cast<ComplexType>(T)->getElementType()); 1227 Width = EltInfo.first*2; 1228 Align = EltInfo.second; 1229 break; 1230 } 1231 case Type::ObjCObject: 1232 return getTypeInfo(cast<ObjCObjectType>(T)->getBaseType().getTypePtr()); 1233 case Type::ObjCInterface: { 1234 const ObjCInterfaceType *ObjCI = cast<ObjCInterfaceType>(T); 1235 const ASTRecordLayout &Layout = getASTObjCInterfaceLayout(ObjCI->getDecl()); 1236 Width = toBits(Layout.getSize()); 1237 Align = toBits(Layout.getAlignment()); 1238 break; 1239 } 1240 case Type::Record: 1241 case Type::Enum: { 1242 const TagType *TT = cast<TagType>(T); 1243 1244 if (TT->getDecl()->isInvalidDecl()) { 1245 Width = 8; 1246 Align = 8; 1247 break; 1248 } 1249 1250 if (const EnumType *ET = dyn_cast<EnumType>(TT)) 1251 return getTypeInfo(ET->getDecl()->getIntegerType()); 1252 1253 const RecordType *RT = cast<RecordType>(TT); 1254 const ASTRecordLayout &Layout = getASTRecordLayout(RT->getDecl()); 1255 Width = toBits(Layout.getSize()); 1256 Align = toBits(Layout.getAlignment()); 1257 break; 1258 } 1259 1260 case Type::SubstTemplateTypeParm: 1261 return getTypeInfo(cast<SubstTemplateTypeParmType>(T)-> 1262 getReplacementType().getTypePtr()); 1263 1264 case Type::Auto: { 1265 const AutoType *A = cast<AutoType>(T); 1266 assert(A->isDeduced() && "Cannot request the size of a dependent type"); 1267 return getTypeInfo(A->getDeducedType().getTypePtr()); 1268 } 1269 1270 case Type::Paren: 1271 return getTypeInfo(cast<ParenType>(T)->getInnerType().getTypePtr()); 1272 1273 case Type::Typedef: { 1274 const TypedefNameDecl *Typedef = cast<TypedefType>(T)->getDecl(); 1275 std::pair<uint64_t, unsigned> Info 1276 = getTypeInfo(Typedef->getUnderlyingType().getTypePtr()); 1277 // If the typedef has an aligned attribute on it, it overrides any computed 1278 // alignment we have. This violates the GCC documentation (which says that 1279 // attribute(aligned) can only round up) but matches its implementation. 1280 if (unsigned AttrAlign = Typedef->getMaxAlignment()) 1281 Align = AttrAlign; 1282 else 1283 Align = Info.second; 1284 Width = Info.first; 1285 break; 1286 } 1287 1288 case Type::TypeOfExpr: 1289 return getTypeInfo(cast<TypeOfExprType>(T)->getUnderlyingExpr()->getType() 1290 .getTypePtr()); 1291 1292 case Type::TypeOf: 1293 return getTypeInfo(cast<TypeOfType>(T)->getUnderlyingType().getTypePtr()); 1294 1295 case Type::Decltype: 1296 return getTypeInfo(cast<DecltypeType>(T)->getUnderlyingExpr()->getType() 1297 .getTypePtr()); 1298 1299 case Type::UnaryTransform: 1300 return getTypeInfo(cast<UnaryTransformType>(T)->getUnderlyingType()); 1301 1302 case Type::Elaborated: 1303 return getTypeInfo(cast<ElaboratedType>(T)->getNamedType().getTypePtr()); 1304 1305 case Type::Attributed: 1306 return getTypeInfo( 1307 cast<AttributedType>(T)->getEquivalentType().getTypePtr()); 1308 1309 case Type::TemplateSpecialization: { 1310 assert(getCanonicalType(T) != T && 1311 "Cannot request the size of a dependent type"); 1312 const TemplateSpecializationType *TST = cast<TemplateSpecializationType>(T); 1313 // A type alias template specialization may refer to a typedef with the 1314 // aligned attribute on it. 1315 if (TST->isTypeAlias()) 1316 return getTypeInfo(TST->getAliasedType().getTypePtr()); 1317 else 1318 return getTypeInfo(getCanonicalType(T)); 1319 } 1320 1321 case Type::Atomic: { 1322 std::pair<uint64_t, unsigned> Info 1323 = getTypeInfo(cast<AtomicType>(T)->getValueType()); 1324 Width = Info.first; 1325 Align = Info.second; 1326 if (Width != 0 && Width <= Target->getMaxAtomicPromoteWidth() && 1327 llvm::isPowerOf2_64(Width)) { 1328 // We can potentially perform lock-free atomic operations for this 1329 // type; promote the alignment appropriately. 1330 // FIXME: We could potentially promote the width here as well... 1331 // is that worthwhile? (Non-struct atomic types generally have 1332 // power-of-two size anyway, but structs might not. Requires a bit 1333 // of implementation work to make sure we zero out the extra bits.) 1334 Align = static_cast<unsigned>(Width); 1335 } 1336 } 1337 1338 } 1339 1340 assert(llvm::isPowerOf2_32(Align) && "Alignment must be power of 2"); 1341 return std::make_pair(Width, Align); 1342} 1343 1344/// toCharUnitsFromBits - Convert a size in bits to a size in characters. 1345CharUnits ASTContext::toCharUnitsFromBits(int64_t BitSize) const { 1346 return CharUnits::fromQuantity(BitSize / getCharWidth()); 1347} 1348 1349/// toBits - Convert a size in characters to a size in characters. 1350int64_t ASTContext::toBits(CharUnits CharSize) const { 1351 return CharSize.getQuantity() * getCharWidth(); 1352} 1353 1354/// getTypeSizeInChars - Return the size of the specified type, in characters. 1355/// This method does not work on incomplete types. 1356CharUnits ASTContext::getTypeSizeInChars(QualType T) const { 1357 return toCharUnitsFromBits(getTypeSize(T)); 1358} 1359CharUnits ASTContext::getTypeSizeInChars(const Type *T) const { 1360 return toCharUnitsFromBits(getTypeSize(T)); 1361} 1362 1363/// getTypeAlignInChars - Return the ABI-specified alignment of a type, in 1364/// characters. This method does not work on incomplete types. 1365CharUnits ASTContext::getTypeAlignInChars(QualType T) const { 1366 return toCharUnitsFromBits(getTypeAlign(T)); 1367} 1368CharUnits ASTContext::getTypeAlignInChars(const Type *T) const { 1369 return toCharUnitsFromBits(getTypeAlign(T)); 1370} 1371 1372/// getPreferredTypeAlign - Return the "preferred" alignment of the specified 1373/// type for the current target in bits. This can be different than the ABI 1374/// alignment in cases where it is beneficial for performance to overalign 1375/// a data type. 1376unsigned ASTContext::getPreferredTypeAlign(const Type *T) const { 1377 unsigned ABIAlign = getTypeAlign(T); 1378 1379 // Double and long long should be naturally aligned if possible. 1380 if (const ComplexType* CT = T->getAs<ComplexType>()) 1381 T = CT->getElementType().getTypePtr(); 1382 if (T->isSpecificBuiltinType(BuiltinType::Double) || 1383 T->isSpecificBuiltinType(BuiltinType::LongLong) || 1384 T->isSpecificBuiltinType(BuiltinType::ULongLong)) 1385 return std::max(ABIAlign, (unsigned)getTypeSize(T)); 1386 1387 return ABIAlign; 1388} 1389 1390/// DeepCollectObjCIvars - 1391/// This routine first collects all declared, but not synthesized, ivars in 1392/// super class and then collects all ivars, including those synthesized for 1393/// current class. This routine is used for implementation of current class 1394/// when all ivars, declared and synthesized are known. 1395/// 1396void ASTContext::DeepCollectObjCIvars(const ObjCInterfaceDecl *OI, 1397 bool leafClass, 1398 SmallVectorImpl<const ObjCIvarDecl*> &Ivars) const { 1399 if (const ObjCInterfaceDecl *SuperClass = OI->getSuperClass()) 1400 DeepCollectObjCIvars(SuperClass, false, Ivars); 1401 if (!leafClass) { 1402 for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(), 1403 E = OI->ivar_end(); I != E; ++I) 1404 Ivars.push_back(*I); 1405 } else { 1406 ObjCInterfaceDecl *IDecl = const_cast<ObjCInterfaceDecl *>(OI); 1407 for (const ObjCIvarDecl *Iv = IDecl->all_declared_ivar_begin(); Iv; 1408 Iv= Iv->getNextIvar()) 1409 Ivars.push_back(Iv); 1410 } 1411} 1412 1413/// CollectInheritedProtocols - Collect all protocols in current class and 1414/// those inherited by it. 1415void ASTContext::CollectInheritedProtocols(const Decl *CDecl, 1416 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> &Protocols) { 1417 if (const ObjCInterfaceDecl *OI = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1418 // We can use protocol_iterator here instead of 1419 // all_referenced_protocol_iterator since we are walking all categories. 1420 for (ObjCInterfaceDecl::all_protocol_iterator P = OI->all_referenced_protocol_begin(), 1421 PE = OI->all_referenced_protocol_end(); P != PE; ++P) { 1422 ObjCProtocolDecl *Proto = (*P); 1423 Protocols.insert(Proto->getCanonicalDecl()); 1424 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1425 PE = Proto->protocol_end(); P != PE; ++P) { 1426 Protocols.insert((*P)->getCanonicalDecl()); 1427 CollectInheritedProtocols(*P, Protocols); 1428 } 1429 } 1430 1431 // Categories of this Interface. 1432 for (const ObjCCategoryDecl *CDeclChain = OI->getCategoryList(); 1433 CDeclChain; CDeclChain = CDeclChain->getNextClassCategory()) 1434 CollectInheritedProtocols(CDeclChain, Protocols); 1435 if (ObjCInterfaceDecl *SD = OI->getSuperClass()) 1436 while (SD) { 1437 CollectInheritedProtocols(SD, Protocols); 1438 SD = SD->getSuperClass(); 1439 } 1440 } else if (const ObjCCategoryDecl *OC = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1441 for (ObjCCategoryDecl::protocol_iterator P = OC->protocol_begin(), 1442 PE = OC->protocol_end(); P != PE; ++P) { 1443 ObjCProtocolDecl *Proto = (*P); 1444 Protocols.insert(Proto->getCanonicalDecl()); 1445 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1446 PE = Proto->protocol_end(); P != PE; ++P) 1447 CollectInheritedProtocols(*P, Protocols); 1448 } 1449 } else if (const ObjCProtocolDecl *OP = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1450 for (ObjCProtocolDecl::protocol_iterator P = OP->protocol_begin(), 1451 PE = OP->protocol_end(); P != PE; ++P) { 1452 ObjCProtocolDecl *Proto = (*P); 1453 Protocols.insert(Proto->getCanonicalDecl()); 1454 for (ObjCProtocolDecl::protocol_iterator P = Proto->protocol_begin(), 1455 PE = Proto->protocol_end(); P != PE; ++P) 1456 CollectInheritedProtocols(*P, Protocols); 1457 } 1458 } 1459} 1460 1461unsigned ASTContext::CountNonClassIvars(const ObjCInterfaceDecl *OI) const { 1462 unsigned count = 0; 1463 // Count ivars declared in class extension. 1464 for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl; 1465 CDecl = CDecl->getNextClassExtension()) 1466 count += CDecl->ivar_size(); 1467 1468 // Count ivar defined in this class's implementation. This 1469 // includes synthesized ivars. 1470 if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) 1471 count += ImplDecl->ivar_size(); 1472 1473 return count; 1474} 1475 1476bool ASTContext::isSentinelNullExpr(const Expr *E) { 1477 if (!E) 1478 return false; 1479 1480 // nullptr_t is always treated as null. 1481 if (E->getType()->isNullPtrType()) return true; 1482 1483 if (E->getType()->isAnyPointerType() && 1484 E->IgnoreParenCasts()->isNullPointerConstant(*this, 1485 Expr::NPC_ValueDependentIsNull)) 1486 return true; 1487 1488 // Unfortunately, __null has type 'int'. 1489 if (isa<GNUNullExpr>(E)) return true; 1490 1491 return false; 1492} 1493 1494/// \brief Get the implementation of ObjCInterfaceDecl,or NULL if none exists. 1495ObjCImplementationDecl *ASTContext::getObjCImplementation(ObjCInterfaceDecl *D) { 1496 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1497 I = ObjCImpls.find(D); 1498 if (I != ObjCImpls.end()) 1499 return cast<ObjCImplementationDecl>(I->second); 1500 return 0; 1501} 1502/// \brief Get the implementation of ObjCCategoryDecl, or NULL if none exists. 1503ObjCCategoryImplDecl *ASTContext::getObjCImplementation(ObjCCategoryDecl *D) { 1504 llvm::DenseMap<ObjCContainerDecl*, ObjCImplDecl*>::iterator 1505 I = ObjCImpls.find(D); 1506 if (I != ObjCImpls.end()) 1507 return cast<ObjCCategoryImplDecl>(I->second); 1508 return 0; 1509} 1510 1511/// \brief Set the implementation of ObjCInterfaceDecl. 1512void ASTContext::setObjCImplementation(ObjCInterfaceDecl *IFaceD, 1513 ObjCImplementationDecl *ImplD) { 1514 assert(IFaceD && ImplD && "Passed null params"); 1515 ObjCImpls[IFaceD] = ImplD; 1516} 1517/// \brief Set the implementation of ObjCCategoryDecl. 1518void ASTContext::setObjCImplementation(ObjCCategoryDecl *CatD, 1519 ObjCCategoryImplDecl *ImplD) { 1520 assert(CatD && ImplD && "Passed null params"); 1521 ObjCImpls[CatD] = ImplD; 1522} 1523 1524ObjCInterfaceDecl *ASTContext::getObjContainingInterface(NamedDecl *ND) const { 1525 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ND->getDeclContext())) 1526 return ID; 1527 if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ND->getDeclContext())) 1528 return CD->getClassInterface(); 1529 if (ObjCImplDecl *IMD = dyn_cast<ObjCImplDecl>(ND->getDeclContext())) 1530 return IMD->getClassInterface(); 1531 1532 return 0; 1533} 1534 1535/// \brief Get the copy initialization expression of VarDecl,or NULL if 1536/// none exists. 1537Expr *ASTContext::getBlockVarCopyInits(const VarDecl*VD) { 1538 assert(VD && "Passed null params"); 1539 assert(VD->hasAttr<BlocksAttr>() && 1540 "getBlockVarCopyInits - not __block var"); 1541 llvm::DenseMap<const VarDecl*, Expr*>::iterator 1542 I = BlockVarCopyInits.find(VD); 1543 return (I != BlockVarCopyInits.end()) ? cast<Expr>(I->second) : 0; 1544} 1545 1546/// \brief Set the copy inialization expression of a block var decl. 1547void ASTContext::setBlockVarCopyInits(VarDecl*VD, Expr* Init) { 1548 assert(VD && Init && "Passed null params"); 1549 assert(VD->hasAttr<BlocksAttr>() && 1550 "setBlockVarCopyInits - not __block var"); 1551 BlockVarCopyInits[VD] = Init; 1552} 1553 1554TypeSourceInfo *ASTContext::CreateTypeSourceInfo(QualType T, 1555 unsigned DataSize) const { 1556 if (!DataSize) 1557 DataSize = TypeLoc::getFullDataSizeForType(T); 1558 else 1559 assert(DataSize == TypeLoc::getFullDataSizeForType(T) && 1560 "incorrect data size provided to CreateTypeSourceInfo!"); 1561 1562 TypeSourceInfo *TInfo = 1563 (TypeSourceInfo*)BumpAlloc.Allocate(sizeof(TypeSourceInfo) + DataSize, 8); 1564 new (TInfo) TypeSourceInfo(T); 1565 return TInfo; 1566} 1567 1568TypeSourceInfo *ASTContext::getTrivialTypeSourceInfo(QualType T, 1569 SourceLocation L) const { 1570 TypeSourceInfo *DI = CreateTypeSourceInfo(T); 1571 DI->getTypeLoc().initialize(const_cast<ASTContext &>(*this), L); 1572 return DI; 1573} 1574 1575const ASTRecordLayout & 1576ASTContext::getASTObjCInterfaceLayout(const ObjCInterfaceDecl *D) const { 1577 return getObjCLayout(D, 0); 1578} 1579 1580const ASTRecordLayout & 1581ASTContext::getASTObjCImplementationLayout( 1582 const ObjCImplementationDecl *D) const { 1583 return getObjCLayout(D->getClassInterface(), D); 1584} 1585 1586//===----------------------------------------------------------------------===// 1587// Type creation/memoization methods 1588//===----------------------------------------------------------------------===// 1589 1590QualType 1591ASTContext::getExtQualType(const Type *baseType, Qualifiers quals) const { 1592 unsigned fastQuals = quals.getFastQualifiers(); 1593 quals.removeFastQualifiers(); 1594 1595 // Check if we've already instantiated this type. 1596 llvm::FoldingSetNodeID ID; 1597 ExtQuals::Profile(ID, baseType, quals); 1598 void *insertPos = 0; 1599 if (ExtQuals *eq = ExtQualNodes.FindNodeOrInsertPos(ID, insertPos)) { 1600 assert(eq->getQualifiers() == quals); 1601 return QualType(eq, fastQuals); 1602 } 1603 1604 // If the base type is not canonical, make the appropriate canonical type. 1605 QualType canon; 1606 if (!baseType->isCanonicalUnqualified()) { 1607 SplitQualType canonSplit = baseType->getCanonicalTypeInternal().split(); 1608 canonSplit.Quals.addConsistentQualifiers(quals); 1609 canon = getExtQualType(canonSplit.Ty, canonSplit.Quals); 1610 1611 // Re-find the insert position. 1612 (void) ExtQualNodes.FindNodeOrInsertPos(ID, insertPos); 1613 } 1614 1615 ExtQuals *eq = new (*this, TypeAlignment) ExtQuals(baseType, canon, quals); 1616 ExtQualNodes.InsertNode(eq, insertPos); 1617 return QualType(eq, fastQuals); 1618} 1619 1620QualType 1621ASTContext::getAddrSpaceQualType(QualType T, unsigned AddressSpace) const { 1622 QualType CanT = getCanonicalType(T); 1623 if (CanT.getAddressSpace() == AddressSpace) 1624 return T; 1625 1626 // If we are composing extended qualifiers together, merge together 1627 // into one ExtQuals node. 1628 QualifierCollector Quals; 1629 const Type *TypeNode = Quals.strip(T); 1630 1631 // If this type already has an address space specified, it cannot get 1632 // another one. 1633 assert(!Quals.hasAddressSpace() && 1634 "Type cannot be in multiple addr spaces!"); 1635 Quals.addAddressSpace(AddressSpace); 1636 1637 return getExtQualType(TypeNode, Quals); 1638} 1639 1640QualType ASTContext::getObjCGCQualType(QualType T, 1641 Qualifiers::GC GCAttr) const { 1642 QualType CanT = getCanonicalType(T); 1643 if (CanT.getObjCGCAttr() == GCAttr) 1644 return T; 1645 1646 if (const PointerType *ptr = T->getAs<PointerType>()) { 1647 QualType Pointee = ptr->getPointeeType(); 1648 if (Pointee->isAnyPointerType()) { 1649 QualType ResultType = getObjCGCQualType(Pointee, GCAttr); 1650 return getPointerType(ResultType); 1651 } 1652 } 1653 1654 // If we are composing extended qualifiers together, merge together 1655 // into one ExtQuals node. 1656 QualifierCollector Quals; 1657 const Type *TypeNode = Quals.strip(T); 1658 1659 // If this type already has an ObjCGC specified, it cannot get 1660 // another one. 1661 assert(!Quals.hasObjCGCAttr() && 1662 "Type cannot have multiple ObjCGCs!"); 1663 Quals.addObjCGCAttr(GCAttr); 1664 1665 return getExtQualType(TypeNode, Quals); 1666} 1667 1668const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T, 1669 FunctionType::ExtInfo Info) { 1670 if (T->getExtInfo() == Info) 1671 return T; 1672 1673 QualType Result; 1674 if (const FunctionNoProtoType *FNPT = dyn_cast<FunctionNoProtoType>(T)) { 1675 Result = getFunctionNoProtoType(FNPT->getResultType(), Info); 1676 } else { 1677 const FunctionProtoType *FPT = cast<FunctionProtoType>(T); 1678 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 1679 EPI.ExtInfo = Info; 1680 Result = getFunctionType(FPT->getResultType(), FPT->arg_type_begin(), 1681 FPT->getNumArgs(), EPI); 1682 } 1683 1684 return cast<FunctionType>(Result.getTypePtr()); 1685} 1686 1687/// getComplexType - Return the uniqued reference to the type for a complex 1688/// number with the specified element type. 1689QualType ASTContext::getComplexType(QualType T) const { 1690 // Unique pointers, to guarantee there is only one pointer of a particular 1691 // structure. 1692 llvm::FoldingSetNodeID ID; 1693 ComplexType::Profile(ID, T); 1694 1695 void *InsertPos = 0; 1696 if (ComplexType *CT = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos)) 1697 return QualType(CT, 0); 1698 1699 // If the pointee type isn't canonical, this won't be a canonical type either, 1700 // so fill in the canonical type field. 1701 QualType Canonical; 1702 if (!T.isCanonical()) { 1703 Canonical = getComplexType(getCanonicalType(T)); 1704 1705 // Get the new insert position for the node we care about. 1706 ComplexType *NewIP = ComplexTypes.FindNodeOrInsertPos(ID, InsertPos); 1707 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1708 } 1709 ComplexType *New = new (*this, TypeAlignment) ComplexType(T, Canonical); 1710 Types.push_back(New); 1711 ComplexTypes.InsertNode(New, InsertPos); 1712 return QualType(New, 0); 1713} 1714 1715/// getPointerType - Return the uniqued reference to the type for a pointer to 1716/// the specified type. 1717QualType ASTContext::getPointerType(QualType T) const { 1718 // Unique pointers, to guarantee there is only one pointer of a particular 1719 // structure. 1720 llvm::FoldingSetNodeID ID; 1721 PointerType::Profile(ID, T); 1722 1723 void *InsertPos = 0; 1724 if (PointerType *PT = PointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1725 return QualType(PT, 0); 1726 1727 // If the pointee type isn't canonical, this won't be a canonical type either, 1728 // so fill in the canonical type field. 1729 QualType Canonical; 1730 if (!T.isCanonical()) { 1731 Canonical = getPointerType(getCanonicalType(T)); 1732 1733 // Get the new insert position for the node we care about. 1734 PointerType *NewIP = PointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1735 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1736 } 1737 PointerType *New = new (*this, TypeAlignment) PointerType(T, Canonical); 1738 Types.push_back(New); 1739 PointerTypes.InsertNode(New, InsertPos); 1740 return QualType(New, 0); 1741} 1742 1743/// getBlockPointerType - Return the uniqued reference to the type for 1744/// a pointer to the specified block. 1745QualType ASTContext::getBlockPointerType(QualType T) const { 1746 assert(T->isFunctionType() && "block of function types only"); 1747 // Unique pointers, to guarantee there is only one block of a particular 1748 // structure. 1749 llvm::FoldingSetNodeID ID; 1750 BlockPointerType::Profile(ID, T); 1751 1752 void *InsertPos = 0; 1753 if (BlockPointerType *PT = 1754 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1755 return QualType(PT, 0); 1756 1757 // If the block pointee type isn't canonical, this won't be a canonical 1758 // type either so fill in the canonical type field. 1759 QualType Canonical; 1760 if (!T.isCanonical()) { 1761 Canonical = getBlockPointerType(getCanonicalType(T)); 1762 1763 // Get the new insert position for the node we care about. 1764 BlockPointerType *NewIP = 1765 BlockPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1766 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1767 } 1768 BlockPointerType *New 1769 = new (*this, TypeAlignment) BlockPointerType(T, Canonical); 1770 Types.push_back(New); 1771 BlockPointerTypes.InsertNode(New, InsertPos); 1772 return QualType(New, 0); 1773} 1774 1775/// getLValueReferenceType - Return the uniqued reference to the type for an 1776/// lvalue reference to the specified type. 1777QualType 1778ASTContext::getLValueReferenceType(QualType T, bool SpelledAsLValue) const { 1779 assert(getCanonicalType(T) != OverloadTy && 1780 "Unresolved overloaded function type"); 1781 1782 // Unique pointers, to guarantee there is only one pointer of a particular 1783 // structure. 1784 llvm::FoldingSetNodeID ID; 1785 ReferenceType::Profile(ID, T, SpelledAsLValue); 1786 1787 void *InsertPos = 0; 1788 if (LValueReferenceType *RT = 1789 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1790 return QualType(RT, 0); 1791 1792 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1793 1794 // If the referencee type isn't canonical, this won't be a canonical type 1795 // either, so fill in the canonical type field. 1796 QualType Canonical; 1797 if (!SpelledAsLValue || InnerRef || !T.isCanonical()) { 1798 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1799 Canonical = getLValueReferenceType(getCanonicalType(PointeeType)); 1800 1801 // Get the new insert position for the node we care about. 1802 LValueReferenceType *NewIP = 1803 LValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1804 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1805 } 1806 1807 LValueReferenceType *New 1808 = new (*this, TypeAlignment) LValueReferenceType(T, Canonical, 1809 SpelledAsLValue); 1810 Types.push_back(New); 1811 LValueReferenceTypes.InsertNode(New, InsertPos); 1812 1813 return QualType(New, 0); 1814} 1815 1816/// getRValueReferenceType - Return the uniqued reference to the type for an 1817/// rvalue reference to the specified type. 1818QualType ASTContext::getRValueReferenceType(QualType T) const { 1819 // Unique pointers, to guarantee there is only one pointer of a particular 1820 // structure. 1821 llvm::FoldingSetNodeID ID; 1822 ReferenceType::Profile(ID, T, false); 1823 1824 void *InsertPos = 0; 1825 if (RValueReferenceType *RT = 1826 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos)) 1827 return QualType(RT, 0); 1828 1829 const ReferenceType *InnerRef = T->getAs<ReferenceType>(); 1830 1831 // If the referencee type isn't canonical, this won't be a canonical type 1832 // either, so fill in the canonical type field. 1833 QualType Canonical; 1834 if (InnerRef || !T.isCanonical()) { 1835 QualType PointeeType = (InnerRef ? InnerRef->getPointeeType() : T); 1836 Canonical = getRValueReferenceType(getCanonicalType(PointeeType)); 1837 1838 // Get the new insert position for the node we care about. 1839 RValueReferenceType *NewIP = 1840 RValueReferenceTypes.FindNodeOrInsertPos(ID, InsertPos); 1841 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1842 } 1843 1844 RValueReferenceType *New 1845 = new (*this, TypeAlignment) RValueReferenceType(T, Canonical); 1846 Types.push_back(New); 1847 RValueReferenceTypes.InsertNode(New, InsertPos); 1848 return QualType(New, 0); 1849} 1850 1851/// getMemberPointerType - Return the uniqued reference to the type for a 1852/// member pointer to the specified type, in the specified class. 1853QualType ASTContext::getMemberPointerType(QualType T, const Type *Cls) const { 1854 // Unique pointers, to guarantee there is only one pointer of a particular 1855 // structure. 1856 llvm::FoldingSetNodeID ID; 1857 MemberPointerType::Profile(ID, T, Cls); 1858 1859 void *InsertPos = 0; 1860 if (MemberPointerType *PT = 1861 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 1862 return QualType(PT, 0); 1863 1864 // If the pointee or class type isn't canonical, this won't be a canonical 1865 // type either, so fill in the canonical type field. 1866 QualType Canonical; 1867 if (!T.isCanonical() || !Cls->isCanonicalUnqualified()) { 1868 Canonical = getMemberPointerType(getCanonicalType(T),getCanonicalType(Cls)); 1869 1870 // Get the new insert position for the node we care about. 1871 MemberPointerType *NewIP = 1872 MemberPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 1873 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1874 } 1875 MemberPointerType *New 1876 = new (*this, TypeAlignment) MemberPointerType(T, Cls, Canonical); 1877 Types.push_back(New); 1878 MemberPointerTypes.InsertNode(New, InsertPos); 1879 return QualType(New, 0); 1880} 1881 1882/// getConstantArrayType - Return the unique reference to the type for an 1883/// array of the specified element type. 1884QualType ASTContext::getConstantArrayType(QualType EltTy, 1885 const llvm::APInt &ArySizeIn, 1886 ArrayType::ArraySizeModifier ASM, 1887 unsigned IndexTypeQuals) const { 1888 assert((EltTy->isDependentType() || 1889 EltTy->isIncompleteType() || EltTy->isConstantSizeType()) && 1890 "Constant array of VLAs is illegal!"); 1891 1892 // Convert the array size into a canonical width matching the pointer size for 1893 // the target. 1894 llvm::APInt ArySize(ArySizeIn); 1895 ArySize = 1896 ArySize.zextOrTrunc(Target->getPointerWidth(getTargetAddressSpace(EltTy))); 1897 1898 llvm::FoldingSetNodeID ID; 1899 ConstantArrayType::Profile(ID, EltTy, ArySize, ASM, IndexTypeQuals); 1900 1901 void *InsertPos = 0; 1902 if (ConstantArrayType *ATP = 1903 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos)) 1904 return QualType(ATP, 0); 1905 1906 // If the element type isn't canonical or has qualifiers, this won't 1907 // be a canonical type either, so fill in the canonical type field. 1908 QualType Canon; 1909 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 1910 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 1911 Canon = getConstantArrayType(QualType(canonSplit.Ty, 0), ArySize, 1912 ASM, IndexTypeQuals); 1913 Canon = getQualifiedType(Canon, canonSplit.Quals); 1914 1915 // Get the new insert position for the node we care about. 1916 ConstantArrayType *NewIP = 1917 ConstantArrayTypes.FindNodeOrInsertPos(ID, InsertPos); 1918 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 1919 } 1920 1921 ConstantArrayType *New = new(*this,TypeAlignment) 1922 ConstantArrayType(EltTy, Canon, ArySize, ASM, IndexTypeQuals); 1923 ConstantArrayTypes.InsertNode(New, InsertPos); 1924 Types.push_back(New); 1925 return QualType(New, 0); 1926} 1927 1928/// getVariableArrayDecayedType - Turns the given type, which may be 1929/// variably-modified, into the corresponding type with all the known 1930/// sizes replaced with [*]. 1931QualType ASTContext::getVariableArrayDecayedType(QualType type) const { 1932 // Vastly most common case. 1933 if (!type->isVariablyModifiedType()) return type; 1934 1935 QualType result; 1936 1937 SplitQualType split = type.getSplitDesugaredType(); 1938 const Type *ty = split.Ty; 1939 switch (ty->getTypeClass()) { 1940#define TYPE(Class, Base) 1941#define ABSTRACT_TYPE(Class, Base) 1942#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 1943#include "clang/AST/TypeNodes.def" 1944 llvm_unreachable("didn't desugar past all non-canonical types?"); 1945 1946 // These types should never be variably-modified. 1947 case Type::Builtin: 1948 case Type::Complex: 1949 case Type::Vector: 1950 case Type::ExtVector: 1951 case Type::DependentSizedExtVector: 1952 case Type::ObjCObject: 1953 case Type::ObjCInterface: 1954 case Type::ObjCObjectPointer: 1955 case Type::Record: 1956 case Type::Enum: 1957 case Type::UnresolvedUsing: 1958 case Type::TypeOfExpr: 1959 case Type::TypeOf: 1960 case Type::Decltype: 1961 case Type::UnaryTransform: 1962 case Type::DependentName: 1963 case Type::InjectedClassName: 1964 case Type::TemplateSpecialization: 1965 case Type::DependentTemplateSpecialization: 1966 case Type::TemplateTypeParm: 1967 case Type::SubstTemplateTypeParmPack: 1968 case Type::Auto: 1969 case Type::PackExpansion: 1970 llvm_unreachable("type should never be variably-modified"); 1971 1972 // These types can be variably-modified but should never need to 1973 // further decay. 1974 case Type::FunctionNoProto: 1975 case Type::FunctionProto: 1976 case Type::BlockPointer: 1977 case Type::MemberPointer: 1978 return type; 1979 1980 // These types can be variably-modified. All these modifications 1981 // preserve structure except as noted by comments. 1982 // TODO: if we ever care about optimizing VLAs, there are no-op 1983 // optimizations available here. 1984 case Type::Pointer: 1985 result = getPointerType(getVariableArrayDecayedType( 1986 cast<PointerType>(ty)->getPointeeType())); 1987 break; 1988 1989 case Type::LValueReference: { 1990 const LValueReferenceType *lv = cast<LValueReferenceType>(ty); 1991 result = getLValueReferenceType( 1992 getVariableArrayDecayedType(lv->getPointeeType()), 1993 lv->isSpelledAsLValue()); 1994 break; 1995 } 1996 1997 case Type::RValueReference: { 1998 const RValueReferenceType *lv = cast<RValueReferenceType>(ty); 1999 result = getRValueReferenceType( 2000 getVariableArrayDecayedType(lv->getPointeeType())); 2001 break; 2002 } 2003 2004 case Type::Atomic: { 2005 const AtomicType *at = cast<AtomicType>(ty); 2006 result = getAtomicType(getVariableArrayDecayedType(at->getValueType())); 2007 break; 2008 } 2009 2010 case Type::ConstantArray: { 2011 const ConstantArrayType *cat = cast<ConstantArrayType>(ty); 2012 result = getConstantArrayType( 2013 getVariableArrayDecayedType(cat->getElementType()), 2014 cat->getSize(), 2015 cat->getSizeModifier(), 2016 cat->getIndexTypeCVRQualifiers()); 2017 break; 2018 } 2019 2020 case Type::DependentSizedArray: { 2021 const DependentSizedArrayType *dat = cast<DependentSizedArrayType>(ty); 2022 result = getDependentSizedArrayType( 2023 getVariableArrayDecayedType(dat->getElementType()), 2024 dat->getSizeExpr(), 2025 dat->getSizeModifier(), 2026 dat->getIndexTypeCVRQualifiers(), 2027 dat->getBracketsRange()); 2028 break; 2029 } 2030 2031 // Turn incomplete types into [*] types. 2032 case Type::IncompleteArray: { 2033 const IncompleteArrayType *iat = cast<IncompleteArrayType>(ty); 2034 result = getVariableArrayType( 2035 getVariableArrayDecayedType(iat->getElementType()), 2036 /*size*/ 0, 2037 ArrayType::Normal, 2038 iat->getIndexTypeCVRQualifiers(), 2039 SourceRange()); 2040 break; 2041 } 2042 2043 // Turn VLA types into [*] types. 2044 case Type::VariableArray: { 2045 const VariableArrayType *vat = cast<VariableArrayType>(ty); 2046 result = getVariableArrayType( 2047 getVariableArrayDecayedType(vat->getElementType()), 2048 /*size*/ 0, 2049 ArrayType::Star, 2050 vat->getIndexTypeCVRQualifiers(), 2051 vat->getBracketsRange()); 2052 break; 2053 } 2054 } 2055 2056 // Apply the top-level qualifiers from the original. 2057 return getQualifiedType(result, split.Quals); 2058} 2059 2060/// getVariableArrayType - Returns a non-unique reference to the type for a 2061/// variable array of the specified element type. 2062QualType ASTContext::getVariableArrayType(QualType EltTy, 2063 Expr *NumElts, 2064 ArrayType::ArraySizeModifier ASM, 2065 unsigned IndexTypeQuals, 2066 SourceRange Brackets) const { 2067 // Since we don't unique expressions, it isn't possible to unique VLA's 2068 // that have an expression provided for their size. 2069 QualType Canon; 2070 2071 // Be sure to pull qualifiers off the element type. 2072 if (!EltTy.isCanonical() || EltTy.hasLocalQualifiers()) { 2073 SplitQualType canonSplit = getCanonicalType(EltTy).split(); 2074 Canon = getVariableArrayType(QualType(canonSplit.Ty, 0), NumElts, ASM, 2075 IndexTypeQuals, Brackets); 2076 Canon = getQualifiedType(Canon, canonSplit.Quals); 2077 } 2078 2079 VariableArrayType *New = new(*this, TypeAlignment) 2080 VariableArrayType(EltTy, Canon, NumElts, ASM, IndexTypeQuals, Brackets); 2081 2082 VariableArrayTypes.push_back(New); 2083 Types.push_back(New); 2084 return QualType(New, 0); 2085} 2086 2087/// getDependentSizedArrayType - Returns a non-unique reference to 2088/// the type for a dependently-sized array of the specified element 2089/// type. 2090QualType ASTContext::getDependentSizedArrayType(QualType elementType, 2091 Expr *numElements, 2092 ArrayType::ArraySizeModifier ASM, 2093 unsigned elementTypeQuals, 2094 SourceRange brackets) const { 2095 assert((!numElements || numElements->isTypeDependent() || 2096 numElements->isValueDependent()) && 2097 "Size must be type- or value-dependent!"); 2098 2099 // Dependently-sized array types that do not have a specified number 2100 // of elements will have their sizes deduced from a dependent 2101 // initializer. We do no canonicalization here at all, which is okay 2102 // because they can't be used in most locations. 2103 if (!numElements) { 2104 DependentSizedArrayType *newType 2105 = new (*this, TypeAlignment) 2106 DependentSizedArrayType(*this, elementType, QualType(), 2107 numElements, ASM, elementTypeQuals, 2108 brackets); 2109 Types.push_back(newType); 2110 return QualType(newType, 0); 2111 } 2112 2113 // Otherwise, we actually build a new type every time, but we 2114 // also build a canonical type. 2115 2116 SplitQualType canonElementType = getCanonicalType(elementType).split(); 2117 2118 void *insertPos = 0; 2119 llvm::FoldingSetNodeID ID; 2120 DependentSizedArrayType::Profile(ID, *this, 2121 QualType(canonElementType.Ty, 0), 2122 ASM, elementTypeQuals, numElements); 2123 2124 // Look for an existing type with these properties. 2125 DependentSizedArrayType *canonTy = 2126 DependentSizedArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2127 2128 // If we don't have one, build one. 2129 if (!canonTy) { 2130 canonTy = new (*this, TypeAlignment) 2131 DependentSizedArrayType(*this, QualType(canonElementType.Ty, 0), 2132 QualType(), numElements, ASM, elementTypeQuals, 2133 brackets); 2134 DependentSizedArrayTypes.InsertNode(canonTy, insertPos); 2135 Types.push_back(canonTy); 2136 } 2137 2138 // Apply qualifiers from the element type to the array. 2139 QualType canon = getQualifiedType(QualType(canonTy,0), 2140 canonElementType.Quals); 2141 2142 // If we didn't need extra canonicalization for the element type, 2143 // then just use that as our result. 2144 if (QualType(canonElementType.Ty, 0) == elementType) 2145 return canon; 2146 2147 // Otherwise, we need to build a type which follows the spelling 2148 // of the element type. 2149 DependentSizedArrayType *sugaredType 2150 = new (*this, TypeAlignment) 2151 DependentSizedArrayType(*this, elementType, canon, numElements, 2152 ASM, elementTypeQuals, brackets); 2153 Types.push_back(sugaredType); 2154 return QualType(sugaredType, 0); 2155} 2156 2157QualType ASTContext::getIncompleteArrayType(QualType elementType, 2158 ArrayType::ArraySizeModifier ASM, 2159 unsigned elementTypeQuals) const { 2160 llvm::FoldingSetNodeID ID; 2161 IncompleteArrayType::Profile(ID, elementType, ASM, elementTypeQuals); 2162 2163 void *insertPos = 0; 2164 if (IncompleteArrayType *iat = 2165 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos)) 2166 return QualType(iat, 0); 2167 2168 // If the element type isn't canonical, this won't be a canonical type 2169 // either, so fill in the canonical type field. We also have to pull 2170 // qualifiers off the element type. 2171 QualType canon; 2172 2173 if (!elementType.isCanonical() || elementType.hasLocalQualifiers()) { 2174 SplitQualType canonSplit = getCanonicalType(elementType).split(); 2175 canon = getIncompleteArrayType(QualType(canonSplit.Ty, 0), 2176 ASM, elementTypeQuals); 2177 canon = getQualifiedType(canon, canonSplit.Quals); 2178 2179 // Get the new insert position for the node we care about. 2180 IncompleteArrayType *existing = 2181 IncompleteArrayTypes.FindNodeOrInsertPos(ID, insertPos); 2182 assert(!existing && "Shouldn't be in the map!"); (void) existing; 2183 } 2184 2185 IncompleteArrayType *newType = new (*this, TypeAlignment) 2186 IncompleteArrayType(elementType, canon, ASM, elementTypeQuals); 2187 2188 IncompleteArrayTypes.InsertNode(newType, insertPos); 2189 Types.push_back(newType); 2190 return QualType(newType, 0); 2191} 2192 2193/// getVectorType - Return the unique reference to a vector type of 2194/// the specified element type and size. VectorType must be a built-in type. 2195QualType ASTContext::getVectorType(QualType vecType, unsigned NumElts, 2196 VectorType::VectorKind VecKind) const { 2197 assert(vecType->isBuiltinType()); 2198 2199 // Check if we've already instantiated a vector of this type. 2200 llvm::FoldingSetNodeID ID; 2201 VectorType::Profile(ID, vecType, NumElts, Type::Vector, VecKind); 2202 2203 void *InsertPos = 0; 2204 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2205 return QualType(VTP, 0); 2206 2207 // If the element type isn't canonical, this won't be a canonical type either, 2208 // so fill in the canonical type field. 2209 QualType Canonical; 2210 if (!vecType.isCanonical()) { 2211 Canonical = getVectorType(getCanonicalType(vecType), NumElts, VecKind); 2212 2213 // Get the new insert position for the node we care about. 2214 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2215 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2216 } 2217 VectorType *New = new (*this, TypeAlignment) 2218 VectorType(vecType, NumElts, Canonical, VecKind); 2219 VectorTypes.InsertNode(New, InsertPos); 2220 Types.push_back(New); 2221 return QualType(New, 0); 2222} 2223 2224/// getExtVectorType - Return the unique reference to an extended vector type of 2225/// the specified element type and size. VectorType must be a built-in type. 2226QualType 2227ASTContext::getExtVectorType(QualType vecType, unsigned NumElts) const { 2228 assert(vecType->isBuiltinType() || vecType->isDependentType()); 2229 2230 // Check if we've already instantiated a vector of this type. 2231 llvm::FoldingSetNodeID ID; 2232 VectorType::Profile(ID, vecType, NumElts, Type::ExtVector, 2233 VectorType::GenericVector); 2234 void *InsertPos = 0; 2235 if (VectorType *VTP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos)) 2236 return QualType(VTP, 0); 2237 2238 // If the element type isn't canonical, this won't be a canonical type either, 2239 // so fill in the canonical type field. 2240 QualType Canonical; 2241 if (!vecType.isCanonical()) { 2242 Canonical = getExtVectorType(getCanonicalType(vecType), NumElts); 2243 2244 // Get the new insert position for the node we care about. 2245 VectorType *NewIP = VectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2246 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2247 } 2248 ExtVectorType *New = new (*this, TypeAlignment) 2249 ExtVectorType(vecType, NumElts, Canonical); 2250 VectorTypes.InsertNode(New, InsertPos); 2251 Types.push_back(New); 2252 return QualType(New, 0); 2253} 2254 2255QualType 2256ASTContext::getDependentSizedExtVectorType(QualType vecType, 2257 Expr *SizeExpr, 2258 SourceLocation AttrLoc) const { 2259 llvm::FoldingSetNodeID ID; 2260 DependentSizedExtVectorType::Profile(ID, *this, getCanonicalType(vecType), 2261 SizeExpr); 2262 2263 void *InsertPos = 0; 2264 DependentSizedExtVectorType *Canon 2265 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2266 DependentSizedExtVectorType *New; 2267 if (Canon) { 2268 // We already have a canonical version of this array type; use it as 2269 // the canonical type for a newly-built type. 2270 New = new (*this, TypeAlignment) 2271 DependentSizedExtVectorType(*this, vecType, QualType(Canon, 0), 2272 SizeExpr, AttrLoc); 2273 } else { 2274 QualType CanonVecTy = getCanonicalType(vecType); 2275 if (CanonVecTy == vecType) { 2276 New = new (*this, TypeAlignment) 2277 DependentSizedExtVectorType(*this, vecType, QualType(), SizeExpr, 2278 AttrLoc); 2279 2280 DependentSizedExtVectorType *CanonCheck 2281 = DependentSizedExtVectorTypes.FindNodeOrInsertPos(ID, InsertPos); 2282 assert(!CanonCheck && "Dependent-sized ext_vector canonical type broken"); 2283 (void)CanonCheck; 2284 DependentSizedExtVectorTypes.InsertNode(New, InsertPos); 2285 } else { 2286 QualType Canon = getDependentSizedExtVectorType(CanonVecTy, SizeExpr, 2287 SourceLocation()); 2288 New = new (*this, TypeAlignment) 2289 DependentSizedExtVectorType(*this, vecType, Canon, SizeExpr, AttrLoc); 2290 } 2291 } 2292 2293 Types.push_back(New); 2294 return QualType(New, 0); 2295} 2296 2297/// getFunctionNoProtoType - Return a K&R style C function type like 'int()'. 2298/// 2299QualType 2300ASTContext::getFunctionNoProtoType(QualType ResultTy, 2301 const FunctionType::ExtInfo &Info) const { 2302 const CallingConv DefaultCC = Info.getCC(); 2303 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2304 CC_X86StdCall : DefaultCC; 2305 // Unique functions, to guarantee there is only one function of a particular 2306 // structure. 2307 llvm::FoldingSetNodeID ID; 2308 FunctionNoProtoType::Profile(ID, ResultTy, Info); 2309 2310 void *InsertPos = 0; 2311 if (FunctionNoProtoType *FT = 2312 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2313 return QualType(FT, 0); 2314 2315 QualType Canonical; 2316 if (!ResultTy.isCanonical() || 2317 getCanonicalCallConv(CallConv) != CallConv) { 2318 Canonical = 2319 getFunctionNoProtoType(getCanonicalType(ResultTy), 2320 Info.withCallingConv(getCanonicalCallConv(CallConv))); 2321 2322 // Get the new insert position for the node we care about. 2323 FunctionNoProtoType *NewIP = 2324 FunctionNoProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2325 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2326 } 2327 2328 FunctionProtoType::ExtInfo newInfo = Info.withCallingConv(CallConv); 2329 FunctionNoProtoType *New = new (*this, TypeAlignment) 2330 FunctionNoProtoType(ResultTy, Canonical, newInfo); 2331 Types.push_back(New); 2332 FunctionNoProtoTypes.InsertNode(New, InsertPos); 2333 return QualType(New, 0); 2334} 2335 2336/// getFunctionType - Return a normal function type with a typed argument 2337/// list. isVariadic indicates whether the argument list includes '...'. 2338QualType 2339ASTContext::getFunctionType(QualType ResultTy, 2340 const QualType *ArgArray, unsigned NumArgs, 2341 const FunctionProtoType::ExtProtoInfo &EPI) const { 2342 // Unique functions, to guarantee there is only one function of a particular 2343 // structure. 2344 llvm::FoldingSetNodeID ID; 2345 FunctionProtoType::Profile(ID, ResultTy, ArgArray, NumArgs, EPI, *this); 2346 2347 void *InsertPos = 0; 2348 if (FunctionProtoType *FTP = 2349 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos)) 2350 return QualType(FTP, 0); 2351 2352 // Determine whether the type being created is already canonical or not. 2353 bool isCanonical = 2354 EPI.ExceptionSpecType == EST_None && ResultTy.isCanonical() && 2355 !EPI.HasTrailingReturn; 2356 for (unsigned i = 0; i != NumArgs && isCanonical; ++i) 2357 if (!ArgArray[i].isCanonicalAsParam()) 2358 isCanonical = false; 2359 2360 const CallingConv DefaultCC = EPI.ExtInfo.getCC(); 2361 const CallingConv CallConv = (LangOpts.MRTD && DefaultCC == CC_Default) ? 2362 CC_X86StdCall : DefaultCC; 2363 2364 // If this type isn't canonical, get the canonical version of it. 2365 // The exception spec is not part of the canonical type. 2366 QualType Canonical; 2367 if (!isCanonical || getCanonicalCallConv(CallConv) != CallConv) { 2368 SmallVector<QualType, 16> CanonicalArgs; 2369 CanonicalArgs.reserve(NumArgs); 2370 for (unsigned i = 0; i != NumArgs; ++i) 2371 CanonicalArgs.push_back(getCanonicalParamType(ArgArray[i])); 2372 2373 FunctionProtoType::ExtProtoInfo CanonicalEPI = EPI; 2374 CanonicalEPI.HasTrailingReturn = false; 2375 CanonicalEPI.ExceptionSpecType = EST_None; 2376 CanonicalEPI.NumExceptions = 0; 2377 CanonicalEPI.ExtInfo 2378 = CanonicalEPI.ExtInfo.withCallingConv(getCanonicalCallConv(CallConv)); 2379 2380 Canonical = getFunctionType(getCanonicalType(ResultTy), 2381 CanonicalArgs.data(), NumArgs, 2382 CanonicalEPI); 2383 2384 // Get the new insert position for the node we care about. 2385 FunctionProtoType *NewIP = 2386 FunctionProtoTypes.FindNodeOrInsertPos(ID, InsertPos); 2387 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 2388 } 2389 2390 // FunctionProtoType objects are allocated with extra bytes after 2391 // them for three variable size arrays at the end: 2392 // - parameter types 2393 // - exception types 2394 // - consumed-arguments flags 2395 // Instead of the exception types, there could be a noexcept 2396 // expression, or information used to resolve the exception 2397 // specification. 2398 size_t Size = sizeof(FunctionProtoType) + 2399 NumArgs * sizeof(QualType); 2400 if (EPI.ExceptionSpecType == EST_Dynamic) { 2401 Size += EPI.NumExceptions * sizeof(QualType); 2402 } else if (EPI.ExceptionSpecType == EST_ComputedNoexcept) { 2403 Size += sizeof(Expr*); 2404 } else if (EPI.ExceptionSpecType == EST_Uninstantiated) { 2405 Size += 2 * sizeof(FunctionDecl*); 2406 } else if (EPI.ExceptionSpecType == EST_Unevaluated) { 2407 Size += sizeof(FunctionDecl*); 2408 } 2409 if (EPI.ConsumedArguments) 2410 Size += NumArgs * sizeof(bool); 2411 2412 FunctionProtoType *FTP = (FunctionProtoType*) Allocate(Size, TypeAlignment); 2413 FunctionProtoType::ExtProtoInfo newEPI = EPI; 2414 newEPI.ExtInfo = EPI.ExtInfo.withCallingConv(CallConv); 2415 new (FTP) FunctionProtoType(ResultTy, ArgArray, NumArgs, Canonical, newEPI); 2416 Types.push_back(FTP); 2417 FunctionProtoTypes.InsertNode(FTP, InsertPos); 2418 return QualType(FTP, 0); 2419} 2420 2421#ifndef NDEBUG 2422static bool NeedsInjectedClassNameType(const RecordDecl *D) { 2423 if (!isa<CXXRecordDecl>(D)) return false; 2424 const CXXRecordDecl *RD = cast<CXXRecordDecl>(D); 2425 if (isa<ClassTemplatePartialSpecializationDecl>(RD)) 2426 return true; 2427 if (RD->getDescribedClassTemplate() && 2428 !isa<ClassTemplateSpecializationDecl>(RD)) 2429 return true; 2430 return false; 2431} 2432#endif 2433 2434/// getInjectedClassNameType - Return the unique reference to the 2435/// injected class name type for the specified templated declaration. 2436QualType ASTContext::getInjectedClassNameType(CXXRecordDecl *Decl, 2437 QualType TST) const { 2438 assert(NeedsInjectedClassNameType(Decl)); 2439 if (Decl->TypeForDecl) { 2440 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2441 } else if (CXXRecordDecl *PrevDecl = Decl->getPreviousDecl()) { 2442 assert(PrevDecl->TypeForDecl && "previous declaration has no type"); 2443 Decl->TypeForDecl = PrevDecl->TypeForDecl; 2444 assert(isa<InjectedClassNameType>(Decl->TypeForDecl)); 2445 } else { 2446 Type *newType = 2447 new (*this, TypeAlignment) InjectedClassNameType(Decl, TST); 2448 Decl->TypeForDecl = newType; 2449 Types.push_back(newType); 2450 } 2451 return QualType(Decl->TypeForDecl, 0); 2452} 2453 2454/// getTypeDeclType - Return the unique reference to the type for the 2455/// specified type declaration. 2456QualType ASTContext::getTypeDeclTypeSlow(const TypeDecl *Decl) const { 2457 assert(Decl && "Passed null for Decl param"); 2458 assert(!Decl->TypeForDecl && "TypeForDecl present in slow case"); 2459 2460 if (const TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Decl)) 2461 return getTypedefType(Typedef); 2462 2463 assert(!isa<TemplateTypeParmDecl>(Decl) && 2464 "Template type parameter types are always available."); 2465 2466 if (const RecordDecl *Record = dyn_cast<RecordDecl>(Decl)) { 2467 assert(!Record->getPreviousDecl() && 2468 "struct/union has previous declaration"); 2469 assert(!NeedsInjectedClassNameType(Record)); 2470 return getRecordType(Record); 2471 } else if (const EnumDecl *Enum = dyn_cast<EnumDecl>(Decl)) { 2472 assert(!Enum->getPreviousDecl() && 2473 "enum has previous declaration"); 2474 return getEnumType(Enum); 2475 } else if (const UnresolvedUsingTypenameDecl *Using = 2476 dyn_cast<UnresolvedUsingTypenameDecl>(Decl)) { 2477 Type *newType = new (*this, TypeAlignment) UnresolvedUsingType(Using); 2478 Decl->TypeForDecl = newType; 2479 Types.push_back(newType); 2480 } else 2481 llvm_unreachable("TypeDecl without a type?"); 2482 2483 return QualType(Decl->TypeForDecl, 0); 2484} 2485 2486/// getTypedefType - Return the unique reference to the type for the 2487/// specified typedef name decl. 2488QualType 2489ASTContext::getTypedefType(const TypedefNameDecl *Decl, 2490 QualType Canonical) const { 2491 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2492 2493 if (Canonical.isNull()) 2494 Canonical = getCanonicalType(Decl->getUnderlyingType()); 2495 TypedefType *newType = new(*this, TypeAlignment) 2496 TypedefType(Type::Typedef, Decl, Canonical); 2497 Decl->TypeForDecl = newType; 2498 Types.push_back(newType); 2499 return QualType(newType, 0); 2500} 2501 2502QualType ASTContext::getRecordType(const RecordDecl *Decl) const { 2503 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2504 2505 if (const RecordDecl *PrevDecl = Decl->getPreviousDecl()) 2506 if (PrevDecl->TypeForDecl) 2507 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2508 2509 RecordType *newType = new (*this, TypeAlignment) RecordType(Decl); 2510 Decl->TypeForDecl = newType; 2511 Types.push_back(newType); 2512 return QualType(newType, 0); 2513} 2514 2515QualType ASTContext::getEnumType(const EnumDecl *Decl) const { 2516 if (Decl->TypeForDecl) return QualType(Decl->TypeForDecl, 0); 2517 2518 if (const EnumDecl *PrevDecl = Decl->getPreviousDecl()) 2519 if (PrevDecl->TypeForDecl) 2520 return QualType(Decl->TypeForDecl = PrevDecl->TypeForDecl, 0); 2521 2522 EnumType *newType = new (*this, TypeAlignment) EnumType(Decl); 2523 Decl->TypeForDecl = newType; 2524 Types.push_back(newType); 2525 return QualType(newType, 0); 2526} 2527 2528QualType ASTContext::getAttributedType(AttributedType::Kind attrKind, 2529 QualType modifiedType, 2530 QualType equivalentType) { 2531 llvm::FoldingSetNodeID id; 2532 AttributedType::Profile(id, attrKind, modifiedType, equivalentType); 2533 2534 void *insertPos = 0; 2535 AttributedType *type = AttributedTypes.FindNodeOrInsertPos(id, insertPos); 2536 if (type) return QualType(type, 0); 2537 2538 QualType canon = getCanonicalType(equivalentType); 2539 type = new (*this, TypeAlignment) 2540 AttributedType(canon, attrKind, modifiedType, equivalentType); 2541 2542 Types.push_back(type); 2543 AttributedTypes.InsertNode(type, insertPos); 2544 2545 return QualType(type, 0); 2546} 2547 2548 2549/// \brief Retrieve a substitution-result type. 2550QualType 2551ASTContext::getSubstTemplateTypeParmType(const TemplateTypeParmType *Parm, 2552 QualType Replacement) const { 2553 assert(Replacement.isCanonical() 2554 && "replacement types must always be canonical"); 2555 2556 llvm::FoldingSetNodeID ID; 2557 SubstTemplateTypeParmType::Profile(ID, Parm, Replacement); 2558 void *InsertPos = 0; 2559 SubstTemplateTypeParmType *SubstParm 2560 = SubstTemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2561 2562 if (!SubstParm) { 2563 SubstParm = new (*this, TypeAlignment) 2564 SubstTemplateTypeParmType(Parm, Replacement); 2565 Types.push_back(SubstParm); 2566 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2567 } 2568 2569 return QualType(SubstParm, 0); 2570} 2571 2572/// \brief Retrieve a 2573QualType ASTContext::getSubstTemplateTypeParmPackType( 2574 const TemplateTypeParmType *Parm, 2575 const TemplateArgument &ArgPack) { 2576#ifndef NDEBUG 2577 for (TemplateArgument::pack_iterator P = ArgPack.pack_begin(), 2578 PEnd = ArgPack.pack_end(); 2579 P != PEnd; ++P) { 2580 assert(P->getKind() == TemplateArgument::Type &&"Pack contains a non-type"); 2581 assert(P->getAsType().isCanonical() && "Pack contains non-canonical type"); 2582 } 2583#endif 2584 2585 llvm::FoldingSetNodeID ID; 2586 SubstTemplateTypeParmPackType::Profile(ID, Parm, ArgPack); 2587 void *InsertPos = 0; 2588 if (SubstTemplateTypeParmPackType *SubstParm 2589 = SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos)) 2590 return QualType(SubstParm, 0); 2591 2592 QualType Canon; 2593 if (!Parm->isCanonicalUnqualified()) { 2594 Canon = getCanonicalType(QualType(Parm, 0)); 2595 Canon = getSubstTemplateTypeParmPackType(cast<TemplateTypeParmType>(Canon), 2596 ArgPack); 2597 SubstTemplateTypeParmPackTypes.FindNodeOrInsertPos(ID, InsertPos); 2598 } 2599 2600 SubstTemplateTypeParmPackType *SubstParm 2601 = new (*this, TypeAlignment) SubstTemplateTypeParmPackType(Parm, Canon, 2602 ArgPack); 2603 Types.push_back(SubstParm); 2604 SubstTemplateTypeParmTypes.InsertNode(SubstParm, InsertPos); 2605 return QualType(SubstParm, 0); 2606} 2607 2608/// \brief Retrieve the template type parameter type for a template 2609/// parameter or parameter pack with the given depth, index, and (optionally) 2610/// name. 2611QualType ASTContext::getTemplateTypeParmType(unsigned Depth, unsigned Index, 2612 bool ParameterPack, 2613 TemplateTypeParmDecl *TTPDecl) const { 2614 llvm::FoldingSetNodeID ID; 2615 TemplateTypeParmType::Profile(ID, Depth, Index, ParameterPack, TTPDecl); 2616 void *InsertPos = 0; 2617 TemplateTypeParmType *TypeParm 2618 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2619 2620 if (TypeParm) 2621 return QualType(TypeParm, 0); 2622 2623 if (TTPDecl) { 2624 QualType Canon = getTemplateTypeParmType(Depth, Index, ParameterPack); 2625 TypeParm = new (*this, TypeAlignment) TemplateTypeParmType(TTPDecl, Canon); 2626 2627 TemplateTypeParmType *TypeCheck 2628 = TemplateTypeParmTypes.FindNodeOrInsertPos(ID, InsertPos); 2629 assert(!TypeCheck && "Template type parameter canonical type broken"); 2630 (void)TypeCheck; 2631 } else 2632 TypeParm = new (*this, TypeAlignment) 2633 TemplateTypeParmType(Depth, Index, ParameterPack); 2634 2635 Types.push_back(TypeParm); 2636 TemplateTypeParmTypes.InsertNode(TypeParm, InsertPos); 2637 2638 return QualType(TypeParm, 0); 2639} 2640 2641TypeSourceInfo * 2642ASTContext::getTemplateSpecializationTypeInfo(TemplateName Name, 2643 SourceLocation NameLoc, 2644 const TemplateArgumentListInfo &Args, 2645 QualType Underlying) const { 2646 assert(!Name.getAsDependentTemplateName() && 2647 "No dependent template names here!"); 2648 QualType TST = getTemplateSpecializationType(Name, Args, Underlying); 2649 2650 TypeSourceInfo *DI = CreateTypeSourceInfo(TST); 2651 TemplateSpecializationTypeLoc TL 2652 = cast<TemplateSpecializationTypeLoc>(DI->getTypeLoc()); 2653 TL.setTemplateKeywordLoc(SourceLocation()); 2654 TL.setTemplateNameLoc(NameLoc); 2655 TL.setLAngleLoc(Args.getLAngleLoc()); 2656 TL.setRAngleLoc(Args.getRAngleLoc()); 2657 for (unsigned i = 0, e = TL.getNumArgs(); i != e; ++i) 2658 TL.setArgLocInfo(i, Args[i].getLocInfo()); 2659 return DI; 2660} 2661 2662QualType 2663ASTContext::getTemplateSpecializationType(TemplateName Template, 2664 const TemplateArgumentListInfo &Args, 2665 QualType Underlying) const { 2666 assert(!Template.getAsDependentTemplateName() && 2667 "No dependent template names here!"); 2668 2669 unsigned NumArgs = Args.size(); 2670 2671 SmallVector<TemplateArgument, 4> ArgVec; 2672 ArgVec.reserve(NumArgs); 2673 for (unsigned i = 0; i != NumArgs; ++i) 2674 ArgVec.push_back(Args[i].getArgument()); 2675 2676 return getTemplateSpecializationType(Template, ArgVec.data(), NumArgs, 2677 Underlying); 2678} 2679 2680#ifndef NDEBUG 2681static bool hasAnyPackExpansions(const TemplateArgument *Args, 2682 unsigned NumArgs) { 2683 for (unsigned I = 0; I != NumArgs; ++I) 2684 if (Args[I].isPackExpansion()) 2685 return true; 2686 2687 return true; 2688} 2689#endif 2690 2691QualType 2692ASTContext::getTemplateSpecializationType(TemplateName Template, 2693 const TemplateArgument *Args, 2694 unsigned NumArgs, 2695 QualType Underlying) const { 2696 assert(!Template.getAsDependentTemplateName() && 2697 "No dependent template names here!"); 2698 // Look through qualified template names. 2699 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2700 Template = TemplateName(QTN->getTemplateDecl()); 2701 2702 bool IsTypeAlias = 2703 Template.getAsTemplateDecl() && 2704 isa<TypeAliasTemplateDecl>(Template.getAsTemplateDecl()); 2705 QualType CanonType; 2706 if (!Underlying.isNull()) 2707 CanonType = getCanonicalType(Underlying); 2708 else { 2709 // We can get here with an alias template when the specialization contains 2710 // a pack expansion that does not match up with a parameter pack. 2711 assert((!IsTypeAlias || hasAnyPackExpansions(Args, NumArgs)) && 2712 "Caller must compute aliased type"); 2713 IsTypeAlias = false; 2714 CanonType = getCanonicalTemplateSpecializationType(Template, Args, 2715 NumArgs); 2716 } 2717 2718 // Allocate the (non-canonical) template specialization type, but don't 2719 // try to unique it: these types typically have location information that 2720 // we don't unique and don't want to lose. 2721 void *Mem = Allocate(sizeof(TemplateSpecializationType) + 2722 sizeof(TemplateArgument) * NumArgs + 2723 (IsTypeAlias? sizeof(QualType) : 0), 2724 TypeAlignment); 2725 TemplateSpecializationType *Spec 2726 = new (Mem) TemplateSpecializationType(Template, Args, NumArgs, CanonType, 2727 IsTypeAlias ? Underlying : QualType()); 2728 2729 Types.push_back(Spec); 2730 return QualType(Spec, 0); 2731} 2732 2733QualType 2734ASTContext::getCanonicalTemplateSpecializationType(TemplateName Template, 2735 const TemplateArgument *Args, 2736 unsigned NumArgs) const { 2737 assert(!Template.getAsDependentTemplateName() && 2738 "No dependent template names here!"); 2739 2740 // Look through qualified template names. 2741 if (QualifiedTemplateName *QTN = Template.getAsQualifiedTemplateName()) 2742 Template = TemplateName(QTN->getTemplateDecl()); 2743 2744 // Build the canonical template specialization type. 2745 TemplateName CanonTemplate = getCanonicalTemplateName(Template); 2746 SmallVector<TemplateArgument, 4> CanonArgs; 2747 CanonArgs.reserve(NumArgs); 2748 for (unsigned I = 0; I != NumArgs; ++I) 2749 CanonArgs.push_back(getCanonicalTemplateArgument(Args[I])); 2750 2751 // Determine whether this canonical template specialization type already 2752 // exists. 2753 llvm::FoldingSetNodeID ID; 2754 TemplateSpecializationType::Profile(ID, CanonTemplate, 2755 CanonArgs.data(), NumArgs, *this); 2756 2757 void *InsertPos = 0; 2758 TemplateSpecializationType *Spec 2759 = TemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2760 2761 if (!Spec) { 2762 // Allocate a new canonical template specialization type. 2763 void *Mem = Allocate((sizeof(TemplateSpecializationType) + 2764 sizeof(TemplateArgument) * NumArgs), 2765 TypeAlignment); 2766 Spec = new (Mem) TemplateSpecializationType(CanonTemplate, 2767 CanonArgs.data(), NumArgs, 2768 QualType(), QualType()); 2769 Types.push_back(Spec); 2770 TemplateSpecializationTypes.InsertNode(Spec, InsertPos); 2771 } 2772 2773 assert(Spec->isDependentType() && 2774 "Non-dependent template-id type must have a canonical type"); 2775 return QualType(Spec, 0); 2776} 2777 2778QualType 2779ASTContext::getElaboratedType(ElaboratedTypeKeyword Keyword, 2780 NestedNameSpecifier *NNS, 2781 QualType NamedType) const { 2782 llvm::FoldingSetNodeID ID; 2783 ElaboratedType::Profile(ID, Keyword, NNS, NamedType); 2784 2785 void *InsertPos = 0; 2786 ElaboratedType *T = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2787 if (T) 2788 return QualType(T, 0); 2789 2790 QualType Canon = NamedType; 2791 if (!Canon.isCanonical()) { 2792 Canon = getCanonicalType(NamedType); 2793 ElaboratedType *CheckT = ElaboratedTypes.FindNodeOrInsertPos(ID, InsertPos); 2794 assert(!CheckT && "Elaborated canonical type broken"); 2795 (void)CheckT; 2796 } 2797 2798 T = new (*this) ElaboratedType(Keyword, NNS, NamedType, Canon); 2799 Types.push_back(T); 2800 ElaboratedTypes.InsertNode(T, InsertPos); 2801 return QualType(T, 0); 2802} 2803 2804QualType 2805ASTContext::getParenType(QualType InnerType) const { 2806 llvm::FoldingSetNodeID ID; 2807 ParenType::Profile(ID, InnerType); 2808 2809 void *InsertPos = 0; 2810 ParenType *T = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2811 if (T) 2812 return QualType(T, 0); 2813 2814 QualType Canon = InnerType; 2815 if (!Canon.isCanonical()) { 2816 Canon = getCanonicalType(InnerType); 2817 ParenType *CheckT = ParenTypes.FindNodeOrInsertPos(ID, InsertPos); 2818 assert(!CheckT && "Paren canonical type broken"); 2819 (void)CheckT; 2820 } 2821 2822 T = new (*this) ParenType(InnerType, Canon); 2823 Types.push_back(T); 2824 ParenTypes.InsertNode(T, InsertPos); 2825 return QualType(T, 0); 2826} 2827 2828QualType ASTContext::getDependentNameType(ElaboratedTypeKeyword Keyword, 2829 NestedNameSpecifier *NNS, 2830 const IdentifierInfo *Name, 2831 QualType Canon) const { 2832 assert(NNS->isDependent() && "nested-name-specifier must be dependent"); 2833 2834 if (Canon.isNull()) { 2835 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2836 ElaboratedTypeKeyword CanonKeyword = Keyword; 2837 if (Keyword == ETK_None) 2838 CanonKeyword = ETK_Typename; 2839 2840 if (CanonNNS != NNS || CanonKeyword != Keyword) 2841 Canon = getDependentNameType(CanonKeyword, CanonNNS, Name); 2842 } 2843 2844 llvm::FoldingSetNodeID ID; 2845 DependentNameType::Profile(ID, Keyword, NNS, Name); 2846 2847 void *InsertPos = 0; 2848 DependentNameType *T 2849 = DependentNameTypes.FindNodeOrInsertPos(ID, InsertPos); 2850 if (T) 2851 return QualType(T, 0); 2852 2853 T = new (*this) DependentNameType(Keyword, NNS, Name, Canon); 2854 Types.push_back(T); 2855 DependentNameTypes.InsertNode(T, InsertPos); 2856 return QualType(T, 0); 2857} 2858 2859QualType 2860ASTContext::getDependentTemplateSpecializationType( 2861 ElaboratedTypeKeyword Keyword, 2862 NestedNameSpecifier *NNS, 2863 const IdentifierInfo *Name, 2864 const TemplateArgumentListInfo &Args) const { 2865 // TODO: avoid this copy 2866 SmallVector<TemplateArgument, 16> ArgCopy; 2867 for (unsigned I = 0, E = Args.size(); I != E; ++I) 2868 ArgCopy.push_back(Args[I].getArgument()); 2869 return getDependentTemplateSpecializationType(Keyword, NNS, Name, 2870 ArgCopy.size(), 2871 ArgCopy.data()); 2872} 2873 2874QualType 2875ASTContext::getDependentTemplateSpecializationType( 2876 ElaboratedTypeKeyword Keyword, 2877 NestedNameSpecifier *NNS, 2878 const IdentifierInfo *Name, 2879 unsigned NumArgs, 2880 const TemplateArgument *Args) const { 2881 assert((!NNS || NNS->isDependent()) && 2882 "nested-name-specifier must be dependent"); 2883 2884 llvm::FoldingSetNodeID ID; 2885 DependentTemplateSpecializationType::Profile(ID, *this, Keyword, NNS, 2886 Name, NumArgs, Args); 2887 2888 void *InsertPos = 0; 2889 DependentTemplateSpecializationType *T 2890 = DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2891 if (T) 2892 return QualType(T, 0); 2893 2894 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 2895 2896 ElaboratedTypeKeyword CanonKeyword = Keyword; 2897 if (Keyword == ETK_None) CanonKeyword = ETK_Typename; 2898 2899 bool AnyNonCanonArgs = false; 2900 SmallVector<TemplateArgument, 16> CanonArgs(NumArgs); 2901 for (unsigned I = 0; I != NumArgs; ++I) { 2902 CanonArgs[I] = getCanonicalTemplateArgument(Args[I]); 2903 if (!CanonArgs[I].structurallyEquals(Args[I])) 2904 AnyNonCanonArgs = true; 2905 } 2906 2907 QualType Canon; 2908 if (AnyNonCanonArgs || CanonNNS != NNS || CanonKeyword != Keyword) { 2909 Canon = getDependentTemplateSpecializationType(CanonKeyword, CanonNNS, 2910 Name, NumArgs, 2911 CanonArgs.data()); 2912 2913 // Find the insert position again. 2914 DependentTemplateSpecializationTypes.FindNodeOrInsertPos(ID, InsertPos); 2915 } 2916 2917 void *Mem = Allocate((sizeof(DependentTemplateSpecializationType) + 2918 sizeof(TemplateArgument) * NumArgs), 2919 TypeAlignment); 2920 T = new (Mem) DependentTemplateSpecializationType(Keyword, NNS, 2921 Name, NumArgs, Args, Canon); 2922 Types.push_back(T); 2923 DependentTemplateSpecializationTypes.InsertNode(T, InsertPos); 2924 return QualType(T, 0); 2925} 2926 2927QualType ASTContext::getPackExpansionType(QualType Pattern, 2928 llvm::Optional<unsigned> NumExpansions) { 2929 llvm::FoldingSetNodeID ID; 2930 PackExpansionType::Profile(ID, Pattern, NumExpansions); 2931 2932 assert(Pattern->containsUnexpandedParameterPack() && 2933 "Pack expansions must expand one or more parameter packs"); 2934 void *InsertPos = 0; 2935 PackExpansionType *T 2936 = PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2937 if (T) 2938 return QualType(T, 0); 2939 2940 QualType Canon; 2941 if (!Pattern.isCanonical()) { 2942 Canon = getCanonicalType(Pattern); 2943 // The canonical type might not contain an unexpanded parameter pack, if it 2944 // contains an alias template specialization which ignores one of its 2945 // parameters. 2946 if (Canon->containsUnexpandedParameterPack()) { 2947 Canon = getPackExpansionType(getCanonicalType(Pattern), NumExpansions); 2948 2949 // Find the insert position again, in case we inserted an element into 2950 // PackExpansionTypes and invalidated our insert position. 2951 PackExpansionTypes.FindNodeOrInsertPos(ID, InsertPos); 2952 } 2953 } 2954 2955 T = new (*this) PackExpansionType(Pattern, Canon, NumExpansions); 2956 Types.push_back(T); 2957 PackExpansionTypes.InsertNode(T, InsertPos); 2958 return QualType(T, 0); 2959} 2960 2961/// CmpProtocolNames - Comparison predicate for sorting protocols 2962/// alphabetically. 2963static bool CmpProtocolNames(const ObjCProtocolDecl *LHS, 2964 const ObjCProtocolDecl *RHS) { 2965 return LHS->getDeclName() < RHS->getDeclName(); 2966} 2967 2968static bool areSortedAndUniqued(ObjCProtocolDecl * const *Protocols, 2969 unsigned NumProtocols) { 2970 if (NumProtocols == 0) return true; 2971 2972 if (Protocols[0]->getCanonicalDecl() != Protocols[0]) 2973 return false; 2974 2975 for (unsigned i = 1; i != NumProtocols; ++i) 2976 if (!CmpProtocolNames(Protocols[i-1], Protocols[i]) || 2977 Protocols[i]->getCanonicalDecl() != Protocols[i]) 2978 return false; 2979 return true; 2980} 2981 2982static void SortAndUniqueProtocols(ObjCProtocolDecl **Protocols, 2983 unsigned &NumProtocols) { 2984 ObjCProtocolDecl **ProtocolsEnd = Protocols+NumProtocols; 2985 2986 // Sort protocols, keyed by name. 2987 std::sort(Protocols, Protocols+NumProtocols, CmpProtocolNames); 2988 2989 // Canonicalize. 2990 for (unsigned I = 0, N = NumProtocols; I != N; ++I) 2991 Protocols[I] = Protocols[I]->getCanonicalDecl(); 2992 2993 // Remove duplicates. 2994 ProtocolsEnd = std::unique(Protocols, ProtocolsEnd); 2995 NumProtocols = ProtocolsEnd-Protocols; 2996} 2997 2998QualType ASTContext::getObjCObjectType(QualType BaseType, 2999 ObjCProtocolDecl * const *Protocols, 3000 unsigned NumProtocols) const { 3001 // If the base type is an interface and there aren't any protocols 3002 // to add, then the interface type will do just fine. 3003 if (!NumProtocols && isa<ObjCInterfaceType>(BaseType)) 3004 return BaseType; 3005 3006 // Look in the folding set for an existing type. 3007 llvm::FoldingSetNodeID ID; 3008 ObjCObjectTypeImpl::Profile(ID, BaseType, Protocols, NumProtocols); 3009 void *InsertPos = 0; 3010 if (ObjCObjectType *QT = ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos)) 3011 return QualType(QT, 0); 3012 3013 // Build the canonical type, which has the canonical base type and 3014 // a sorted-and-uniqued list of protocols. 3015 QualType Canonical; 3016 bool ProtocolsSorted = areSortedAndUniqued(Protocols, NumProtocols); 3017 if (!ProtocolsSorted || !BaseType.isCanonical()) { 3018 if (!ProtocolsSorted) { 3019 SmallVector<ObjCProtocolDecl*, 8> Sorted(Protocols, 3020 Protocols + NumProtocols); 3021 unsigned UniqueCount = NumProtocols; 3022 3023 SortAndUniqueProtocols(&Sorted[0], UniqueCount); 3024 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3025 &Sorted[0], UniqueCount); 3026 } else { 3027 Canonical = getObjCObjectType(getCanonicalType(BaseType), 3028 Protocols, NumProtocols); 3029 } 3030 3031 // Regenerate InsertPos. 3032 ObjCObjectTypes.FindNodeOrInsertPos(ID, InsertPos); 3033 } 3034 3035 unsigned Size = sizeof(ObjCObjectTypeImpl); 3036 Size += NumProtocols * sizeof(ObjCProtocolDecl *); 3037 void *Mem = Allocate(Size, TypeAlignment); 3038 ObjCObjectTypeImpl *T = 3039 new (Mem) ObjCObjectTypeImpl(Canonical, BaseType, Protocols, NumProtocols); 3040 3041 Types.push_back(T); 3042 ObjCObjectTypes.InsertNode(T, InsertPos); 3043 return QualType(T, 0); 3044} 3045 3046/// getObjCObjectPointerType - Return a ObjCObjectPointerType type for 3047/// the given object type. 3048QualType ASTContext::getObjCObjectPointerType(QualType ObjectT) const { 3049 llvm::FoldingSetNodeID ID; 3050 ObjCObjectPointerType::Profile(ID, ObjectT); 3051 3052 void *InsertPos = 0; 3053 if (ObjCObjectPointerType *QT = 3054 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos)) 3055 return QualType(QT, 0); 3056 3057 // Find the canonical object type. 3058 QualType Canonical; 3059 if (!ObjectT.isCanonical()) { 3060 Canonical = getObjCObjectPointerType(getCanonicalType(ObjectT)); 3061 3062 // Regenerate InsertPos. 3063 ObjCObjectPointerTypes.FindNodeOrInsertPos(ID, InsertPos); 3064 } 3065 3066 // No match. 3067 void *Mem = Allocate(sizeof(ObjCObjectPointerType), TypeAlignment); 3068 ObjCObjectPointerType *QType = 3069 new (Mem) ObjCObjectPointerType(Canonical, ObjectT); 3070 3071 Types.push_back(QType); 3072 ObjCObjectPointerTypes.InsertNode(QType, InsertPos); 3073 return QualType(QType, 0); 3074} 3075 3076/// getObjCInterfaceType - Return the unique reference to the type for the 3077/// specified ObjC interface decl. The list of protocols is optional. 3078QualType ASTContext::getObjCInterfaceType(const ObjCInterfaceDecl *Decl, 3079 ObjCInterfaceDecl *PrevDecl) const { 3080 if (Decl->TypeForDecl) 3081 return QualType(Decl->TypeForDecl, 0); 3082 3083 if (PrevDecl) { 3084 assert(PrevDecl->TypeForDecl && "previous decl has no TypeForDecl"); 3085 Decl->TypeForDecl = PrevDecl->TypeForDecl; 3086 return QualType(PrevDecl->TypeForDecl, 0); 3087 } 3088 3089 // Prefer the definition, if there is one. 3090 if (const ObjCInterfaceDecl *Def = Decl->getDefinition()) 3091 Decl = Def; 3092 3093 void *Mem = Allocate(sizeof(ObjCInterfaceType), TypeAlignment); 3094 ObjCInterfaceType *T = new (Mem) ObjCInterfaceType(Decl); 3095 Decl->TypeForDecl = T; 3096 Types.push_back(T); 3097 return QualType(T, 0); 3098} 3099 3100/// getTypeOfExprType - Unlike many "get<Type>" functions, we can't unique 3101/// TypeOfExprType AST's (since expression's are never shared). For example, 3102/// multiple declarations that refer to "typeof(x)" all contain different 3103/// DeclRefExpr's. This doesn't effect the type checker, since it operates 3104/// on canonical type's (which are always unique). 3105QualType ASTContext::getTypeOfExprType(Expr *tofExpr) const { 3106 TypeOfExprType *toe; 3107 if (tofExpr->isTypeDependent()) { 3108 llvm::FoldingSetNodeID ID; 3109 DependentTypeOfExprType::Profile(ID, *this, tofExpr); 3110 3111 void *InsertPos = 0; 3112 DependentTypeOfExprType *Canon 3113 = DependentTypeOfExprTypes.FindNodeOrInsertPos(ID, InsertPos); 3114 if (Canon) { 3115 // We already have a "canonical" version of an identical, dependent 3116 // typeof(expr) type. Use that as our canonical type. 3117 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, 3118 QualType((TypeOfExprType*)Canon, 0)); 3119 } else { 3120 // Build a new, canonical typeof(expr) type. 3121 Canon 3122 = new (*this, TypeAlignment) DependentTypeOfExprType(*this, tofExpr); 3123 DependentTypeOfExprTypes.InsertNode(Canon, InsertPos); 3124 toe = Canon; 3125 } 3126 } else { 3127 QualType Canonical = getCanonicalType(tofExpr->getType()); 3128 toe = new (*this, TypeAlignment) TypeOfExprType(tofExpr, Canonical); 3129 } 3130 Types.push_back(toe); 3131 return QualType(toe, 0); 3132} 3133 3134/// getTypeOfType - Unlike many "get<Type>" functions, we don't unique 3135/// TypeOfType AST's. The only motivation to unique these nodes would be 3136/// memory savings. Since typeof(t) is fairly uncommon, space shouldn't be 3137/// an issue. This doesn't effect the type checker, since it operates 3138/// on canonical type's (which are always unique). 3139QualType ASTContext::getTypeOfType(QualType tofType) const { 3140 QualType Canonical = getCanonicalType(tofType); 3141 TypeOfType *tot = new (*this, TypeAlignment) TypeOfType(tofType, Canonical); 3142 Types.push_back(tot); 3143 return QualType(tot, 0); 3144} 3145 3146 3147/// getDecltypeType - Unlike many "get<Type>" functions, we don't unique 3148/// DecltypeType AST's. The only motivation to unique these nodes would be 3149/// memory savings. Since decltype(t) is fairly uncommon, space shouldn't be 3150/// an issue. This doesn't effect the type checker, since it operates 3151/// on canonical types (which are always unique). 3152QualType ASTContext::getDecltypeType(Expr *e, QualType UnderlyingType) const { 3153 DecltypeType *dt; 3154 3155 // C++0x [temp.type]p2: 3156 // If an expression e involves a template parameter, decltype(e) denotes a 3157 // unique dependent type. Two such decltype-specifiers refer to the same 3158 // type only if their expressions are equivalent (14.5.6.1). 3159 if (e->isInstantiationDependent()) { 3160 llvm::FoldingSetNodeID ID; 3161 DependentDecltypeType::Profile(ID, *this, e); 3162 3163 void *InsertPos = 0; 3164 DependentDecltypeType *Canon 3165 = DependentDecltypeTypes.FindNodeOrInsertPos(ID, InsertPos); 3166 if (Canon) { 3167 // We already have a "canonical" version of an equivalent, dependent 3168 // decltype type. Use that as our canonical type. 3169 dt = new (*this, TypeAlignment) DecltypeType(e, DependentTy, 3170 QualType((DecltypeType*)Canon, 0)); 3171 } else { 3172 // Build a new, canonical typeof(expr) type. 3173 Canon = new (*this, TypeAlignment) DependentDecltypeType(*this, e); 3174 DependentDecltypeTypes.InsertNode(Canon, InsertPos); 3175 dt = Canon; 3176 } 3177 } else { 3178 dt = new (*this, TypeAlignment) DecltypeType(e, UnderlyingType, 3179 getCanonicalType(UnderlyingType)); 3180 } 3181 Types.push_back(dt); 3182 return QualType(dt, 0); 3183} 3184 3185/// getUnaryTransformationType - We don't unique these, since the memory 3186/// savings are minimal and these are rare. 3187QualType ASTContext::getUnaryTransformType(QualType BaseType, 3188 QualType UnderlyingType, 3189 UnaryTransformType::UTTKind Kind) 3190 const { 3191 UnaryTransformType *Ty = 3192 new (*this, TypeAlignment) UnaryTransformType (BaseType, UnderlyingType, 3193 Kind, 3194 UnderlyingType->isDependentType() ? 3195 QualType() : getCanonicalType(UnderlyingType)); 3196 Types.push_back(Ty); 3197 return QualType(Ty, 0); 3198} 3199 3200/// getAutoType - We only unique auto types after they've been deduced. 3201QualType ASTContext::getAutoType(QualType DeducedType) const { 3202 void *InsertPos = 0; 3203 if (!DeducedType.isNull()) { 3204 // Look in the folding set for an existing type. 3205 llvm::FoldingSetNodeID ID; 3206 AutoType::Profile(ID, DeducedType); 3207 if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos)) 3208 return QualType(AT, 0); 3209 } 3210 3211 AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType); 3212 Types.push_back(AT); 3213 if (InsertPos) 3214 AutoTypes.InsertNode(AT, InsertPos); 3215 return QualType(AT, 0); 3216} 3217 3218/// getAtomicType - Return the uniqued reference to the atomic type for 3219/// the given value type. 3220QualType ASTContext::getAtomicType(QualType T) const { 3221 // Unique pointers, to guarantee there is only one pointer of a particular 3222 // structure. 3223 llvm::FoldingSetNodeID ID; 3224 AtomicType::Profile(ID, T); 3225 3226 void *InsertPos = 0; 3227 if (AtomicType *AT = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos)) 3228 return QualType(AT, 0); 3229 3230 // If the atomic value type isn't canonical, this won't be a canonical type 3231 // either, so fill in the canonical type field. 3232 QualType Canonical; 3233 if (!T.isCanonical()) { 3234 Canonical = getAtomicType(getCanonicalType(T)); 3235 3236 // Get the new insert position for the node we care about. 3237 AtomicType *NewIP = AtomicTypes.FindNodeOrInsertPos(ID, InsertPos); 3238 assert(NewIP == 0 && "Shouldn't be in the map!"); (void)NewIP; 3239 } 3240 AtomicType *New = new (*this, TypeAlignment) AtomicType(T, Canonical); 3241 Types.push_back(New); 3242 AtomicTypes.InsertNode(New, InsertPos); 3243 return QualType(New, 0); 3244} 3245 3246/// getAutoDeductType - Get type pattern for deducing against 'auto'. 3247QualType ASTContext::getAutoDeductType() const { 3248 if (AutoDeductTy.isNull()) 3249 AutoDeductTy = getAutoType(QualType()); 3250 assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern"); 3251 return AutoDeductTy; 3252} 3253 3254/// getAutoRRefDeductType - Get type pattern for deducing against 'auto &&'. 3255QualType ASTContext::getAutoRRefDeductType() const { 3256 if (AutoRRefDeductTy.isNull()) 3257 AutoRRefDeductTy = getRValueReferenceType(getAutoDeductType()); 3258 assert(!AutoRRefDeductTy.isNull() && "can't build 'auto &&' pattern"); 3259 return AutoRRefDeductTy; 3260} 3261 3262/// getTagDeclType - Return the unique reference to the type for the 3263/// specified TagDecl (struct/union/class/enum) decl. 3264QualType ASTContext::getTagDeclType(const TagDecl *Decl) const { 3265 assert (Decl); 3266 // FIXME: What is the design on getTagDeclType when it requires casting 3267 // away const? mutable? 3268 return getTypeDeclType(const_cast<TagDecl*>(Decl)); 3269} 3270 3271/// getSizeType - Return the unique type for "size_t" (C99 7.17), the result 3272/// of the sizeof operator (C99 6.5.3.4p4). The value is target dependent and 3273/// needs to agree with the definition in <stddef.h>. 3274CanQualType ASTContext::getSizeType() const { 3275 return getFromTargetType(Target->getSizeType()); 3276} 3277 3278/// getIntMaxType - Return the unique type for "intmax_t" (C99 7.18.1.5). 3279CanQualType ASTContext::getIntMaxType() const { 3280 return getFromTargetType(Target->getIntMaxType()); 3281} 3282 3283/// getUIntMaxType - Return the unique type for "uintmax_t" (C99 7.18.1.5). 3284CanQualType ASTContext::getUIntMaxType() const { 3285 return getFromTargetType(Target->getUIntMaxType()); 3286} 3287 3288/// getSignedWCharType - Return the type of "signed wchar_t". 3289/// Used when in C++, as a GCC extension. 3290QualType ASTContext::getSignedWCharType() const { 3291 // FIXME: derive from "Target" ? 3292 return WCharTy; 3293} 3294 3295/// getUnsignedWCharType - Return the type of "unsigned wchar_t". 3296/// Used when in C++, as a GCC extension. 3297QualType ASTContext::getUnsignedWCharType() const { 3298 // FIXME: derive from "Target" ? 3299 return UnsignedIntTy; 3300} 3301 3302/// getPointerDiffType - Return the unique type for "ptrdiff_t" (C99 7.17) 3303/// defined in <stddef.h>. Pointer - pointer requires this (C99 6.5.6p9). 3304QualType ASTContext::getPointerDiffType() const { 3305 return getFromTargetType(Target->getPtrDiffType(0)); 3306} 3307 3308//===----------------------------------------------------------------------===// 3309// Type Operators 3310//===----------------------------------------------------------------------===// 3311 3312CanQualType ASTContext::getCanonicalParamType(QualType T) const { 3313 // Push qualifiers into arrays, and then discard any remaining 3314 // qualifiers. 3315 T = getCanonicalType(T); 3316 T = getVariableArrayDecayedType(T); 3317 const Type *Ty = T.getTypePtr(); 3318 QualType Result; 3319 if (isa<ArrayType>(Ty)) { 3320 Result = getArrayDecayedType(QualType(Ty,0)); 3321 } else if (isa<FunctionType>(Ty)) { 3322 Result = getPointerType(QualType(Ty, 0)); 3323 } else { 3324 Result = QualType(Ty, 0); 3325 } 3326 3327 return CanQualType::CreateUnsafe(Result); 3328} 3329 3330QualType ASTContext::getUnqualifiedArrayType(QualType type, 3331 Qualifiers &quals) { 3332 SplitQualType splitType = type.getSplitUnqualifiedType(); 3333 3334 // FIXME: getSplitUnqualifiedType() actually walks all the way to 3335 // the unqualified desugared type and then drops it on the floor. 3336 // We then have to strip that sugar back off with 3337 // getUnqualifiedDesugaredType(), which is silly. 3338 const ArrayType *AT = 3339 dyn_cast<ArrayType>(splitType.Ty->getUnqualifiedDesugaredType()); 3340 3341 // If we don't have an array, just use the results in splitType. 3342 if (!AT) { 3343 quals = splitType.Quals; 3344 return QualType(splitType.Ty, 0); 3345 } 3346 3347 // Otherwise, recurse on the array's element type. 3348 QualType elementType = AT->getElementType(); 3349 QualType unqualElementType = getUnqualifiedArrayType(elementType, quals); 3350 3351 // If that didn't change the element type, AT has no qualifiers, so we 3352 // can just use the results in splitType. 3353 if (elementType == unqualElementType) { 3354 assert(quals.empty()); // from the recursive call 3355 quals = splitType.Quals; 3356 return QualType(splitType.Ty, 0); 3357 } 3358 3359 // Otherwise, add in the qualifiers from the outermost type, then 3360 // build the type back up. 3361 quals.addConsistentQualifiers(splitType.Quals); 3362 3363 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 3364 return getConstantArrayType(unqualElementType, CAT->getSize(), 3365 CAT->getSizeModifier(), 0); 3366 } 3367 3368 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) { 3369 return getIncompleteArrayType(unqualElementType, IAT->getSizeModifier(), 0); 3370 } 3371 3372 if (const VariableArrayType *VAT = dyn_cast<VariableArrayType>(AT)) { 3373 return getVariableArrayType(unqualElementType, 3374 VAT->getSizeExpr(), 3375 VAT->getSizeModifier(), 3376 VAT->getIndexTypeCVRQualifiers(), 3377 VAT->getBracketsRange()); 3378 } 3379 3380 const DependentSizedArrayType *DSAT = cast<DependentSizedArrayType>(AT); 3381 return getDependentSizedArrayType(unqualElementType, DSAT->getSizeExpr(), 3382 DSAT->getSizeModifier(), 0, 3383 SourceRange()); 3384} 3385 3386/// UnwrapSimilarPointerTypes - If T1 and T2 are pointer types that 3387/// may be similar (C++ 4.4), replaces T1 and T2 with the type that 3388/// they point to and return true. If T1 and T2 aren't pointer types 3389/// or pointer-to-member types, or if they are not similar at this 3390/// level, returns false and leaves T1 and T2 unchanged. Top-level 3391/// qualifiers on T1 and T2 are ignored. This function will typically 3392/// be called in a loop that successively "unwraps" pointer and 3393/// pointer-to-member types to compare them at each level. 3394bool ASTContext::UnwrapSimilarPointerTypes(QualType &T1, QualType &T2) { 3395 const PointerType *T1PtrType = T1->getAs<PointerType>(), 3396 *T2PtrType = T2->getAs<PointerType>(); 3397 if (T1PtrType && T2PtrType) { 3398 T1 = T1PtrType->getPointeeType(); 3399 T2 = T2PtrType->getPointeeType(); 3400 return true; 3401 } 3402 3403 const MemberPointerType *T1MPType = T1->getAs<MemberPointerType>(), 3404 *T2MPType = T2->getAs<MemberPointerType>(); 3405 if (T1MPType && T2MPType && 3406 hasSameUnqualifiedType(QualType(T1MPType->getClass(), 0), 3407 QualType(T2MPType->getClass(), 0))) { 3408 T1 = T1MPType->getPointeeType(); 3409 T2 = T2MPType->getPointeeType(); 3410 return true; 3411 } 3412 3413 if (getLangOpts().ObjC1) { 3414 const ObjCObjectPointerType *T1OPType = T1->getAs<ObjCObjectPointerType>(), 3415 *T2OPType = T2->getAs<ObjCObjectPointerType>(); 3416 if (T1OPType && T2OPType) { 3417 T1 = T1OPType->getPointeeType(); 3418 T2 = T2OPType->getPointeeType(); 3419 return true; 3420 } 3421 } 3422 3423 // FIXME: Block pointers, too? 3424 3425 return false; 3426} 3427 3428DeclarationNameInfo 3429ASTContext::getNameForTemplate(TemplateName Name, 3430 SourceLocation NameLoc) const { 3431 switch (Name.getKind()) { 3432 case TemplateName::QualifiedTemplate: 3433 case TemplateName::Template: 3434 // DNInfo work in progress: CHECKME: what about DNLoc? 3435 return DeclarationNameInfo(Name.getAsTemplateDecl()->getDeclName(), 3436 NameLoc); 3437 3438 case TemplateName::OverloadedTemplate: { 3439 OverloadedTemplateStorage *Storage = Name.getAsOverloadedTemplate(); 3440 // DNInfo work in progress: CHECKME: what about DNLoc? 3441 return DeclarationNameInfo((*Storage->begin())->getDeclName(), NameLoc); 3442 } 3443 3444 case TemplateName::DependentTemplate: { 3445 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3446 DeclarationName DName; 3447 if (DTN->isIdentifier()) { 3448 DName = DeclarationNames.getIdentifier(DTN->getIdentifier()); 3449 return DeclarationNameInfo(DName, NameLoc); 3450 } else { 3451 DName = DeclarationNames.getCXXOperatorName(DTN->getOperator()); 3452 // DNInfo work in progress: FIXME: source locations? 3453 DeclarationNameLoc DNLoc; 3454 DNLoc.CXXOperatorName.BeginOpNameLoc = SourceLocation().getRawEncoding(); 3455 DNLoc.CXXOperatorName.EndOpNameLoc = SourceLocation().getRawEncoding(); 3456 return DeclarationNameInfo(DName, NameLoc, DNLoc); 3457 } 3458 } 3459 3460 case TemplateName::SubstTemplateTemplateParm: { 3461 SubstTemplateTemplateParmStorage *subst 3462 = Name.getAsSubstTemplateTemplateParm(); 3463 return DeclarationNameInfo(subst->getParameter()->getDeclName(), 3464 NameLoc); 3465 } 3466 3467 case TemplateName::SubstTemplateTemplateParmPack: { 3468 SubstTemplateTemplateParmPackStorage *subst 3469 = Name.getAsSubstTemplateTemplateParmPack(); 3470 return DeclarationNameInfo(subst->getParameterPack()->getDeclName(), 3471 NameLoc); 3472 } 3473 } 3474 3475 llvm_unreachable("bad template name kind!"); 3476} 3477 3478TemplateName ASTContext::getCanonicalTemplateName(TemplateName Name) const { 3479 switch (Name.getKind()) { 3480 case TemplateName::QualifiedTemplate: 3481 case TemplateName::Template: { 3482 TemplateDecl *Template = Name.getAsTemplateDecl(); 3483 if (TemplateTemplateParmDecl *TTP 3484 = dyn_cast<TemplateTemplateParmDecl>(Template)) 3485 Template = getCanonicalTemplateTemplateParmDecl(TTP); 3486 3487 // The canonical template name is the canonical template declaration. 3488 return TemplateName(cast<TemplateDecl>(Template->getCanonicalDecl())); 3489 } 3490 3491 case TemplateName::OverloadedTemplate: 3492 llvm_unreachable("cannot canonicalize overloaded template"); 3493 3494 case TemplateName::DependentTemplate: { 3495 DependentTemplateName *DTN = Name.getAsDependentTemplateName(); 3496 assert(DTN && "Non-dependent template names must refer to template decls."); 3497 return DTN->CanonicalTemplateName; 3498 } 3499 3500 case TemplateName::SubstTemplateTemplateParm: { 3501 SubstTemplateTemplateParmStorage *subst 3502 = Name.getAsSubstTemplateTemplateParm(); 3503 return getCanonicalTemplateName(subst->getReplacement()); 3504 } 3505 3506 case TemplateName::SubstTemplateTemplateParmPack: { 3507 SubstTemplateTemplateParmPackStorage *subst 3508 = Name.getAsSubstTemplateTemplateParmPack(); 3509 TemplateTemplateParmDecl *canonParameter 3510 = getCanonicalTemplateTemplateParmDecl(subst->getParameterPack()); 3511 TemplateArgument canonArgPack 3512 = getCanonicalTemplateArgument(subst->getArgumentPack()); 3513 return getSubstTemplateTemplateParmPack(canonParameter, canonArgPack); 3514 } 3515 } 3516 3517 llvm_unreachable("bad template name!"); 3518} 3519 3520bool ASTContext::hasSameTemplateName(TemplateName X, TemplateName Y) { 3521 X = getCanonicalTemplateName(X); 3522 Y = getCanonicalTemplateName(Y); 3523 return X.getAsVoidPointer() == Y.getAsVoidPointer(); 3524} 3525 3526TemplateArgument 3527ASTContext::getCanonicalTemplateArgument(const TemplateArgument &Arg) const { 3528 switch (Arg.getKind()) { 3529 case TemplateArgument::Null: 3530 return Arg; 3531 3532 case TemplateArgument::Expression: 3533 return Arg; 3534 3535 case TemplateArgument::Declaration: { 3536 if (Decl *D = Arg.getAsDecl()) 3537 return TemplateArgument(D->getCanonicalDecl()); 3538 return TemplateArgument((Decl*)0); 3539 } 3540 3541 case TemplateArgument::Template: 3542 return TemplateArgument(getCanonicalTemplateName(Arg.getAsTemplate())); 3543 3544 case TemplateArgument::TemplateExpansion: 3545 return TemplateArgument(getCanonicalTemplateName( 3546 Arg.getAsTemplateOrTemplatePattern()), 3547 Arg.getNumTemplateExpansions()); 3548 3549 case TemplateArgument::Integral: 3550 return TemplateArgument(Arg, getCanonicalType(Arg.getIntegralType())); 3551 3552 case TemplateArgument::Type: 3553 return TemplateArgument(getCanonicalType(Arg.getAsType())); 3554 3555 case TemplateArgument::Pack: { 3556 if (Arg.pack_size() == 0) 3557 return Arg; 3558 3559 TemplateArgument *CanonArgs 3560 = new (*this) TemplateArgument[Arg.pack_size()]; 3561 unsigned Idx = 0; 3562 for (TemplateArgument::pack_iterator A = Arg.pack_begin(), 3563 AEnd = Arg.pack_end(); 3564 A != AEnd; (void)++A, ++Idx) 3565 CanonArgs[Idx] = getCanonicalTemplateArgument(*A); 3566 3567 return TemplateArgument(CanonArgs, Arg.pack_size()); 3568 } 3569 } 3570 3571 // Silence GCC warning 3572 llvm_unreachable("Unhandled template argument kind"); 3573} 3574 3575NestedNameSpecifier * 3576ASTContext::getCanonicalNestedNameSpecifier(NestedNameSpecifier *NNS) const { 3577 if (!NNS) 3578 return 0; 3579 3580 switch (NNS->getKind()) { 3581 case NestedNameSpecifier::Identifier: 3582 // Canonicalize the prefix but keep the identifier the same. 3583 return NestedNameSpecifier::Create(*this, 3584 getCanonicalNestedNameSpecifier(NNS->getPrefix()), 3585 NNS->getAsIdentifier()); 3586 3587 case NestedNameSpecifier::Namespace: 3588 // A namespace is canonical; build a nested-name-specifier with 3589 // this namespace and no prefix. 3590 return NestedNameSpecifier::Create(*this, 0, 3591 NNS->getAsNamespace()->getOriginalNamespace()); 3592 3593 case NestedNameSpecifier::NamespaceAlias: 3594 // A namespace is canonical; build a nested-name-specifier with 3595 // this namespace and no prefix. 3596 return NestedNameSpecifier::Create(*this, 0, 3597 NNS->getAsNamespaceAlias()->getNamespace() 3598 ->getOriginalNamespace()); 3599 3600 case NestedNameSpecifier::TypeSpec: 3601 case NestedNameSpecifier::TypeSpecWithTemplate: { 3602 QualType T = getCanonicalType(QualType(NNS->getAsType(), 0)); 3603 3604 // If we have some kind of dependent-named type (e.g., "typename T::type"), 3605 // break it apart into its prefix and identifier, then reconsititute those 3606 // as the canonical nested-name-specifier. This is required to canonicalize 3607 // a dependent nested-name-specifier involving typedefs of dependent-name 3608 // types, e.g., 3609 // typedef typename T::type T1; 3610 // typedef typename T1::type T2; 3611 if (const DependentNameType *DNT = T->getAs<DependentNameType>()) 3612 return NestedNameSpecifier::Create(*this, DNT->getQualifier(), 3613 const_cast<IdentifierInfo *>(DNT->getIdentifier())); 3614 3615 // Otherwise, just canonicalize the type, and force it to be a TypeSpec. 3616 // FIXME: Why are TypeSpec and TypeSpecWithTemplate distinct in the 3617 // first place? 3618 return NestedNameSpecifier::Create(*this, 0, false, 3619 const_cast<Type*>(T.getTypePtr())); 3620 } 3621 3622 case NestedNameSpecifier::Global: 3623 // The global specifier is canonical and unique. 3624 return NNS; 3625 } 3626 3627 llvm_unreachable("Invalid NestedNameSpecifier::Kind!"); 3628} 3629 3630 3631const ArrayType *ASTContext::getAsArrayType(QualType T) const { 3632 // Handle the non-qualified case efficiently. 3633 if (!T.hasLocalQualifiers()) { 3634 // Handle the common positive case fast. 3635 if (const ArrayType *AT = dyn_cast<ArrayType>(T)) 3636 return AT; 3637 } 3638 3639 // Handle the common negative case fast. 3640 if (!isa<ArrayType>(T.getCanonicalType())) 3641 return 0; 3642 3643 // Apply any qualifiers from the array type to the element type. This 3644 // implements C99 6.7.3p8: "If the specification of an array type includes 3645 // any type qualifiers, the element type is so qualified, not the array type." 3646 3647 // If we get here, we either have type qualifiers on the type, or we have 3648 // sugar such as a typedef in the way. If we have type qualifiers on the type 3649 // we must propagate them down into the element type. 3650 3651 SplitQualType split = T.getSplitDesugaredType(); 3652 Qualifiers qs = split.Quals; 3653 3654 // If we have a simple case, just return now. 3655 const ArrayType *ATy = dyn_cast<ArrayType>(split.Ty); 3656 if (ATy == 0 || qs.empty()) 3657 return ATy; 3658 3659 // Otherwise, we have an array and we have qualifiers on it. Push the 3660 // qualifiers into the array element type and return a new array type. 3661 QualType NewEltTy = getQualifiedType(ATy->getElementType(), qs); 3662 3663 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(ATy)) 3664 return cast<ArrayType>(getConstantArrayType(NewEltTy, CAT->getSize(), 3665 CAT->getSizeModifier(), 3666 CAT->getIndexTypeCVRQualifiers())); 3667 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(ATy)) 3668 return cast<ArrayType>(getIncompleteArrayType(NewEltTy, 3669 IAT->getSizeModifier(), 3670 IAT->getIndexTypeCVRQualifiers())); 3671 3672 if (const DependentSizedArrayType *DSAT 3673 = dyn_cast<DependentSizedArrayType>(ATy)) 3674 return cast<ArrayType>( 3675 getDependentSizedArrayType(NewEltTy, 3676 DSAT->getSizeExpr(), 3677 DSAT->getSizeModifier(), 3678 DSAT->getIndexTypeCVRQualifiers(), 3679 DSAT->getBracketsRange())); 3680 3681 const VariableArrayType *VAT = cast<VariableArrayType>(ATy); 3682 return cast<ArrayType>(getVariableArrayType(NewEltTy, 3683 VAT->getSizeExpr(), 3684 VAT->getSizeModifier(), 3685 VAT->getIndexTypeCVRQualifiers(), 3686 VAT->getBracketsRange())); 3687} 3688 3689QualType ASTContext::getAdjustedParameterType(QualType T) const { 3690 // C99 6.7.5.3p7: 3691 // A declaration of a parameter as "array of type" shall be 3692 // adjusted to "qualified pointer to type", where the type 3693 // qualifiers (if any) are those specified within the [ and ] of 3694 // the array type derivation. 3695 if (T->isArrayType()) 3696 return getArrayDecayedType(T); 3697 3698 // C99 6.7.5.3p8: 3699 // A declaration of a parameter as "function returning type" 3700 // shall be adjusted to "pointer to function returning type", as 3701 // in 6.3.2.1. 3702 if (T->isFunctionType()) 3703 return getPointerType(T); 3704 3705 return T; 3706} 3707 3708QualType ASTContext::getSignatureParameterType(QualType T) const { 3709 T = getVariableArrayDecayedType(T); 3710 T = getAdjustedParameterType(T); 3711 return T.getUnqualifiedType(); 3712} 3713 3714/// getArrayDecayedType - Return the properly qualified result of decaying the 3715/// specified array type to a pointer. This operation is non-trivial when 3716/// handling typedefs etc. The canonical type of "T" must be an array type, 3717/// this returns a pointer to a properly qualified element of the array. 3718/// 3719/// See C99 6.7.5.3p7 and C99 6.3.2.1p3. 3720QualType ASTContext::getArrayDecayedType(QualType Ty) const { 3721 // Get the element type with 'getAsArrayType' so that we don't lose any 3722 // typedefs in the element type of the array. This also handles propagation 3723 // of type qualifiers from the array type into the element type if present 3724 // (C99 6.7.3p8). 3725 const ArrayType *PrettyArrayType = getAsArrayType(Ty); 3726 assert(PrettyArrayType && "Not an array type!"); 3727 3728 QualType PtrTy = getPointerType(PrettyArrayType->getElementType()); 3729 3730 // int x[restrict 4] -> int *restrict 3731 return getQualifiedType(PtrTy, PrettyArrayType->getIndexTypeQualifiers()); 3732} 3733 3734QualType ASTContext::getBaseElementType(const ArrayType *array) const { 3735 return getBaseElementType(array->getElementType()); 3736} 3737 3738QualType ASTContext::getBaseElementType(QualType type) const { 3739 Qualifiers qs; 3740 while (true) { 3741 SplitQualType split = type.getSplitDesugaredType(); 3742 const ArrayType *array = split.Ty->getAsArrayTypeUnsafe(); 3743 if (!array) break; 3744 3745 type = array->getElementType(); 3746 qs.addConsistentQualifiers(split.Quals); 3747 } 3748 3749 return getQualifiedType(type, qs); 3750} 3751 3752/// getConstantArrayElementCount - Returns number of constant array elements. 3753uint64_t 3754ASTContext::getConstantArrayElementCount(const ConstantArrayType *CA) const { 3755 uint64_t ElementCount = 1; 3756 do { 3757 ElementCount *= CA->getSize().getZExtValue(); 3758 CA = dyn_cast<ConstantArrayType>(CA->getElementType()); 3759 } while (CA); 3760 return ElementCount; 3761} 3762 3763/// getFloatingRank - Return a relative rank for floating point types. 3764/// This routine will assert if passed a built-in type that isn't a float. 3765static FloatingRank getFloatingRank(QualType T) { 3766 if (const ComplexType *CT = T->getAs<ComplexType>()) 3767 return getFloatingRank(CT->getElementType()); 3768 3769 assert(T->getAs<BuiltinType>() && "getFloatingRank(): not a floating type"); 3770 switch (T->getAs<BuiltinType>()->getKind()) { 3771 default: llvm_unreachable("getFloatingRank(): not a floating type"); 3772 case BuiltinType::Half: return HalfRank; 3773 case BuiltinType::Float: return FloatRank; 3774 case BuiltinType::Double: return DoubleRank; 3775 case BuiltinType::LongDouble: return LongDoubleRank; 3776 } 3777} 3778 3779/// getFloatingTypeOfSizeWithinDomain - Returns a real floating 3780/// point or a complex type (based on typeDomain/typeSize). 3781/// 'typeDomain' is a real floating point or complex type. 3782/// 'typeSize' is a real floating point or complex type. 3783QualType ASTContext::getFloatingTypeOfSizeWithinDomain(QualType Size, 3784 QualType Domain) const { 3785 FloatingRank EltRank = getFloatingRank(Size); 3786 if (Domain->isComplexType()) { 3787 switch (EltRank) { 3788 case HalfRank: llvm_unreachable("Complex half is not supported"); 3789 case FloatRank: return FloatComplexTy; 3790 case DoubleRank: return DoubleComplexTy; 3791 case LongDoubleRank: return LongDoubleComplexTy; 3792 } 3793 } 3794 3795 assert(Domain->isRealFloatingType() && "Unknown domain!"); 3796 switch (EltRank) { 3797 case HalfRank: llvm_unreachable("Half ranks are not valid here"); 3798 case FloatRank: return FloatTy; 3799 case DoubleRank: return DoubleTy; 3800 case LongDoubleRank: return LongDoubleTy; 3801 } 3802 llvm_unreachable("getFloatingRank(): illegal value for rank"); 3803} 3804 3805/// getFloatingTypeOrder - Compare the rank of the two specified floating 3806/// point types, ignoring the domain of the type (i.e. 'double' == 3807/// '_Complex double'). If LHS > RHS, return 1. If LHS == RHS, return 0. If 3808/// LHS < RHS, return -1. 3809int ASTContext::getFloatingTypeOrder(QualType LHS, QualType RHS) const { 3810 FloatingRank LHSR = getFloatingRank(LHS); 3811 FloatingRank RHSR = getFloatingRank(RHS); 3812 3813 if (LHSR == RHSR) 3814 return 0; 3815 if (LHSR > RHSR) 3816 return 1; 3817 return -1; 3818} 3819 3820/// getIntegerRank - Return an integer conversion rank (C99 6.3.1.1p1). This 3821/// routine will assert if passed a built-in type that isn't an integer or enum, 3822/// or if it is not canonicalized. 3823unsigned ASTContext::getIntegerRank(const Type *T) const { 3824 assert(T->isCanonicalUnqualified() && "T should be canonicalized"); 3825 3826 switch (cast<BuiltinType>(T)->getKind()) { 3827 default: llvm_unreachable("getIntegerRank(): not a built-in integer"); 3828 case BuiltinType::Bool: 3829 return 1 + (getIntWidth(BoolTy) << 3); 3830 case BuiltinType::Char_S: 3831 case BuiltinType::Char_U: 3832 case BuiltinType::SChar: 3833 case BuiltinType::UChar: 3834 return 2 + (getIntWidth(CharTy) << 3); 3835 case BuiltinType::Short: 3836 case BuiltinType::UShort: 3837 return 3 + (getIntWidth(ShortTy) << 3); 3838 case BuiltinType::Int: 3839 case BuiltinType::UInt: 3840 return 4 + (getIntWidth(IntTy) << 3); 3841 case BuiltinType::Long: 3842 case BuiltinType::ULong: 3843 return 5 + (getIntWidth(LongTy) << 3); 3844 case BuiltinType::LongLong: 3845 case BuiltinType::ULongLong: 3846 return 6 + (getIntWidth(LongLongTy) << 3); 3847 case BuiltinType::Int128: 3848 case BuiltinType::UInt128: 3849 return 7 + (getIntWidth(Int128Ty) << 3); 3850 } 3851} 3852 3853/// \brief Whether this is a promotable bitfield reference according 3854/// to C99 6.3.1.1p2, bullet 2 (and GCC extensions). 3855/// 3856/// \returns the type this bit-field will promote to, or NULL if no 3857/// promotion occurs. 3858QualType ASTContext::isPromotableBitField(Expr *E) const { 3859 if (E->isTypeDependent() || E->isValueDependent()) 3860 return QualType(); 3861 3862 FieldDecl *Field = E->getBitField(); 3863 if (!Field) 3864 return QualType(); 3865 3866 QualType FT = Field->getType(); 3867 3868 uint64_t BitWidth = Field->getBitWidthValue(*this); 3869 uint64_t IntSize = getTypeSize(IntTy); 3870 // GCC extension compatibility: if the bit-field size is less than or equal 3871 // to the size of int, it gets promoted no matter what its type is. 3872 // For instance, unsigned long bf : 4 gets promoted to signed int. 3873 if (BitWidth < IntSize) 3874 return IntTy; 3875 3876 if (BitWidth == IntSize) 3877 return FT->isSignedIntegerType() ? IntTy : UnsignedIntTy; 3878 3879 // Types bigger than int are not subject to promotions, and therefore act 3880 // like the base type. 3881 // FIXME: This doesn't quite match what gcc does, but what gcc does here 3882 // is ridiculous. 3883 return QualType(); 3884} 3885 3886/// getPromotedIntegerType - Returns the type that Promotable will 3887/// promote to: C99 6.3.1.1p2, assuming that Promotable is a promotable 3888/// integer type. 3889QualType ASTContext::getPromotedIntegerType(QualType Promotable) const { 3890 assert(!Promotable.isNull()); 3891 assert(Promotable->isPromotableIntegerType()); 3892 if (const EnumType *ET = Promotable->getAs<EnumType>()) 3893 return ET->getDecl()->getPromotionType(); 3894 3895 if (const BuiltinType *BT = Promotable->getAs<BuiltinType>()) { 3896 // C++ [conv.prom]: A prvalue of type char16_t, char32_t, or wchar_t 3897 // (3.9.1) can be converted to a prvalue of the first of the following 3898 // types that can represent all the values of its underlying type: 3899 // int, unsigned int, long int, unsigned long int, long long int, or 3900 // unsigned long long int [...] 3901 // FIXME: Is there some better way to compute this? 3902 if (BT->getKind() == BuiltinType::WChar_S || 3903 BT->getKind() == BuiltinType::WChar_U || 3904 BT->getKind() == BuiltinType::Char16 || 3905 BT->getKind() == BuiltinType::Char32) { 3906 bool FromIsSigned = BT->getKind() == BuiltinType::WChar_S; 3907 uint64_t FromSize = getTypeSize(BT); 3908 QualType PromoteTypes[] = { IntTy, UnsignedIntTy, LongTy, UnsignedLongTy, 3909 LongLongTy, UnsignedLongLongTy }; 3910 for (size_t Idx = 0; Idx < llvm::array_lengthof(PromoteTypes); ++Idx) { 3911 uint64_t ToSize = getTypeSize(PromoteTypes[Idx]); 3912 if (FromSize < ToSize || 3913 (FromSize == ToSize && 3914 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) 3915 return PromoteTypes[Idx]; 3916 } 3917 llvm_unreachable("char type should fit into long long"); 3918 } 3919 } 3920 3921 // At this point, we should have a signed or unsigned integer type. 3922 if (Promotable->isSignedIntegerType()) 3923 return IntTy; 3924 uint64_t PromotableSize = getTypeSize(Promotable); 3925 uint64_t IntSize = getTypeSize(IntTy); 3926 assert(Promotable->isUnsignedIntegerType() && PromotableSize <= IntSize); 3927 return (PromotableSize != IntSize) ? IntTy : UnsignedIntTy; 3928} 3929 3930/// \brief Recurses in pointer/array types until it finds an objc retainable 3931/// type and returns its ownership. 3932Qualifiers::ObjCLifetime ASTContext::getInnerObjCOwnership(QualType T) const { 3933 while (!T.isNull()) { 3934 if (T.getObjCLifetime() != Qualifiers::OCL_None) 3935 return T.getObjCLifetime(); 3936 if (T->isArrayType()) 3937 T = getBaseElementType(T); 3938 else if (const PointerType *PT = T->getAs<PointerType>()) 3939 T = PT->getPointeeType(); 3940 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 3941 T = RT->getPointeeType(); 3942 else 3943 break; 3944 } 3945 3946 return Qualifiers::OCL_None; 3947} 3948 3949/// getIntegerTypeOrder - Returns the highest ranked integer type: 3950/// C99 6.3.1.8p1. If LHS > RHS, return 1. If LHS == RHS, return 0. If 3951/// LHS < RHS, return -1. 3952int ASTContext::getIntegerTypeOrder(QualType LHS, QualType RHS) const { 3953 const Type *LHSC = getCanonicalType(LHS).getTypePtr(); 3954 const Type *RHSC = getCanonicalType(RHS).getTypePtr(); 3955 if (LHSC == RHSC) return 0; 3956 3957 bool LHSUnsigned = LHSC->isUnsignedIntegerType(); 3958 bool RHSUnsigned = RHSC->isUnsignedIntegerType(); 3959 3960 unsigned LHSRank = getIntegerRank(LHSC); 3961 unsigned RHSRank = getIntegerRank(RHSC); 3962 3963 if (LHSUnsigned == RHSUnsigned) { // Both signed or both unsigned. 3964 if (LHSRank == RHSRank) return 0; 3965 return LHSRank > RHSRank ? 1 : -1; 3966 } 3967 3968 // Otherwise, the LHS is signed and the RHS is unsigned or visa versa. 3969 if (LHSUnsigned) { 3970 // If the unsigned [LHS] type is larger, return it. 3971 if (LHSRank >= RHSRank) 3972 return 1; 3973 3974 // If the signed type can represent all values of the unsigned type, it 3975 // wins. Because we are dealing with 2's complement and types that are 3976 // powers of two larger than each other, this is always safe. 3977 return -1; 3978 } 3979 3980 // If the unsigned [RHS] type is larger, return it. 3981 if (RHSRank >= LHSRank) 3982 return -1; 3983 3984 // If the signed type can represent all values of the unsigned type, it 3985 // wins. Because we are dealing with 2's complement and types that are 3986 // powers of two larger than each other, this is always safe. 3987 return 1; 3988} 3989 3990static RecordDecl * 3991CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK, 3992 DeclContext *DC, IdentifierInfo *Id) { 3993 SourceLocation Loc; 3994 if (Ctx.getLangOpts().CPlusPlus) 3995 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3996 else 3997 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id); 3998} 3999 4000// getCFConstantStringType - Return the type used for constant CFStrings. 4001QualType ASTContext::getCFConstantStringType() const { 4002 if (!CFConstantStringTypeDecl) { 4003 CFConstantStringTypeDecl = 4004 CreateRecordDecl(*this, TTK_Struct, TUDecl, 4005 &Idents.get("NSConstantString")); 4006 CFConstantStringTypeDecl->startDefinition(); 4007 4008 QualType FieldTypes[4]; 4009 4010 // const int *isa; 4011 FieldTypes[0] = getPointerType(IntTy.withConst()); 4012 // int flags; 4013 FieldTypes[1] = IntTy; 4014 // const char *str; 4015 FieldTypes[2] = getPointerType(CharTy.withConst()); 4016 // long length; 4017 FieldTypes[3] = LongTy; 4018 4019 // Create fields 4020 for (unsigned i = 0; i < 4; ++i) { 4021 FieldDecl *Field = FieldDecl::Create(*this, CFConstantStringTypeDecl, 4022 SourceLocation(), 4023 SourceLocation(), 0, 4024 FieldTypes[i], /*TInfo=*/0, 4025 /*BitWidth=*/0, 4026 /*Mutable=*/false, 4027 ICIS_NoInit); 4028 Field->setAccess(AS_public); 4029 CFConstantStringTypeDecl->addDecl(Field); 4030 } 4031 4032 CFConstantStringTypeDecl->completeDefinition(); 4033 } 4034 4035 return getTagDeclType(CFConstantStringTypeDecl); 4036} 4037 4038void ASTContext::setCFConstantStringType(QualType T) { 4039 const RecordType *Rec = T->getAs<RecordType>(); 4040 assert(Rec && "Invalid CFConstantStringType"); 4041 CFConstantStringTypeDecl = Rec->getDecl(); 4042} 4043 4044QualType ASTContext::getBlockDescriptorType() const { 4045 if (BlockDescriptorType) 4046 return getTagDeclType(BlockDescriptorType); 4047 4048 RecordDecl *T; 4049 // FIXME: Needs the FlagAppleBlock bit. 4050 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4051 &Idents.get("__block_descriptor")); 4052 T->startDefinition(); 4053 4054 QualType FieldTypes[] = { 4055 UnsignedLongTy, 4056 UnsignedLongTy, 4057 }; 4058 4059 const char *FieldNames[] = { 4060 "reserved", 4061 "Size" 4062 }; 4063 4064 for (size_t i = 0; i < 2; ++i) { 4065 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4066 SourceLocation(), 4067 &Idents.get(FieldNames[i]), 4068 FieldTypes[i], /*TInfo=*/0, 4069 /*BitWidth=*/0, 4070 /*Mutable=*/false, 4071 ICIS_NoInit); 4072 Field->setAccess(AS_public); 4073 T->addDecl(Field); 4074 } 4075 4076 T->completeDefinition(); 4077 4078 BlockDescriptorType = T; 4079 4080 return getTagDeclType(BlockDescriptorType); 4081} 4082 4083QualType ASTContext::getBlockDescriptorExtendedType() const { 4084 if (BlockDescriptorExtendedType) 4085 return getTagDeclType(BlockDescriptorExtendedType); 4086 4087 RecordDecl *T; 4088 // FIXME: Needs the FlagAppleBlock bit. 4089 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, 4090 &Idents.get("__block_descriptor_withcopydispose")); 4091 T->startDefinition(); 4092 4093 QualType FieldTypes[] = { 4094 UnsignedLongTy, 4095 UnsignedLongTy, 4096 getPointerType(VoidPtrTy), 4097 getPointerType(VoidPtrTy) 4098 }; 4099 4100 const char *FieldNames[] = { 4101 "reserved", 4102 "Size", 4103 "CopyFuncPtr", 4104 "DestroyFuncPtr" 4105 }; 4106 4107 for (size_t i = 0; i < 4; ++i) { 4108 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4109 SourceLocation(), 4110 &Idents.get(FieldNames[i]), 4111 FieldTypes[i], /*TInfo=*/0, 4112 /*BitWidth=*/0, 4113 /*Mutable=*/false, 4114 ICIS_NoInit); 4115 Field->setAccess(AS_public); 4116 T->addDecl(Field); 4117 } 4118 4119 T->completeDefinition(); 4120 4121 BlockDescriptorExtendedType = T; 4122 4123 return getTagDeclType(BlockDescriptorExtendedType); 4124} 4125 4126bool ASTContext::BlockRequiresCopying(QualType Ty) const { 4127 if (Ty->isObjCRetainableType()) 4128 return true; 4129 if (getLangOpts().CPlusPlus) { 4130 if (const RecordType *RT = Ty->getAs<RecordType>()) { 4131 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 4132 return RD->hasConstCopyConstructor(); 4133 4134 } 4135 } 4136 return false; 4137} 4138 4139QualType 4140ASTContext::BuildByRefType(StringRef DeclName, QualType Ty) const { 4141 // type = struct __Block_byref_1_X { 4142 // void *__isa; 4143 // struct __Block_byref_1_X *__forwarding; 4144 // unsigned int __flags; 4145 // unsigned int __size; 4146 // void *__copy_helper; // as needed 4147 // void *__destroy_help // as needed 4148 // int X; 4149 // } * 4150 4151 bool HasCopyAndDispose = BlockRequiresCopying(Ty); 4152 4153 // FIXME: Move up 4154 SmallString<36> Name; 4155 llvm::raw_svector_ostream(Name) << "__Block_byref_" << 4156 ++UniqueBlockByRefTypeID << '_' << DeclName; 4157 RecordDecl *T; 4158 T = CreateRecordDecl(*this, TTK_Struct, TUDecl, &Idents.get(Name.str())); 4159 T->startDefinition(); 4160 QualType Int32Ty = IntTy; 4161 assert(getIntWidth(IntTy) == 32 && "non-32bit int not supported"); 4162 QualType FieldTypes[] = { 4163 getPointerType(VoidPtrTy), 4164 getPointerType(getTagDeclType(T)), 4165 Int32Ty, 4166 Int32Ty, 4167 getPointerType(VoidPtrTy), 4168 getPointerType(VoidPtrTy), 4169 Ty 4170 }; 4171 4172 StringRef FieldNames[] = { 4173 "__isa", 4174 "__forwarding", 4175 "__flags", 4176 "__size", 4177 "__copy_helper", 4178 "__destroy_helper", 4179 DeclName, 4180 }; 4181 4182 for (size_t i = 0; i < 7; ++i) { 4183 if (!HasCopyAndDispose && i >=4 && i <= 5) 4184 continue; 4185 FieldDecl *Field = FieldDecl::Create(*this, T, SourceLocation(), 4186 SourceLocation(), 4187 &Idents.get(FieldNames[i]), 4188 FieldTypes[i], /*TInfo=*/0, 4189 /*BitWidth=*/0, /*Mutable=*/false, 4190 ICIS_NoInit); 4191 Field->setAccess(AS_public); 4192 T->addDecl(Field); 4193 } 4194 4195 T->completeDefinition(); 4196 4197 return getPointerType(getTagDeclType(T)); 4198} 4199 4200TypedefDecl *ASTContext::getObjCInstanceTypeDecl() { 4201 if (!ObjCInstanceTypeDecl) 4202 ObjCInstanceTypeDecl = TypedefDecl::Create(*this, 4203 getTranslationUnitDecl(), 4204 SourceLocation(), 4205 SourceLocation(), 4206 &Idents.get("instancetype"), 4207 getTrivialTypeSourceInfo(getObjCIdType())); 4208 return ObjCInstanceTypeDecl; 4209} 4210 4211// This returns true if a type has been typedefed to BOOL: 4212// typedef <type> BOOL; 4213static bool isTypeTypedefedAsBOOL(QualType T) { 4214 if (const TypedefType *TT = dyn_cast<TypedefType>(T)) 4215 if (IdentifierInfo *II = TT->getDecl()->getIdentifier()) 4216 return II->isStr("BOOL"); 4217 4218 return false; 4219} 4220 4221/// getObjCEncodingTypeSize returns size of type for objective-c encoding 4222/// purpose. 4223CharUnits ASTContext::getObjCEncodingTypeSize(QualType type) const { 4224 if (!type->isIncompleteArrayType() && type->isIncompleteType()) 4225 return CharUnits::Zero(); 4226 4227 CharUnits sz = getTypeSizeInChars(type); 4228 4229 // Make all integer and enum types at least as large as an int 4230 if (sz.isPositive() && type->isIntegralOrEnumerationType()) 4231 sz = std::max(sz, getTypeSizeInChars(IntTy)); 4232 // Treat arrays as pointers, since that's how they're passed in. 4233 else if (type->isArrayType()) 4234 sz = getTypeSizeInChars(VoidPtrTy); 4235 return sz; 4236} 4237 4238static inline 4239std::string charUnitsToString(const CharUnits &CU) { 4240 return llvm::itostr(CU.getQuantity()); 4241} 4242 4243/// getObjCEncodingForBlock - Return the encoded type for this block 4244/// declaration. 4245std::string ASTContext::getObjCEncodingForBlock(const BlockExpr *Expr) const { 4246 std::string S; 4247 4248 const BlockDecl *Decl = Expr->getBlockDecl(); 4249 QualType BlockTy = 4250 Expr->getType()->getAs<BlockPointerType>()->getPointeeType(); 4251 // Encode result type. 4252 getObjCEncodingForType(BlockTy->getAs<FunctionType>()->getResultType(), S); 4253 // Compute size of all parameters. 4254 // Start with computing size of a pointer in number of bytes. 4255 // FIXME: There might(should) be a better way of doing this computation! 4256 SourceLocation Loc; 4257 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4258 CharUnits ParmOffset = PtrSize; 4259 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), 4260 E = Decl->param_end(); PI != E; ++PI) { 4261 QualType PType = (*PI)->getType(); 4262 CharUnits sz = getObjCEncodingTypeSize(PType); 4263 if (sz.isZero()) 4264 continue; 4265 assert (sz.isPositive() && "BlockExpr - Incomplete param type"); 4266 ParmOffset += sz; 4267 } 4268 // Size of the argument frame 4269 S += charUnitsToString(ParmOffset); 4270 // Block pointer and offset. 4271 S += "@?0"; 4272 4273 // Argument types. 4274 ParmOffset = PtrSize; 4275 for (BlockDecl::param_const_iterator PI = Decl->param_begin(), E = 4276 Decl->param_end(); PI != E; ++PI) { 4277 ParmVarDecl *PVDecl = *PI; 4278 QualType PType = PVDecl->getOriginalType(); 4279 if (const ArrayType *AT = 4280 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4281 // Use array's original type only if it has known number of 4282 // elements. 4283 if (!isa<ConstantArrayType>(AT)) 4284 PType = PVDecl->getType(); 4285 } else if (PType->isFunctionType()) 4286 PType = PVDecl->getType(); 4287 getObjCEncodingForType(PType, S); 4288 S += charUnitsToString(ParmOffset); 4289 ParmOffset += getObjCEncodingTypeSize(PType); 4290 } 4291 4292 return S; 4293} 4294 4295bool ASTContext::getObjCEncodingForFunctionDecl(const FunctionDecl *Decl, 4296 std::string& S) { 4297 // Encode result type. 4298 getObjCEncodingForType(Decl->getResultType(), S); 4299 CharUnits ParmOffset; 4300 // Compute size of all parameters. 4301 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4302 E = Decl->param_end(); PI != E; ++PI) { 4303 QualType PType = (*PI)->getType(); 4304 CharUnits sz = getObjCEncodingTypeSize(PType); 4305 if (sz.isZero()) 4306 continue; 4307 4308 assert (sz.isPositive() && 4309 "getObjCEncodingForFunctionDecl - Incomplete param type"); 4310 ParmOffset += sz; 4311 } 4312 S += charUnitsToString(ParmOffset); 4313 ParmOffset = CharUnits::Zero(); 4314 4315 // Argument types. 4316 for (FunctionDecl::param_const_iterator PI = Decl->param_begin(), 4317 E = Decl->param_end(); PI != E; ++PI) { 4318 ParmVarDecl *PVDecl = *PI; 4319 QualType PType = PVDecl->getOriginalType(); 4320 if (const ArrayType *AT = 4321 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4322 // Use array's original type only if it has known number of 4323 // elements. 4324 if (!isa<ConstantArrayType>(AT)) 4325 PType = PVDecl->getType(); 4326 } else if (PType->isFunctionType()) 4327 PType = PVDecl->getType(); 4328 getObjCEncodingForType(PType, S); 4329 S += charUnitsToString(ParmOffset); 4330 ParmOffset += getObjCEncodingTypeSize(PType); 4331 } 4332 4333 return false; 4334} 4335 4336/// getObjCEncodingForMethodParameter - Return the encoded type for a single 4337/// method parameter or return type. If Extended, include class names and 4338/// block object types. 4339void ASTContext::getObjCEncodingForMethodParameter(Decl::ObjCDeclQualifier QT, 4340 QualType T, std::string& S, 4341 bool Extended) const { 4342 // Encode type qualifer, 'in', 'inout', etc. for the parameter. 4343 getObjCEncodingForTypeQualifier(QT, S); 4344 // Encode parameter type. 4345 getObjCEncodingForTypeImpl(T, S, true, true, 0, 4346 true /*OutermostType*/, 4347 false /*EncodingProperty*/, 4348 false /*StructField*/, 4349 Extended /*EncodeBlockParameters*/, 4350 Extended /*EncodeClassNames*/); 4351} 4352 4353/// getObjCEncodingForMethodDecl - Return the encoded type for this method 4354/// declaration. 4355bool ASTContext::getObjCEncodingForMethodDecl(const ObjCMethodDecl *Decl, 4356 std::string& S, 4357 bool Extended) const { 4358 // FIXME: This is not very efficient. 4359 // Encode return type. 4360 getObjCEncodingForMethodParameter(Decl->getObjCDeclQualifier(), 4361 Decl->getResultType(), S, Extended); 4362 // Compute size of all parameters. 4363 // Start with computing size of a pointer in number of bytes. 4364 // FIXME: There might(should) be a better way of doing this computation! 4365 SourceLocation Loc; 4366 CharUnits PtrSize = getTypeSizeInChars(VoidPtrTy); 4367 // The first two arguments (self and _cmd) are pointers; account for 4368 // their size. 4369 CharUnits ParmOffset = 2 * PtrSize; 4370 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4371 E = Decl->sel_param_end(); PI != E; ++PI) { 4372 QualType PType = (*PI)->getType(); 4373 CharUnits sz = getObjCEncodingTypeSize(PType); 4374 if (sz.isZero()) 4375 continue; 4376 4377 assert (sz.isPositive() && 4378 "getObjCEncodingForMethodDecl - Incomplete param type"); 4379 ParmOffset += sz; 4380 } 4381 S += charUnitsToString(ParmOffset); 4382 S += "@0:"; 4383 S += charUnitsToString(PtrSize); 4384 4385 // Argument types. 4386 ParmOffset = 2 * PtrSize; 4387 for (ObjCMethodDecl::param_const_iterator PI = Decl->param_begin(), 4388 E = Decl->sel_param_end(); PI != E; ++PI) { 4389 const ParmVarDecl *PVDecl = *PI; 4390 QualType PType = PVDecl->getOriginalType(); 4391 if (const ArrayType *AT = 4392 dyn_cast<ArrayType>(PType->getCanonicalTypeInternal())) { 4393 // Use array's original type only if it has known number of 4394 // elements. 4395 if (!isa<ConstantArrayType>(AT)) 4396 PType = PVDecl->getType(); 4397 } else if (PType->isFunctionType()) 4398 PType = PVDecl->getType(); 4399 getObjCEncodingForMethodParameter(PVDecl->getObjCDeclQualifier(), 4400 PType, S, Extended); 4401 S += charUnitsToString(ParmOffset); 4402 ParmOffset += getObjCEncodingTypeSize(PType); 4403 } 4404 4405 return false; 4406} 4407 4408/// getObjCEncodingForPropertyDecl - Return the encoded type for this 4409/// property declaration. If non-NULL, Container must be either an 4410/// ObjCCategoryImplDecl or ObjCImplementationDecl; it should only be 4411/// NULL when getting encodings for protocol properties. 4412/// Property attributes are stored as a comma-delimited C string. The simple 4413/// attributes readonly and bycopy are encoded as single characters. The 4414/// parametrized attributes, getter=name, setter=name, and ivar=name, are 4415/// encoded as single characters, followed by an identifier. Property types 4416/// are also encoded as a parametrized attribute. The characters used to encode 4417/// these attributes are defined by the following enumeration: 4418/// @code 4419/// enum PropertyAttributes { 4420/// kPropertyReadOnly = 'R', // property is read-only. 4421/// kPropertyBycopy = 'C', // property is a copy of the value last assigned 4422/// kPropertyByref = '&', // property is a reference to the value last assigned 4423/// kPropertyDynamic = 'D', // property is dynamic 4424/// kPropertyGetter = 'G', // followed by getter selector name 4425/// kPropertySetter = 'S', // followed by setter selector name 4426/// kPropertyInstanceVariable = 'V' // followed by instance variable name 4427/// kPropertyType = 'T' // followed by old-style type encoding. 4428/// kPropertyWeak = 'W' // 'weak' property 4429/// kPropertyStrong = 'P' // property GC'able 4430/// kPropertyNonAtomic = 'N' // property non-atomic 4431/// }; 4432/// @endcode 4433void ASTContext::getObjCEncodingForPropertyDecl(const ObjCPropertyDecl *PD, 4434 const Decl *Container, 4435 std::string& S) const { 4436 // Collect information from the property implementation decl(s). 4437 bool Dynamic = false; 4438 ObjCPropertyImplDecl *SynthesizePID = 0; 4439 4440 // FIXME: Duplicated code due to poor abstraction. 4441 if (Container) { 4442 if (const ObjCCategoryImplDecl *CID = 4443 dyn_cast<ObjCCategoryImplDecl>(Container)) { 4444 for (ObjCCategoryImplDecl::propimpl_iterator 4445 i = CID->propimpl_begin(), e = CID->propimpl_end(); 4446 i != e; ++i) { 4447 ObjCPropertyImplDecl *PID = *i; 4448 if (PID->getPropertyDecl() == PD) { 4449 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4450 Dynamic = true; 4451 } else { 4452 SynthesizePID = PID; 4453 } 4454 } 4455 } 4456 } else { 4457 const ObjCImplementationDecl *OID=cast<ObjCImplementationDecl>(Container); 4458 for (ObjCCategoryImplDecl::propimpl_iterator 4459 i = OID->propimpl_begin(), e = OID->propimpl_end(); 4460 i != e; ++i) { 4461 ObjCPropertyImplDecl *PID = *i; 4462 if (PID->getPropertyDecl() == PD) { 4463 if (PID->getPropertyImplementation()==ObjCPropertyImplDecl::Dynamic) { 4464 Dynamic = true; 4465 } else { 4466 SynthesizePID = PID; 4467 } 4468 } 4469 } 4470 } 4471 } 4472 4473 // FIXME: This is not very efficient. 4474 S = "T"; 4475 4476 // Encode result type. 4477 // GCC has some special rules regarding encoding of properties which 4478 // closely resembles encoding of ivars. 4479 getObjCEncodingForTypeImpl(PD->getType(), S, true, true, 0, 4480 true /* outermost type */, 4481 true /* encoding for property */); 4482 4483 if (PD->isReadOnly()) { 4484 S += ",R"; 4485 } else { 4486 switch (PD->getSetterKind()) { 4487 case ObjCPropertyDecl::Assign: break; 4488 case ObjCPropertyDecl::Copy: S += ",C"; break; 4489 case ObjCPropertyDecl::Retain: S += ",&"; break; 4490 case ObjCPropertyDecl::Weak: S += ",W"; break; 4491 } 4492 } 4493 4494 // It really isn't clear at all what this means, since properties 4495 // are "dynamic by default". 4496 if (Dynamic) 4497 S += ",D"; 4498 4499 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 4500 S += ",N"; 4501 4502 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_getter) { 4503 S += ",G"; 4504 S += PD->getGetterName().getAsString(); 4505 } 4506 4507 if (PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_setter) { 4508 S += ",S"; 4509 S += PD->getSetterName().getAsString(); 4510 } 4511 4512 if (SynthesizePID) { 4513 const ObjCIvarDecl *OID = SynthesizePID->getPropertyIvarDecl(); 4514 S += ",V"; 4515 S += OID->getNameAsString(); 4516 } 4517 4518 // FIXME: OBJCGC: weak & strong 4519} 4520 4521/// getLegacyIntegralTypeEncoding - 4522/// Another legacy compatibility encoding: 32-bit longs are encoded as 4523/// 'l' or 'L' , but not always. For typedefs, we need to use 4524/// 'i' or 'I' instead if encoding a struct field, or a pointer! 4525/// 4526void ASTContext::getLegacyIntegralTypeEncoding (QualType &PointeeTy) const { 4527 if (isa<TypedefType>(PointeeTy.getTypePtr())) { 4528 if (const BuiltinType *BT = PointeeTy->getAs<BuiltinType>()) { 4529 if (BT->getKind() == BuiltinType::ULong && getIntWidth(PointeeTy) == 32) 4530 PointeeTy = UnsignedIntTy; 4531 else 4532 if (BT->getKind() == BuiltinType::Long && getIntWidth(PointeeTy) == 32) 4533 PointeeTy = IntTy; 4534 } 4535 } 4536} 4537 4538void ASTContext::getObjCEncodingForType(QualType T, std::string& S, 4539 const FieldDecl *Field) const { 4540 // We follow the behavior of gcc, expanding structures which are 4541 // directly pointed to, and expanding embedded structures. Note that 4542 // these rules are sufficient to prevent recursive encoding of the 4543 // same type. 4544 getObjCEncodingForTypeImpl(T, S, true, true, Field, 4545 true /* outermost type */); 4546} 4547 4548static char ObjCEncodingForPrimitiveKind(const ASTContext *C, QualType T) { 4549 switch (T->getAs<BuiltinType>()->getKind()) { 4550 default: llvm_unreachable("Unhandled builtin type kind"); 4551 case BuiltinType::Void: return 'v'; 4552 case BuiltinType::Bool: return 'B'; 4553 case BuiltinType::Char_U: 4554 case BuiltinType::UChar: return 'C'; 4555 case BuiltinType::UShort: return 'S'; 4556 case BuiltinType::UInt: return 'I'; 4557 case BuiltinType::ULong: 4558 return C->getIntWidth(T) == 32 ? 'L' : 'Q'; 4559 case BuiltinType::UInt128: return 'T'; 4560 case BuiltinType::ULongLong: return 'Q'; 4561 case BuiltinType::Char_S: 4562 case BuiltinType::SChar: return 'c'; 4563 case BuiltinType::Short: return 's'; 4564 case BuiltinType::WChar_S: 4565 case BuiltinType::WChar_U: 4566 case BuiltinType::Int: return 'i'; 4567 case BuiltinType::Long: 4568 return C->getIntWidth(T) == 32 ? 'l' : 'q'; 4569 case BuiltinType::LongLong: return 'q'; 4570 case BuiltinType::Int128: return 't'; 4571 case BuiltinType::Float: return 'f'; 4572 case BuiltinType::Double: return 'd'; 4573 case BuiltinType::LongDouble: return 'D'; 4574 } 4575} 4576 4577static char ObjCEncodingForEnumType(const ASTContext *C, const EnumType *ET) { 4578 EnumDecl *Enum = ET->getDecl(); 4579 4580 // The encoding of an non-fixed enum type is always 'i', regardless of size. 4581 if (!Enum->isFixed()) 4582 return 'i'; 4583 4584 // The encoding of a fixed enum type matches its fixed underlying type. 4585 return ObjCEncodingForPrimitiveKind(C, Enum->getIntegerType()); 4586} 4587 4588static void EncodeBitField(const ASTContext *Ctx, std::string& S, 4589 QualType T, const FieldDecl *FD) { 4590 assert(FD->isBitField() && "not a bitfield - getObjCEncodingForTypeImpl"); 4591 S += 'b'; 4592 // The NeXT runtime encodes bit fields as b followed by the number of bits. 4593 // The GNU runtime requires more information; bitfields are encoded as b, 4594 // then the offset (in bits) of the first element, then the type of the 4595 // bitfield, then the size in bits. For example, in this structure: 4596 // 4597 // struct 4598 // { 4599 // int integer; 4600 // int flags:2; 4601 // }; 4602 // On a 32-bit system, the encoding for flags would be b2 for the NeXT 4603 // runtime, but b32i2 for the GNU runtime. The reason for this extra 4604 // information is not especially sensible, but we're stuck with it for 4605 // compatibility with GCC, although providing it breaks anything that 4606 // actually uses runtime introspection and wants to work on both runtimes... 4607 if (Ctx->getLangOpts().ObjCRuntime.isGNUFamily()) { 4608 const RecordDecl *RD = FD->getParent(); 4609 const ASTRecordLayout &RL = Ctx->getASTRecordLayout(RD); 4610 S += llvm::utostr(RL.getFieldOffset(FD->getFieldIndex())); 4611 if (const EnumType *ET = T->getAs<EnumType>()) 4612 S += ObjCEncodingForEnumType(Ctx, ET); 4613 else 4614 S += ObjCEncodingForPrimitiveKind(Ctx, T); 4615 } 4616 S += llvm::utostr(FD->getBitWidthValue(*Ctx)); 4617} 4618 4619// FIXME: Use SmallString for accumulating string. 4620void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S, 4621 bool ExpandPointedToStructures, 4622 bool ExpandStructures, 4623 const FieldDecl *FD, 4624 bool OutermostType, 4625 bool EncodingProperty, 4626 bool StructField, 4627 bool EncodeBlockParameters, 4628 bool EncodeClassNames) const { 4629 if (T->getAs<BuiltinType>()) { 4630 if (FD && FD->isBitField()) 4631 return EncodeBitField(this, S, T, FD); 4632 S += ObjCEncodingForPrimitiveKind(this, T); 4633 return; 4634 } 4635 4636 if (const ComplexType *CT = T->getAs<ComplexType>()) { 4637 S += 'j'; 4638 getObjCEncodingForTypeImpl(CT->getElementType(), S, false, false, 0, false, 4639 false); 4640 return; 4641 } 4642 4643 // encoding for pointer or r3eference types. 4644 QualType PointeeTy; 4645 if (const PointerType *PT = T->getAs<PointerType>()) { 4646 if (PT->isObjCSelType()) { 4647 S += ':'; 4648 return; 4649 } 4650 PointeeTy = PT->getPointeeType(); 4651 } 4652 else if (const ReferenceType *RT = T->getAs<ReferenceType>()) 4653 PointeeTy = RT->getPointeeType(); 4654 if (!PointeeTy.isNull()) { 4655 bool isReadOnly = false; 4656 // For historical/compatibility reasons, the read-only qualifier of the 4657 // pointee gets emitted _before_ the '^'. The read-only qualifier of 4658 // the pointer itself gets ignored, _unless_ we are looking at a typedef! 4659 // Also, do not emit the 'r' for anything but the outermost type! 4660 if (isa<TypedefType>(T.getTypePtr())) { 4661 if (OutermostType && T.isConstQualified()) { 4662 isReadOnly = true; 4663 S += 'r'; 4664 } 4665 } else if (OutermostType) { 4666 QualType P = PointeeTy; 4667 while (P->getAs<PointerType>()) 4668 P = P->getAs<PointerType>()->getPointeeType(); 4669 if (P.isConstQualified()) { 4670 isReadOnly = true; 4671 S += 'r'; 4672 } 4673 } 4674 if (isReadOnly) { 4675 // Another legacy compatibility encoding. Some ObjC qualifier and type 4676 // combinations need to be rearranged. 4677 // Rewrite "in const" from "nr" to "rn" 4678 if (StringRef(S).endswith("nr")) 4679 S.replace(S.end()-2, S.end(), "rn"); 4680 } 4681 4682 if (PointeeTy->isCharType()) { 4683 // char pointer types should be encoded as '*' unless it is a 4684 // type that has been typedef'd to 'BOOL'. 4685 if (!isTypeTypedefedAsBOOL(PointeeTy)) { 4686 S += '*'; 4687 return; 4688 } 4689 } else if (const RecordType *RTy = PointeeTy->getAs<RecordType>()) { 4690 // GCC binary compat: Need to convert "struct objc_class *" to "#". 4691 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_class")) { 4692 S += '#'; 4693 return; 4694 } 4695 // GCC binary compat: Need to convert "struct objc_object *" to "@". 4696 if (RTy->getDecl()->getIdentifier() == &Idents.get("objc_object")) { 4697 S += '@'; 4698 return; 4699 } 4700 // fall through... 4701 } 4702 S += '^'; 4703 getLegacyIntegralTypeEncoding(PointeeTy); 4704 4705 getObjCEncodingForTypeImpl(PointeeTy, S, false, ExpandPointedToStructures, 4706 NULL); 4707 return; 4708 } 4709 4710 if (const ArrayType *AT = 4711 // Ignore type qualifiers etc. 4712 dyn_cast<ArrayType>(T->getCanonicalTypeInternal())) { 4713 if (isa<IncompleteArrayType>(AT) && !StructField) { 4714 // Incomplete arrays are encoded as a pointer to the array element. 4715 S += '^'; 4716 4717 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4718 false, ExpandStructures, FD); 4719 } else { 4720 S += '['; 4721 4722 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) { 4723 if (getTypeSize(CAT->getElementType()) == 0) 4724 S += '0'; 4725 else 4726 S += llvm::utostr(CAT->getSize().getZExtValue()); 4727 } else { 4728 //Variable length arrays are encoded as a regular array with 0 elements. 4729 assert((isa<VariableArrayType>(AT) || isa<IncompleteArrayType>(AT)) && 4730 "Unknown array type!"); 4731 S += '0'; 4732 } 4733 4734 getObjCEncodingForTypeImpl(AT->getElementType(), S, 4735 false, ExpandStructures, FD); 4736 S += ']'; 4737 } 4738 return; 4739 } 4740 4741 if (T->getAs<FunctionType>()) { 4742 S += '?'; 4743 return; 4744 } 4745 4746 if (const RecordType *RTy = T->getAs<RecordType>()) { 4747 RecordDecl *RDecl = RTy->getDecl(); 4748 S += RDecl->isUnion() ? '(' : '{'; 4749 // Anonymous structures print as '?' 4750 if (const IdentifierInfo *II = RDecl->getIdentifier()) { 4751 S += II->getName(); 4752 if (ClassTemplateSpecializationDecl *Spec 4753 = dyn_cast<ClassTemplateSpecializationDecl>(RDecl)) { 4754 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 4755 std::string TemplateArgsStr 4756 = TemplateSpecializationType::PrintTemplateArgumentList( 4757 TemplateArgs.data(), 4758 TemplateArgs.size(), 4759 (*this).getPrintingPolicy()); 4760 4761 S += TemplateArgsStr; 4762 } 4763 } else { 4764 S += '?'; 4765 } 4766 if (ExpandStructures) { 4767 S += '='; 4768 if (!RDecl->isUnion()) { 4769 getObjCEncodingForStructureImpl(RDecl, S, FD); 4770 } else { 4771 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4772 FieldEnd = RDecl->field_end(); 4773 Field != FieldEnd; ++Field) { 4774 if (FD) { 4775 S += '"'; 4776 S += Field->getNameAsString(); 4777 S += '"'; 4778 } 4779 4780 // Special case bit-fields. 4781 if (Field->isBitField()) { 4782 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, 4783 *Field); 4784 } else { 4785 QualType qt = Field->getType(); 4786 getLegacyIntegralTypeEncoding(qt); 4787 getObjCEncodingForTypeImpl(qt, S, false, true, 4788 FD, /*OutermostType*/false, 4789 /*EncodingProperty*/false, 4790 /*StructField*/true); 4791 } 4792 } 4793 } 4794 } 4795 S += RDecl->isUnion() ? ')' : '}'; 4796 return; 4797 } 4798 4799 if (const EnumType *ET = T->getAs<EnumType>()) { 4800 if (FD && FD->isBitField()) 4801 EncodeBitField(this, S, T, FD); 4802 else 4803 S += ObjCEncodingForEnumType(this, ET); 4804 return; 4805 } 4806 4807 if (const BlockPointerType *BT = T->getAs<BlockPointerType>()) { 4808 S += "@?"; // Unlike a pointer-to-function, which is "^?". 4809 if (EncodeBlockParameters) { 4810 const FunctionType *FT = BT->getPointeeType()->getAs<FunctionType>(); 4811 4812 S += '<'; 4813 // Block return type 4814 getObjCEncodingForTypeImpl(FT->getResultType(), S, 4815 ExpandPointedToStructures, ExpandStructures, 4816 FD, 4817 false /* OutermostType */, 4818 EncodingProperty, 4819 false /* StructField */, 4820 EncodeBlockParameters, 4821 EncodeClassNames); 4822 // Block self 4823 S += "@?"; 4824 // Block parameters 4825 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(FT)) { 4826 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin(), 4827 E = FPT->arg_type_end(); I && (I != E); ++I) { 4828 getObjCEncodingForTypeImpl(*I, S, 4829 ExpandPointedToStructures, 4830 ExpandStructures, 4831 FD, 4832 false /* OutermostType */, 4833 EncodingProperty, 4834 false /* StructField */, 4835 EncodeBlockParameters, 4836 EncodeClassNames); 4837 } 4838 } 4839 S += '>'; 4840 } 4841 return; 4842 } 4843 4844 // Ignore protocol qualifiers when mangling at this level. 4845 if (const ObjCObjectType *OT = T->getAs<ObjCObjectType>()) 4846 T = OT->getBaseType(); 4847 4848 if (const ObjCInterfaceType *OIT = T->getAs<ObjCInterfaceType>()) { 4849 // @encode(class_name) 4850 ObjCInterfaceDecl *OI = OIT->getDecl(); 4851 S += '{'; 4852 const IdentifierInfo *II = OI->getIdentifier(); 4853 S += II->getName(); 4854 S += '='; 4855 SmallVector<const ObjCIvarDecl*, 32> Ivars; 4856 DeepCollectObjCIvars(OI, true, Ivars); 4857 for (unsigned i = 0, e = Ivars.size(); i != e; ++i) { 4858 const FieldDecl *Field = cast<FieldDecl>(Ivars[i]); 4859 if (Field->isBitField()) 4860 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, Field); 4861 else 4862 getObjCEncodingForTypeImpl(Field->getType(), S, false, true, FD); 4863 } 4864 S += '}'; 4865 return; 4866 } 4867 4868 if (const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>()) { 4869 if (OPT->isObjCIdType()) { 4870 S += '@'; 4871 return; 4872 } 4873 4874 if (OPT->isObjCClassType() || OPT->isObjCQualifiedClassType()) { 4875 // FIXME: Consider if we need to output qualifiers for 'Class<p>'. 4876 // Since this is a binary compatibility issue, need to consult with runtime 4877 // folks. Fortunately, this is a *very* obsure construct. 4878 S += '#'; 4879 return; 4880 } 4881 4882 if (OPT->isObjCQualifiedIdType()) { 4883 getObjCEncodingForTypeImpl(getObjCIdType(), S, 4884 ExpandPointedToStructures, 4885 ExpandStructures, FD); 4886 if (FD || EncodingProperty || EncodeClassNames) { 4887 // Note that we do extended encoding of protocol qualifer list 4888 // Only when doing ivar or property encoding. 4889 S += '"'; 4890 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4891 E = OPT->qual_end(); I != E; ++I) { 4892 S += '<'; 4893 S += (*I)->getNameAsString(); 4894 S += '>'; 4895 } 4896 S += '"'; 4897 } 4898 return; 4899 } 4900 4901 QualType PointeeTy = OPT->getPointeeType(); 4902 if (!EncodingProperty && 4903 isa<TypedefType>(PointeeTy.getTypePtr())) { 4904 // Another historical/compatibility reason. 4905 // We encode the underlying type which comes out as 4906 // {...}; 4907 S += '^'; 4908 getObjCEncodingForTypeImpl(PointeeTy, S, 4909 false, ExpandPointedToStructures, 4910 NULL); 4911 return; 4912 } 4913 4914 S += '@'; 4915 if (OPT->getInterfaceDecl() && 4916 (FD || EncodingProperty || EncodeClassNames)) { 4917 S += '"'; 4918 S += OPT->getInterfaceDecl()->getIdentifier()->getName(); 4919 for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), 4920 E = OPT->qual_end(); I != E; ++I) { 4921 S += '<'; 4922 S += (*I)->getNameAsString(); 4923 S += '>'; 4924 } 4925 S += '"'; 4926 } 4927 return; 4928 } 4929 4930 // gcc just blithely ignores member pointers. 4931 // TODO: maybe there should be a mangling for these 4932 if (T->getAs<MemberPointerType>()) 4933 return; 4934 4935 if (T->isVectorType()) { 4936 // This matches gcc's encoding, even though technically it is 4937 // insufficient. 4938 // FIXME. We should do a better job than gcc. 4939 return; 4940 } 4941 4942 llvm_unreachable("@encode for type not implemented!"); 4943} 4944 4945void ASTContext::getObjCEncodingForStructureImpl(RecordDecl *RDecl, 4946 std::string &S, 4947 const FieldDecl *FD, 4948 bool includeVBases) const { 4949 assert(RDecl && "Expected non-null RecordDecl"); 4950 assert(!RDecl->isUnion() && "Should not be called for unions"); 4951 if (!RDecl->getDefinition()) 4952 return; 4953 4954 CXXRecordDecl *CXXRec = dyn_cast<CXXRecordDecl>(RDecl); 4955 std::multimap<uint64_t, NamedDecl *> FieldOrBaseOffsets; 4956 const ASTRecordLayout &layout = getASTRecordLayout(RDecl); 4957 4958 if (CXXRec) { 4959 for (CXXRecordDecl::base_class_iterator 4960 BI = CXXRec->bases_begin(), 4961 BE = CXXRec->bases_end(); BI != BE; ++BI) { 4962 if (!BI->isVirtual()) { 4963 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4964 if (base->isEmpty()) 4965 continue; 4966 uint64_t offs = toBits(layout.getBaseClassOffset(base)); 4967 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4968 std::make_pair(offs, base)); 4969 } 4970 } 4971 } 4972 4973 unsigned i = 0; 4974 for (RecordDecl::field_iterator Field = RDecl->field_begin(), 4975 FieldEnd = RDecl->field_end(); 4976 Field != FieldEnd; ++Field, ++i) { 4977 uint64_t offs = layout.getFieldOffset(i); 4978 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 4979 std::make_pair(offs, *Field)); 4980 } 4981 4982 if (CXXRec && includeVBases) { 4983 for (CXXRecordDecl::base_class_iterator 4984 BI = CXXRec->vbases_begin(), 4985 BE = CXXRec->vbases_end(); BI != BE; ++BI) { 4986 CXXRecordDecl *base = BI->getType()->getAsCXXRecordDecl(); 4987 if (base->isEmpty()) 4988 continue; 4989 uint64_t offs = toBits(layout.getVBaseClassOffset(base)); 4990 if (FieldOrBaseOffsets.find(offs) == FieldOrBaseOffsets.end()) 4991 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.end(), 4992 std::make_pair(offs, base)); 4993 } 4994 } 4995 4996 CharUnits size; 4997 if (CXXRec) { 4998 size = includeVBases ? layout.getSize() : layout.getNonVirtualSize(); 4999 } else { 5000 size = layout.getSize(); 5001 } 5002 5003 uint64_t CurOffs = 0; 5004 std::multimap<uint64_t, NamedDecl *>::iterator 5005 CurLayObj = FieldOrBaseOffsets.begin(); 5006 5007 if (CXXRec && CXXRec->isDynamicClass() && 5008 (CurLayObj == FieldOrBaseOffsets.end() || CurLayObj->first != 0)) { 5009 if (FD) { 5010 S += "\"_vptr$"; 5011 std::string recname = CXXRec->getNameAsString(); 5012 if (recname.empty()) recname = "?"; 5013 S += recname; 5014 S += '"'; 5015 } 5016 S += "^^?"; 5017 CurOffs += getTypeSize(VoidPtrTy); 5018 } 5019 5020 if (!RDecl->hasFlexibleArrayMember()) { 5021 // Mark the end of the structure. 5022 uint64_t offs = toBits(size); 5023 FieldOrBaseOffsets.insert(FieldOrBaseOffsets.upper_bound(offs), 5024 std::make_pair(offs, (NamedDecl*)0)); 5025 } 5026 5027 for (; CurLayObj != FieldOrBaseOffsets.end(); ++CurLayObj) { 5028 assert(CurOffs <= CurLayObj->first); 5029 5030 if (CurOffs < CurLayObj->first) { 5031 uint64_t padding = CurLayObj->first - CurOffs; 5032 // FIXME: There doesn't seem to be a way to indicate in the encoding that 5033 // packing/alignment of members is different that normal, in which case 5034 // the encoding will be out-of-sync with the real layout. 5035 // If the runtime switches to just consider the size of types without 5036 // taking into account alignment, we could make padding explicit in the 5037 // encoding (e.g. using arrays of chars). The encoding strings would be 5038 // longer then though. 5039 CurOffs += padding; 5040 } 5041 5042 NamedDecl *dcl = CurLayObj->second; 5043 if (dcl == 0) 5044 break; // reached end of structure. 5045 5046 if (CXXRecordDecl *base = dyn_cast<CXXRecordDecl>(dcl)) { 5047 // We expand the bases without their virtual bases since those are going 5048 // in the initial structure. Note that this differs from gcc which 5049 // expands virtual bases each time one is encountered in the hierarchy, 5050 // making the encoding type bigger than it really is. 5051 getObjCEncodingForStructureImpl(base, S, FD, /*includeVBases*/false); 5052 assert(!base->isEmpty()); 5053 CurOffs += toBits(getASTRecordLayout(base).getNonVirtualSize()); 5054 } else { 5055 FieldDecl *field = cast<FieldDecl>(dcl); 5056 if (FD) { 5057 S += '"'; 5058 S += field->getNameAsString(); 5059 S += '"'; 5060 } 5061 5062 if (field->isBitField()) { 5063 EncodeBitField(this, S, field->getType(), field); 5064 CurOffs += field->getBitWidthValue(*this); 5065 } else { 5066 QualType qt = field->getType(); 5067 getLegacyIntegralTypeEncoding(qt); 5068 getObjCEncodingForTypeImpl(qt, S, false, true, FD, 5069 /*OutermostType*/false, 5070 /*EncodingProperty*/false, 5071 /*StructField*/true); 5072 CurOffs += getTypeSize(field->getType()); 5073 } 5074 } 5075 } 5076} 5077 5078void ASTContext::getObjCEncodingForTypeQualifier(Decl::ObjCDeclQualifier QT, 5079 std::string& S) const { 5080 if (QT & Decl::OBJC_TQ_In) 5081 S += 'n'; 5082 if (QT & Decl::OBJC_TQ_Inout) 5083 S += 'N'; 5084 if (QT & Decl::OBJC_TQ_Out) 5085 S += 'o'; 5086 if (QT & Decl::OBJC_TQ_Bycopy) 5087 S += 'O'; 5088 if (QT & Decl::OBJC_TQ_Byref) 5089 S += 'R'; 5090 if (QT & Decl::OBJC_TQ_Oneway) 5091 S += 'V'; 5092} 5093 5094TypedefDecl *ASTContext::getObjCIdDecl() const { 5095 if (!ObjCIdDecl) { 5096 QualType T = getObjCObjectType(ObjCBuiltinIdTy, 0, 0); 5097 T = getObjCObjectPointerType(T); 5098 TypeSourceInfo *IdInfo = getTrivialTypeSourceInfo(T); 5099 ObjCIdDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5100 getTranslationUnitDecl(), 5101 SourceLocation(), SourceLocation(), 5102 &Idents.get("id"), IdInfo); 5103 } 5104 5105 return ObjCIdDecl; 5106} 5107 5108TypedefDecl *ASTContext::getObjCSelDecl() const { 5109 if (!ObjCSelDecl) { 5110 QualType SelT = getPointerType(ObjCBuiltinSelTy); 5111 TypeSourceInfo *SelInfo = getTrivialTypeSourceInfo(SelT); 5112 ObjCSelDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5113 getTranslationUnitDecl(), 5114 SourceLocation(), SourceLocation(), 5115 &Idents.get("SEL"), SelInfo); 5116 } 5117 return ObjCSelDecl; 5118} 5119 5120TypedefDecl *ASTContext::getObjCClassDecl() const { 5121 if (!ObjCClassDecl) { 5122 QualType T = getObjCObjectType(ObjCBuiltinClassTy, 0, 0); 5123 T = getObjCObjectPointerType(T); 5124 TypeSourceInfo *ClassInfo = getTrivialTypeSourceInfo(T); 5125 ObjCClassDecl = TypedefDecl::Create(const_cast<ASTContext &>(*this), 5126 getTranslationUnitDecl(), 5127 SourceLocation(), SourceLocation(), 5128 &Idents.get("Class"), ClassInfo); 5129 } 5130 5131 return ObjCClassDecl; 5132} 5133 5134ObjCInterfaceDecl *ASTContext::getObjCProtocolDecl() const { 5135 if (!ObjCProtocolClassDecl) { 5136 ObjCProtocolClassDecl 5137 = ObjCInterfaceDecl::Create(*this, getTranslationUnitDecl(), 5138 SourceLocation(), 5139 &Idents.get("Protocol"), 5140 /*PrevDecl=*/0, 5141 SourceLocation(), true); 5142 } 5143 5144 return ObjCProtocolClassDecl; 5145} 5146 5147//===----------------------------------------------------------------------===// 5148// __builtin_va_list Construction Functions 5149//===----------------------------------------------------------------------===// 5150 5151static TypedefDecl *CreateCharPtrBuiltinVaListDecl(const ASTContext *Context) { 5152 // typedef char* __builtin_va_list; 5153 QualType CharPtrType = Context->getPointerType(Context->CharTy); 5154 TypeSourceInfo *TInfo 5155 = Context->getTrivialTypeSourceInfo(CharPtrType); 5156 5157 TypedefDecl *VaListTypeDecl 5158 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5159 Context->getTranslationUnitDecl(), 5160 SourceLocation(), SourceLocation(), 5161 &Context->Idents.get("__builtin_va_list"), 5162 TInfo); 5163 return VaListTypeDecl; 5164} 5165 5166static TypedefDecl *CreateVoidPtrBuiltinVaListDecl(const ASTContext *Context) { 5167 // typedef void* __builtin_va_list; 5168 QualType VoidPtrType = Context->getPointerType(Context->VoidTy); 5169 TypeSourceInfo *TInfo 5170 = Context->getTrivialTypeSourceInfo(VoidPtrType); 5171 5172 TypedefDecl *VaListTypeDecl 5173 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5174 Context->getTranslationUnitDecl(), 5175 SourceLocation(), SourceLocation(), 5176 &Context->Idents.get("__builtin_va_list"), 5177 TInfo); 5178 return VaListTypeDecl; 5179} 5180 5181static TypedefDecl *CreatePowerABIBuiltinVaListDecl(const ASTContext *Context) { 5182 // typedef struct __va_list_tag { 5183 RecordDecl *VaListTagDecl; 5184 5185 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5186 Context->getTranslationUnitDecl(), 5187 &Context->Idents.get("__va_list_tag")); 5188 VaListTagDecl->startDefinition(); 5189 5190 const size_t NumFields = 5; 5191 QualType FieldTypes[NumFields]; 5192 const char *FieldNames[NumFields]; 5193 5194 // unsigned char gpr; 5195 FieldTypes[0] = Context->UnsignedCharTy; 5196 FieldNames[0] = "gpr"; 5197 5198 // unsigned char fpr; 5199 FieldTypes[1] = Context->UnsignedCharTy; 5200 FieldNames[1] = "fpr"; 5201 5202 // unsigned short reserved; 5203 FieldTypes[2] = Context->UnsignedShortTy; 5204 FieldNames[2] = "reserved"; 5205 5206 // void* overflow_arg_area; 5207 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5208 FieldNames[3] = "overflow_arg_area"; 5209 5210 // void* reg_save_area; 5211 FieldTypes[4] = Context->getPointerType(Context->VoidTy); 5212 FieldNames[4] = "reg_save_area"; 5213 5214 // Create fields 5215 for (unsigned i = 0; i < NumFields; ++i) { 5216 FieldDecl *Field = FieldDecl::Create(*Context, VaListTagDecl, 5217 SourceLocation(), 5218 SourceLocation(), 5219 &Context->Idents.get(FieldNames[i]), 5220 FieldTypes[i], /*TInfo=*/0, 5221 /*BitWidth=*/0, 5222 /*Mutable=*/false, 5223 ICIS_NoInit); 5224 Field->setAccess(AS_public); 5225 VaListTagDecl->addDecl(Field); 5226 } 5227 VaListTagDecl->completeDefinition(); 5228 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5229 Context->VaListTagTy = VaListTagType; 5230 5231 // } __va_list_tag; 5232 TypedefDecl *VaListTagTypedefDecl 5233 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5234 Context->getTranslationUnitDecl(), 5235 SourceLocation(), SourceLocation(), 5236 &Context->Idents.get("__va_list_tag"), 5237 Context->getTrivialTypeSourceInfo(VaListTagType)); 5238 QualType VaListTagTypedefType = 5239 Context->getTypedefType(VaListTagTypedefDecl); 5240 5241 // typedef __va_list_tag __builtin_va_list[1]; 5242 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5243 QualType VaListTagArrayType 5244 = Context->getConstantArrayType(VaListTagTypedefType, 5245 Size, ArrayType::Normal, 0); 5246 TypeSourceInfo *TInfo 5247 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5248 TypedefDecl *VaListTypedefDecl 5249 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5250 Context->getTranslationUnitDecl(), 5251 SourceLocation(), SourceLocation(), 5252 &Context->Idents.get("__builtin_va_list"), 5253 TInfo); 5254 5255 return VaListTypedefDecl; 5256} 5257 5258static TypedefDecl * 5259CreateX86_64ABIBuiltinVaListDecl(const ASTContext *Context) { 5260 // typedef struct __va_list_tag { 5261 RecordDecl *VaListTagDecl; 5262 VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct, 5263 Context->getTranslationUnitDecl(), 5264 &Context->Idents.get("__va_list_tag")); 5265 VaListTagDecl->startDefinition(); 5266 5267 const size_t NumFields = 4; 5268 QualType FieldTypes[NumFields]; 5269 const char *FieldNames[NumFields]; 5270 5271 // unsigned gp_offset; 5272 FieldTypes[0] = Context->UnsignedIntTy; 5273 FieldNames[0] = "gp_offset"; 5274 5275 // unsigned fp_offset; 5276 FieldTypes[1] = Context->UnsignedIntTy; 5277 FieldNames[1] = "fp_offset"; 5278 5279 // void* overflow_arg_area; 5280 FieldTypes[2] = Context->getPointerType(Context->VoidTy); 5281 FieldNames[2] = "overflow_arg_area"; 5282 5283 // void* reg_save_area; 5284 FieldTypes[3] = Context->getPointerType(Context->VoidTy); 5285 FieldNames[3] = "reg_save_area"; 5286 5287 // Create fields 5288 for (unsigned i = 0; i < NumFields; ++i) { 5289 FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context), 5290 VaListTagDecl, 5291 SourceLocation(), 5292 SourceLocation(), 5293 &Context->Idents.get(FieldNames[i]), 5294 FieldTypes[i], /*TInfo=*/0, 5295 /*BitWidth=*/0, 5296 /*Mutable=*/false, 5297 ICIS_NoInit); 5298 Field->setAccess(AS_public); 5299 VaListTagDecl->addDecl(Field); 5300 } 5301 VaListTagDecl->completeDefinition(); 5302 QualType VaListTagType = Context->getRecordType(VaListTagDecl); 5303 Context->VaListTagTy = VaListTagType; 5304 5305 // } __va_list_tag; 5306 TypedefDecl *VaListTagTypedefDecl 5307 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5308 Context->getTranslationUnitDecl(), 5309 SourceLocation(), SourceLocation(), 5310 &Context->Idents.get("__va_list_tag"), 5311 Context->getTrivialTypeSourceInfo(VaListTagType)); 5312 QualType VaListTagTypedefType = 5313 Context->getTypedefType(VaListTagTypedefDecl); 5314 5315 // typedef __va_list_tag __builtin_va_list[1]; 5316 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1); 5317 QualType VaListTagArrayType 5318 = Context->getConstantArrayType(VaListTagTypedefType, 5319 Size, ArrayType::Normal,0); 5320 TypeSourceInfo *TInfo 5321 = Context->getTrivialTypeSourceInfo(VaListTagArrayType); 5322 TypedefDecl *VaListTypedefDecl 5323 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5324 Context->getTranslationUnitDecl(), 5325 SourceLocation(), SourceLocation(), 5326 &Context->Idents.get("__builtin_va_list"), 5327 TInfo); 5328 5329 return VaListTypedefDecl; 5330} 5331 5332static TypedefDecl *CreatePNaClABIBuiltinVaListDecl(const ASTContext *Context) { 5333 // typedef int __builtin_va_list[4]; 5334 llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 4); 5335 QualType IntArrayType 5336 = Context->getConstantArrayType(Context->IntTy, 5337 Size, ArrayType::Normal, 0); 5338 TypedefDecl *VaListTypedefDecl 5339 = TypedefDecl::Create(const_cast<ASTContext &>(*Context), 5340 Context->getTranslationUnitDecl(), 5341 SourceLocation(), SourceLocation(), 5342 &Context->Idents.get("__builtin_va_list"), 5343 Context->getTrivialTypeSourceInfo(IntArrayType)); 5344 5345 return VaListTypedefDecl; 5346} 5347 5348static TypedefDecl *CreateVaListDecl(const ASTContext *Context, 5349 TargetInfo::BuiltinVaListKind Kind) { 5350 switch (Kind) { 5351 case TargetInfo::CharPtrBuiltinVaList: 5352 return CreateCharPtrBuiltinVaListDecl(Context); 5353 case TargetInfo::VoidPtrBuiltinVaList: 5354 return CreateVoidPtrBuiltinVaListDecl(Context); 5355 case TargetInfo::PowerABIBuiltinVaList: 5356 return CreatePowerABIBuiltinVaListDecl(Context); 5357 case TargetInfo::X86_64ABIBuiltinVaList: 5358 return CreateX86_64ABIBuiltinVaListDecl(Context); 5359 case TargetInfo::PNaClABIBuiltinVaList: 5360 return CreatePNaClABIBuiltinVaListDecl(Context); 5361 } 5362 5363 llvm_unreachable("Unhandled __builtin_va_list type kind"); 5364} 5365 5366TypedefDecl *ASTContext::getBuiltinVaListDecl() const { 5367 if (!BuiltinVaListDecl) 5368 BuiltinVaListDecl = CreateVaListDecl(this, Target->getBuiltinVaListKind()); 5369 5370 return BuiltinVaListDecl; 5371} 5372 5373QualType ASTContext::getVaListTagType() const { 5374 // Force the creation of VaListTagTy by building the __builtin_va_list 5375 // declaration. 5376 if (VaListTagTy.isNull()) 5377 (void) getBuiltinVaListDecl(); 5378 5379 return VaListTagTy; 5380} 5381 5382void ASTContext::setObjCConstantStringInterface(ObjCInterfaceDecl *Decl) { 5383 assert(ObjCConstantStringType.isNull() && 5384 "'NSConstantString' type already set!"); 5385 5386 ObjCConstantStringType = getObjCInterfaceType(Decl); 5387} 5388 5389/// \brief Retrieve the template name that corresponds to a non-empty 5390/// lookup. 5391TemplateName 5392ASTContext::getOverloadedTemplateName(UnresolvedSetIterator Begin, 5393 UnresolvedSetIterator End) const { 5394 unsigned size = End - Begin; 5395 assert(size > 1 && "set is not overloaded!"); 5396 5397 void *memory = Allocate(sizeof(OverloadedTemplateStorage) + 5398 size * sizeof(FunctionTemplateDecl*)); 5399 OverloadedTemplateStorage *OT = new(memory) OverloadedTemplateStorage(size); 5400 5401 NamedDecl **Storage = OT->getStorage(); 5402 for (UnresolvedSetIterator I = Begin; I != End; ++I) { 5403 NamedDecl *D = *I; 5404 assert(isa<FunctionTemplateDecl>(D) || 5405 (isa<UsingShadowDecl>(D) && 5406 isa<FunctionTemplateDecl>(D->getUnderlyingDecl()))); 5407 *Storage++ = D; 5408 } 5409 5410 return TemplateName(OT); 5411} 5412 5413/// \brief Retrieve the template name that represents a qualified 5414/// template name such as \c std::vector. 5415TemplateName 5416ASTContext::getQualifiedTemplateName(NestedNameSpecifier *NNS, 5417 bool TemplateKeyword, 5418 TemplateDecl *Template) const { 5419 assert(NNS && "Missing nested-name-specifier in qualified template name"); 5420 5421 // FIXME: Canonicalization? 5422 llvm::FoldingSetNodeID ID; 5423 QualifiedTemplateName::Profile(ID, NNS, TemplateKeyword, Template); 5424 5425 void *InsertPos = 0; 5426 QualifiedTemplateName *QTN = 5427 QualifiedTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5428 if (!QTN) { 5429 QTN = new (*this,4) QualifiedTemplateName(NNS, TemplateKeyword, Template); 5430 QualifiedTemplateNames.InsertNode(QTN, InsertPos); 5431 } 5432 5433 return TemplateName(QTN); 5434} 5435 5436/// \brief Retrieve the template name that represents a dependent 5437/// template name such as \c MetaFun::template apply. 5438TemplateName 5439ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5440 const IdentifierInfo *Name) const { 5441 assert((!NNS || NNS->isDependent()) && 5442 "Nested name specifier must be dependent"); 5443 5444 llvm::FoldingSetNodeID ID; 5445 DependentTemplateName::Profile(ID, NNS, Name); 5446 5447 void *InsertPos = 0; 5448 DependentTemplateName *QTN = 5449 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5450 5451 if (QTN) 5452 return TemplateName(QTN); 5453 5454 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5455 if (CanonNNS == NNS) { 5456 QTN = new (*this,4) DependentTemplateName(NNS, Name); 5457 } else { 5458 TemplateName Canon = getDependentTemplateName(CanonNNS, Name); 5459 QTN = new (*this,4) DependentTemplateName(NNS, Name, Canon); 5460 DependentTemplateName *CheckQTN = 5461 DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5462 assert(!CheckQTN && "Dependent type name canonicalization broken"); 5463 (void)CheckQTN; 5464 } 5465 5466 DependentTemplateNames.InsertNode(QTN, InsertPos); 5467 return TemplateName(QTN); 5468} 5469 5470/// \brief Retrieve the template name that represents a dependent 5471/// template name such as \c MetaFun::template operator+. 5472TemplateName 5473ASTContext::getDependentTemplateName(NestedNameSpecifier *NNS, 5474 OverloadedOperatorKind Operator) const { 5475 assert((!NNS || NNS->isDependent()) && 5476 "Nested name specifier must be dependent"); 5477 5478 llvm::FoldingSetNodeID ID; 5479 DependentTemplateName::Profile(ID, NNS, Operator); 5480 5481 void *InsertPos = 0; 5482 DependentTemplateName *QTN 5483 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5484 5485 if (QTN) 5486 return TemplateName(QTN); 5487 5488 NestedNameSpecifier *CanonNNS = getCanonicalNestedNameSpecifier(NNS); 5489 if (CanonNNS == NNS) { 5490 QTN = new (*this,4) DependentTemplateName(NNS, Operator); 5491 } else { 5492 TemplateName Canon = getDependentTemplateName(CanonNNS, Operator); 5493 QTN = new (*this,4) DependentTemplateName(NNS, Operator, Canon); 5494 5495 DependentTemplateName *CheckQTN 5496 = DependentTemplateNames.FindNodeOrInsertPos(ID, InsertPos); 5497 assert(!CheckQTN && "Dependent template name canonicalization broken"); 5498 (void)CheckQTN; 5499 } 5500 5501 DependentTemplateNames.InsertNode(QTN, InsertPos); 5502 return TemplateName(QTN); 5503} 5504 5505TemplateName 5506ASTContext::getSubstTemplateTemplateParm(TemplateTemplateParmDecl *param, 5507 TemplateName replacement) const { 5508 llvm::FoldingSetNodeID ID; 5509 SubstTemplateTemplateParmStorage::Profile(ID, param, replacement); 5510 5511 void *insertPos = 0; 5512 SubstTemplateTemplateParmStorage *subst 5513 = SubstTemplateTemplateParms.FindNodeOrInsertPos(ID, insertPos); 5514 5515 if (!subst) { 5516 subst = new (*this) SubstTemplateTemplateParmStorage(param, replacement); 5517 SubstTemplateTemplateParms.InsertNode(subst, insertPos); 5518 } 5519 5520 return TemplateName(subst); 5521} 5522 5523TemplateName 5524ASTContext::getSubstTemplateTemplateParmPack(TemplateTemplateParmDecl *Param, 5525 const TemplateArgument &ArgPack) const { 5526 ASTContext &Self = const_cast<ASTContext &>(*this); 5527 llvm::FoldingSetNodeID ID; 5528 SubstTemplateTemplateParmPackStorage::Profile(ID, Self, Param, ArgPack); 5529 5530 void *InsertPos = 0; 5531 SubstTemplateTemplateParmPackStorage *Subst 5532 = SubstTemplateTemplateParmPacks.FindNodeOrInsertPos(ID, InsertPos); 5533 5534 if (!Subst) { 5535 Subst = new (*this) SubstTemplateTemplateParmPackStorage(Param, 5536 ArgPack.pack_size(), 5537 ArgPack.pack_begin()); 5538 SubstTemplateTemplateParmPacks.InsertNode(Subst, InsertPos); 5539 } 5540 5541 return TemplateName(Subst); 5542} 5543 5544/// getFromTargetType - Given one of the integer types provided by 5545/// TargetInfo, produce the corresponding type. The unsigned @p Type 5546/// is actually a value of type @c TargetInfo::IntType. 5547CanQualType ASTContext::getFromTargetType(unsigned Type) const { 5548 switch (Type) { 5549 case TargetInfo::NoInt: return CanQualType(); 5550 case TargetInfo::SignedShort: return ShortTy; 5551 case TargetInfo::UnsignedShort: return UnsignedShortTy; 5552 case TargetInfo::SignedInt: return IntTy; 5553 case TargetInfo::UnsignedInt: return UnsignedIntTy; 5554 case TargetInfo::SignedLong: return LongTy; 5555 case TargetInfo::UnsignedLong: return UnsignedLongTy; 5556 case TargetInfo::SignedLongLong: return LongLongTy; 5557 case TargetInfo::UnsignedLongLong: return UnsignedLongLongTy; 5558 } 5559 5560 llvm_unreachable("Unhandled TargetInfo::IntType value"); 5561} 5562 5563//===----------------------------------------------------------------------===// 5564// Type Predicates. 5565//===----------------------------------------------------------------------===// 5566 5567/// getObjCGCAttr - Returns one of GCNone, Weak or Strong objc's 5568/// garbage collection attribute. 5569/// 5570Qualifiers::GC ASTContext::getObjCGCAttrKind(QualType Ty) const { 5571 if (getLangOpts().getGC() == LangOptions::NonGC) 5572 return Qualifiers::GCNone; 5573 5574 assert(getLangOpts().ObjC1); 5575 Qualifiers::GC GCAttrs = Ty.getObjCGCAttr(); 5576 5577 // Default behaviour under objective-C's gc is for ObjC pointers 5578 // (or pointers to them) be treated as though they were declared 5579 // as __strong. 5580 if (GCAttrs == Qualifiers::GCNone) { 5581 if (Ty->isObjCObjectPointerType() || Ty->isBlockPointerType()) 5582 return Qualifiers::Strong; 5583 else if (Ty->isPointerType()) 5584 return getObjCGCAttrKind(Ty->getAs<PointerType>()->getPointeeType()); 5585 } else { 5586 // It's not valid to set GC attributes on anything that isn't a 5587 // pointer. 5588#ifndef NDEBUG 5589 QualType CT = Ty->getCanonicalTypeInternal(); 5590 while (const ArrayType *AT = dyn_cast<ArrayType>(CT)) 5591 CT = AT->getElementType(); 5592 assert(CT->isAnyPointerType() || CT->isBlockPointerType()); 5593#endif 5594 } 5595 return GCAttrs; 5596} 5597 5598//===----------------------------------------------------------------------===// 5599// Type Compatibility Testing 5600//===----------------------------------------------------------------------===// 5601 5602/// areCompatVectorTypes - Return true if the two specified vector types are 5603/// compatible. 5604static bool areCompatVectorTypes(const VectorType *LHS, 5605 const VectorType *RHS) { 5606 assert(LHS->isCanonicalUnqualified() && RHS->isCanonicalUnqualified()); 5607 return LHS->getElementType() == RHS->getElementType() && 5608 LHS->getNumElements() == RHS->getNumElements(); 5609} 5610 5611bool ASTContext::areCompatibleVectorTypes(QualType FirstVec, 5612 QualType SecondVec) { 5613 assert(FirstVec->isVectorType() && "FirstVec should be a vector type"); 5614 assert(SecondVec->isVectorType() && "SecondVec should be a vector type"); 5615 5616 if (hasSameUnqualifiedType(FirstVec, SecondVec)) 5617 return true; 5618 5619 // Treat Neon vector types and most AltiVec vector types as if they are the 5620 // equivalent GCC vector types. 5621 const VectorType *First = FirstVec->getAs<VectorType>(); 5622 const VectorType *Second = SecondVec->getAs<VectorType>(); 5623 if (First->getNumElements() == Second->getNumElements() && 5624 hasSameType(First->getElementType(), Second->getElementType()) && 5625 First->getVectorKind() != VectorType::AltiVecPixel && 5626 First->getVectorKind() != VectorType::AltiVecBool && 5627 Second->getVectorKind() != VectorType::AltiVecPixel && 5628 Second->getVectorKind() != VectorType::AltiVecBool) 5629 return true; 5630 5631 return false; 5632} 5633 5634//===----------------------------------------------------------------------===// 5635// ObjCQualifiedIdTypesAreCompatible - Compatibility testing for qualified id's. 5636//===----------------------------------------------------------------------===// 5637 5638/// ProtocolCompatibleWithProtocol - return 'true' if 'lProto' is in the 5639/// inheritance hierarchy of 'rProto'. 5640bool 5641ASTContext::ProtocolCompatibleWithProtocol(ObjCProtocolDecl *lProto, 5642 ObjCProtocolDecl *rProto) const { 5643 if (declaresSameEntity(lProto, rProto)) 5644 return true; 5645 for (ObjCProtocolDecl::protocol_iterator PI = rProto->protocol_begin(), 5646 E = rProto->protocol_end(); PI != E; ++PI) 5647 if (ProtocolCompatibleWithProtocol(lProto, *PI)) 5648 return true; 5649 return false; 5650} 5651 5652/// QualifiedIdConformsQualifiedId - compare id<p,...> with id<p1,...> 5653/// return true if lhs's protocols conform to rhs's protocol; false 5654/// otherwise. 5655bool ASTContext::QualifiedIdConformsQualifiedId(QualType lhs, QualType rhs) { 5656 if (lhs->isObjCQualifiedIdType() && rhs->isObjCQualifiedIdType()) 5657 return ObjCQualifiedIdTypesAreCompatible(lhs, rhs, false); 5658 return false; 5659} 5660 5661/// ObjCQualifiedClassTypesAreCompatible - compare Class<p,...> and 5662/// Class<p1, ...>. 5663bool ASTContext::ObjCQualifiedClassTypesAreCompatible(QualType lhs, 5664 QualType rhs) { 5665 const ObjCObjectPointerType *lhsQID = lhs->getAs<ObjCObjectPointerType>(); 5666 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5667 assert ((lhsQID && rhsOPT) && "ObjCQualifiedClassTypesAreCompatible"); 5668 5669 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5670 E = lhsQID->qual_end(); I != E; ++I) { 5671 bool match = false; 5672 ObjCProtocolDecl *lhsProto = *I; 5673 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5674 E = rhsOPT->qual_end(); J != E; ++J) { 5675 ObjCProtocolDecl *rhsProto = *J; 5676 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto)) { 5677 match = true; 5678 break; 5679 } 5680 } 5681 if (!match) 5682 return false; 5683 } 5684 return true; 5685} 5686 5687/// ObjCQualifiedIdTypesAreCompatible - We know that one of lhs/rhs is an 5688/// ObjCQualifiedIDType. 5689bool ASTContext::ObjCQualifiedIdTypesAreCompatible(QualType lhs, QualType rhs, 5690 bool compare) { 5691 // Allow id<P..> and an 'id' or void* type in all cases. 5692 if (lhs->isVoidPointerType() || 5693 lhs->isObjCIdType() || lhs->isObjCClassType()) 5694 return true; 5695 else if (rhs->isVoidPointerType() || 5696 rhs->isObjCIdType() || rhs->isObjCClassType()) 5697 return true; 5698 5699 if (const ObjCObjectPointerType *lhsQID = lhs->getAsObjCQualifiedIdType()) { 5700 const ObjCObjectPointerType *rhsOPT = rhs->getAs<ObjCObjectPointerType>(); 5701 5702 if (!rhsOPT) return false; 5703 5704 if (rhsOPT->qual_empty()) { 5705 // If the RHS is a unqualified interface pointer "NSString*", 5706 // make sure we check the class hierarchy. 5707 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5708 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5709 E = lhsQID->qual_end(); I != E; ++I) { 5710 // when comparing an id<P> on lhs with a static type on rhs, 5711 // see if static class implements all of id's protocols, directly or 5712 // through its super class and categories. 5713 if (!rhsID->ClassImplementsProtocol(*I, true)) 5714 return false; 5715 } 5716 } 5717 // If there are no qualifiers and no interface, we have an 'id'. 5718 return true; 5719 } 5720 // Both the right and left sides have qualifiers. 5721 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5722 E = lhsQID->qual_end(); I != E; ++I) { 5723 ObjCProtocolDecl *lhsProto = *I; 5724 bool match = false; 5725 5726 // when comparing an id<P> on lhs with a static type on rhs, 5727 // see if static class implements all of id's protocols, directly or 5728 // through its super class and categories. 5729 for (ObjCObjectPointerType::qual_iterator J = rhsOPT->qual_begin(), 5730 E = rhsOPT->qual_end(); J != E; ++J) { 5731 ObjCProtocolDecl *rhsProto = *J; 5732 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5733 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5734 match = true; 5735 break; 5736 } 5737 } 5738 // If the RHS is a qualified interface pointer "NSString<P>*", 5739 // make sure we check the class hierarchy. 5740 if (ObjCInterfaceDecl *rhsID = rhsOPT->getInterfaceDecl()) { 5741 for (ObjCObjectPointerType::qual_iterator I = lhsQID->qual_begin(), 5742 E = lhsQID->qual_end(); I != E; ++I) { 5743 // when comparing an id<P> on lhs with a static type on rhs, 5744 // see if static class implements all of id's protocols, directly or 5745 // through its super class and categories. 5746 if (rhsID->ClassImplementsProtocol(*I, true)) { 5747 match = true; 5748 break; 5749 } 5750 } 5751 } 5752 if (!match) 5753 return false; 5754 } 5755 5756 return true; 5757 } 5758 5759 const ObjCObjectPointerType *rhsQID = rhs->getAsObjCQualifiedIdType(); 5760 assert(rhsQID && "One of the LHS/RHS should be id<x>"); 5761 5762 if (const ObjCObjectPointerType *lhsOPT = 5763 lhs->getAsObjCInterfacePointerType()) { 5764 // If both the right and left sides have qualifiers. 5765 for (ObjCObjectPointerType::qual_iterator I = lhsOPT->qual_begin(), 5766 E = lhsOPT->qual_end(); I != E; ++I) { 5767 ObjCProtocolDecl *lhsProto = *I; 5768 bool match = false; 5769 5770 // when comparing an id<P> on rhs with a static type on lhs, 5771 // see if static class implements all of id's protocols, directly or 5772 // through its super class and categories. 5773 // First, lhs protocols in the qualifier list must be found, direct 5774 // or indirect in rhs's qualifier list or it is a mismatch. 5775 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5776 E = rhsQID->qual_end(); J != E; ++J) { 5777 ObjCProtocolDecl *rhsProto = *J; 5778 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5779 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5780 match = true; 5781 break; 5782 } 5783 } 5784 if (!match) 5785 return false; 5786 } 5787 5788 // Static class's protocols, or its super class or category protocols 5789 // must be found, direct or indirect in rhs's qualifier list or it is a mismatch. 5790 if (ObjCInterfaceDecl *lhsID = lhsOPT->getInterfaceDecl()) { 5791 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5792 CollectInheritedProtocols(lhsID, LHSInheritedProtocols); 5793 // This is rather dubious but matches gcc's behavior. If lhs has 5794 // no type qualifier and its class has no static protocol(s) 5795 // assume that it is mismatch. 5796 if (LHSInheritedProtocols.empty() && lhsOPT->qual_empty()) 5797 return false; 5798 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5799 LHSInheritedProtocols.begin(), 5800 E = LHSInheritedProtocols.end(); I != E; ++I) { 5801 bool match = false; 5802 ObjCProtocolDecl *lhsProto = (*I); 5803 for (ObjCObjectPointerType::qual_iterator J = rhsQID->qual_begin(), 5804 E = rhsQID->qual_end(); J != E; ++J) { 5805 ObjCProtocolDecl *rhsProto = *J; 5806 if (ProtocolCompatibleWithProtocol(lhsProto, rhsProto) || 5807 (compare && ProtocolCompatibleWithProtocol(rhsProto, lhsProto))) { 5808 match = true; 5809 break; 5810 } 5811 } 5812 if (!match) 5813 return false; 5814 } 5815 } 5816 return true; 5817 } 5818 return false; 5819} 5820 5821/// canAssignObjCInterfaces - Return true if the two interface types are 5822/// compatible for assignment from RHS to LHS. This handles validation of any 5823/// protocol qualifiers on the LHS or RHS. 5824/// 5825bool ASTContext::canAssignObjCInterfaces(const ObjCObjectPointerType *LHSOPT, 5826 const ObjCObjectPointerType *RHSOPT) { 5827 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5828 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5829 5830 // If either type represents the built-in 'id' or 'Class' types, return true. 5831 if (LHS->isObjCUnqualifiedIdOrClass() || 5832 RHS->isObjCUnqualifiedIdOrClass()) 5833 return true; 5834 5835 if (LHS->isObjCQualifiedId() || RHS->isObjCQualifiedId()) 5836 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5837 QualType(RHSOPT,0), 5838 false); 5839 5840 if (LHS->isObjCQualifiedClass() && RHS->isObjCQualifiedClass()) 5841 return ObjCQualifiedClassTypesAreCompatible(QualType(LHSOPT,0), 5842 QualType(RHSOPT,0)); 5843 5844 // If we have 2 user-defined types, fall into that path. 5845 if (LHS->getInterface() && RHS->getInterface()) 5846 return canAssignObjCInterfaces(LHS, RHS); 5847 5848 return false; 5849} 5850 5851/// canAssignObjCInterfacesInBlockPointer - This routine is specifically written 5852/// for providing type-safety for objective-c pointers used to pass/return 5853/// arguments in block literals. When passed as arguments, passing 'A*' where 5854/// 'id' is expected is not OK. Passing 'Sub *" where 'Super *" is expected is 5855/// not OK. For the return type, the opposite is not OK. 5856bool ASTContext::canAssignObjCInterfacesInBlockPointer( 5857 const ObjCObjectPointerType *LHSOPT, 5858 const ObjCObjectPointerType *RHSOPT, 5859 bool BlockReturnType) { 5860 if (RHSOPT->isObjCBuiltinType() || LHSOPT->isObjCIdType()) 5861 return true; 5862 5863 if (LHSOPT->isObjCBuiltinType()) { 5864 return RHSOPT->isObjCBuiltinType() || RHSOPT->isObjCQualifiedIdType(); 5865 } 5866 5867 if (LHSOPT->isObjCQualifiedIdType() || RHSOPT->isObjCQualifiedIdType()) 5868 return ObjCQualifiedIdTypesAreCompatible(QualType(LHSOPT,0), 5869 QualType(RHSOPT,0), 5870 false); 5871 5872 const ObjCInterfaceType* LHS = LHSOPT->getInterfaceType(); 5873 const ObjCInterfaceType* RHS = RHSOPT->getInterfaceType(); 5874 if (LHS && RHS) { // We have 2 user-defined types. 5875 if (LHS != RHS) { 5876 if (LHS->getDecl()->isSuperClassOf(RHS->getDecl())) 5877 return BlockReturnType; 5878 if (RHS->getDecl()->isSuperClassOf(LHS->getDecl())) 5879 return !BlockReturnType; 5880 } 5881 else 5882 return true; 5883 } 5884 return false; 5885} 5886 5887/// getIntersectionOfProtocols - This routine finds the intersection of set 5888/// of protocols inherited from two distinct objective-c pointer objects. 5889/// It is used to build composite qualifier list of the composite type of 5890/// the conditional expression involving two objective-c pointer objects. 5891static 5892void getIntersectionOfProtocols(ASTContext &Context, 5893 const ObjCObjectPointerType *LHSOPT, 5894 const ObjCObjectPointerType *RHSOPT, 5895 SmallVectorImpl<ObjCProtocolDecl *> &IntersectionOfProtocols) { 5896 5897 const ObjCObjectType* LHS = LHSOPT->getObjectType(); 5898 const ObjCObjectType* RHS = RHSOPT->getObjectType(); 5899 assert(LHS->getInterface() && "LHS must have an interface base"); 5900 assert(RHS->getInterface() && "RHS must have an interface base"); 5901 5902 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> InheritedProtocolSet; 5903 unsigned LHSNumProtocols = LHS->getNumProtocols(); 5904 if (LHSNumProtocols > 0) 5905 InheritedProtocolSet.insert(LHS->qual_begin(), LHS->qual_end()); 5906 else { 5907 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> LHSInheritedProtocols; 5908 Context.CollectInheritedProtocols(LHS->getInterface(), 5909 LHSInheritedProtocols); 5910 InheritedProtocolSet.insert(LHSInheritedProtocols.begin(), 5911 LHSInheritedProtocols.end()); 5912 } 5913 5914 unsigned RHSNumProtocols = RHS->getNumProtocols(); 5915 if (RHSNumProtocols > 0) { 5916 ObjCProtocolDecl **RHSProtocols = 5917 const_cast<ObjCProtocolDecl **>(RHS->qual_begin()); 5918 for (unsigned i = 0; i < RHSNumProtocols; ++i) 5919 if (InheritedProtocolSet.count(RHSProtocols[i])) 5920 IntersectionOfProtocols.push_back(RHSProtocols[i]); 5921 } else { 5922 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> RHSInheritedProtocols; 5923 Context.CollectInheritedProtocols(RHS->getInterface(), 5924 RHSInheritedProtocols); 5925 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 5926 RHSInheritedProtocols.begin(), 5927 E = RHSInheritedProtocols.end(); I != E; ++I) 5928 if (InheritedProtocolSet.count((*I))) 5929 IntersectionOfProtocols.push_back((*I)); 5930 } 5931} 5932 5933/// areCommonBaseCompatible - Returns common base class of the two classes if 5934/// one found. Note that this is O'2 algorithm. But it will be called as the 5935/// last type comparison in a ?-exp of ObjC pointer types before a 5936/// warning is issued. So, its invokation is extremely rare. 5937QualType ASTContext::areCommonBaseCompatible( 5938 const ObjCObjectPointerType *Lptr, 5939 const ObjCObjectPointerType *Rptr) { 5940 const ObjCObjectType *LHS = Lptr->getObjectType(); 5941 const ObjCObjectType *RHS = Rptr->getObjectType(); 5942 const ObjCInterfaceDecl* LDecl = LHS->getInterface(); 5943 const ObjCInterfaceDecl* RDecl = RHS->getInterface(); 5944 if (!LDecl || !RDecl || (declaresSameEntity(LDecl, RDecl))) 5945 return QualType(); 5946 5947 do { 5948 LHS = cast<ObjCInterfaceType>(getObjCInterfaceType(LDecl)); 5949 if (canAssignObjCInterfaces(LHS, RHS)) { 5950 SmallVector<ObjCProtocolDecl *, 8> Protocols; 5951 getIntersectionOfProtocols(*this, Lptr, Rptr, Protocols); 5952 5953 QualType Result = QualType(LHS, 0); 5954 if (!Protocols.empty()) 5955 Result = getObjCObjectType(Result, Protocols.data(), Protocols.size()); 5956 Result = getObjCObjectPointerType(Result); 5957 return Result; 5958 } 5959 } while ((LDecl = LDecl->getSuperClass())); 5960 5961 return QualType(); 5962} 5963 5964bool ASTContext::canAssignObjCInterfaces(const ObjCObjectType *LHS, 5965 const ObjCObjectType *RHS) { 5966 assert(LHS->getInterface() && "LHS is not an interface type"); 5967 assert(RHS->getInterface() && "RHS is not an interface type"); 5968 5969 // Verify that the base decls are compatible: the RHS must be a subclass of 5970 // the LHS. 5971 if (!LHS->getInterface()->isSuperClassOf(RHS->getInterface())) 5972 return false; 5973 5974 // RHS must have a superset of the protocols in the LHS. If the LHS is not 5975 // protocol qualified at all, then we are good. 5976 if (LHS->getNumProtocols() == 0) 5977 return true; 5978 5979 // Okay, we know the LHS has protocol qualifiers. If the RHS doesn't, 5980 // more detailed analysis is required. 5981 if (RHS->getNumProtocols() == 0) { 5982 // OK, if LHS is a superclass of RHS *and* 5983 // this superclass is assignment compatible with LHS. 5984 // false otherwise. 5985 bool IsSuperClass = 5986 LHS->getInterface()->isSuperClassOf(RHS->getInterface()); 5987 if (IsSuperClass) { 5988 // OK if conversion of LHS to SuperClass results in narrowing of types 5989 // ; i.e., SuperClass may implement at least one of the protocols 5990 // in LHS's protocol list. Example, SuperObj<P1> = lhs<P1,P2> is ok. 5991 // But not SuperObj<P1,P2,P3> = lhs<P1,P2>. 5992 llvm::SmallPtrSet<ObjCProtocolDecl *, 8> SuperClassInheritedProtocols; 5993 CollectInheritedProtocols(RHS->getInterface(), SuperClassInheritedProtocols); 5994 // If super class has no protocols, it is not a match. 5995 if (SuperClassInheritedProtocols.empty()) 5996 return false; 5997 5998 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 5999 LHSPE = LHS->qual_end(); 6000 LHSPI != LHSPE; LHSPI++) { 6001 bool SuperImplementsProtocol = false; 6002 ObjCProtocolDecl *LHSProto = (*LHSPI); 6003 6004 for (llvm::SmallPtrSet<ObjCProtocolDecl*,8>::iterator I = 6005 SuperClassInheritedProtocols.begin(), 6006 E = SuperClassInheritedProtocols.end(); I != E; ++I) { 6007 ObjCProtocolDecl *SuperClassProto = (*I); 6008 if (SuperClassProto->lookupProtocolNamed(LHSProto->getIdentifier())) { 6009 SuperImplementsProtocol = true; 6010 break; 6011 } 6012 } 6013 if (!SuperImplementsProtocol) 6014 return false; 6015 } 6016 return true; 6017 } 6018 return false; 6019 } 6020 6021 for (ObjCObjectType::qual_iterator LHSPI = LHS->qual_begin(), 6022 LHSPE = LHS->qual_end(); 6023 LHSPI != LHSPE; LHSPI++) { 6024 bool RHSImplementsProtocol = false; 6025 6026 // If the RHS doesn't implement the protocol on the left, the types 6027 // are incompatible. 6028 for (ObjCObjectType::qual_iterator RHSPI = RHS->qual_begin(), 6029 RHSPE = RHS->qual_end(); 6030 RHSPI != RHSPE; RHSPI++) { 6031 if ((*RHSPI)->lookupProtocolNamed((*LHSPI)->getIdentifier())) { 6032 RHSImplementsProtocol = true; 6033 break; 6034 } 6035 } 6036 // FIXME: For better diagnostics, consider passing back the protocol name. 6037 if (!RHSImplementsProtocol) 6038 return false; 6039 } 6040 // The RHS implements all protocols listed on the LHS. 6041 return true; 6042} 6043 6044bool ASTContext::areComparableObjCPointerTypes(QualType LHS, QualType RHS) { 6045 // get the "pointed to" types 6046 const ObjCObjectPointerType *LHSOPT = LHS->getAs<ObjCObjectPointerType>(); 6047 const ObjCObjectPointerType *RHSOPT = RHS->getAs<ObjCObjectPointerType>(); 6048 6049 if (!LHSOPT || !RHSOPT) 6050 return false; 6051 6052 return canAssignObjCInterfaces(LHSOPT, RHSOPT) || 6053 canAssignObjCInterfaces(RHSOPT, LHSOPT); 6054} 6055 6056bool ASTContext::canBindObjCObjectType(QualType To, QualType From) { 6057 return canAssignObjCInterfaces( 6058 getObjCObjectPointerType(To)->getAs<ObjCObjectPointerType>(), 6059 getObjCObjectPointerType(From)->getAs<ObjCObjectPointerType>()); 6060} 6061 6062/// typesAreCompatible - C99 6.7.3p9: For two qualified types to be compatible, 6063/// both shall have the identically qualified version of a compatible type. 6064/// C99 6.2.7p1: Two types have compatible types if their types are the 6065/// same. See 6.7.[2,3,5] for additional rules. 6066bool ASTContext::typesAreCompatible(QualType LHS, QualType RHS, 6067 bool CompareUnqualified) { 6068 if (getLangOpts().CPlusPlus) 6069 return hasSameType(LHS, RHS); 6070 6071 return !mergeTypes(LHS, RHS, false, CompareUnqualified).isNull(); 6072} 6073 6074bool ASTContext::propertyTypesAreCompatible(QualType LHS, QualType RHS) { 6075 return typesAreCompatible(LHS, RHS); 6076} 6077 6078bool ASTContext::typesAreBlockPointerCompatible(QualType LHS, QualType RHS) { 6079 return !mergeTypes(LHS, RHS, true).isNull(); 6080} 6081 6082/// mergeTransparentUnionType - if T is a transparent union type and a member 6083/// of T is compatible with SubType, return the merged type, else return 6084/// QualType() 6085QualType ASTContext::mergeTransparentUnionType(QualType T, QualType SubType, 6086 bool OfBlockPointer, 6087 bool Unqualified) { 6088 if (const RecordType *UT = T->getAsUnionType()) { 6089 RecordDecl *UD = UT->getDecl(); 6090 if (UD->hasAttr<TransparentUnionAttr>()) { 6091 for (RecordDecl::field_iterator it = UD->field_begin(), 6092 itend = UD->field_end(); it != itend; ++it) { 6093 QualType ET = it->getType().getUnqualifiedType(); 6094 QualType MT = mergeTypes(ET, SubType, OfBlockPointer, Unqualified); 6095 if (!MT.isNull()) 6096 return MT; 6097 } 6098 } 6099 } 6100 6101 return QualType(); 6102} 6103 6104/// mergeFunctionArgumentTypes - merge two types which appear as function 6105/// argument types 6106QualType ASTContext::mergeFunctionArgumentTypes(QualType lhs, QualType rhs, 6107 bool OfBlockPointer, 6108 bool Unqualified) { 6109 // GNU extension: two types are compatible if they appear as a function 6110 // argument, one of the types is a transparent union type and the other 6111 // type is compatible with a union member 6112 QualType lmerge = mergeTransparentUnionType(lhs, rhs, OfBlockPointer, 6113 Unqualified); 6114 if (!lmerge.isNull()) 6115 return lmerge; 6116 6117 QualType rmerge = mergeTransparentUnionType(rhs, lhs, OfBlockPointer, 6118 Unqualified); 6119 if (!rmerge.isNull()) 6120 return rmerge; 6121 6122 return mergeTypes(lhs, rhs, OfBlockPointer, Unqualified); 6123} 6124 6125QualType ASTContext::mergeFunctionTypes(QualType lhs, QualType rhs, 6126 bool OfBlockPointer, 6127 bool Unqualified) { 6128 const FunctionType *lbase = lhs->getAs<FunctionType>(); 6129 const FunctionType *rbase = rhs->getAs<FunctionType>(); 6130 const FunctionProtoType *lproto = dyn_cast<FunctionProtoType>(lbase); 6131 const FunctionProtoType *rproto = dyn_cast<FunctionProtoType>(rbase); 6132 bool allLTypes = true; 6133 bool allRTypes = true; 6134 6135 // Check return type 6136 QualType retType; 6137 if (OfBlockPointer) { 6138 QualType RHS = rbase->getResultType(); 6139 QualType LHS = lbase->getResultType(); 6140 bool UnqualifiedResult = Unqualified; 6141 if (!UnqualifiedResult) 6142 UnqualifiedResult = (!RHS.hasQualifiers() && LHS.hasQualifiers()); 6143 retType = mergeTypes(LHS, RHS, true, UnqualifiedResult, true); 6144 } 6145 else 6146 retType = mergeTypes(lbase->getResultType(), rbase->getResultType(), false, 6147 Unqualified); 6148 if (retType.isNull()) return QualType(); 6149 6150 if (Unqualified) 6151 retType = retType.getUnqualifiedType(); 6152 6153 CanQualType LRetType = getCanonicalType(lbase->getResultType()); 6154 CanQualType RRetType = getCanonicalType(rbase->getResultType()); 6155 if (Unqualified) { 6156 LRetType = LRetType.getUnqualifiedType(); 6157 RRetType = RRetType.getUnqualifiedType(); 6158 } 6159 6160 if (getCanonicalType(retType) != LRetType) 6161 allLTypes = false; 6162 if (getCanonicalType(retType) != RRetType) 6163 allRTypes = false; 6164 6165 // FIXME: double check this 6166 // FIXME: should we error if lbase->getRegParmAttr() != 0 && 6167 // rbase->getRegParmAttr() != 0 && 6168 // lbase->getRegParmAttr() != rbase->getRegParmAttr()? 6169 FunctionType::ExtInfo lbaseInfo = lbase->getExtInfo(); 6170 FunctionType::ExtInfo rbaseInfo = rbase->getExtInfo(); 6171 6172 // Compatible functions must have compatible calling conventions 6173 if (!isSameCallConv(lbaseInfo.getCC(), rbaseInfo.getCC())) 6174 return QualType(); 6175 6176 // Regparm is part of the calling convention. 6177 if (lbaseInfo.getHasRegParm() != rbaseInfo.getHasRegParm()) 6178 return QualType(); 6179 if (lbaseInfo.getRegParm() != rbaseInfo.getRegParm()) 6180 return QualType(); 6181 6182 if (lbaseInfo.getProducesResult() != rbaseInfo.getProducesResult()) 6183 return QualType(); 6184 6185 // functypes which return are preferred over those that do not. 6186 if (lbaseInfo.getNoReturn() && !rbaseInfo.getNoReturn()) 6187 allLTypes = false; 6188 else if (!lbaseInfo.getNoReturn() && rbaseInfo.getNoReturn()) 6189 allRTypes = false; 6190 // FIXME: some uses, e.g. conditional exprs, really want this to be 'both'. 6191 bool NoReturn = lbaseInfo.getNoReturn() || rbaseInfo.getNoReturn(); 6192 6193 FunctionType::ExtInfo einfo = lbaseInfo.withNoReturn(NoReturn); 6194 6195 if (lproto && rproto) { // two C99 style function prototypes 6196 assert(!lproto->hasExceptionSpec() && !rproto->hasExceptionSpec() && 6197 "C++ shouldn't be here"); 6198 unsigned lproto_nargs = lproto->getNumArgs(); 6199 unsigned rproto_nargs = rproto->getNumArgs(); 6200 6201 // Compatible functions must have the same number of arguments 6202 if (lproto_nargs != rproto_nargs) 6203 return QualType(); 6204 6205 // Variadic and non-variadic functions aren't compatible 6206 if (lproto->isVariadic() != rproto->isVariadic()) 6207 return QualType(); 6208 6209 if (lproto->getTypeQuals() != rproto->getTypeQuals()) 6210 return QualType(); 6211 6212 if (LangOpts.ObjCAutoRefCount && 6213 !FunctionTypesMatchOnNSConsumedAttrs(rproto, lproto)) 6214 return QualType(); 6215 6216 // Check argument compatibility 6217 SmallVector<QualType, 10> types; 6218 for (unsigned i = 0; i < lproto_nargs; i++) { 6219 QualType largtype = lproto->getArgType(i).getUnqualifiedType(); 6220 QualType rargtype = rproto->getArgType(i).getUnqualifiedType(); 6221 QualType argtype = mergeFunctionArgumentTypes(largtype, rargtype, 6222 OfBlockPointer, 6223 Unqualified); 6224 if (argtype.isNull()) return QualType(); 6225 6226 if (Unqualified) 6227 argtype = argtype.getUnqualifiedType(); 6228 6229 types.push_back(argtype); 6230 if (Unqualified) { 6231 largtype = largtype.getUnqualifiedType(); 6232 rargtype = rargtype.getUnqualifiedType(); 6233 } 6234 6235 if (getCanonicalType(argtype) != getCanonicalType(largtype)) 6236 allLTypes = false; 6237 if (getCanonicalType(argtype) != getCanonicalType(rargtype)) 6238 allRTypes = false; 6239 } 6240 6241 if (allLTypes) return lhs; 6242 if (allRTypes) return rhs; 6243 6244 FunctionProtoType::ExtProtoInfo EPI = lproto->getExtProtoInfo(); 6245 EPI.ExtInfo = einfo; 6246 return getFunctionType(retType, types.begin(), types.size(), EPI); 6247 } 6248 6249 if (lproto) allRTypes = false; 6250 if (rproto) allLTypes = false; 6251 6252 const FunctionProtoType *proto = lproto ? lproto : rproto; 6253 if (proto) { 6254 assert(!proto->hasExceptionSpec() && "C++ shouldn't be here"); 6255 if (proto->isVariadic()) return QualType(); 6256 // Check that the types are compatible with the types that 6257 // would result from default argument promotions (C99 6.7.5.3p15). 6258 // The only types actually affected are promotable integer 6259 // types and floats, which would be passed as a different 6260 // type depending on whether the prototype is visible. 6261 unsigned proto_nargs = proto->getNumArgs(); 6262 for (unsigned i = 0; i < proto_nargs; ++i) { 6263 QualType argTy = proto->getArgType(i); 6264 6265 // Look at the promotion type of enum types, since that is the type used 6266 // to pass enum values. 6267 if (const EnumType *Enum = argTy->getAs<EnumType>()) 6268 argTy = Enum->getDecl()->getPromotionType(); 6269 6270 if (argTy->isPromotableIntegerType() || 6271 getCanonicalType(argTy).getUnqualifiedType() == FloatTy) 6272 return QualType(); 6273 } 6274 6275 if (allLTypes) return lhs; 6276 if (allRTypes) return rhs; 6277 6278 FunctionProtoType::ExtProtoInfo EPI = proto->getExtProtoInfo(); 6279 EPI.ExtInfo = einfo; 6280 return getFunctionType(retType, proto->arg_type_begin(), 6281 proto->getNumArgs(), EPI); 6282 } 6283 6284 if (allLTypes) return lhs; 6285 if (allRTypes) return rhs; 6286 return getFunctionNoProtoType(retType, einfo); 6287} 6288 6289QualType ASTContext::mergeTypes(QualType LHS, QualType RHS, 6290 bool OfBlockPointer, 6291 bool Unqualified, bool BlockReturnType) { 6292 // C++ [expr]: If an expression initially has the type "reference to T", the 6293 // type is adjusted to "T" prior to any further analysis, the expression 6294 // designates the object or function denoted by the reference, and the 6295 // expression is an lvalue unless the reference is an rvalue reference and 6296 // the expression is a function call (possibly inside parentheses). 6297 assert(!LHS->getAs<ReferenceType>() && "LHS is a reference type?"); 6298 assert(!RHS->getAs<ReferenceType>() && "RHS is a reference type?"); 6299 6300 if (Unqualified) { 6301 LHS = LHS.getUnqualifiedType(); 6302 RHS = RHS.getUnqualifiedType(); 6303 } 6304 6305 QualType LHSCan = getCanonicalType(LHS), 6306 RHSCan = getCanonicalType(RHS); 6307 6308 // If two types are identical, they are compatible. 6309 if (LHSCan == RHSCan) 6310 return LHS; 6311 6312 // If the qualifiers are different, the types aren't compatible... mostly. 6313 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6314 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6315 if (LQuals != RQuals) { 6316 // If any of these qualifiers are different, we have a type 6317 // mismatch. 6318 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6319 LQuals.getAddressSpace() != RQuals.getAddressSpace() || 6320 LQuals.getObjCLifetime() != RQuals.getObjCLifetime()) 6321 return QualType(); 6322 6323 // Exactly one GC qualifier difference is allowed: __strong is 6324 // okay if the other type has no GC qualifier but is an Objective 6325 // C object pointer (i.e. implicitly strong by default). We fix 6326 // this by pretending that the unqualified type was actually 6327 // qualified __strong. 6328 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6329 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6330 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6331 6332 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6333 return QualType(); 6334 6335 if (GC_L == Qualifiers::Strong && RHSCan->isObjCObjectPointerType()) { 6336 return mergeTypes(LHS, getObjCGCQualType(RHS, Qualifiers::Strong)); 6337 } 6338 if (GC_R == Qualifiers::Strong && LHSCan->isObjCObjectPointerType()) { 6339 return mergeTypes(getObjCGCQualType(LHS, Qualifiers::Strong), RHS); 6340 } 6341 return QualType(); 6342 } 6343 6344 // Okay, qualifiers are equal. 6345 6346 Type::TypeClass LHSClass = LHSCan->getTypeClass(); 6347 Type::TypeClass RHSClass = RHSCan->getTypeClass(); 6348 6349 // We want to consider the two function types to be the same for these 6350 // comparisons, just force one to the other. 6351 if (LHSClass == Type::FunctionProto) LHSClass = Type::FunctionNoProto; 6352 if (RHSClass == Type::FunctionProto) RHSClass = Type::FunctionNoProto; 6353 6354 // Same as above for arrays 6355 if (LHSClass == Type::VariableArray || LHSClass == Type::IncompleteArray) 6356 LHSClass = Type::ConstantArray; 6357 if (RHSClass == Type::VariableArray || RHSClass == Type::IncompleteArray) 6358 RHSClass = Type::ConstantArray; 6359 6360 // ObjCInterfaces are just specialized ObjCObjects. 6361 if (LHSClass == Type::ObjCInterface) LHSClass = Type::ObjCObject; 6362 if (RHSClass == Type::ObjCInterface) RHSClass = Type::ObjCObject; 6363 6364 // Canonicalize ExtVector -> Vector. 6365 if (LHSClass == Type::ExtVector) LHSClass = Type::Vector; 6366 if (RHSClass == Type::ExtVector) RHSClass = Type::Vector; 6367 6368 // If the canonical type classes don't match. 6369 if (LHSClass != RHSClass) { 6370 // C99 6.7.2.2p4: Each enumerated type shall be compatible with char, 6371 // a signed integer type, or an unsigned integer type. 6372 // Compatibility is based on the underlying type, not the promotion 6373 // type. 6374 if (const EnumType* ETy = LHS->getAs<EnumType>()) { 6375 QualType TINT = ETy->getDecl()->getIntegerType(); 6376 if (!TINT.isNull() && hasSameType(TINT, RHSCan.getUnqualifiedType())) 6377 return RHS; 6378 } 6379 if (const EnumType* ETy = RHS->getAs<EnumType>()) { 6380 QualType TINT = ETy->getDecl()->getIntegerType(); 6381 if (!TINT.isNull() && hasSameType(TINT, LHSCan.getUnqualifiedType())) 6382 return LHS; 6383 } 6384 // allow block pointer type to match an 'id' type. 6385 if (OfBlockPointer && !BlockReturnType) { 6386 if (LHS->isObjCIdType() && RHS->isBlockPointerType()) 6387 return LHS; 6388 if (RHS->isObjCIdType() && LHS->isBlockPointerType()) 6389 return RHS; 6390 } 6391 6392 return QualType(); 6393 } 6394 6395 // The canonical type classes match. 6396 switch (LHSClass) { 6397#define TYPE(Class, Base) 6398#define ABSTRACT_TYPE(Class, Base) 6399#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class: 6400#define NON_CANONICAL_TYPE(Class, Base) case Type::Class: 6401#define DEPENDENT_TYPE(Class, Base) case Type::Class: 6402#include "clang/AST/TypeNodes.def" 6403 llvm_unreachable("Non-canonical and dependent types shouldn't get here"); 6404 6405 case Type::LValueReference: 6406 case Type::RValueReference: 6407 case Type::MemberPointer: 6408 llvm_unreachable("C++ should never be in mergeTypes"); 6409 6410 case Type::ObjCInterface: 6411 case Type::IncompleteArray: 6412 case Type::VariableArray: 6413 case Type::FunctionProto: 6414 case Type::ExtVector: 6415 llvm_unreachable("Types are eliminated above"); 6416 6417 case Type::Pointer: 6418 { 6419 // Merge two pointer types, while trying to preserve typedef info 6420 QualType LHSPointee = LHS->getAs<PointerType>()->getPointeeType(); 6421 QualType RHSPointee = RHS->getAs<PointerType>()->getPointeeType(); 6422 if (Unqualified) { 6423 LHSPointee = LHSPointee.getUnqualifiedType(); 6424 RHSPointee = RHSPointee.getUnqualifiedType(); 6425 } 6426 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, false, 6427 Unqualified); 6428 if (ResultType.isNull()) return QualType(); 6429 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6430 return LHS; 6431 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6432 return RHS; 6433 return getPointerType(ResultType); 6434 } 6435 case Type::BlockPointer: 6436 { 6437 // Merge two block pointer types, while trying to preserve typedef info 6438 QualType LHSPointee = LHS->getAs<BlockPointerType>()->getPointeeType(); 6439 QualType RHSPointee = RHS->getAs<BlockPointerType>()->getPointeeType(); 6440 if (Unqualified) { 6441 LHSPointee = LHSPointee.getUnqualifiedType(); 6442 RHSPointee = RHSPointee.getUnqualifiedType(); 6443 } 6444 QualType ResultType = mergeTypes(LHSPointee, RHSPointee, OfBlockPointer, 6445 Unqualified); 6446 if (ResultType.isNull()) return QualType(); 6447 if (getCanonicalType(LHSPointee) == getCanonicalType(ResultType)) 6448 return LHS; 6449 if (getCanonicalType(RHSPointee) == getCanonicalType(ResultType)) 6450 return RHS; 6451 return getBlockPointerType(ResultType); 6452 } 6453 case Type::Atomic: 6454 { 6455 // Merge two pointer types, while trying to preserve typedef info 6456 QualType LHSValue = LHS->getAs<AtomicType>()->getValueType(); 6457 QualType RHSValue = RHS->getAs<AtomicType>()->getValueType(); 6458 if (Unqualified) { 6459 LHSValue = LHSValue.getUnqualifiedType(); 6460 RHSValue = RHSValue.getUnqualifiedType(); 6461 } 6462 QualType ResultType = mergeTypes(LHSValue, RHSValue, false, 6463 Unqualified); 6464 if (ResultType.isNull()) return QualType(); 6465 if (getCanonicalType(LHSValue) == getCanonicalType(ResultType)) 6466 return LHS; 6467 if (getCanonicalType(RHSValue) == getCanonicalType(ResultType)) 6468 return RHS; 6469 return getAtomicType(ResultType); 6470 } 6471 case Type::ConstantArray: 6472 { 6473 const ConstantArrayType* LCAT = getAsConstantArrayType(LHS); 6474 const ConstantArrayType* RCAT = getAsConstantArrayType(RHS); 6475 if (LCAT && RCAT && RCAT->getSize() != LCAT->getSize()) 6476 return QualType(); 6477 6478 QualType LHSElem = getAsArrayType(LHS)->getElementType(); 6479 QualType RHSElem = getAsArrayType(RHS)->getElementType(); 6480 if (Unqualified) { 6481 LHSElem = LHSElem.getUnqualifiedType(); 6482 RHSElem = RHSElem.getUnqualifiedType(); 6483 } 6484 6485 QualType ResultType = mergeTypes(LHSElem, RHSElem, false, Unqualified); 6486 if (ResultType.isNull()) return QualType(); 6487 if (LCAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6488 return LHS; 6489 if (RCAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6490 return RHS; 6491 if (LCAT) return getConstantArrayType(ResultType, LCAT->getSize(), 6492 ArrayType::ArraySizeModifier(), 0); 6493 if (RCAT) return getConstantArrayType(ResultType, RCAT->getSize(), 6494 ArrayType::ArraySizeModifier(), 0); 6495 const VariableArrayType* LVAT = getAsVariableArrayType(LHS); 6496 const VariableArrayType* RVAT = getAsVariableArrayType(RHS); 6497 if (LVAT && getCanonicalType(LHSElem) == getCanonicalType(ResultType)) 6498 return LHS; 6499 if (RVAT && getCanonicalType(RHSElem) == getCanonicalType(ResultType)) 6500 return RHS; 6501 if (LVAT) { 6502 // FIXME: This isn't correct! But tricky to implement because 6503 // the array's size has to be the size of LHS, but the type 6504 // has to be different. 6505 return LHS; 6506 } 6507 if (RVAT) { 6508 // FIXME: This isn't correct! But tricky to implement because 6509 // the array's size has to be the size of RHS, but the type 6510 // has to be different. 6511 return RHS; 6512 } 6513 if (getCanonicalType(LHSElem) == getCanonicalType(ResultType)) return LHS; 6514 if (getCanonicalType(RHSElem) == getCanonicalType(ResultType)) return RHS; 6515 return getIncompleteArrayType(ResultType, 6516 ArrayType::ArraySizeModifier(), 0); 6517 } 6518 case Type::FunctionNoProto: 6519 return mergeFunctionTypes(LHS, RHS, OfBlockPointer, Unqualified); 6520 case Type::Record: 6521 case Type::Enum: 6522 return QualType(); 6523 case Type::Builtin: 6524 // Only exactly equal builtin types are compatible, which is tested above. 6525 return QualType(); 6526 case Type::Complex: 6527 // Distinct complex types are incompatible. 6528 return QualType(); 6529 case Type::Vector: 6530 // FIXME: The merged type should be an ExtVector! 6531 if (areCompatVectorTypes(LHSCan->getAs<VectorType>(), 6532 RHSCan->getAs<VectorType>())) 6533 return LHS; 6534 return QualType(); 6535 case Type::ObjCObject: { 6536 // Check if the types are assignment compatible. 6537 // FIXME: This should be type compatibility, e.g. whether 6538 // "LHS x; RHS x;" at global scope is legal. 6539 const ObjCObjectType* LHSIface = LHS->getAs<ObjCObjectType>(); 6540 const ObjCObjectType* RHSIface = RHS->getAs<ObjCObjectType>(); 6541 if (canAssignObjCInterfaces(LHSIface, RHSIface)) 6542 return LHS; 6543 6544 return QualType(); 6545 } 6546 case Type::ObjCObjectPointer: { 6547 if (OfBlockPointer) { 6548 if (canAssignObjCInterfacesInBlockPointer( 6549 LHS->getAs<ObjCObjectPointerType>(), 6550 RHS->getAs<ObjCObjectPointerType>(), 6551 BlockReturnType)) 6552 return LHS; 6553 return QualType(); 6554 } 6555 if (canAssignObjCInterfaces(LHS->getAs<ObjCObjectPointerType>(), 6556 RHS->getAs<ObjCObjectPointerType>())) 6557 return LHS; 6558 6559 return QualType(); 6560 } 6561 } 6562 6563 llvm_unreachable("Invalid Type::Class!"); 6564} 6565 6566bool ASTContext::FunctionTypesMatchOnNSConsumedAttrs( 6567 const FunctionProtoType *FromFunctionType, 6568 const FunctionProtoType *ToFunctionType) { 6569 if (FromFunctionType->hasAnyConsumedArgs() != 6570 ToFunctionType->hasAnyConsumedArgs()) 6571 return false; 6572 FunctionProtoType::ExtProtoInfo FromEPI = 6573 FromFunctionType->getExtProtoInfo(); 6574 FunctionProtoType::ExtProtoInfo ToEPI = 6575 ToFunctionType->getExtProtoInfo(); 6576 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments) 6577 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs(); 6578 ArgIdx != NumArgs; ++ArgIdx) { 6579 if (FromEPI.ConsumedArguments[ArgIdx] != 6580 ToEPI.ConsumedArguments[ArgIdx]) 6581 return false; 6582 } 6583 return true; 6584} 6585 6586/// mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 6587/// 'RHS' attributes and returns the merged version; including for function 6588/// return types. 6589QualType ASTContext::mergeObjCGCQualifiers(QualType LHS, QualType RHS) { 6590 QualType LHSCan = getCanonicalType(LHS), 6591 RHSCan = getCanonicalType(RHS); 6592 // If two types are identical, they are compatible. 6593 if (LHSCan == RHSCan) 6594 return LHS; 6595 if (RHSCan->isFunctionType()) { 6596 if (!LHSCan->isFunctionType()) 6597 return QualType(); 6598 QualType OldReturnType = 6599 cast<FunctionType>(RHSCan.getTypePtr())->getResultType(); 6600 QualType NewReturnType = 6601 cast<FunctionType>(LHSCan.getTypePtr())->getResultType(); 6602 QualType ResReturnType = 6603 mergeObjCGCQualifiers(NewReturnType, OldReturnType); 6604 if (ResReturnType.isNull()) 6605 return QualType(); 6606 if (ResReturnType == NewReturnType || ResReturnType == OldReturnType) { 6607 // id foo(); ... __strong id foo(); or: __strong id foo(); ... id foo(); 6608 // In either case, use OldReturnType to build the new function type. 6609 const FunctionType *F = LHS->getAs<FunctionType>(); 6610 if (const FunctionProtoType *FPT = cast<FunctionProtoType>(F)) { 6611 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo(); 6612 EPI.ExtInfo = getFunctionExtInfo(LHS); 6613 QualType ResultType 6614 = getFunctionType(OldReturnType, FPT->arg_type_begin(), 6615 FPT->getNumArgs(), EPI); 6616 return ResultType; 6617 } 6618 } 6619 return QualType(); 6620 } 6621 6622 // If the qualifiers are different, the types can still be merged. 6623 Qualifiers LQuals = LHSCan.getLocalQualifiers(); 6624 Qualifiers RQuals = RHSCan.getLocalQualifiers(); 6625 if (LQuals != RQuals) { 6626 // If any of these qualifiers are different, we have a type mismatch. 6627 if (LQuals.getCVRQualifiers() != RQuals.getCVRQualifiers() || 6628 LQuals.getAddressSpace() != RQuals.getAddressSpace()) 6629 return QualType(); 6630 6631 // Exactly one GC qualifier difference is allowed: __strong is 6632 // okay if the other type has no GC qualifier but is an Objective 6633 // C object pointer (i.e. implicitly strong by default). We fix 6634 // this by pretending that the unqualified type was actually 6635 // qualified __strong. 6636 Qualifiers::GC GC_L = LQuals.getObjCGCAttr(); 6637 Qualifiers::GC GC_R = RQuals.getObjCGCAttr(); 6638 assert((GC_L != GC_R) && "unequal qualifier sets had only equal elements"); 6639 6640 if (GC_L == Qualifiers::Weak || GC_R == Qualifiers::Weak) 6641 return QualType(); 6642 6643 if (GC_L == Qualifiers::Strong) 6644 return LHS; 6645 if (GC_R == Qualifiers::Strong) 6646 return RHS; 6647 return QualType(); 6648 } 6649 6650 if (LHSCan->isObjCObjectPointerType() && RHSCan->isObjCObjectPointerType()) { 6651 QualType LHSBaseQT = LHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6652 QualType RHSBaseQT = RHS->getAs<ObjCObjectPointerType>()->getPointeeType(); 6653 QualType ResQT = mergeObjCGCQualifiers(LHSBaseQT, RHSBaseQT); 6654 if (ResQT == LHSBaseQT) 6655 return LHS; 6656 if (ResQT == RHSBaseQT) 6657 return RHS; 6658 } 6659 return QualType(); 6660} 6661 6662//===----------------------------------------------------------------------===// 6663// Integer Predicates 6664//===----------------------------------------------------------------------===// 6665 6666unsigned ASTContext::getIntWidth(QualType T) const { 6667 if (const EnumType *ET = dyn_cast<EnumType>(T)) 6668 T = ET->getDecl()->getIntegerType(); 6669 if (T->isBooleanType()) 6670 return 1; 6671 // For builtin types, just use the standard type sizing method 6672 return (unsigned)getTypeSize(T); 6673} 6674 6675QualType ASTContext::getCorrespondingUnsignedType(QualType T) { 6676 assert(T->hasSignedIntegerRepresentation() && "Unexpected type"); 6677 6678 // Turn <4 x signed int> -> <4 x unsigned int> 6679 if (const VectorType *VTy = T->getAs<VectorType>()) 6680 return getVectorType(getCorrespondingUnsignedType(VTy->getElementType()), 6681 VTy->getNumElements(), VTy->getVectorKind()); 6682 6683 // For enums, we return the unsigned version of the base type. 6684 if (const EnumType *ETy = T->getAs<EnumType>()) 6685 T = ETy->getDecl()->getIntegerType(); 6686 6687 const BuiltinType *BTy = T->getAs<BuiltinType>(); 6688 assert(BTy && "Unexpected signed integer type"); 6689 switch (BTy->getKind()) { 6690 case BuiltinType::Char_S: 6691 case BuiltinType::SChar: 6692 return UnsignedCharTy; 6693 case BuiltinType::Short: 6694 return UnsignedShortTy; 6695 case BuiltinType::Int: 6696 return UnsignedIntTy; 6697 case BuiltinType::Long: 6698 return UnsignedLongTy; 6699 case BuiltinType::LongLong: 6700 return UnsignedLongLongTy; 6701 case BuiltinType::Int128: 6702 return UnsignedInt128Ty; 6703 default: 6704 llvm_unreachable("Unexpected signed integer type"); 6705 } 6706} 6707 6708ASTMutationListener::~ASTMutationListener() { } 6709 6710 6711//===----------------------------------------------------------------------===// 6712// Builtin Type Computation 6713//===----------------------------------------------------------------------===// 6714 6715/// DecodeTypeFromStr - This decodes one type descriptor from Str, advancing the 6716/// pointer over the consumed characters. This returns the resultant type. If 6717/// AllowTypeModifiers is false then modifier like * are not parsed, just basic 6718/// types. This allows "v2i*" to be parsed as a pointer to a v2i instead of 6719/// a vector of "i*". 6720/// 6721/// RequiresICE is filled in on return to indicate whether the value is required 6722/// to be an Integer Constant Expression. 6723static QualType DecodeTypeFromStr(const char *&Str, const ASTContext &Context, 6724 ASTContext::GetBuiltinTypeError &Error, 6725 bool &RequiresICE, 6726 bool AllowTypeModifiers) { 6727 // Modifiers. 6728 int HowLong = 0; 6729 bool Signed = false, Unsigned = false; 6730 RequiresICE = false; 6731 6732 // Read the prefixed modifiers first. 6733 bool Done = false; 6734 while (!Done) { 6735 switch (*Str++) { 6736 default: Done = true; --Str; break; 6737 case 'I': 6738 RequiresICE = true; 6739 break; 6740 case 'S': 6741 assert(!Unsigned && "Can't use both 'S' and 'U' modifiers!"); 6742 assert(!Signed && "Can't use 'S' modifier multiple times!"); 6743 Signed = true; 6744 break; 6745 case 'U': 6746 assert(!Signed && "Can't use both 'S' and 'U' modifiers!"); 6747 assert(!Unsigned && "Can't use 'S' modifier multiple times!"); 6748 Unsigned = true; 6749 break; 6750 case 'L': 6751 assert(HowLong <= 2 && "Can't have LLLL modifier"); 6752 ++HowLong; 6753 break; 6754 } 6755 } 6756 6757 QualType Type; 6758 6759 // Read the base type. 6760 switch (*Str++) { 6761 default: llvm_unreachable("Unknown builtin type letter!"); 6762 case 'v': 6763 assert(HowLong == 0 && !Signed && !Unsigned && 6764 "Bad modifiers used with 'v'!"); 6765 Type = Context.VoidTy; 6766 break; 6767 case 'f': 6768 assert(HowLong == 0 && !Signed && !Unsigned && 6769 "Bad modifiers used with 'f'!"); 6770 Type = Context.FloatTy; 6771 break; 6772 case 'd': 6773 assert(HowLong < 2 && !Signed && !Unsigned && 6774 "Bad modifiers used with 'd'!"); 6775 if (HowLong) 6776 Type = Context.LongDoubleTy; 6777 else 6778 Type = Context.DoubleTy; 6779 break; 6780 case 's': 6781 assert(HowLong == 0 && "Bad modifiers used with 's'!"); 6782 if (Unsigned) 6783 Type = Context.UnsignedShortTy; 6784 else 6785 Type = Context.ShortTy; 6786 break; 6787 case 'i': 6788 if (HowLong == 3) 6789 Type = Unsigned ? Context.UnsignedInt128Ty : Context.Int128Ty; 6790 else if (HowLong == 2) 6791 Type = Unsigned ? Context.UnsignedLongLongTy : Context.LongLongTy; 6792 else if (HowLong == 1) 6793 Type = Unsigned ? Context.UnsignedLongTy : Context.LongTy; 6794 else 6795 Type = Unsigned ? Context.UnsignedIntTy : Context.IntTy; 6796 break; 6797 case 'c': 6798 assert(HowLong == 0 && "Bad modifiers used with 'c'!"); 6799 if (Signed) 6800 Type = Context.SignedCharTy; 6801 else if (Unsigned) 6802 Type = Context.UnsignedCharTy; 6803 else 6804 Type = Context.CharTy; 6805 break; 6806 case 'b': // boolean 6807 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'b'!"); 6808 Type = Context.BoolTy; 6809 break; 6810 case 'z': // size_t. 6811 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'z'!"); 6812 Type = Context.getSizeType(); 6813 break; 6814 case 'F': 6815 Type = Context.getCFConstantStringType(); 6816 break; 6817 case 'G': 6818 Type = Context.getObjCIdType(); 6819 break; 6820 case 'H': 6821 Type = Context.getObjCSelType(); 6822 break; 6823 case 'a': 6824 Type = Context.getBuiltinVaListType(); 6825 assert(!Type.isNull() && "builtin va list type not initialized!"); 6826 break; 6827 case 'A': 6828 // This is a "reference" to a va_list; however, what exactly 6829 // this means depends on how va_list is defined. There are two 6830 // different kinds of va_list: ones passed by value, and ones 6831 // passed by reference. An example of a by-value va_list is 6832 // x86, where va_list is a char*. An example of by-ref va_list 6833 // is x86-64, where va_list is a __va_list_tag[1]. For x86, 6834 // we want this argument to be a char*&; for x86-64, we want 6835 // it to be a __va_list_tag*. 6836 Type = Context.getBuiltinVaListType(); 6837 assert(!Type.isNull() && "builtin va list type not initialized!"); 6838 if (Type->isArrayType()) 6839 Type = Context.getArrayDecayedType(Type); 6840 else 6841 Type = Context.getLValueReferenceType(Type); 6842 break; 6843 case 'V': { 6844 char *End; 6845 unsigned NumElements = strtoul(Str, &End, 10); 6846 assert(End != Str && "Missing vector size"); 6847 Str = End; 6848 6849 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, 6850 RequiresICE, false); 6851 assert(!RequiresICE && "Can't require vector ICE"); 6852 6853 // TODO: No way to make AltiVec vectors in builtins yet. 6854 Type = Context.getVectorType(ElementType, NumElements, 6855 VectorType::GenericVector); 6856 break; 6857 } 6858 case 'E': { 6859 char *End; 6860 6861 unsigned NumElements = strtoul(Str, &End, 10); 6862 assert(End != Str && "Missing vector size"); 6863 6864 Str = End; 6865 6866 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6867 false); 6868 Type = Context.getExtVectorType(ElementType, NumElements); 6869 break; 6870 } 6871 case 'X': { 6872 QualType ElementType = DecodeTypeFromStr(Str, Context, Error, RequiresICE, 6873 false); 6874 assert(!RequiresICE && "Can't require complex ICE"); 6875 Type = Context.getComplexType(ElementType); 6876 break; 6877 } 6878 case 'Y' : { 6879 Type = Context.getPointerDiffType(); 6880 break; 6881 } 6882 case 'P': 6883 Type = Context.getFILEType(); 6884 if (Type.isNull()) { 6885 Error = ASTContext::GE_Missing_stdio; 6886 return QualType(); 6887 } 6888 break; 6889 case 'J': 6890 if (Signed) 6891 Type = Context.getsigjmp_bufType(); 6892 else 6893 Type = Context.getjmp_bufType(); 6894 6895 if (Type.isNull()) { 6896 Error = ASTContext::GE_Missing_setjmp; 6897 return QualType(); 6898 } 6899 break; 6900 case 'K': 6901 assert(HowLong == 0 && !Signed && !Unsigned && "Bad modifiers for 'K'!"); 6902 Type = Context.getucontext_tType(); 6903 6904 if (Type.isNull()) { 6905 Error = ASTContext::GE_Missing_ucontext; 6906 return QualType(); 6907 } 6908 break; 6909 } 6910 6911 // If there are modifiers and if we're allowed to parse them, go for it. 6912 Done = !AllowTypeModifiers; 6913 while (!Done) { 6914 switch (char c = *Str++) { 6915 default: Done = true; --Str; break; 6916 case '*': 6917 case '&': { 6918 // Both pointers and references can have their pointee types 6919 // qualified with an address space. 6920 char *End; 6921 unsigned AddrSpace = strtoul(Str, &End, 10); 6922 if (End != Str && AddrSpace != 0) { 6923 Type = Context.getAddrSpaceQualType(Type, AddrSpace); 6924 Str = End; 6925 } 6926 if (c == '*') 6927 Type = Context.getPointerType(Type); 6928 else 6929 Type = Context.getLValueReferenceType(Type); 6930 break; 6931 } 6932 // FIXME: There's no way to have a built-in with an rvalue ref arg. 6933 case 'C': 6934 Type = Type.withConst(); 6935 break; 6936 case 'D': 6937 Type = Context.getVolatileType(Type); 6938 break; 6939 case 'R': 6940 Type = Type.withRestrict(); 6941 break; 6942 } 6943 } 6944 6945 assert((!RequiresICE || Type->isIntegralOrEnumerationType()) && 6946 "Integer constant 'I' type must be an integer"); 6947 6948 return Type; 6949} 6950 6951/// GetBuiltinType - Return the type for the specified builtin. 6952QualType ASTContext::GetBuiltinType(unsigned Id, 6953 GetBuiltinTypeError &Error, 6954 unsigned *IntegerConstantArgs) const { 6955 const char *TypeStr = BuiltinInfo.GetTypeString(Id); 6956 6957 SmallVector<QualType, 8> ArgTypes; 6958 6959 bool RequiresICE = false; 6960 Error = GE_None; 6961 QualType ResType = DecodeTypeFromStr(TypeStr, *this, Error, 6962 RequiresICE, true); 6963 if (Error != GE_None) 6964 return QualType(); 6965 6966 assert(!RequiresICE && "Result of intrinsic cannot be required to be an ICE"); 6967 6968 while (TypeStr[0] && TypeStr[0] != '.') { 6969 QualType Ty = DecodeTypeFromStr(TypeStr, *this, Error, RequiresICE, true); 6970 if (Error != GE_None) 6971 return QualType(); 6972 6973 // If this argument is required to be an IntegerConstantExpression and the 6974 // caller cares, fill in the bitmask we return. 6975 if (RequiresICE && IntegerConstantArgs) 6976 *IntegerConstantArgs |= 1 << ArgTypes.size(); 6977 6978 // Do array -> pointer decay. The builtin should use the decayed type. 6979 if (Ty->isArrayType()) 6980 Ty = getArrayDecayedType(Ty); 6981 6982 ArgTypes.push_back(Ty); 6983 } 6984 6985 assert((TypeStr[0] != '.' || TypeStr[1] == 0) && 6986 "'.' should only occur at end of builtin type list!"); 6987 6988 FunctionType::ExtInfo EI; 6989 if (BuiltinInfo.isNoReturn(Id)) EI = EI.withNoReturn(true); 6990 6991 bool Variadic = (TypeStr[0] == '.'); 6992 6993 // We really shouldn't be making a no-proto type here, especially in C++. 6994 if (ArgTypes.empty() && Variadic) 6995 return getFunctionNoProtoType(ResType, EI); 6996 6997 FunctionProtoType::ExtProtoInfo EPI; 6998 EPI.ExtInfo = EI; 6999 EPI.Variadic = Variadic; 7000 7001 return getFunctionType(ResType, ArgTypes.data(), ArgTypes.size(), EPI); 7002} 7003 7004GVALinkage ASTContext::GetGVALinkageForFunction(const FunctionDecl *FD) { 7005 GVALinkage External = GVA_StrongExternal; 7006 7007 Linkage L = FD->getLinkage(); 7008 switch (L) { 7009 case NoLinkage: 7010 case InternalLinkage: 7011 case UniqueExternalLinkage: 7012 return GVA_Internal; 7013 7014 case ExternalLinkage: 7015 switch (FD->getTemplateSpecializationKind()) { 7016 case TSK_Undeclared: 7017 case TSK_ExplicitSpecialization: 7018 External = GVA_StrongExternal; 7019 break; 7020 7021 case TSK_ExplicitInstantiationDefinition: 7022 return GVA_ExplicitTemplateInstantiation; 7023 7024 case TSK_ExplicitInstantiationDeclaration: 7025 case TSK_ImplicitInstantiation: 7026 External = GVA_TemplateInstantiation; 7027 break; 7028 } 7029 } 7030 7031 if (!FD->isInlined()) 7032 return External; 7033 7034 if (!getLangOpts().CPlusPlus || FD->hasAttr<GNUInlineAttr>()) { 7035 // GNU or C99 inline semantics. Determine whether this symbol should be 7036 // externally visible. 7037 if (FD->isInlineDefinitionExternallyVisible()) 7038 return External; 7039 7040 // C99 inline semantics, where the symbol is not externally visible. 7041 return GVA_C99Inline; 7042 } 7043 7044 // C++0x [temp.explicit]p9: 7045 // [ Note: The intent is that an inline function that is the subject of 7046 // an explicit instantiation declaration will still be implicitly 7047 // instantiated when used so that the body can be considered for 7048 // inlining, but that no out-of-line copy of the inline function would be 7049 // generated in the translation unit. -- end note ] 7050 if (FD->getTemplateSpecializationKind() 7051 == TSK_ExplicitInstantiationDeclaration) 7052 return GVA_C99Inline; 7053 7054 return GVA_CXXInline; 7055} 7056 7057GVALinkage ASTContext::GetGVALinkageForVariable(const VarDecl *VD) { 7058 // If this is a static data member, compute the kind of template 7059 // specialization. Otherwise, this variable is not part of a 7060 // template. 7061 TemplateSpecializationKind TSK = TSK_Undeclared; 7062 if (VD->isStaticDataMember()) 7063 TSK = VD->getTemplateSpecializationKind(); 7064 7065 Linkage L = VD->getLinkage(); 7066 if (L == ExternalLinkage && getLangOpts().CPlusPlus && 7067 VD->getType()->getLinkage() == UniqueExternalLinkage) 7068 L = UniqueExternalLinkage; 7069 7070 switch (L) { 7071 case NoLinkage: 7072 case InternalLinkage: 7073 case UniqueExternalLinkage: 7074 return GVA_Internal; 7075 7076 case ExternalLinkage: 7077 switch (TSK) { 7078 case TSK_Undeclared: 7079 case TSK_ExplicitSpecialization: 7080 return GVA_StrongExternal; 7081 7082 case TSK_ExplicitInstantiationDeclaration: 7083 llvm_unreachable("Variable should not be instantiated"); 7084 // Fall through to treat this like any other instantiation. 7085 7086 case TSK_ExplicitInstantiationDefinition: 7087 return GVA_ExplicitTemplateInstantiation; 7088 7089 case TSK_ImplicitInstantiation: 7090 return GVA_TemplateInstantiation; 7091 } 7092 } 7093 7094 llvm_unreachable("Invalid Linkage!"); 7095} 7096 7097bool ASTContext::DeclMustBeEmitted(const Decl *D) { 7098 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 7099 if (!VD->isFileVarDecl()) 7100 return false; 7101 } else if (!isa<FunctionDecl>(D)) 7102 return false; 7103 7104 // Weak references don't produce any output by themselves. 7105 if (D->hasAttr<WeakRefAttr>()) 7106 return false; 7107 7108 // Aliases and used decls are required. 7109 if (D->hasAttr<AliasAttr>() || D->hasAttr<UsedAttr>()) 7110 return true; 7111 7112 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) { 7113 // Forward declarations aren't required. 7114 if (!FD->doesThisDeclarationHaveABody()) 7115 return FD->doesDeclarationForceExternallyVisibleDefinition(); 7116 7117 // Constructors and destructors are required. 7118 if (FD->hasAttr<ConstructorAttr>() || FD->hasAttr<DestructorAttr>()) 7119 return true; 7120 7121 // The key function for a class is required. 7122 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) { 7123 const CXXRecordDecl *RD = MD->getParent(); 7124 if (MD->isOutOfLine() && RD->isDynamicClass()) { 7125 const CXXMethodDecl *KeyFunc = getKeyFunction(RD); 7126 if (KeyFunc && KeyFunc->getCanonicalDecl() == MD->getCanonicalDecl()) 7127 return true; 7128 } 7129 } 7130 7131 GVALinkage Linkage = GetGVALinkageForFunction(FD); 7132 7133 // static, static inline, always_inline, and extern inline functions can 7134 // always be deferred. Normal inline functions can be deferred in C99/C++. 7135 // Implicit template instantiations can also be deferred in C++. 7136 if (Linkage == GVA_Internal || Linkage == GVA_C99Inline || 7137 Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation) 7138 return false; 7139 return true; 7140 } 7141 7142 const VarDecl *VD = cast<VarDecl>(D); 7143 assert(VD->isFileVarDecl() && "Expected file scoped var"); 7144 7145 if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) 7146 return false; 7147 7148 // Structs that have non-trivial constructors or destructors are required. 7149 7150 // FIXME: Handle references. 7151 // FIXME: Be more selective about which constructors we care about. 7152 if (const RecordType *RT = VD->getType()->getAs<RecordType>()) { 7153 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl())) { 7154 if (RD->hasDefinition() && !(RD->hasTrivialDefaultConstructor() && 7155 RD->hasTrivialCopyConstructor() && 7156 RD->hasTrivialMoveConstructor() && 7157 RD->hasTrivialDestructor())) 7158 return true; 7159 } 7160 } 7161 7162 GVALinkage L = GetGVALinkageForVariable(VD); 7163 if (L == GVA_Internal || L == GVA_TemplateInstantiation) { 7164 if (!(VD->getInit() && VD->getInit()->HasSideEffects(*this))) 7165 return false; 7166 } 7167 7168 return true; 7169} 7170 7171CallingConv ASTContext::getDefaultCXXMethodCallConv(bool isVariadic) { 7172 // Pass through to the C++ ABI object 7173 return ABI->getDefaultMethodCallConv(isVariadic); 7174} 7175 7176CallingConv ASTContext::getCanonicalCallConv(CallingConv CC) const { 7177 if (CC == CC_C && !LangOpts.MRTD && getTargetInfo().getCXXABI() != CXXABI_Microsoft) 7178 return CC_Default; 7179 return CC; 7180} 7181 7182bool ASTContext::isNearlyEmpty(const CXXRecordDecl *RD) const { 7183 // Pass through to the C++ ABI object 7184 return ABI->isNearlyEmpty(RD); 7185} 7186 7187MangleContext *ASTContext::createMangleContext() { 7188 switch (Target->getCXXABI()) { 7189 case CXXABI_ARM: 7190 case CXXABI_Itanium: 7191 return createItaniumMangleContext(*this, getDiagnostics()); 7192 case CXXABI_Microsoft: 7193 return createMicrosoftMangleContext(*this, getDiagnostics()); 7194 } 7195 llvm_unreachable("Unsupported ABI"); 7196} 7197 7198CXXABI::~CXXABI() {} 7199 7200size_t ASTContext::getSideTableAllocatedMemory() const { 7201 return ASTRecordLayouts.getMemorySize() 7202 + llvm::capacity_in_bytes(ObjCLayouts) 7203 + llvm::capacity_in_bytes(KeyFunctions) 7204 + llvm::capacity_in_bytes(ObjCImpls) 7205 + llvm::capacity_in_bytes(BlockVarCopyInits) 7206 + llvm::capacity_in_bytes(DeclAttrs) 7207 + llvm::capacity_in_bytes(InstantiatedFromStaticDataMember) 7208 + llvm::capacity_in_bytes(InstantiatedFromUsingDecl) 7209 + llvm::capacity_in_bytes(InstantiatedFromUsingShadowDecl) 7210 + llvm::capacity_in_bytes(InstantiatedFromUnnamedFieldDecl) 7211 + llvm::capacity_in_bytes(OverriddenMethods) 7212 + llvm::capacity_in_bytes(Types) 7213 + llvm::capacity_in_bytes(VariableArrayTypes) 7214 + llvm::capacity_in_bytes(ClassScopeSpecializationPattern); 7215} 7216 7217unsigned ASTContext::getLambdaManglingNumber(CXXMethodDecl *CallOperator) { 7218 CXXRecordDecl *Lambda = CallOperator->getParent(); 7219 return LambdaMangleContexts[Lambda->getDeclContext()] 7220 .getManglingNumber(CallOperator); 7221} 7222 7223 7224void ASTContext::setParameterIndex(const ParmVarDecl *D, unsigned int index) { 7225 ParamIndices[D] = index; 7226} 7227 7228unsigned ASTContext::getParameterIndex(const ParmVarDecl *D) const { 7229 ParameterIndexTable::const_iterator I = ParamIndices.find(D); 7230 assert(I != ParamIndices.end() && 7231 "ParmIndices lacks entry set by ParmVarDecl"); 7232 return I->second; 7233} 7234