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