Decl.cpp revision f76b092e1a6f0df4a5c64aae3c71d6e81e4b717c
1//===--- Decl.cpp - Declaration AST Node Implementation -------------------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the Decl subclasses. 11// 12//===----------------------------------------------------------------------===// 13 14#include "clang/AST/Decl.h" 15#include "clang/AST/DeclCXX.h" 16#include "clang/AST/DeclObjC.h" 17#include "clang/AST/DeclTemplate.h" 18#include "clang/AST/ASTContext.h" 19#include "clang/AST/TypeLoc.h" 20#include "clang/AST/Stmt.h" 21#include "clang/AST/Expr.h" 22#include "clang/AST/ExprCXX.h" 23#include "clang/AST/PrettyPrinter.h" 24#include "clang/AST/ASTMutationListener.h" 25#include "clang/Basic/Builtins.h" 26#include "clang/Basic/IdentifierTable.h" 27#include "clang/Basic/Specifiers.h" 28#include "llvm/Support/ErrorHandling.h" 29 30using namespace clang; 31 32//===----------------------------------------------------------------------===// 33// NamedDecl Implementation 34//===----------------------------------------------------------------------===// 35 36static const VisibilityAttr *GetExplicitVisibility(const Decl *d) { 37 // Use the most recent declaration of a variable. 38 if (const VarDecl *var = dyn_cast<VarDecl>(d)) 39 return var->getMostRecentDeclaration()->getAttr<VisibilityAttr>(); 40 41 // Use the most recent declaration of a function, and also handle 42 // function template specializations. 43 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(d)) { 44 if (const VisibilityAttr *attr 45 = fn->getMostRecentDeclaration()->getAttr<VisibilityAttr>()) 46 return attr; 47 48 // If the function is a specialization of a template with an 49 // explicit visibility attribute, use that. 50 if (FunctionTemplateSpecializationInfo *templateInfo 51 = fn->getTemplateSpecializationInfo()) 52 return templateInfo->getTemplate()->getTemplatedDecl() 53 ->getAttr<VisibilityAttr>(); 54 55 return 0; 56 } 57 58 // Otherwise, just check the declaration itself first. 59 if (const VisibilityAttr *attr = d->getAttr<VisibilityAttr>()) 60 return attr; 61 62 // If there wasn't explicit visibility there, and this is a 63 // specialization of a class template, check for visibility 64 // on the pattern. 65 if (const ClassTemplateSpecializationDecl *spec 66 = dyn_cast<ClassTemplateSpecializationDecl>(d)) 67 return spec->getSpecializedTemplate()->getTemplatedDecl() 68 ->getAttr<VisibilityAttr>(); 69 70 return 0; 71} 72 73static Visibility GetVisibilityFromAttr(const VisibilityAttr *A) { 74 switch (A->getVisibility()) { 75 case VisibilityAttr::Default: 76 return DefaultVisibility; 77 case VisibilityAttr::Hidden: 78 return HiddenVisibility; 79 case VisibilityAttr::Protected: 80 return ProtectedVisibility; 81 } 82 return DefaultVisibility; 83} 84 85typedef NamedDecl::LinkageInfo LinkageInfo; 86typedef std::pair<Linkage,Visibility> LVPair; 87 88static LVPair merge(LVPair L, LVPair R) { 89 return LVPair(minLinkage(L.first, R.first), 90 minVisibility(L.second, R.second)); 91} 92 93static LVPair merge(LVPair L, LinkageInfo R) { 94 return LVPair(minLinkage(L.first, R.linkage()), 95 minVisibility(L.second, R.visibility())); 96} 97 98namespace { 99/// Flags controlling the computation of linkage and visibility. 100struct LVFlags { 101 bool ConsiderGlobalVisibility; 102 bool ConsiderVisibilityAttributes; 103 104 LVFlags() : ConsiderGlobalVisibility(true), 105 ConsiderVisibilityAttributes(true) { 106 } 107 108 /// \brief Returns a set of flags that is only useful for computing the 109 /// linkage, not the visibility, of a declaration. 110 static LVFlags CreateOnlyDeclLinkage() { 111 LVFlags F; 112 F.ConsiderGlobalVisibility = false; 113 F.ConsiderVisibilityAttributes = false; 114 return F; 115 } 116 117 /// Returns a set of flags, otherwise based on these, which ignores 118 /// off all sources of visibility except template arguments. 119 LVFlags onlyTemplateVisibility() const { 120 LVFlags F = *this; 121 F.ConsiderGlobalVisibility = false; 122 F.ConsiderVisibilityAttributes = false; 123 return F; 124 } 125}; 126} // end anonymous namespace 127 128/// \brief Get the most restrictive linkage for the types in the given 129/// template parameter list. 130static LVPair 131getLVForTemplateParameterList(const TemplateParameterList *Params) { 132 LVPair LV(ExternalLinkage, DefaultVisibility); 133 for (TemplateParameterList::const_iterator P = Params->begin(), 134 PEnd = Params->end(); 135 P != PEnd; ++P) { 136 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 137 if (NTTP->isExpandedParameterPack()) { 138 for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) { 139 QualType T = NTTP->getExpansionType(I); 140 if (!T->isDependentType()) 141 LV = merge(LV, T->getLinkageAndVisibility()); 142 } 143 continue; 144 } 145 146 if (!NTTP->getType()->isDependentType()) { 147 LV = merge(LV, NTTP->getType()->getLinkageAndVisibility()); 148 continue; 149 } 150 } 151 152 if (TemplateTemplateParmDecl *TTP 153 = dyn_cast<TemplateTemplateParmDecl>(*P)) { 154 LV = merge(LV, getLVForTemplateParameterList(TTP->getTemplateParameters())); 155 } 156 } 157 158 return LV; 159} 160 161/// getLVForDecl - Get the linkage and visibility for the given declaration. 162static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F); 163 164/// \brief Get the most restrictive linkage for the types and 165/// declarations in the given template argument list. 166static LVPair getLVForTemplateArgumentList(const TemplateArgument *Args, 167 unsigned NumArgs, 168 LVFlags &F) { 169 LVPair LV(ExternalLinkage, DefaultVisibility); 170 171 for (unsigned I = 0; I != NumArgs; ++I) { 172 switch (Args[I].getKind()) { 173 case TemplateArgument::Null: 174 case TemplateArgument::Integral: 175 case TemplateArgument::Expression: 176 break; 177 178 case TemplateArgument::Type: 179 LV = merge(LV, Args[I].getAsType()->getLinkageAndVisibility()); 180 break; 181 182 case TemplateArgument::Declaration: 183 // The decl can validly be null as the representation of nullptr 184 // arguments, valid only in C++0x. 185 if (Decl *D = Args[I].getAsDecl()) { 186 if (NamedDecl *ND = dyn_cast<NamedDecl>(D)) 187 LV = merge(LV, getLVForDecl(ND, F)); 188 } 189 break; 190 191 case TemplateArgument::Template: 192 case TemplateArgument::TemplateExpansion: 193 if (TemplateDecl *Template 194 = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 195 LV = merge(LV, getLVForDecl(Template, F)); 196 break; 197 198 case TemplateArgument::Pack: 199 LV = merge(LV, getLVForTemplateArgumentList(Args[I].pack_begin(), 200 Args[I].pack_size(), 201 F)); 202 break; 203 } 204 } 205 206 return LV; 207} 208 209static LVPair 210getLVForTemplateArgumentList(const TemplateArgumentList &TArgs, 211 LVFlags &F) { 212 return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F); 213} 214 215static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) { 216 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 217 "Not a name having namespace scope"); 218 ASTContext &Context = D->getASTContext(); 219 220 // C++ [basic.link]p3: 221 // A name having namespace scope (3.3.6) has internal linkage if it 222 // is the name of 223 // - an object, reference, function or function template that is 224 // explicitly declared static; or, 225 // (This bullet corresponds to C99 6.2.2p3.) 226 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 227 // Explicitly declared static. 228 if (Var->getStorageClass() == SC_Static) 229 return LinkageInfo::internal(); 230 231 // - an object or reference that is explicitly declared const 232 // and neither explicitly declared extern nor previously 233 // declared to have external linkage; or 234 // (there is no equivalent in C99) 235 if (Context.getLangOptions().CPlusPlus && 236 Var->getType().isConstant(Context) && 237 Var->getStorageClass() != SC_Extern && 238 Var->getStorageClass() != SC_PrivateExtern) { 239 bool FoundExtern = false; 240 for (const VarDecl *PrevVar = Var->getPreviousDeclaration(); 241 PrevVar && !FoundExtern; 242 PrevVar = PrevVar->getPreviousDeclaration()) 243 if (isExternalLinkage(PrevVar->getLinkage())) 244 FoundExtern = true; 245 246 if (!FoundExtern) 247 return LinkageInfo::internal(); 248 } 249 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 250 // C++ [temp]p4: 251 // A non-member function template can have internal linkage; any 252 // other template name shall have external linkage. 253 const FunctionDecl *Function = 0; 254 if (const FunctionTemplateDecl *FunTmpl 255 = dyn_cast<FunctionTemplateDecl>(D)) 256 Function = FunTmpl->getTemplatedDecl(); 257 else 258 Function = cast<FunctionDecl>(D); 259 260 // Explicitly declared static. 261 if (Function->getStorageClass() == SC_Static) 262 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 263 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 264 // - a data member of an anonymous union. 265 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 266 return LinkageInfo::internal(); 267 } 268 269 if (D->isInAnonymousNamespace()) 270 return LinkageInfo::uniqueExternal(); 271 272 // Set up the defaults. 273 274 // C99 6.2.2p5: 275 // If the declaration of an identifier for an object has file 276 // scope and no storage-class specifier, its linkage is 277 // external. 278 LinkageInfo LV; 279 280 if (F.ConsiderVisibilityAttributes) { 281 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) { 282 LV.setVisibility(GetVisibilityFromAttr(VA), true); 283 F.ConsiderGlobalVisibility = false; 284 } else { 285 // If we're declared in a namespace with a visibility attribute, 286 // use that namespace's visibility, but don't call it explicit. 287 for (const DeclContext *DC = D->getDeclContext(); 288 !isa<TranslationUnitDecl>(DC); 289 DC = DC->getParent()) { 290 if (!isa<NamespaceDecl>(DC)) continue; 291 if (const VisibilityAttr *VA = 292 cast<NamespaceDecl>(DC)->getAttr<VisibilityAttr>()) { 293 LV.setVisibility(GetVisibilityFromAttr(VA), false); 294 F.ConsiderGlobalVisibility = false; 295 break; 296 } 297 } 298 } 299 } 300 301 // C++ [basic.link]p4: 302 303 // A name having namespace scope has external linkage if it is the 304 // name of 305 // 306 // - an object or reference, unless it has internal linkage; or 307 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 308 // GCC applies the following optimization to variables and static 309 // data members, but not to functions: 310 // 311 // Modify the variable's LV by the LV of its type unless this is 312 // C or extern "C". This follows from [basic.link]p9: 313 // A type without linkage shall not be used as the type of a 314 // variable or function with external linkage unless 315 // - the entity has C language linkage, or 316 // - the entity is declared within an unnamed namespace, or 317 // - the entity is not used or is defined in the same 318 // translation unit. 319 // and [basic.link]p10: 320 // ...the types specified by all declarations referring to a 321 // given variable or function shall be identical... 322 // C does not have an equivalent rule. 323 // 324 // Ignore this if we've got an explicit attribute; the user 325 // probably knows what they're doing. 326 // 327 // Note that we don't want to make the variable non-external 328 // because of this, but unique-external linkage suits us. 329 if (Context.getLangOptions().CPlusPlus && !Var->isExternC()) { 330 LVPair TypeLV = Var->getType()->getLinkageAndVisibility(); 331 if (TypeLV.first != ExternalLinkage) 332 return LinkageInfo::uniqueExternal(); 333 if (!LV.visibilityExplicit()) 334 LV.mergeVisibility(TypeLV.second); 335 } 336 337 if (Var->getStorageClass() == SC_PrivateExtern) 338 LV.setVisibility(HiddenVisibility, true); 339 340 if (!Context.getLangOptions().CPlusPlus && 341 (Var->getStorageClass() == SC_Extern || 342 Var->getStorageClass() == SC_PrivateExtern)) { 343 344 // C99 6.2.2p4: 345 // For an identifier declared with the storage-class specifier 346 // extern in a scope in which a prior declaration of that 347 // identifier is visible, if the prior declaration specifies 348 // internal or external linkage, the linkage of the identifier 349 // at the later declaration is the same as the linkage 350 // specified at the prior declaration. If no prior declaration 351 // is visible, or if the prior declaration specifies no 352 // linkage, then the identifier has external linkage. 353 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) { 354 LinkageInfo PrevLV = getLVForDecl(PrevVar, F); 355 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 356 LV.mergeVisibility(PrevLV); 357 } 358 } 359 360 // - a function, unless it has internal linkage; or 361 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 362 // In theory, we can modify the function's LV by the LV of its 363 // type unless it has C linkage (see comment above about variables 364 // for justification). In practice, GCC doesn't do this, so it's 365 // just too painful to make work. 366 367 if (Function->getStorageClass() == SC_PrivateExtern) 368 LV.setVisibility(HiddenVisibility, true); 369 370 // C99 6.2.2p5: 371 // If the declaration of an identifier for a function has no 372 // storage-class specifier, its linkage is determined exactly 373 // as if it were declared with the storage-class specifier 374 // extern. 375 if (!Context.getLangOptions().CPlusPlus && 376 (Function->getStorageClass() == SC_Extern || 377 Function->getStorageClass() == SC_PrivateExtern || 378 Function->getStorageClass() == SC_None)) { 379 // C99 6.2.2p4: 380 // For an identifier declared with the storage-class specifier 381 // extern in a scope in which a prior declaration of that 382 // identifier is visible, if the prior declaration specifies 383 // internal or external linkage, the linkage of the identifier 384 // at the later declaration is the same as the linkage 385 // specified at the prior declaration. If no prior declaration 386 // is visible, or if the prior declaration specifies no 387 // linkage, then the identifier has external linkage. 388 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) { 389 LinkageInfo PrevLV = getLVForDecl(PrevFunc, F); 390 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 391 LV.mergeVisibility(PrevLV); 392 } 393 } 394 395 if (FunctionTemplateSpecializationInfo *SpecInfo 396 = Function->getTemplateSpecializationInfo()) { 397 LV.merge(getLVForDecl(SpecInfo->getTemplate(), 398 F.onlyTemplateVisibility())); 399 const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments; 400 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F)); 401 } 402 403 // - a named class (Clause 9), or an unnamed class defined in a 404 // typedef declaration in which the class has the typedef name 405 // for linkage purposes (7.1.3); or 406 // - a named enumeration (7.2), or an unnamed enumeration 407 // defined in a typedef declaration in which the enumeration 408 // has the typedef name for linkage purposes (7.1.3); or 409 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) { 410 // Unnamed tags have no linkage. 411 if (!Tag->getDeclName() && !Tag->getTypedefForAnonDecl()) 412 return LinkageInfo::none(); 413 414 // If this is a class template specialization, consider the 415 // linkage of the template and template arguments. 416 if (const ClassTemplateSpecializationDecl *Spec 417 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 418 // From the template. 419 LV.merge(getLVForDecl(Spec->getSpecializedTemplate(), 420 F.onlyTemplateVisibility())); 421 422 // The arguments at which the template was instantiated. 423 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 424 LV.merge(getLVForTemplateArgumentList(TemplateArgs, F)); 425 } 426 427 // Consider -fvisibility unless the type has C linkage. 428 if (F.ConsiderGlobalVisibility) 429 F.ConsiderGlobalVisibility = 430 (Context.getLangOptions().CPlusPlus && 431 !Tag->getDeclContext()->isExternCContext()); 432 433 // - an enumerator belonging to an enumeration with external linkage; 434 } else if (isa<EnumConstantDecl>(D)) { 435 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F); 436 if (!isExternalLinkage(EnumLV.linkage())) 437 return LinkageInfo::none(); 438 LV.merge(EnumLV); 439 440 // - a template, unless it is a function template that has 441 // internal linkage (Clause 14); 442 } else if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 443 LV.merge(getLVForTemplateParameterList(Template->getTemplateParameters())); 444 445 // - a namespace (7.3), unless it is declared within an unnamed 446 // namespace. 447 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) { 448 return LV; 449 450 // By extension, we assign external linkage to Objective-C 451 // interfaces. 452 } else if (isa<ObjCInterfaceDecl>(D)) { 453 // fallout 454 455 // Everything not covered here has no linkage. 456 } else { 457 return LinkageInfo::none(); 458 } 459 460 // If we ended up with non-external linkage, visibility should 461 // always be default. 462 if (LV.linkage() != ExternalLinkage) 463 return LinkageInfo(LV.linkage(), DefaultVisibility, false); 464 465 // If we didn't end up with hidden visibility, consider attributes 466 // and -fvisibility. 467 if (F.ConsiderGlobalVisibility) 468 LV.mergeVisibility(Context.getLangOptions().getVisibilityMode()); 469 470 return LV; 471} 472 473static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) { 474 // Only certain class members have linkage. Note that fields don't 475 // really have linkage, but it's convenient to say they do for the 476 // purposes of calculating linkage of pointer-to-data-member 477 // template arguments. 478 if (!(isa<CXXMethodDecl>(D) || 479 isa<VarDecl>(D) || 480 isa<FieldDecl>(D) || 481 (isa<TagDecl>(D) && 482 (D->getDeclName() || cast<TagDecl>(D)->getTypedefForAnonDecl())))) 483 return LinkageInfo::none(); 484 485 LinkageInfo LV; 486 487 // The flags we're going to use to compute the class's visibility. 488 LVFlags ClassF = F; 489 490 // If we have an explicit visibility attribute, merge that in. 491 if (F.ConsiderVisibilityAttributes) { 492 if (const VisibilityAttr *VA = GetExplicitVisibility(D)) { 493 LV.mergeVisibility(GetVisibilityFromAttr(VA), true); 494 495 // Ignore global visibility later, but not this attribute. 496 F.ConsiderGlobalVisibility = false; 497 498 // Ignore both global visibility and attributes when computing our 499 // parent's visibility. 500 ClassF = F.onlyTemplateVisibility(); 501 } 502 } 503 504 // Class members only have linkage if their class has external 505 // linkage. 506 LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF)); 507 if (!isExternalLinkage(LV.linkage())) 508 return LinkageInfo::none(); 509 510 // If the class already has unique-external linkage, we can't improve. 511 if (LV.linkage() == UniqueExternalLinkage) 512 return LinkageInfo::uniqueExternal(); 513 514 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 515 TemplateSpecializationKind TSK = TSK_Undeclared; 516 517 // If this is a method template specialization, use the linkage for 518 // the template parameters and arguments. 519 if (FunctionTemplateSpecializationInfo *Spec 520 = MD->getTemplateSpecializationInfo()) { 521 LV.merge(getLVForTemplateArgumentList(*Spec->TemplateArguments, F)); 522 LV.merge(getLVForTemplateParameterList( 523 Spec->getTemplate()->getTemplateParameters())); 524 525 TSK = Spec->getTemplateSpecializationKind(); 526 } else if (MemberSpecializationInfo *MSI = 527 MD->getMemberSpecializationInfo()) { 528 TSK = MSI->getTemplateSpecializationKind(); 529 } 530 531 // If we're paying attention to global visibility, apply 532 // -finline-visibility-hidden if this is an inline method. 533 // 534 // Note that ConsiderGlobalVisibility doesn't yet have information 535 // about whether containing classes have visibility attributes, 536 // and that's intentional. 537 if (TSK != TSK_ExplicitInstantiationDeclaration && 538 F.ConsiderGlobalVisibility && 539 MD->getASTContext().getLangOptions().InlineVisibilityHidden) { 540 // InlineVisibilityHidden only applies to definitions, and 541 // isInlined() only gives meaningful answers on definitions 542 // anyway. 543 const FunctionDecl *Def = 0; 544 if (MD->hasBody(Def) && Def->isInlined()) 545 LV.setVisibility(HiddenVisibility); 546 } 547 548 // Note that in contrast to basically every other situation, we 549 // *do* apply -fvisibility to method declarations. 550 551 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 552 if (const ClassTemplateSpecializationDecl *Spec 553 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 554 // Merge template argument/parameter information for member 555 // class template specializations. 556 LV.merge(getLVForTemplateArgumentList(Spec->getTemplateArgs(), F)); 557 LV.merge(getLVForTemplateParameterList( 558 Spec->getSpecializedTemplate()->getTemplateParameters())); 559 } 560 561 // Static data members. 562 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 563 // Modify the variable's linkage by its type, but ignore the 564 // type's visibility unless it's a definition. 565 LVPair TypeLV = VD->getType()->getLinkageAndVisibility(); 566 if (TypeLV.first != ExternalLinkage) 567 LV.mergeLinkage(UniqueExternalLinkage); 568 if (!LV.visibilityExplicit()) 569 LV.mergeVisibility(TypeLV.second); 570 } 571 572 F.ConsiderGlobalVisibility &= !LV.visibilityExplicit(); 573 574 // Apply -fvisibility if desired. 575 if (F.ConsiderGlobalVisibility && LV.visibility() != HiddenVisibility) { 576 LV.mergeVisibility(D->getASTContext().getLangOptions().getVisibilityMode()); 577 } 578 579 return LV; 580} 581 582static void clearLinkageForClass(const CXXRecordDecl *record) { 583 for (CXXRecordDecl::decl_iterator 584 i = record->decls_begin(), e = record->decls_end(); i != e; ++i) { 585 Decl *child = *i; 586 if (isa<NamedDecl>(child)) 587 cast<NamedDecl>(child)->ClearLinkageCache(); 588 } 589} 590 591void NamedDecl::ClearLinkageCache() { 592 // Note that we can't skip clearing the linkage of children just 593 // because the parent doesn't have cached linkage: we don't cache 594 // when computing linkage for parent contexts. 595 596 HasCachedLinkage = 0; 597 598 // If we're changing the linkage of a class, we need to reset the 599 // linkage of child declarations, too. 600 if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this)) 601 clearLinkageForClass(record); 602 603 if (const ClassTemplateDecl *temp = dyn_cast<ClassTemplateDecl>(this)) { 604 // Clear linkage for the template pattern. 605 CXXRecordDecl *record = temp->getTemplatedDecl(); 606 record->HasCachedLinkage = 0; 607 clearLinkageForClass(record); 608 609 // ...do we need to clear linkage for specializations, too? 610 } 611} 612 613Linkage NamedDecl::getLinkage() const { 614 if (HasCachedLinkage) { 615 assert(Linkage(CachedLinkage) == 616 getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage()); 617 return Linkage(CachedLinkage); 618 } 619 620 CachedLinkage = getLVForDecl(this, 621 LVFlags::CreateOnlyDeclLinkage()).linkage(); 622 HasCachedLinkage = 1; 623 return Linkage(CachedLinkage); 624} 625 626LinkageInfo NamedDecl::getLinkageAndVisibility() const { 627 LinkageInfo LI = getLVForDecl(this, LVFlags()); 628 assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage()); 629 HasCachedLinkage = 1; 630 CachedLinkage = LI.linkage(); 631 return LI; 632} 633 634static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) { 635 // Objective-C: treat all Objective-C declarations as having external 636 // linkage. 637 switch (D->getKind()) { 638 default: 639 break; 640 case Decl::TemplateTemplateParm: // count these as external 641 case Decl::NonTypeTemplateParm: 642 case Decl::ObjCAtDefsField: 643 case Decl::ObjCCategory: 644 case Decl::ObjCCategoryImpl: 645 case Decl::ObjCCompatibleAlias: 646 case Decl::ObjCForwardProtocol: 647 case Decl::ObjCImplementation: 648 case Decl::ObjCMethod: 649 case Decl::ObjCProperty: 650 case Decl::ObjCPropertyImpl: 651 case Decl::ObjCProtocol: 652 return LinkageInfo::external(); 653 } 654 655 // Handle linkage for namespace-scope names. 656 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 657 return getLVForNamespaceScopeDecl(D, Flags); 658 659 // C++ [basic.link]p5: 660 // In addition, a member function, static data member, a named 661 // class or enumeration of class scope, or an unnamed class or 662 // enumeration defined in a class-scope typedef declaration such 663 // that the class or enumeration has the typedef name for linkage 664 // purposes (7.1.3), has external linkage if the name of the class 665 // has external linkage. 666 if (D->getDeclContext()->isRecord()) 667 return getLVForClassMember(D, Flags); 668 669 // C++ [basic.link]p6: 670 // The name of a function declared in block scope and the name of 671 // an object declared by a block scope extern declaration have 672 // linkage. If there is a visible declaration of an entity with 673 // linkage having the same name and type, ignoring entities 674 // declared outside the innermost enclosing namespace scope, the 675 // block scope declaration declares that same entity and receives 676 // the linkage of the previous declaration. If there is more than 677 // one such matching entity, the program is ill-formed. Otherwise, 678 // if no matching entity is found, the block scope entity receives 679 // external linkage. 680 if (D->getLexicalDeclContext()->isFunctionOrMethod()) { 681 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 682 if (Function->isInAnonymousNamespace()) 683 return LinkageInfo::uniqueExternal(); 684 685 LinkageInfo LV; 686 if (Flags.ConsiderVisibilityAttributes) { 687 if (const VisibilityAttr *VA = GetExplicitVisibility(Function)) 688 LV.setVisibility(GetVisibilityFromAttr(VA)); 689 } 690 691 if (const FunctionDecl *Prev = Function->getPreviousDeclaration()) { 692 LinkageInfo PrevLV = getLVForDecl(Prev, Flags); 693 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 694 LV.mergeVisibility(PrevLV); 695 } 696 697 return LV; 698 } 699 700 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) 701 if (Var->getStorageClass() == SC_Extern || 702 Var->getStorageClass() == SC_PrivateExtern) { 703 if (Var->isInAnonymousNamespace()) 704 return LinkageInfo::uniqueExternal(); 705 706 LinkageInfo LV; 707 if (Var->getStorageClass() == SC_PrivateExtern) 708 LV.setVisibility(HiddenVisibility); 709 else if (Flags.ConsiderVisibilityAttributes) { 710 if (const VisibilityAttr *VA = GetExplicitVisibility(Var)) 711 LV.setVisibility(GetVisibilityFromAttr(VA)); 712 } 713 714 if (const VarDecl *Prev = Var->getPreviousDeclaration()) { 715 LinkageInfo PrevLV = getLVForDecl(Prev, Flags); 716 if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage()); 717 LV.mergeVisibility(PrevLV); 718 } 719 720 return LV; 721 } 722 } 723 724 // C++ [basic.link]p6: 725 // Names not covered by these rules have no linkage. 726 return LinkageInfo::none(); 727} 728 729std::string NamedDecl::getQualifiedNameAsString() const { 730 return getQualifiedNameAsString(getASTContext().getLangOptions()); 731} 732 733std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 734 const DeclContext *Ctx = getDeclContext(); 735 736 if (Ctx->isFunctionOrMethod()) 737 return getNameAsString(); 738 739 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy; 740 ContextsTy Contexts; 741 742 // Collect contexts. 743 while (Ctx && isa<NamedDecl>(Ctx)) { 744 Contexts.push_back(Ctx); 745 Ctx = Ctx->getParent(); 746 }; 747 748 std::string QualName; 749 llvm::raw_string_ostream OS(QualName); 750 751 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 752 I != E; ++I) { 753 if (const ClassTemplateSpecializationDecl *Spec 754 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 755 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 756 std::string TemplateArgsStr 757 = TemplateSpecializationType::PrintTemplateArgumentList( 758 TemplateArgs.data(), 759 TemplateArgs.size(), 760 P); 761 OS << Spec->getName() << TemplateArgsStr; 762 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 763 if (ND->isAnonymousNamespace()) 764 OS << "<anonymous namespace>"; 765 else 766 OS << ND; 767 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 768 if (!RD->getIdentifier()) 769 OS << "<anonymous " << RD->getKindName() << '>'; 770 else 771 OS << RD; 772 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 773 const FunctionProtoType *FT = 0; 774 if (FD->hasWrittenPrototype()) 775 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 776 777 OS << FD << '('; 778 if (FT) { 779 unsigned NumParams = FD->getNumParams(); 780 for (unsigned i = 0; i < NumParams; ++i) { 781 if (i) 782 OS << ", "; 783 std::string Param; 784 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P); 785 OS << Param; 786 } 787 788 if (FT->isVariadic()) { 789 if (NumParams > 0) 790 OS << ", "; 791 OS << "..."; 792 } 793 } 794 OS << ')'; 795 } else { 796 OS << cast<NamedDecl>(*I); 797 } 798 OS << "::"; 799 } 800 801 if (getDeclName()) 802 OS << this; 803 else 804 OS << "<anonymous>"; 805 806 return OS.str(); 807} 808 809bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 810 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 811 812 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 813 // We want to keep it, unless it nominates same namespace. 814 if (getKind() == Decl::UsingDirective) { 815 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() == 816 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace(); 817 } 818 819 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 820 // For function declarations, we keep track of redeclarations. 821 return FD->getPreviousDeclaration() == OldD; 822 823 // For function templates, the underlying function declarations are linked. 824 if (const FunctionTemplateDecl *FunctionTemplate 825 = dyn_cast<FunctionTemplateDecl>(this)) 826 if (const FunctionTemplateDecl *OldFunctionTemplate 827 = dyn_cast<FunctionTemplateDecl>(OldD)) 828 return FunctionTemplate->getTemplatedDecl() 829 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 830 831 // For method declarations, we keep track of redeclarations. 832 if (isa<ObjCMethodDecl>(this)) 833 return false; 834 835 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 836 return true; 837 838 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 839 return cast<UsingShadowDecl>(this)->getTargetDecl() == 840 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 841 842 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) 843 return cast<UsingDecl>(this)->getTargetNestedNameDecl() == 844 cast<UsingDecl>(OldD)->getTargetNestedNameDecl(); 845 846 // For non-function declarations, if the declarations are of the 847 // same kind then this must be a redeclaration, or semantic analysis 848 // would not have given us the new declaration. 849 return this->getKind() == OldD->getKind(); 850} 851 852bool NamedDecl::hasLinkage() const { 853 return getLinkage() != NoLinkage; 854} 855 856NamedDecl *NamedDecl::getUnderlyingDecl() { 857 NamedDecl *ND = this; 858 while (true) { 859 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 860 ND = UD->getTargetDecl(); 861 else if (ObjCCompatibleAliasDecl *AD 862 = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 863 return AD->getClassInterface(); 864 else 865 return ND; 866 } 867} 868 869bool NamedDecl::isCXXInstanceMember() const { 870 assert(isCXXClassMember() && 871 "checking whether non-member is instance member"); 872 873 const NamedDecl *D = this; 874 if (isa<UsingShadowDecl>(D)) 875 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 876 877 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) 878 return true; 879 if (isa<CXXMethodDecl>(D)) 880 return cast<CXXMethodDecl>(D)->isInstance(); 881 if (isa<FunctionTemplateDecl>(D)) 882 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 883 ->getTemplatedDecl())->isInstance(); 884 return false; 885} 886 887//===----------------------------------------------------------------------===// 888// DeclaratorDecl Implementation 889//===----------------------------------------------------------------------===// 890 891template <typename DeclT> 892static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 893 if (decl->getNumTemplateParameterLists() > 0) 894 return decl->getTemplateParameterList(0)->getTemplateLoc(); 895 else 896 return decl->getInnerLocStart(); 897} 898 899SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 900 TypeSourceInfo *TSI = getTypeSourceInfo(); 901 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 902 return SourceLocation(); 903} 904 905void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 906 SourceRange QualifierRange) { 907 if (Qualifier) { 908 // Make sure the extended decl info is allocated. 909 if (!hasExtInfo()) { 910 // Save (non-extended) type source info pointer. 911 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 912 // Allocate external info struct. 913 DeclInfo = new (getASTContext()) ExtInfo; 914 // Restore savedTInfo into (extended) decl info. 915 getExtInfo()->TInfo = savedTInfo; 916 } 917 // Set qualifier info. 918 getExtInfo()->NNS = Qualifier; 919 getExtInfo()->NNSRange = QualifierRange; 920 } 921 else { 922 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 923 assert(QualifierRange.isInvalid()); 924 if (hasExtInfo()) { 925 // Save type source info pointer. 926 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 927 // Deallocate the extended decl info. 928 getASTContext().Deallocate(getExtInfo()); 929 // Restore savedTInfo into (non-extended) decl info. 930 DeclInfo = savedTInfo; 931 } 932 } 933} 934 935SourceLocation DeclaratorDecl::getOuterLocStart() const { 936 return getTemplateOrInnerLocStart(this); 937} 938 939void 940QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 941 unsigned NumTPLists, 942 TemplateParameterList **TPLists) { 943 assert((NumTPLists == 0 || TPLists != 0) && 944 "Empty array of template parameters with positive size!"); 945 assert((NumTPLists == 0 || NNS) && 946 "Nonempty array of template parameters with no qualifier!"); 947 948 // Free previous template parameters (if any). 949 if (NumTemplParamLists > 0) { 950 Context.Deallocate(TemplParamLists); 951 TemplParamLists = 0; 952 NumTemplParamLists = 0; 953 } 954 // Set info on matched template parameter lists (if any). 955 if (NumTPLists > 0) { 956 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 957 NumTemplParamLists = NumTPLists; 958 for (unsigned i = NumTPLists; i-- > 0; ) 959 TemplParamLists[i] = TPLists[i]; 960 } 961} 962 963//===----------------------------------------------------------------------===// 964// VarDecl Implementation 965//===----------------------------------------------------------------------===// 966 967const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 968 switch (SC) { 969 case SC_None: break; 970 case SC_Auto: return "auto"; break; 971 case SC_Extern: return "extern"; break; 972 case SC_PrivateExtern: return "__private_extern__"; break; 973 case SC_Register: return "register"; break; 974 case SC_Static: return "static"; break; 975 } 976 977 assert(0 && "Invalid storage class"); 978 return 0; 979} 980 981VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 982 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 983 StorageClass S, StorageClass SCAsWritten) { 984 return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten); 985} 986 987void VarDecl::setStorageClass(StorageClass SC) { 988 assert(isLegalForVariable(SC)); 989 if (getStorageClass() != SC) 990 ClearLinkageCache(); 991 992 SClass = SC; 993} 994 995SourceLocation VarDecl::getInnerLocStart() const { 996 SourceLocation Start = getTypeSpecStartLoc(); 997 if (Start.isInvalid()) 998 Start = getLocation(); 999 return Start; 1000} 1001 1002SourceRange VarDecl::getSourceRange() const { 1003 if (getInit()) 1004 return SourceRange(getOuterLocStart(), getInit()->getLocEnd()); 1005 return SourceRange(getOuterLocStart(), getLocation()); 1006} 1007 1008bool VarDecl::isExternC() const { 1009 ASTContext &Context = getASTContext(); 1010 if (!Context.getLangOptions().CPlusPlus) 1011 return (getDeclContext()->isTranslationUnit() && 1012 getStorageClass() != SC_Static) || 1013 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); 1014 1015 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 1016 DC = DC->getParent()) { 1017 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 1018 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 1019 return getStorageClass() != SC_Static; 1020 1021 break; 1022 } 1023 1024 if (DC->isFunctionOrMethod()) 1025 return false; 1026 } 1027 1028 return false; 1029} 1030 1031VarDecl *VarDecl::getCanonicalDecl() { 1032 return getFirstDeclaration(); 1033} 1034 1035VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const { 1036 // C++ [basic.def]p2: 1037 // A declaration is a definition unless [...] it contains the 'extern' 1038 // specifier or a linkage-specification and neither an initializer [...], 1039 // it declares a static data member in a class declaration [...]. 1040 // C++ [temp.expl.spec]p15: 1041 // An explicit specialization of a static data member of a template is a 1042 // definition if the declaration includes an initializer; otherwise, it is 1043 // a declaration. 1044 if (isStaticDataMember()) { 1045 if (isOutOfLine() && (hasInit() || 1046 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 1047 return Definition; 1048 else 1049 return DeclarationOnly; 1050 } 1051 // C99 6.7p5: 1052 // A definition of an identifier is a declaration for that identifier that 1053 // [...] causes storage to be reserved for that object. 1054 // Note: that applies for all non-file-scope objects. 1055 // C99 6.9.2p1: 1056 // If the declaration of an identifier for an object has file scope and an 1057 // initializer, the declaration is an external definition for the identifier 1058 if (hasInit()) 1059 return Definition; 1060 // AST for 'extern "C" int foo;' is annotated with 'extern'. 1061 if (hasExternalStorage()) 1062 return DeclarationOnly; 1063 1064 if (getStorageClassAsWritten() == SC_Extern || 1065 getStorageClassAsWritten() == SC_PrivateExtern) { 1066 for (const VarDecl *PrevVar = getPreviousDeclaration(); 1067 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) { 1068 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit()) 1069 return DeclarationOnly; 1070 } 1071 } 1072 // C99 6.9.2p2: 1073 // A declaration of an object that has file scope without an initializer, 1074 // and without a storage class specifier or the scs 'static', constitutes 1075 // a tentative definition. 1076 // No such thing in C++. 1077 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl()) 1078 return TentativeDefinition; 1079 1080 // What's left is (in C, block-scope) declarations without initializers or 1081 // external storage. These are definitions. 1082 return Definition; 1083} 1084 1085VarDecl *VarDecl::getActingDefinition() { 1086 DefinitionKind Kind = isThisDeclarationADefinition(); 1087 if (Kind != TentativeDefinition) 1088 return 0; 1089 1090 VarDecl *LastTentative = 0; 1091 VarDecl *First = getFirstDeclaration(); 1092 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1093 I != E; ++I) { 1094 Kind = (*I)->isThisDeclarationADefinition(); 1095 if (Kind == Definition) 1096 return 0; 1097 else if (Kind == TentativeDefinition) 1098 LastTentative = *I; 1099 } 1100 return LastTentative; 1101} 1102 1103bool VarDecl::isTentativeDefinitionNow() const { 1104 DefinitionKind Kind = isThisDeclarationADefinition(); 1105 if (Kind != TentativeDefinition) 1106 return false; 1107 1108 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1109 if ((*I)->isThisDeclarationADefinition() == Definition) 1110 return false; 1111 } 1112 return true; 1113} 1114 1115VarDecl *VarDecl::getDefinition() { 1116 VarDecl *First = getFirstDeclaration(); 1117 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1118 I != E; ++I) { 1119 if ((*I)->isThisDeclarationADefinition() == Definition) 1120 return *I; 1121 } 1122 return 0; 1123} 1124 1125VarDecl::DefinitionKind VarDecl::hasDefinition() const { 1126 DefinitionKind Kind = DeclarationOnly; 1127 1128 const VarDecl *First = getFirstDeclaration(); 1129 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1130 I != E; ++I) 1131 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition()); 1132 1133 return Kind; 1134} 1135 1136const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 1137 redecl_iterator I = redecls_begin(), E = redecls_end(); 1138 while (I != E && !I->getInit()) 1139 ++I; 1140 1141 if (I != E) { 1142 D = *I; 1143 return I->getInit(); 1144 } 1145 return 0; 1146} 1147 1148bool VarDecl::isOutOfLine() const { 1149 if (Decl::isOutOfLine()) 1150 return true; 1151 1152 if (!isStaticDataMember()) 1153 return false; 1154 1155 // If this static data member was instantiated from a static data member of 1156 // a class template, check whether that static data member was defined 1157 // out-of-line. 1158 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 1159 return VD->isOutOfLine(); 1160 1161 return false; 1162} 1163 1164VarDecl *VarDecl::getOutOfLineDefinition() { 1165 if (!isStaticDataMember()) 1166 return 0; 1167 1168 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 1169 RD != RDEnd; ++RD) { 1170 if (RD->getLexicalDeclContext()->isFileContext()) 1171 return *RD; 1172 } 1173 1174 return 0; 1175} 1176 1177void VarDecl::setInit(Expr *I) { 1178 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 1179 Eval->~EvaluatedStmt(); 1180 getASTContext().Deallocate(Eval); 1181 } 1182 1183 Init = I; 1184} 1185 1186VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 1187 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1188 return cast<VarDecl>(MSI->getInstantiatedFrom()); 1189 1190 return 0; 1191} 1192 1193TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 1194 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1195 return MSI->getTemplateSpecializationKind(); 1196 1197 return TSK_Undeclared; 1198} 1199 1200MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 1201 return getASTContext().getInstantiatedFromStaticDataMember(this); 1202} 1203 1204void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1205 SourceLocation PointOfInstantiation) { 1206 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 1207 assert(MSI && "Not an instantiated static data member?"); 1208 MSI->setTemplateSpecializationKind(TSK); 1209 if (TSK != TSK_ExplicitSpecialization && 1210 PointOfInstantiation.isValid() && 1211 MSI->getPointOfInstantiation().isInvalid()) 1212 MSI->setPointOfInstantiation(PointOfInstantiation); 1213} 1214 1215//===----------------------------------------------------------------------===// 1216// ParmVarDecl Implementation 1217//===----------------------------------------------------------------------===// 1218 1219ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 1220 SourceLocation L, IdentifierInfo *Id, 1221 QualType T, TypeSourceInfo *TInfo, 1222 StorageClass S, StorageClass SCAsWritten, 1223 Expr *DefArg) { 1224 return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo, 1225 S, SCAsWritten, DefArg); 1226} 1227 1228Expr *ParmVarDecl::getDefaultArg() { 1229 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 1230 assert(!hasUninstantiatedDefaultArg() && 1231 "Default argument is not yet instantiated!"); 1232 1233 Expr *Arg = getInit(); 1234 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 1235 return E->getSubExpr(); 1236 1237 return Arg; 1238} 1239 1240unsigned ParmVarDecl::getNumDefaultArgTemporaries() const { 1241 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit())) 1242 return E->getNumTemporaries(); 1243 1244 return 0; 1245} 1246 1247CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) { 1248 assert(getNumDefaultArgTemporaries() && 1249 "Default arguments does not have any temporaries!"); 1250 1251 ExprWithCleanups *E = cast<ExprWithCleanups>(getInit()); 1252 return E->getTemporary(i); 1253} 1254 1255SourceRange ParmVarDecl::getDefaultArgRange() const { 1256 if (const Expr *E = getInit()) 1257 return E->getSourceRange(); 1258 1259 if (hasUninstantiatedDefaultArg()) 1260 return getUninstantiatedDefaultArg()->getSourceRange(); 1261 1262 return SourceRange(); 1263} 1264 1265bool ParmVarDecl::isParameterPack() const { 1266 return isa<PackExpansionType>(getType()); 1267} 1268 1269//===----------------------------------------------------------------------===// 1270// FunctionDecl Implementation 1271//===----------------------------------------------------------------------===// 1272 1273void FunctionDecl::getNameForDiagnostic(std::string &S, 1274 const PrintingPolicy &Policy, 1275 bool Qualified) const { 1276 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 1277 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 1278 if (TemplateArgs) 1279 S += TemplateSpecializationType::PrintTemplateArgumentList( 1280 TemplateArgs->data(), 1281 TemplateArgs->size(), 1282 Policy); 1283 1284} 1285 1286bool FunctionDecl::isVariadic() const { 1287 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 1288 return FT->isVariadic(); 1289 return false; 1290} 1291 1292bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 1293 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1294 if (I->Body) { 1295 Definition = *I; 1296 return true; 1297 } 1298 } 1299 1300 return false; 1301} 1302 1303Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 1304 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1305 if (I->Body) { 1306 Definition = *I; 1307 return I->Body.get(getASTContext().getExternalSource()); 1308 } 1309 } 1310 1311 return 0; 1312} 1313 1314void FunctionDecl::setBody(Stmt *B) { 1315 Body = B; 1316 if (B) 1317 EndRangeLoc = B->getLocEnd(); 1318} 1319 1320void FunctionDecl::setPure(bool P) { 1321 IsPure = P; 1322 if (P) 1323 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 1324 Parent->markedVirtualFunctionPure(); 1325} 1326 1327bool FunctionDecl::isMain() const { 1328 ASTContext &Context = getASTContext(); 1329 return !Context.getLangOptions().Freestanding && 1330 getDeclContext()->getRedeclContext()->isTranslationUnit() && 1331 getIdentifier() && getIdentifier()->isStr("main"); 1332} 1333 1334bool FunctionDecl::isExternC() const { 1335 ASTContext &Context = getASTContext(); 1336 // In C, any non-static, non-overloadable function has external 1337 // linkage. 1338 if (!Context.getLangOptions().CPlusPlus) 1339 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>(); 1340 1341 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 1342 DC = DC->getParent()) { 1343 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 1344 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 1345 return getStorageClass() != SC_Static && 1346 !getAttr<OverloadableAttr>(); 1347 1348 break; 1349 } 1350 1351 if (DC->isRecord()) 1352 break; 1353 } 1354 1355 return isMain(); 1356} 1357 1358bool FunctionDecl::isGlobal() const { 1359 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 1360 return Method->isStatic(); 1361 1362 if (getStorageClass() == SC_Static) 1363 return false; 1364 1365 for (const DeclContext *DC = getDeclContext(); 1366 DC->isNamespace(); 1367 DC = DC->getParent()) { 1368 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 1369 if (!Namespace->getDeclName()) 1370 return false; 1371 break; 1372 } 1373 } 1374 1375 return true; 1376} 1377 1378void 1379FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 1380 redeclarable_base::setPreviousDeclaration(PrevDecl); 1381 1382 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 1383 FunctionTemplateDecl *PrevFunTmpl 1384 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 1385 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 1386 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 1387 } 1388 1389 if (PrevDecl->IsInline) 1390 IsInline = true; 1391} 1392 1393const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 1394 return getFirstDeclaration(); 1395} 1396 1397FunctionDecl *FunctionDecl::getCanonicalDecl() { 1398 return getFirstDeclaration(); 1399} 1400 1401void FunctionDecl::setStorageClass(StorageClass SC) { 1402 assert(isLegalForFunction(SC)); 1403 if (getStorageClass() != SC) 1404 ClearLinkageCache(); 1405 1406 SClass = SC; 1407} 1408 1409/// \brief Returns a value indicating whether this function 1410/// corresponds to a builtin function. 1411/// 1412/// The function corresponds to a built-in function if it is 1413/// declared at translation scope or within an extern "C" block and 1414/// its name matches with the name of a builtin. The returned value 1415/// will be 0 for functions that do not correspond to a builtin, a 1416/// value of type \c Builtin::ID if in the target-independent range 1417/// \c [1,Builtin::First), or a target-specific builtin value. 1418unsigned FunctionDecl::getBuiltinID() const { 1419 ASTContext &Context = getASTContext(); 1420 if (!getIdentifier() || !getIdentifier()->getBuiltinID()) 1421 return 0; 1422 1423 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1424 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1425 return BuiltinID; 1426 1427 // This function has the name of a known C library 1428 // function. Determine whether it actually refers to the C library 1429 // function or whether it just has the same name. 1430 1431 // If this is a static function, it's not a builtin. 1432 if (getStorageClass() == SC_Static) 1433 return 0; 1434 1435 // If this function is at translation-unit scope and we're not in 1436 // C++, it refers to the C library function. 1437 if (!Context.getLangOptions().CPlusPlus && 1438 getDeclContext()->isTranslationUnit()) 1439 return BuiltinID; 1440 1441 // If the function is in an extern "C" linkage specification and is 1442 // not marked "overloadable", it's the real function. 1443 if (isa<LinkageSpecDecl>(getDeclContext()) && 1444 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1445 == LinkageSpecDecl::lang_c && 1446 !getAttr<OverloadableAttr>()) 1447 return BuiltinID; 1448 1449 // Not a builtin 1450 return 0; 1451} 1452 1453 1454/// getNumParams - Return the number of parameters this function must have 1455/// based on its FunctionType. This is the length of the ParamInfo array 1456/// after it has been created. 1457unsigned FunctionDecl::getNumParams() const { 1458 const FunctionType *FT = getType()->getAs<FunctionType>(); 1459 if (isa<FunctionNoProtoType>(FT)) 1460 return 0; 1461 return cast<FunctionProtoType>(FT)->getNumArgs(); 1462 1463} 1464 1465void FunctionDecl::setParams(ASTContext &C, 1466 ParmVarDecl **NewParamInfo, unsigned NumParams) { 1467 assert(ParamInfo == 0 && "Already has param info!"); 1468 assert(NumParams == getNumParams() && "Parameter count mismatch!"); 1469 1470 // Zero params -> null pointer. 1471 if (NumParams) { 1472 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); 1473 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1474 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1475 1476 // Update source range. The check below allows us to set EndRangeLoc before 1477 // setting the parameters. 1478 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation()) 1479 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd(); 1480 } 1481} 1482 1483/// getMinRequiredArguments - Returns the minimum number of arguments 1484/// needed to call this function. This may be fewer than the number of 1485/// function parameters, if some of the parameters have default 1486/// arguments (in C++) or the last parameter is a parameter pack. 1487unsigned FunctionDecl::getMinRequiredArguments() const { 1488 if (!getASTContext().getLangOptions().CPlusPlus) 1489 return getNumParams(); 1490 1491 unsigned NumRequiredArgs = getNumParams(); 1492 1493 // If the last parameter is a parameter pack, we don't need an argument for 1494 // it. 1495 if (NumRequiredArgs > 0 && 1496 getParamDecl(NumRequiredArgs - 1)->isParameterPack()) 1497 --NumRequiredArgs; 1498 1499 // If this parameter has a default argument, we don't need an argument for 1500 // it. 1501 while (NumRequiredArgs > 0 && 1502 getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1503 --NumRequiredArgs; 1504 1505 // We might have parameter packs before the end. These can't be deduced, 1506 // but they can still handle multiple arguments. 1507 unsigned ArgIdx = NumRequiredArgs; 1508 while (ArgIdx > 0) { 1509 if (getParamDecl(ArgIdx - 1)->isParameterPack()) 1510 NumRequiredArgs = ArgIdx; 1511 1512 --ArgIdx; 1513 } 1514 1515 return NumRequiredArgs; 1516} 1517 1518bool FunctionDecl::isInlined() const { 1519 if (IsInline) 1520 return true; 1521 1522 if (isa<CXXMethodDecl>(this)) { 1523 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1524 return true; 1525 } 1526 1527 switch (getTemplateSpecializationKind()) { 1528 case TSK_Undeclared: 1529 case TSK_ExplicitSpecialization: 1530 return false; 1531 1532 case TSK_ImplicitInstantiation: 1533 case TSK_ExplicitInstantiationDeclaration: 1534 case TSK_ExplicitInstantiationDefinition: 1535 // Handle below. 1536 break; 1537 } 1538 1539 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1540 bool HasPattern = false; 1541 if (PatternDecl) 1542 HasPattern = PatternDecl->hasBody(PatternDecl); 1543 1544 if (HasPattern && PatternDecl) 1545 return PatternDecl->isInlined(); 1546 1547 return false; 1548} 1549 1550/// \brief For an inline function definition in C or C++, determine whether the 1551/// definition will be externally visible. 1552/// 1553/// Inline function definitions are always available for inlining optimizations. 1554/// However, depending on the language dialect, declaration specifiers, and 1555/// attributes, the definition of an inline function may or may not be 1556/// "externally" visible to other translation units in the program. 1557/// 1558/// In C99, inline definitions are not externally visible by default. However, 1559/// if even one of the global-scope declarations is marked "extern inline", the 1560/// inline definition becomes externally visible (C99 6.7.4p6). 1561/// 1562/// In GNU89 mode, or if the gnu_inline attribute is attached to the function 1563/// definition, we use the GNU semantics for inline, which are nearly the 1564/// opposite of C99 semantics. In particular, "inline" by itself will create 1565/// an externally visible symbol, but "extern inline" will not create an 1566/// externally visible symbol. 1567bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 1568 assert(isThisDeclarationADefinition() && "Must have the function definition"); 1569 assert(isInlined() && "Function must be inline"); 1570 ASTContext &Context = getASTContext(); 1571 1572 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) { 1573 // If it's not the case that both 'inline' and 'extern' are 1574 // specified on the definition, then this inline definition is 1575 // externally visible. 1576 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern)) 1577 return true; 1578 1579 // If any declaration is 'inline' but not 'extern', then this definition 1580 // is externally visible. 1581 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1582 Redecl != RedeclEnd; 1583 ++Redecl) { 1584 if (Redecl->isInlineSpecified() && 1585 Redecl->getStorageClassAsWritten() != SC_Extern) 1586 return true; 1587 } 1588 1589 return false; 1590 } 1591 1592 // C99 6.7.4p6: 1593 // [...] If all of the file scope declarations for a function in a 1594 // translation unit include the inline function specifier without extern, 1595 // then the definition in that translation unit is an inline definition. 1596 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1597 Redecl != RedeclEnd; 1598 ++Redecl) { 1599 // Only consider file-scope declarations in this test. 1600 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1601 continue; 1602 1603 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 1604 return true; // Not an inline definition 1605 } 1606 1607 // C99 6.7.4p6: 1608 // An inline definition does not provide an external definition for the 1609 // function, and does not forbid an external definition in another 1610 // translation unit. 1611 return false; 1612} 1613 1614/// getOverloadedOperator - Which C++ overloaded operator this 1615/// function represents, if any. 1616OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 1617 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 1618 return getDeclName().getCXXOverloadedOperator(); 1619 else 1620 return OO_None; 1621} 1622 1623/// getLiteralIdentifier - The literal suffix identifier this function 1624/// represents, if any. 1625const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 1626 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 1627 return getDeclName().getCXXLiteralIdentifier(); 1628 else 1629 return 0; 1630} 1631 1632FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 1633 if (TemplateOrSpecialization.isNull()) 1634 return TK_NonTemplate; 1635 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 1636 return TK_FunctionTemplate; 1637 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 1638 return TK_MemberSpecialization; 1639 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 1640 return TK_FunctionTemplateSpecialization; 1641 if (TemplateOrSpecialization.is 1642 <DependentFunctionTemplateSpecializationInfo*>()) 1643 return TK_DependentFunctionTemplateSpecialization; 1644 1645 assert(false && "Did we miss a TemplateOrSpecialization type?"); 1646 return TK_NonTemplate; 1647} 1648 1649FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 1650 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 1651 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 1652 1653 return 0; 1654} 1655 1656MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 1657 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1658} 1659 1660void 1661FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 1662 FunctionDecl *FD, 1663 TemplateSpecializationKind TSK) { 1664 assert(TemplateOrSpecialization.isNull() && 1665 "Member function is already a specialization"); 1666 MemberSpecializationInfo *Info 1667 = new (C) MemberSpecializationInfo(FD, TSK); 1668 TemplateOrSpecialization = Info; 1669} 1670 1671bool FunctionDecl::isImplicitlyInstantiable() const { 1672 // If the function is invalid, it can't be implicitly instantiated. 1673 if (isInvalidDecl()) 1674 return false; 1675 1676 switch (getTemplateSpecializationKind()) { 1677 case TSK_Undeclared: 1678 case TSK_ExplicitSpecialization: 1679 case TSK_ExplicitInstantiationDefinition: 1680 return false; 1681 1682 case TSK_ImplicitInstantiation: 1683 return true; 1684 1685 case TSK_ExplicitInstantiationDeclaration: 1686 // Handled below. 1687 break; 1688 } 1689 1690 // Find the actual template from which we will instantiate. 1691 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1692 bool HasPattern = false; 1693 if (PatternDecl) 1694 HasPattern = PatternDecl->hasBody(PatternDecl); 1695 1696 // C++0x [temp.explicit]p9: 1697 // Except for inline functions, other explicit instantiation declarations 1698 // have the effect of suppressing the implicit instantiation of the entity 1699 // to which they refer. 1700 if (!HasPattern || !PatternDecl) 1701 return true; 1702 1703 return PatternDecl->isInlined(); 1704} 1705 1706FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 1707 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 1708 while (Primary->getInstantiatedFromMemberTemplate()) { 1709 // If we have hit a point where the user provided a specialization of 1710 // this template, we're done looking. 1711 if (Primary->isMemberSpecialization()) 1712 break; 1713 1714 Primary = Primary->getInstantiatedFromMemberTemplate(); 1715 } 1716 1717 return Primary->getTemplatedDecl(); 1718 } 1719 1720 return getInstantiatedFromMemberFunction(); 1721} 1722 1723FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 1724 if (FunctionTemplateSpecializationInfo *Info 1725 = TemplateOrSpecialization 1726 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1727 return Info->Template.getPointer(); 1728 } 1729 return 0; 1730} 1731 1732const TemplateArgumentList * 1733FunctionDecl::getTemplateSpecializationArgs() const { 1734 if (FunctionTemplateSpecializationInfo *Info 1735 = TemplateOrSpecialization 1736 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1737 return Info->TemplateArguments; 1738 } 1739 return 0; 1740} 1741 1742const TemplateArgumentListInfo * 1743FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 1744 if (FunctionTemplateSpecializationInfo *Info 1745 = TemplateOrSpecialization 1746 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1747 return Info->TemplateArgumentsAsWritten; 1748 } 1749 return 0; 1750} 1751 1752void 1753FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 1754 FunctionTemplateDecl *Template, 1755 const TemplateArgumentList *TemplateArgs, 1756 void *InsertPos, 1757 TemplateSpecializationKind TSK, 1758 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1759 SourceLocation PointOfInstantiation) { 1760 assert(TSK != TSK_Undeclared && 1761 "Must specify the type of function template specialization"); 1762 FunctionTemplateSpecializationInfo *Info 1763 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1764 if (!Info) 1765 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 1766 TemplateArgs, 1767 TemplateArgsAsWritten, 1768 PointOfInstantiation); 1769 TemplateOrSpecialization = Info; 1770 1771 // Insert this function template specialization into the set of known 1772 // function template specializations. 1773 if (InsertPos) 1774 Template->getSpecializations().InsertNode(Info, InsertPos); 1775 else { 1776 // Try to insert the new node. If there is an existing node, leave it, the 1777 // set will contain the canonical decls while 1778 // FunctionTemplateDecl::findSpecialization will return 1779 // the most recent redeclarations. 1780 FunctionTemplateSpecializationInfo *Existing 1781 = Template->getSpecializations().GetOrInsertNode(Info); 1782 (void)Existing; 1783 assert((!Existing || Existing->Function->isCanonicalDecl()) && 1784 "Set is supposed to only contain canonical decls"); 1785 } 1786} 1787 1788void 1789FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 1790 const UnresolvedSetImpl &Templates, 1791 const TemplateArgumentListInfo &TemplateArgs) { 1792 assert(TemplateOrSpecialization.isNull()); 1793 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 1794 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 1795 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 1796 void *Buffer = Context.Allocate(Size); 1797 DependentFunctionTemplateSpecializationInfo *Info = 1798 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 1799 TemplateArgs); 1800 TemplateOrSpecialization = Info; 1801} 1802 1803DependentFunctionTemplateSpecializationInfo:: 1804DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 1805 const TemplateArgumentListInfo &TArgs) 1806 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 1807 1808 d.NumTemplates = Ts.size(); 1809 d.NumArgs = TArgs.size(); 1810 1811 FunctionTemplateDecl **TsArray = 1812 const_cast<FunctionTemplateDecl**>(getTemplates()); 1813 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 1814 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 1815 1816 TemplateArgumentLoc *ArgsArray = 1817 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 1818 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 1819 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 1820} 1821 1822TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 1823 // For a function template specialization, query the specialization 1824 // information object. 1825 FunctionTemplateSpecializationInfo *FTSInfo 1826 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1827 if (FTSInfo) 1828 return FTSInfo->getTemplateSpecializationKind(); 1829 1830 MemberSpecializationInfo *MSInfo 1831 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1832 if (MSInfo) 1833 return MSInfo->getTemplateSpecializationKind(); 1834 1835 return TSK_Undeclared; 1836} 1837 1838void 1839FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1840 SourceLocation PointOfInstantiation) { 1841 if (FunctionTemplateSpecializationInfo *FTSInfo 1842 = TemplateOrSpecialization.dyn_cast< 1843 FunctionTemplateSpecializationInfo*>()) { 1844 FTSInfo->setTemplateSpecializationKind(TSK); 1845 if (TSK != TSK_ExplicitSpecialization && 1846 PointOfInstantiation.isValid() && 1847 FTSInfo->getPointOfInstantiation().isInvalid()) 1848 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 1849 } else if (MemberSpecializationInfo *MSInfo 1850 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 1851 MSInfo->setTemplateSpecializationKind(TSK); 1852 if (TSK != TSK_ExplicitSpecialization && 1853 PointOfInstantiation.isValid() && 1854 MSInfo->getPointOfInstantiation().isInvalid()) 1855 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1856 } else 1857 assert(false && "Function cannot have a template specialization kind"); 1858} 1859 1860SourceLocation FunctionDecl::getPointOfInstantiation() const { 1861 if (FunctionTemplateSpecializationInfo *FTSInfo 1862 = TemplateOrSpecialization.dyn_cast< 1863 FunctionTemplateSpecializationInfo*>()) 1864 return FTSInfo->getPointOfInstantiation(); 1865 else if (MemberSpecializationInfo *MSInfo 1866 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 1867 return MSInfo->getPointOfInstantiation(); 1868 1869 return SourceLocation(); 1870} 1871 1872bool FunctionDecl::isOutOfLine() const { 1873 if (Decl::isOutOfLine()) 1874 return true; 1875 1876 // If this function was instantiated from a member function of a 1877 // class template, check whether that member function was defined out-of-line. 1878 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 1879 const FunctionDecl *Definition; 1880 if (FD->hasBody(Definition)) 1881 return Definition->isOutOfLine(); 1882 } 1883 1884 // If this function was instantiated from a function template, 1885 // check whether that function template was defined out-of-line. 1886 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 1887 const FunctionDecl *Definition; 1888 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 1889 return Definition->isOutOfLine(); 1890 } 1891 1892 return false; 1893} 1894 1895//===----------------------------------------------------------------------===// 1896// FieldDecl Implementation 1897//===----------------------------------------------------------------------===// 1898 1899FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 1900 SourceLocation L, IdentifierInfo *Id, QualType T, 1901 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) { 1902 return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable); 1903} 1904 1905bool FieldDecl::isAnonymousStructOrUnion() const { 1906 if (!isImplicit() || getDeclName()) 1907 return false; 1908 1909 if (const RecordType *Record = getType()->getAs<RecordType>()) 1910 return Record->getDecl()->isAnonymousStructOrUnion(); 1911 1912 return false; 1913} 1914 1915unsigned FieldDecl::getFieldIndex() const { 1916 if (CachedFieldIndex) return CachedFieldIndex - 1; 1917 1918 unsigned index = 0; 1919 RecordDecl::field_iterator 1920 i = getParent()->field_begin(), e = getParent()->field_end(); 1921 while (true) { 1922 assert(i != e && "failed to find field in parent!"); 1923 if (*i == this) 1924 break; 1925 1926 ++i; 1927 ++index; 1928 } 1929 1930 CachedFieldIndex = index + 1; 1931 return index; 1932} 1933 1934//===----------------------------------------------------------------------===// 1935// TagDecl Implementation 1936//===----------------------------------------------------------------------===// 1937 1938SourceLocation TagDecl::getOuterLocStart() const { 1939 return getTemplateOrInnerLocStart(this); 1940} 1941 1942SourceRange TagDecl::getSourceRange() const { 1943 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 1944 return SourceRange(getOuterLocStart(), E); 1945} 1946 1947TagDecl* TagDecl::getCanonicalDecl() { 1948 return getFirstDeclaration(); 1949} 1950 1951void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) { 1952 TypedefDeclOrQualifier = TDD; 1953 if (TypeForDecl) 1954 const_cast<Type*>(TypeForDecl)->ClearLinkageCache(); 1955 ClearLinkageCache(); 1956} 1957 1958void TagDecl::startDefinition() { 1959 IsBeingDefined = true; 1960 1961 if (isa<CXXRecordDecl>(this)) { 1962 CXXRecordDecl *D = cast<CXXRecordDecl>(this); 1963 struct CXXRecordDecl::DefinitionData *Data = 1964 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 1965 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 1966 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 1967 } 1968} 1969 1970void TagDecl::completeDefinition() { 1971 assert((!isa<CXXRecordDecl>(this) || 1972 cast<CXXRecordDecl>(this)->hasDefinition()) && 1973 "definition completed but not started"); 1974 1975 IsDefinition = true; 1976 IsBeingDefined = false; 1977 1978 if (ASTMutationListener *L = getASTMutationListener()) 1979 L->CompletedTagDefinition(this); 1980} 1981 1982TagDecl* TagDecl::getDefinition() const { 1983 if (isDefinition()) 1984 return const_cast<TagDecl *>(this); 1985 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 1986 return CXXRD->getDefinition(); 1987 1988 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 1989 R != REnd; ++R) 1990 if (R->isDefinition()) 1991 return *R; 1992 1993 return 0; 1994} 1995 1996void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 1997 SourceRange QualifierRange) { 1998 if (Qualifier) { 1999 // Make sure the extended qualifier info is allocated. 2000 if (!hasExtInfo()) 2001 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo; 2002 // Set qualifier info. 2003 getExtInfo()->NNS = Qualifier; 2004 getExtInfo()->NNSRange = QualifierRange; 2005 } 2006 else { 2007 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2008 assert(QualifierRange.isInvalid()); 2009 if (hasExtInfo()) { 2010 getASTContext().Deallocate(getExtInfo()); 2011 TypedefDeclOrQualifier = (TypedefDecl*) 0; 2012 } 2013 } 2014} 2015 2016//===----------------------------------------------------------------------===// 2017// EnumDecl Implementation 2018//===----------------------------------------------------------------------===// 2019 2020EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2021 IdentifierInfo *Id, SourceLocation TKL, 2022 EnumDecl *PrevDecl, bool IsScoped, 2023 bool IsScopedUsingClassTag, bool IsFixed) { 2024 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL, 2025 IsScoped, IsScopedUsingClassTag, IsFixed); 2026 C.getTypeDeclType(Enum, PrevDecl); 2027 return Enum; 2028} 2029 2030EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) { 2031 return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation(), 2032 false, false, false); 2033} 2034 2035void EnumDecl::completeDefinition(QualType NewType, 2036 QualType NewPromotionType, 2037 unsigned NumPositiveBits, 2038 unsigned NumNegativeBits) { 2039 assert(!isDefinition() && "Cannot redefine enums!"); 2040 if (!IntegerType) 2041 IntegerType = NewType.getTypePtr(); 2042 PromotionType = NewPromotionType; 2043 setNumPositiveBits(NumPositiveBits); 2044 setNumNegativeBits(NumNegativeBits); 2045 TagDecl::completeDefinition(); 2046} 2047 2048//===----------------------------------------------------------------------===// 2049// RecordDecl Implementation 2050//===----------------------------------------------------------------------===// 2051 2052RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, 2053 IdentifierInfo *Id, RecordDecl *PrevDecl, 2054 SourceLocation TKL) 2055 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) { 2056 HasFlexibleArrayMember = false; 2057 AnonymousStructOrUnion = false; 2058 HasObjectMember = false; 2059 LoadedFieldsFromExternalStorage = false; 2060 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 2061} 2062 2063RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2064 SourceLocation L, IdentifierInfo *Id, 2065 SourceLocation TKL, RecordDecl* PrevDecl) { 2066 2067 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); 2068 C.getTypeDeclType(R, PrevDecl); 2069 return R; 2070} 2071 2072RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) { 2073 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0, 2074 SourceLocation()); 2075} 2076 2077bool RecordDecl::isInjectedClassName() const { 2078 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 2079 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 2080} 2081 2082RecordDecl::field_iterator RecordDecl::field_begin() const { 2083 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 2084 LoadFieldsFromExternalStorage(); 2085 2086 return field_iterator(decl_iterator(FirstDecl)); 2087} 2088 2089/// completeDefinition - Notes that the definition of this type is now 2090/// complete. 2091void RecordDecl::completeDefinition() { 2092 assert(!isDefinition() && "Cannot redefine record!"); 2093 TagDecl::completeDefinition(); 2094} 2095 2096void RecordDecl::LoadFieldsFromExternalStorage() const { 2097 ExternalASTSource *Source = getASTContext().getExternalSource(); 2098 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 2099 2100 // Notify that we have a RecordDecl doing some initialization. 2101 ExternalASTSource::Deserializing TheFields(Source); 2102 2103 llvm::SmallVector<Decl*, 64> Decls; 2104 if (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) 2105 return; 2106 2107#ifndef NDEBUG 2108 // Check that all decls we got were FieldDecls. 2109 for (unsigned i=0, e=Decls.size(); i != e; ++i) 2110 assert(isa<FieldDecl>(Decls[i])); 2111#endif 2112 2113 LoadedFieldsFromExternalStorage = true; 2114 2115 if (Decls.empty()) 2116 return; 2117 2118 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls); 2119} 2120 2121//===----------------------------------------------------------------------===// 2122// BlockDecl Implementation 2123//===----------------------------------------------------------------------===// 2124 2125void BlockDecl::setParams(ParmVarDecl **NewParamInfo, 2126 unsigned NParms) { 2127 assert(ParamInfo == 0 && "Already has param info!"); 2128 2129 // Zero params -> null pointer. 2130 if (NParms) { 2131 NumParams = NParms; 2132 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 2133 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 2134 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 2135 } 2136} 2137 2138void BlockDecl::setCaptures(ASTContext &Context, 2139 const Capture *begin, 2140 const Capture *end, 2141 bool capturesCXXThis) { 2142 CapturesCXXThis = capturesCXXThis; 2143 2144 if (begin == end) { 2145 NumCaptures = 0; 2146 Captures = 0; 2147 return; 2148 } 2149 2150 NumCaptures = end - begin; 2151 2152 // Avoid new Capture[] because we don't want to provide a default 2153 // constructor. 2154 size_t allocationSize = NumCaptures * sizeof(Capture); 2155 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*)); 2156 memcpy(buffer, begin, allocationSize); 2157 Captures = static_cast<Capture*>(buffer); 2158} 2159 2160SourceRange BlockDecl::getSourceRange() const { 2161 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 2162} 2163 2164//===----------------------------------------------------------------------===// 2165// Other Decl Allocation/Deallocation Method Implementations 2166//===----------------------------------------------------------------------===// 2167 2168TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 2169 return new (C) TranslationUnitDecl(C); 2170} 2171 2172NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2173 SourceLocation L, IdentifierInfo *Id) { 2174 return new (C) NamespaceDecl(DC, L, Id); 2175} 2176 2177NamespaceDecl *NamespaceDecl::getNextNamespace() { 2178 return dyn_cast_or_null<NamespaceDecl>( 2179 NextNamespace.get(getASTContext().getExternalSource())); 2180} 2181 2182ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 2183 SourceLocation L, IdentifierInfo *Id, QualType T) { 2184 return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T); 2185} 2186 2187FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 2188 const DeclarationNameInfo &NameInfo, 2189 QualType T, TypeSourceInfo *TInfo, 2190 StorageClass S, StorageClass SCAsWritten, 2191 bool isInlineSpecified, 2192 bool hasWrittenPrototype) { 2193 FunctionDecl *New = new (C) FunctionDecl(Function, DC, NameInfo, T, TInfo, 2194 S, SCAsWritten, isInlineSpecified); 2195 New->HasWrittenPrototype = hasWrittenPrototype; 2196 return New; 2197} 2198 2199BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 2200 return new (C) BlockDecl(DC, L); 2201} 2202 2203EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 2204 SourceLocation L, 2205 IdentifierInfo *Id, QualType T, 2206 Expr *E, const llvm::APSInt &V) { 2207 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 2208} 2209 2210IndirectFieldDecl * 2211IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2212 IdentifierInfo *Id, QualType T, NamedDecl **CH, 2213 unsigned CHS) { 2214 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 2215} 2216 2217SourceRange EnumConstantDecl::getSourceRange() const { 2218 SourceLocation End = getLocation(); 2219 if (Init) 2220 End = Init->getLocEnd(); 2221 return SourceRange(getLocation(), End); 2222} 2223 2224TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 2225 SourceLocation L, IdentifierInfo *Id, 2226 TypeSourceInfo *TInfo) { 2227 return new (C) TypedefDecl(DC, L, Id, TInfo); 2228} 2229 2230FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 2231 SourceLocation L, 2232 StringLiteral *Str) { 2233 return new (C) FileScopeAsmDecl(DC, L, Str); 2234} 2235