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