Decl.cpp revision f2cf562cec11dec926c0a29a71769a27fed02962
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 // Save type source info pointer. 965 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 966 // Deallocate the extended decl info. 967 getASTContext().Deallocate(getExtInfo()); 968 // Restore savedTInfo into (non-extended) decl info. 969 DeclInfo = savedTInfo; 970 } 971 } 972} 973 974SourceLocation DeclaratorDecl::getOuterLocStart() const { 975 return getTemplateOrInnerLocStart(this); 976} 977 978void 979QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 980 unsigned NumTPLists, 981 TemplateParameterList **TPLists) { 982 assert((NumTPLists == 0 || TPLists != 0) && 983 "Empty array of template parameters with positive size!"); 984 assert((NumTPLists == 0 || QualifierLoc) && 985 "Nonempty array of template parameters with no qualifier!"); 986 987 // Free previous template parameters (if any). 988 if (NumTemplParamLists > 0) { 989 Context.Deallocate(TemplParamLists); 990 TemplParamLists = 0; 991 NumTemplParamLists = 0; 992 } 993 // Set info on matched template parameter lists (if any). 994 if (NumTPLists > 0) { 995 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 996 NumTemplParamLists = NumTPLists; 997 for (unsigned i = NumTPLists; i-- > 0; ) 998 TemplParamLists[i] = TPLists[i]; 999 } 1000} 1001 1002//===----------------------------------------------------------------------===// 1003// VarDecl Implementation 1004//===----------------------------------------------------------------------===// 1005 1006const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1007 switch (SC) { 1008 case SC_None: break; 1009 case SC_Auto: return "auto"; break; 1010 case SC_Extern: return "extern"; break; 1011 case SC_PrivateExtern: return "__private_extern__"; break; 1012 case SC_Register: return "register"; break; 1013 case SC_Static: return "static"; break; 1014 } 1015 1016 assert(0 && "Invalid storage class"); 1017 return 0; 1018} 1019 1020VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1021 SourceLocation StartL, SourceLocation IdL, 1022 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1023 StorageClass S, StorageClass SCAsWritten) { 1024 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten); 1025} 1026 1027void VarDecl::setStorageClass(StorageClass SC) { 1028 assert(isLegalForVariable(SC)); 1029 if (getStorageClass() != SC) 1030 ClearLinkageCache(); 1031 1032 SClass = SC; 1033} 1034 1035SourceRange VarDecl::getSourceRange() const { 1036 if (getInit()) 1037 return SourceRange(getOuterLocStart(), getInit()->getLocEnd()); 1038 return SourceRange(getOuterLocStart(), getLocation()); 1039} 1040 1041bool VarDecl::isExternC() const { 1042 ASTContext &Context = getASTContext(); 1043 if (!Context.getLangOptions().CPlusPlus) 1044 return (getDeclContext()->isTranslationUnit() && 1045 getStorageClass() != SC_Static) || 1046 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); 1047 1048 const DeclContext *DC = getDeclContext(); 1049 if (DC->isFunctionOrMethod()) 1050 return false; 1051 1052 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 1053 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 1054 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 1055 return getStorageClass() != SC_Static; 1056 1057 break; 1058 } 1059 1060 } 1061 1062 return false; 1063} 1064 1065VarDecl *VarDecl::getCanonicalDecl() { 1066 return getFirstDeclaration(); 1067} 1068 1069VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const { 1070 // C++ [basic.def]p2: 1071 // A declaration is a definition unless [...] it contains the 'extern' 1072 // specifier or a linkage-specification and neither an initializer [...], 1073 // it declares a static data member in a class declaration [...]. 1074 // C++ [temp.expl.spec]p15: 1075 // An explicit specialization of a static data member of a template is a 1076 // definition if the declaration includes an initializer; otherwise, it is 1077 // a declaration. 1078 if (isStaticDataMember()) { 1079 if (isOutOfLine() && (hasInit() || 1080 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 1081 return Definition; 1082 else 1083 return DeclarationOnly; 1084 } 1085 // C99 6.7p5: 1086 // A definition of an identifier is a declaration for that identifier that 1087 // [...] causes storage to be reserved for that object. 1088 // Note: that applies for all non-file-scope objects. 1089 // C99 6.9.2p1: 1090 // If the declaration of an identifier for an object has file scope and an 1091 // initializer, the declaration is an external definition for the identifier 1092 if (hasInit()) 1093 return Definition; 1094 // AST for 'extern "C" int foo;' is annotated with 'extern'. 1095 if (hasExternalStorage()) 1096 return DeclarationOnly; 1097 1098 if (getStorageClassAsWritten() == SC_Extern || 1099 getStorageClassAsWritten() == SC_PrivateExtern) { 1100 for (const VarDecl *PrevVar = getPreviousDeclaration(); 1101 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) { 1102 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit()) 1103 return DeclarationOnly; 1104 } 1105 } 1106 // C99 6.9.2p2: 1107 // A declaration of an object that has file scope without an initializer, 1108 // and without a storage class specifier or the scs 'static', constitutes 1109 // a tentative definition. 1110 // No such thing in C++. 1111 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl()) 1112 return TentativeDefinition; 1113 1114 // What's left is (in C, block-scope) declarations without initializers or 1115 // external storage. These are definitions. 1116 return Definition; 1117} 1118 1119VarDecl *VarDecl::getActingDefinition() { 1120 DefinitionKind Kind = isThisDeclarationADefinition(); 1121 if (Kind != TentativeDefinition) 1122 return 0; 1123 1124 VarDecl *LastTentative = 0; 1125 VarDecl *First = getFirstDeclaration(); 1126 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1127 I != E; ++I) { 1128 Kind = (*I)->isThisDeclarationADefinition(); 1129 if (Kind == Definition) 1130 return 0; 1131 else if (Kind == TentativeDefinition) 1132 LastTentative = *I; 1133 } 1134 return LastTentative; 1135} 1136 1137bool VarDecl::isTentativeDefinitionNow() const { 1138 DefinitionKind Kind = isThisDeclarationADefinition(); 1139 if (Kind != TentativeDefinition) 1140 return false; 1141 1142 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1143 if ((*I)->isThisDeclarationADefinition() == Definition) 1144 return false; 1145 } 1146 return true; 1147} 1148 1149VarDecl *VarDecl::getDefinition() { 1150 VarDecl *First = getFirstDeclaration(); 1151 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1152 I != E; ++I) { 1153 if ((*I)->isThisDeclarationADefinition() == Definition) 1154 return *I; 1155 } 1156 return 0; 1157} 1158 1159VarDecl::DefinitionKind VarDecl::hasDefinition() const { 1160 DefinitionKind Kind = DeclarationOnly; 1161 1162 const VarDecl *First = getFirstDeclaration(); 1163 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1164 I != E; ++I) 1165 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition()); 1166 1167 return Kind; 1168} 1169 1170const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 1171 redecl_iterator I = redecls_begin(), E = redecls_end(); 1172 while (I != E && !I->getInit()) 1173 ++I; 1174 1175 if (I != E) { 1176 D = *I; 1177 return I->getInit(); 1178 } 1179 return 0; 1180} 1181 1182bool VarDecl::isOutOfLine() const { 1183 if (Decl::isOutOfLine()) 1184 return true; 1185 1186 if (!isStaticDataMember()) 1187 return false; 1188 1189 // If this static data member was instantiated from a static data member of 1190 // a class template, check whether that static data member was defined 1191 // out-of-line. 1192 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 1193 return VD->isOutOfLine(); 1194 1195 return false; 1196} 1197 1198VarDecl *VarDecl::getOutOfLineDefinition() { 1199 if (!isStaticDataMember()) 1200 return 0; 1201 1202 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 1203 RD != RDEnd; ++RD) { 1204 if (RD->getLexicalDeclContext()->isFileContext()) 1205 return *RD; 1206 } 1207 1208 return 0; 1209} 1210 1211void VarDecl::setInit(Expr *I) { 1212 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 1213 Eval->~EvaluatedStmt(); 1214 getASTContext().Deallocate(Eval); 1215 } 1216 1217 Init = I; 1218} 1219 1220VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 1221 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1222 return cast<VarDecl>(MSI->getInstantiatedFrom()); 1223 1224 return 0; 1225} 1226 1227TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 1228 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1229 return MSI->getTemplateSpecializationKind(); 1230 1231 return TSK_Undeclared; 1232} 1233 1234MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 1235 return getASTContext().getInstantiatedFromStaticDataMember(this); 1236} 1237 1238void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1239 SourceLocation PointOfInstantiation) { 1240 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 1241 assert(MSI && "Not an instantiated static data member?"); 1242 MSI->setTemplateSpecializationKind(TSK); 1243 if (TSK != TSK_ExplicitSpecialization && 1244 PointOfInstantiation.isValid() && 1245 MSI->getPointOfInstantiation().isInvalid()) 1246 MSI->setPointOfInstantiation(PointOfInstantiation); 1247} 1248 1249//===----------------------------------------------------------------------===// 1250// ParmVarDecl Implementation 1251//===----------------------------------------------------------------------===// 1252 1253ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 1254 SourceLocation StartLoc, 1255 SourceLocation IdLoc, IdentifierInfo *Id, 1256 QualType T, TypeSourceInfo *TInfo, 1257 StorageClass S, StorageClass SCAsWritten, 1258 Expr *DefArg) { 1259 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo, 1260 S, SCAsWritten, DefArg); 1261} 1262 1263Expr *ParmVarDecl::getDefaultArg() { 1264 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 1265 assert(!hasUninstantiatedDefaultArg() && 1266 "Default argument is not yet instantiated!"); 1267 1268 Expr *Arg = getInit(); 1269 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 1270 return E->getSubExpr(); 1271 1272 return Arg; 1273} 1274 1275unsigned ParmVarDecl::getNumDefaultArgTemporaries() const { 1276 if (const ExprWithCleanups *E = dyn_cast<ExprWithCleanups>(getInit())) 1277 return E->getNumTemporaries(); 1278 1279 return 0; 1280} 1281 1282CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) { 1283 assert(getNumDefaultArgTemporaries() && 1284 "Default arguments does not have any temporaries!"); 1285 1286 ExprWithCleanups *E = cast<ExprWithCleanups>(getInit()); 1287 return E->getTemporary(i); 1288} 1289 1290SourceRange ParmVarDecl::getDefaultArgRange() const { 1291 if (const Expr *E = getInit()) 1292 return E->getSourceRange(); 1293 1294 if (hasUninstantiatedDefaultArg()) 1295 return getUninstantiatedDefaultArg()->getSourceRange(); 1296 1297 return SourceRange(); 1298} 1299 1300bool ParmVarDecl::isParameterPack() const { 1301 return isa<PackExpansionType>(getType()); 1302} 1303 1304//===----------------------------------------------------------------------===// 1305// FunctionDecl Implementation 1306//===----------------------------------------------------------------------===// 1307 1308void FunctionDecl::getNameForDiagnostic(std::string &S, 1309 const PrintingPolicy &Policy, 1310 bool Qualified) const { 1311 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 1312 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 1313 if (TemplateArgs) 1314 S += TemplateSpecializationType::PrintTemplateArgumentList( 1315 TemplateArgs->data(), 1316 TemplateArgs->size(), 1317 Policy); 1318 1319} 1320 1321bool FunctionDecl::isVariadic() const { 1322 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 1323 return FT->isVariadic(); 1324 return false; 1325} 1326 1327bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 1328 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1329 if (I->Body) { 1330 Definition = *I; 1331 return true; 1332 } 1333 } 1334 1335 return false; 1336} 1337 1338Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 1339 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1340 if (I->Body) { 1341 Definition = *I; 1342 return I->Body.get(getASTContext().getExternalSource()); 1343 } 1344 } 1345 1346 return 0; 1347} 1348 1349void FunctionDecl::setBody(Stmt *B) { 1350 Body = B; 1351 if (B) 1352 EndRangeLoc = B->getLocEnd(); 1353} 1354 1355void FunctionDecl::setPure(bool P) { 1356 IsPure = P; 1357 if (P) 1358 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 1359 Parent->markedVirtualFunctionPure(); 1360} 1361 1362bool FunctionDecl::isMain() const { 1363 ASTContext &Context = getASTContext(); 1364 return !Context.getLangOptions().Freestanding && 1365 getDeclContext()->getRedeclContext()->isTranslationUnit() && 1366 getIdentifier() && getIdentifier()->isStr("main"); 1367} 1368 1369bool FunctionDecl::isExternC() const { 1370 ASTContext &Context = getASTContext(); 1371 // In C, any non-static, non-overloadable function has external 1372 // linkage. 1373 if (!Context.getLangOptions().CPlusPlus) 1374 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>(); 1375 1376 const DeclContext *DC = getDeclContext(); 1377 if (DC->isRecord()) 1378 return false; 1379 1380 for (; !DC->isTranslationUnit(); DC = DC->getParent()) { 1381 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 1382 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 1383 return getStorageClass() != SC_Static && 1384 !getAttr<OverloadableAttr>(); 1385 1386 break; 1387 } 1388 } 1389 1390 return isMain(); 1391} 1392 1393bool FunctionDecl::isGlobal() const { 1394 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 1395 return Method->isStatic(); 1396 1397 if (getStorageClass() == SC_Static) 1398 return false; 1399 1400 for (const DeclContext *DC = getDeclContext(); 1401 DC->isNamespace(); 1402 DC = DC->getParent()) { 1403 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 1404 if (!Namespace->getDeclName()) 1405 return false; 1406 break; 1407 } 1408 } 1409 1410 return true; 1411} 1412 1413void 1414FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 1415 redeclarable_base::setPreviousDeclaration(PrevDecl); 1416 1417 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 1418 FunctionTemplateDecl *PrevFunTmpl 1419 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 1420 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 1421 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 1422 } 1423 1424 if (PrevDecl->IsInline) 1425 IsInline = true; 1426} 1427 1428const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 1429 return getFirstDeclaration(); 1430} 1431 1432FunctionDecl *FunctionDecl::getCanonicalDecl() { 1433 return getFirstDeclaration(); 1434} 1435 1436void FunctionDecl::setStorageClass(StorageClass SC) { 1437 assert(isLegalForFunction(SC)); 1438 if (getStorageClass() != SC) 1439 ClearLinkageCache(); 1440 1441 SClass = SC; 1442} 1443 1444/// \brief Returns a value indicating whether this function 1445/// corresponds to a builtin function. 1446/// 1447/// The function corresponds to a built-in function if it is 1448/// declared at translation scope or within an extern "C" block and 1449/// its name matches with the name of a builtin. The returned value 1450/// will be 0 for functions that do not correspond to a builtin, a 1451/// value of type \c Builtin::ID if in the target-independent range 1452/// \c [1,Builtin::First), or a target-specific builtin value. 1453unsigned FunctionDecl::getBuiltinID() const { 1454 ASTContext &Context = getASTContext(); 1455 if (!getIdentifier() || !getIdentifier()->getBuiltinID()) 1456 return 0; 1457 1458 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1459 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1460 return BuiltinID; 1461 1462 // This function has the name of a known C library 1463 // function. Determine whether it actually refers to the C library 1464 // function or whether it just has the same name. 1465 1466 // If this is a static function, it's not a builtin. 1467 if (getStorageClass() == SC_Static) 1468 return 0; 1469 1470 // If this function is at translation-unit scope and we're not in 1471 // C++, it refers to the C library function. 1472 if (!Context.getLangOptions().CPlusPlus && 1473 getDeclContext()->isTranslationUnit()) 1474 return BuiltinID; 1475 1476 // If the function is in an extern "C" linkage specification and is 1477 // not marked "overloadable", it's the real function. 1478 if (isa<LinkageSpecDecl>(getDeclContext()) && 1479 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1480 == LinkageSpecDecl::lang_c && 1481 !getAttr<OverloadableAttr>()) 1482 return BuiltinID; 1483 1484 // Not a builtin 1485 return 0; 1486} 1487 1488 1489/// getNumParams - Return the number of parameters this function must have 1490/// based on its FunctionType. This is the length of the ParamInfo array 1491/// after it has been created. 1492unsigned FunctionDecl::getNumParams() const { 1493 const FunctionType *FT = getType()->getAs<FunctionType>(); 1494 if (isa<FunctionNoProtoType>(FT)) 1495 return 0; 1496 return cast<FunctionProtoType>(FT)->getNumArgs(); 1497 1498} 1499 1500void FunctionDecl::setParams(ASTContext &C, 1501 ParmVarDecl **NewParamInfo, unsigned NumParams) { 1502 assert(ParamInfo == 0 && "Already has param info!"); 1503 assert(NumParams == getNumParams() && "Parameter count mismatch!"); 1504 1505 // Zero params -> null pointer. 1506 if (NumParams) { 1507 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); 1508 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1509 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1510 1511 // Update source range. The check below allows us to set EndRangeLoc before 1512 // setting the parameters. 1513 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation()) 1514 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd(); 1515 } 1516} 1517 1518/// getMinRequiredArguments - Returns the minimum number of arguments 1519/// needed to call this function. This may be fewer than the number of 1520/// function parameters, if some of the parameters have default 1521/// arguments (in C++) or the last parameter is a parameter pack. 1522unsigned FunctionDecl::getMinRequiredArguments() const { 1523 if (!getASTContext().getLangOptions().CPlusPlus) 1524 return getNumParams(); 1525 1526 unsigned NumRequiredArgs = getNumParams(); 1527 1528 // If the last parameter is a parameter pack, we don't need an argument for 1529 // it. 1530 if (NumRequiredArgs > 0 && 1531 getParamDecl(NumRequiredArgs - 1)->isParameterPack()) 1532 --NumRequiredArgs; 1533 1534 // If this parameter has a default argument, we don't need an argument for 1535 // it. 1536 while (NumRequiredArgs > 0 && 1537 getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1538 --NumRequiredArgs; 1539 1540 // We might have parameter packs before the end. These can't be deduced, 1541 // but they can still handle multiple arguments. 1542 unsigned ArgIdx = NumRequiredArgs; 1543 while (ArgIdx > 0) { 1544 if (getParamDecl(ArgIdx - 1)->isParameterPack()) 1545 NumRequiredArgs = ArgIdx; 1546 1547 --ArgIdx; 1548 } 1549 1550 return NumRequiredArgs; 1551} 1552 1553bool FunctionDecl::isInlined() const { 1554 if (IsInline) 1555 return true; 1556 1557 if (isa<CXXMethodDecl>(this)) { 1558 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1559 return true; 1560 } 1561 1562 switch (getTemplateSpecializationKind()) { 1563 case TSK_Undeclared: 1564 case TSK_ExplicitSpecialization: 1565 return false; 1566 1567 case TSK_ImplicitInstantiation: 1568 case TSK_ExplicitInstantiationDeclaration: 1569 case TSK_ExplicitInstantiationDefinition: 1570 // Handle below. 1571 break; 1572 } 1573 1574 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1575 bool HasPattern = false; 1576 if (PatternDecl) 1577 HasPattern = PatternDecl->hasBody(PatternDecl); 1578 1579 if (HasPattern && PatternDecl) 1580 return PatternDecl->isInlined(); 1581 1582 return false; 1583} 1584 1585/// \brief For an inline function definition in C or C++, determine whether the 1586/// definition will be externally visible. 1587/// 1588/// Inline function definitions are always available for inlining optimizations. 1589/// However, depending on the language dialect, declaration specifiers, and 1590/// attributes, the definition of an inline function may or may not be 1591/// "externally" visible to other translation units in the program. 1592/// 1593/// In C99, inline definitions are not externally visible by default. However, 1594/// if even one of the global-scope declarations is marked "extern inline", the 1595/// inline definition becomes externally visible (C99 6.7.4p6). 1596/// 1597/// In GNU89 mode, or if the gnu_inline attribute is attached to the function 1598/// definition, we use the GNU semantics for inline, which are nearly the 1599/// opposite of C99 semantics. In particular, "inline" by itself will create 1600/// an externally visible symbol, but "extern inline" will not create an 1601/// externally visible symbol. 1602bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 1603 assert(isThisDeclarationADefinition() && "Must have the function definition"); 1604 assert(isInlined() && "Function must be inline"); 1605 ASTContext &Context = getASTContext(); 1606 1607 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) { 1608 // If it's not the case that both 'inline' and 'extern' are 1609 // specified on the definition, then this inline definition is 1610 // externally visible. 1611 if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern)) 1612 return true; 1613 1614 // If any declaration is 'inline' but not 'extern', then this definition 1615 // is externally visible. 1616 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1617 Redecl != RedeclEnd; 1618 ++Redecl) { 1619 if (Redecl->isInlineSpecified() && 1620 Redecl->getStorageClassAsWritten() != SC_Extern) 1621 return true; 1622 } 1623 1624 return false; 1625 } 1626 1627 // C99 6.7.4p6: 1628 // [...] If all of the file scope declarations for a function in a 1629 // translation unit include the inline function specifier without extern, 1630 // then the definition in that translation unit is an inline definition. 1631 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1632 Redecl != RedeclEnd; 1633 ++Redecl) { 1634 // Only consider file-scope declarations in this test. 1635 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1636 continue; 1637 1638 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 1639 return true; // Not an inline definition 1640 } 1641 1642 // C99 6.7.4p6: 1643 // An inline definition does not provide an external definition for the 1644 // function, and does not forbid an external definition in another 1645 // translation unit. 1646 return false; 1647} 1648 1649/// getOverloadedOperator - Which C++ overloaded operator this 1650/// function represents, if any. 1651OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 1652 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 1653 return getDeclName().getCXXOverloadedOperator(); 1654 else 1655 return OO_None; 1656} 1657 1658/// getLiteralIdentifier - The literal suffix identifier this function 1659/// represents, if any. 1660const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 1661 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 1662 return getDeclName().getCXXLiteralIdentifier(); 1663 else 1664 return 0; 1665} 1666 1667FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 1668 if (TemplateOrSpecialization.isNull()) 1669 return TK_NonTemplate; 1670 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 1671 return TK_FunctionTemplate; 1672 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 1673 return TK_MemberSpecialization; 1674 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 1675 return TK_FunctionTemplateSpecialization; 1676 if (TemplateOrSpecialization.is 1677 <DependentFunctionTemplateSpecializationInfo*>()) 1678 return TK_DependentFunctionTemplateSpecialization; 1679 1680 assert(false && "Did we miss a TemplateOrSpecialization type?"); 1681 return TK_NonTemplate; 1682} 1683 1684FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 1685 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 1686 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 1687 1688 return 0; 1689} 1690 1691MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 1692 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1693} 1694 1695void 1696FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 1697 FunctionDecl *FD, 1698 TemplateSpecializationKind TSK) { 1699 assert(TemplateOrSpecialization.isNull() && 1700 "Member function is already a specialization"); 1701 MemberSpecializationInfo *Info 1702 = new (C) MemberSpecializationInfo(FD, TSK); 1703 TemplateOrSpecialization = Info; 1704} 1705 1706bool FunctionDecl::isImplicitlyInstantiable() const { 1707 // If the function is invalid, it can't be implicitly instantiated. 1708 if (isInvalidDecl()) 1709 return false; 1710 1711 switch (getTemplateSpecializationKind()) { 1712 case TSK_Undeclared: 1713 case TSK_ExplicitSpecialization: 1714 case TSK_ExplicitInstantiationDefinition: 1715 return false; 1716 1717 case TSK_ImplicitInstantiation: 1718 return true; 1719 1720 case TSK_ExplicitInstantiationDeclaration: 1721 // Handled below. 1722 break; 1723 } 1724 1725 // Find the actual template from which we will instantiate. 1726 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1727 bool HasPattern = false; 1728 if (PatternDecl) 1729 HasPattern = PatternDecl->hasBody(PatternDecl); 1730 1731 // C++0x [temp.explicit]p9: 1732 // Except for inline functions, other explicit instantiation declarations 1733 // have the effect of suppressing the implicit instantiation of the entity 1734 // to which they refer. 1735 if (!HasPattern || !PatternDecl) 1736 return true; 1737 1738 return PatternDecl->isInlined(); 1739} 1740 1741FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 1742 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 1743 while (Primary->getInstantiatedFromMemberTemplate()) { 1744 // If we have hit a point where the user provided a specialization of 1745 // this template, we're done looking. 1746 if (Primary->isMemberSpecialization()) 1747 break; 1748 1749 Primary = Primary->getInstantiatedFromMemberTemplate(); 1750 } 1751 1752 return Primary->getTemplatedDecl(); 1753 } 1754 1755 return getInstantiatedFromMemberFunction(); 1756} 1757 1758FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 1759 if (FunctionTemplateSpecializationInfo *Info 1760 = TemplateOrSpecialization 1761 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1762 return Info->Template.getPointer(); 1763 } 1764 return 0; 1765} 1766 1767const TemplateArgumentList * 1768FunctionDecl::getTemplateSpecializationArgs() const { 1769 if (FunctionTemplateSpecializationInfo *Info 1770 = TemplateOrSpecialization 1771 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1772 return Info->TemplateArguments; 1773 } 1774 return 0; 1775} 1776 1777const TemplateArgumentListInfo * 1778FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 1779 if (FunctionTemplateSpecializationInfo *Info 1780 = TemplateOrSpecialization 1781 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1782 return Info->TemplateArgumentsAsWritten; 1783 } 1784 return 0; 1785} 1786 1787void 1788FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 1789 FunctionTemplateDecl *Template, 1790 const TemplateArgumentList *TemplateArgs, 1791 void *InsertPos, 1792 TemplateSpecializationKind TSK, 1793 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1794 SourceLocation PointOfInstantiation) { 1795 assert(TSK != TSK_Undeclared && 1796 "Must specify the type of function template specialization"); 1797 FunctionTemplateSpecializationInfo *Info 1798 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1799 if (!Info) 1800 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 1801 TemplateArgs, 1802 TemplateArgsAsWritten, 1803 PointOfInstantiation); 1804 TemplateOrSpecialization = Info; 1805 1806 // Insert this function template specialization into the set of known 1807 // function template specializations. 1808 if (InsertPos) 1809 Template->getSpecializations().InsertNode(Info, InsertPos); 1810 else { 1811 // Try to insert the new node. If there is an existing node, leave it, the 1812 // set will contain the canonical decls while 1813 // FunctionTemplateDecl::findSpecialization will return 1814 // the most recent redeclarations. 1815 FunctionTemplateSpecializationInfo *Existing 1816 = Template->getSpecializations().GetOrInsertNode(Info); 1817 (void)Existing; 1818 assert((!Existing || Existing->Function->isCanonicalDecl()) && 1819 "Set is supposed to only contain canonical decls"); 1820 } 1821} 1822 1823void 1824FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 1825 const UnresolvedSetImpl &Templates, 1826 const TemplateArgumentListInfo &TemplateArgs) { 1827 assert(TemplateOrSpecialization.isNull()); 1828 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 1829 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 1830 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 1831 void *Buffer = Context.Allocate(Size); 1832 DependentFunctionTemplateSpecializationInfo *Info = 1833 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 1834 TemplateArgs); 1835 TemplateOrSpecialization = Info; 1836} 1837 1838DependentFunctionTemplateSpecializationInfo:: 1839DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 1840 const TemplateArgumentListInfo &TArgs) 1841 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 1842 1843 d.NumTemplates = Ts.size(); 1844 d.NumArgs = TArgs.size(); 1845 1846 FunctionTemplateDecl **TsArray = 1847 const_cast<FunctionTemplateDecl**>(getTemplates()); 1848 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 1849 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 1850 1851 TemplateArgumentLoc *ArgsArray = 1852 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 1853 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 1854 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 1855} 1856 1857TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 1858 // For a function template specialization, query the specialization 1859 // information object. 1860 FunctionTemplateSpecializationInfo *FTSInfo 1861 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1862 if (FTSInfo) 1863 return FTSInfo->getTemplateSpecializationKind(); 1864 1865 MemberSpecializationInfo *MSInfo 1866 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1867 if (MSInfo) 1868 return MSInfo->getTemplateSpecializationKind(); 1869 1870 return TSK_Undeclared; 1871} 1872 1873void 1874FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1875 SourceLocation PointOfInstantiation) { 1876 if (FunctionTemplateSpecializationInfo *FTSInfo 1877 = TemplateOrSpecialization.dyn_cast< 1878 FunctionTemplateSpecializationInfo*>()) { 1879 FTSInfo->setTemplateSpecializationKind(TSK); 1880 if (TSK != TSK_ExplicitSpecialization && 1881 PointOfInstantiation.isValid() && 1882 FTSInfo->getPointOfInstantiation().isInvalid()) 1883 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 1884 } else if (MemberSpecializationInfo *MSInfo 1885 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 1886 MSInfo->setTemplateSpecializationKind(TSK); 1887 if (TSK != TSK_ExplicitSpecialization && 1888 PointOfInstantiation.isValid() && 1889 MSInfo->getPointOfInstantiation().isInvalid()) 1890 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1891 } else 1892 assert(false && "Function cannot have a template specialization kind"); 1893} 1894 1895SourceLocation FunctionDecl::getPointOfInstantiation() const { 1896 if (FunctionTemplateSpecializationInfo *FTSInfo 1897 = TemplateOrSpecialization.dyn_cast< 1898 FunctionTemplateSpecializationInfo*>()) 1899 return FTSInfo->getPointOfInstantiation(); 1900 else if (MemberSpecializationInfo *MSInfo 1901 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 1902 return MSInfo->getPointOfInstantiation(); 1903 1904 return SourceLocation(); 1905} 1906 1907bool FunctionDecl::isOutOfLine() const { 1908 if (Decl::isOutOfLine()) 1909 return true; 1910 1911 // If this function was instantiated from a member function of a 1912 // class template, check whether that member function was defined out-of-line. 1913 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 1914 const FunctionDecl *Definition; 1915 if (FD->hasBody(Definition)) 1916 return Definition->isOutOfLine(); 1917 } 1918 1919 // If this function was instantiated from a function template, 1920 // check whether that function template was defined out-of-line. 1921 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 1922 const FunctionDecl *Definition; 1923 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 1924 return Definition->isOutOfLine(); 1925 } 1926 1927 return false; 1928} 1929 1930//===----------------------------------------------------------------------===// 1931// FieldDecl Implementation 1932//===----------------------------------------------------------------------===// 1933 1934FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 1935 SourceLocation StartLoc, SourceLocation IdLoc, 1936 IdentifierInfo *Id, QualType T, 1937 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) { 1938 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 1939 BW, Mutable); 1940} 1941 1942bool FieldDecl::isAnonymousStructOrUnion() const { 1943 if (!isImplicit() || getDeclName()) 1944 return false; 1945 1946 if (const RecordType *Record = getType()->getAs<RecordType>()) 1947 return Record->getDecl()->isAnonymousStructOrUnion(); 1948 1949 return false; 1950} 1951 1952unsigned FieldDecl::getFieldIndex() const { 1953 if (CachedFieldIndex) return CachedFieldIndex - 1; 1954 1955 unsigned index = 0; 1956 RecordDecl::field_iterator 1957 i = getParent()->field_begin(), e = getParent()->field_end(); 1958 while (true) { 1959 assert(i != e && "failed to find field in parent!"); 1960 if (*i == this) 1961 break; 1962 1963 ++i; 1964 ++index; 1965 } 1966 1967 CachedFieldIndex = index + 1; 1968 return index; 1969} 1970 1971SourceRange FieldDecl::getSourceRange() const { 1972 return SourceRange(getInnerLocStart(), 1973 isBitField() ? BitWidth->getLocEnd() : getLocation()); 1974} 1975 1976//===----------------------------------------------------------------------===// 1977// TagDecl Implementation 1978//===----------------------------------------------------------------------===// 1979 1980SourceLocation TagDecl::getOuterLocStart() const { 1981 return getTemplateOrInnerLocStart(this); 1982} 1983 1984SourceRange TagDecl::getSourceRange() const { 1985 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 1986 return SourceRange(getOuterLocStart(), E); 1987} 1988 1989TagDecl* TagDecl::getCanonicalDecl() { 1990 return getFirstDeclaration(); 1991} 1992 1993void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) { 1994 TypedefDeclOrQualifier = TDD; 1995 if (TypeForDecl) 1996 const_cast<Type*>(TypeForDecl)->ClearLinkageCache(); 1997 ClearLinkageCache(); 1998} 1999 2000void TagDecl::startDefinition() { 2001 IsBeingDefined = true; 2002 2003 if (isa<CXXRecordDecl>(this)) { 2004 CXXRecordDecl *D = cast<CXXRecordDecl>(this); 2005 struct CXXRecordDecl::DefinitionData *Data = 2006 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 2007 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 2008 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 2009 } 2010} 2011 2012void TagDecl::completeDefinition() { 2013 assert((!isa<CXXRecordDecl>(this) || 2014 cast<CXXRecordDecl>(this)->hasDefinition()) && 2015 "definition completed but not started"); 2016 2017 IsDefinition = true; 2018 IsBeingDefined = false; 2019 2020 if (ASTMutationListener *L = getASTMutationListener()) 2021 L->CompletedTagDefinition(this); 2022} 2023 2024TagDecl* TagDecl::getDefinition() const { 2025 if (isDefinition()) 2026 return const_cast<TagDecl *>(this); 2027 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 2028 return CXXRD->getDefinition(); 2029 2030 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 2031 R != REnd; ++R) 2032 if (R->isDefinition()) 2033 return *R; 2034 2035 return 0; 2036} 2037 2038void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 2039 if (QualifierLoc) { 2040 // Make sure the extended qualifier info is allocated. 2041 if (!hasExtInfo()) 2042 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo; 2043 // Set qualifier info. 2044 getExtInfo()->QualifierLoc = QualifierLoc; 2045 } 2046 else { 2047 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2048 if (hasExtInfo()) { 2049 getASTContext().Deallocate(getExtInfo()); 2050 TypedefDeclOrQualifier = (TypedefDecl*) 0; 2051 } 2052 } 2053} 2054 2055//===----------------------------------------------------------------------===// 2056// EnumDecl Implementation 2057//===----------------------------------------------------------------------===// 2058 2059EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2060 IdentifierInfo *Id, SourceLocation TKL, 2061 EnumDecl *PrevDecl, bool IsScoped, 2062 bool IsScopedUsingClassTag, bool IsFixed) { 2063 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL, 2064 IsScoped, IsScopedUsingClassTag, IsFixed); 2065 C.getTypeDeclType(Enum, PrevDecl); 2066 return Enum; 2067} 2068 2069EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) { 2070 return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation(), 2071 false, false, false); 2072} 2073 2074void EnumDecl::completeDefinition(QualType NewType, 2075 QualType NewPromotionType, 2076 unsigned NumPositiveBits, 2077 unsigned NumNegativeBits) { 2078 assert(!isDefinition() && "Cannot redefine enums!"); 2079 if (!IntegerType) 2080 IntegerType = NewType.getTypePtr(); 2081 PromotionType = NewPromotionType; 2082 setNumPositiveBits(NumPositiveBits); 2083 setNumNegativeBits(NumNegativeBits); 2084 TagDecl::completeDefinition(); 2085} 2086 2087//===----------------------------------------------------------------------===// 2088// RecordDecl Implementation 2089//===----------------------------------------------------------------------===// 2090 2091RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, 2092 IdentifierInfo *Id, RecordDecl *PrevDecl, 2093 SourceLocation TKL) 2094 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) { 2095 HasFlexibleArrayMember = false; 2096 AnonymousStructOrUnion = false; 2097 HasObjectMember = false; 2098 LoadedFieldsFromExternalStorage = false; 2099 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 2100} 2101 2102RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 2103 SourceLocation L, IdentifierInfo *Id, 2104 SourceLocation TKL, RecordDecl* PrevDecl) { 2105 2106 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); 2107 C.getTypeDeclType(R, PrevDecl); 2108 return R; 2109} 2110 2111RecordDecl *RecordDecl::Create(const ASTContext &C, EmptyShell Empty) { 2112 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0, 2113 SourceLocation()); 2114} 2115 2116bool RecordDecl::isInjectedClassName() const { 2117 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 2118 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 2119} 2120 2121RecordDecl::field_iterator RecordDecl::field_begin() const { 2122 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 2123 LoadFieldsFromExternalStorage(); 2124 2125 return field_iterator(decl_iterator(FirstDecl)); 2126} 2127 2128/// completeDefinition - Notes that the definition of this type is now 2129/// complete. 2130void RecordDecl::completeDefinition() { 2131 assert(!isDefinition() && "Cannot redefine record!"); 2132 TagDecl::completeDefinition(); 2133} 2134 2135void RecordDecl::LoadFieldsFromExternalStorage() const { 2136 ExternalASTSource *Source = getASTContext().getExternalSource(); 2137 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 2138 2139 // Notify that we have a RecordDecl doing some initialization. 2140 ExternalASTSource::Deserializing TheFields(Source); 2141 2142 llvm::SmallVector<Decl*, 64> Decls; 2143 if (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) 2144 return; 2145 2146#ifndef NDEBUG 2147 // Check that all decls we got were FieldDecls. 2148 for (unsigned i=0, e=Decls.size(); i != e; ++i) 2149 assert(isa<FieldDecl>(Decls[i])); 2150#endif 2151 2152 LoadedFieldsFromExternalStorage = true; 2153 2154 if (Decls.empty()) 2155 return; 2156 2157 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls); 2158} 2159 2160//===----------------------------------------------------------------------===// 2161// BlockDecl Implementation 2162//===----------------------------------------------------------------------===// 2163 2164void BlockDecl::setParams(ParmVarDecl **NewParamInfo, 2165 unsigned NParms) { 2166 assert(ParamInfo == 0 && "Already has param info!"); 2167 2168 // Zero params -> null pointer. 2169 if (NParms) { 2170 NumParams = NParms; 2171 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 2172 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 2173 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 2174 } 2175} 2176 2177void BlockDecl::setCaptures(ASTContext &Context, 2178 const Capture *begin, 2179 const Capture *end, 2180 bool capturesCXXThis) { 2181 CapturesCXXThis = capturesCXXThis; 2182 2183 if (begin == end) { 2184 NumCaptures = 0; 2185 Captures = 0; 2186 return; 2187 } 2188 2189 NumCaptures = end - begin; 2190 2191 // Avoid new Capture[] because we don't want to provide a default 2192 // constructor. 2193 size_t allocationSize = NumCaptures * sizeof(Capture); 2194 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*)); 2195 memcpy(buffer, begin, allocationSize); 2196 Captures = static_cast<Capture*>(buffer); 2197} 2198 2199SourceRange BlockDecl::getSourceRange() const { 2200 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 2201} 2202 2203//===----------------------------------------------------------------------===// 2204// Other Decl Allocation/Deallocation Method Implementations 2205//===----------------------------------------------------------------------===// 2206 2207TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 2208 return new (C) TranslationUnitDecl(C); 2209} 2210 2211LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 2212 SourceLocation IdentL, IdentifierInfo *II) { 2213 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL); 2214} 2215 2216LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 2217 SourceLocation IdentL, IdentifierInfo *II, 2218 SourceLocation GnuLabelL) { 2219 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 2220 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL); 2221} 2222 2223 2224NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 2225 SourceLocation L, IdentifierInfo *Id) { 2226 return new (C) NamespaceDecl(DC, L, Id); 2227} 2228 2229NamespaceDecl *NamespaceDecl::getNextNamespace() { 2230 return dyn_cast_or_null<NamespaceDecl>( 2231 NextNamespace.get(getASTContext().getExternalSource())); 2232} 2233 2234ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 2235 SourceLocation IdLoc, 2236 IdentifierInfo *Id, 2237 QualType Type) { 2238 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type); 2239} 2240 2241FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 2242 SourceLocation StartLoc, 2243 const DeclarationNameInfo &NameInfo, 2244 QualType T, TypeSourceInfo *TInfo, 2245 StorageClass SC, StorageClass SCAsWritten, 2246 bool isInlineSpecified, 2247 bool hasWrittenPrototype) { 2248 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo, 2249 T, TInfo, SC, SCAsWritten, 2250 isInlineSpecified); 2251 New->HasWrittenPrototype = hasWrittenPrototype; 2252 return New; 2253} 2254 2255BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 2256 return new (C) BlockDecl(DC, L); 2257} 2258 2259EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 2260 SourceLocation L, 2261 IdentifierInfo *Id, QualType T, 2262 Expr *E, const llvm::APSInt &V) { 2263 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 2264} 2265 2266IndirectFieldDecl * 2267IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 2268 IdentifierInfo *Id, QualType T, NamedDecl **CH, 2269 unsigned CHS) { 2270 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 2271} 2272 2273SourceRange EnumConstantDecl::getSourceRange() const { 2274 SourceLocation End = getLocation(); 2275 if (Init) 2276 End = Init->getLocEnd(); 2277 return SourceRange(getLocation(), End); 2278} 2279 2280TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 2281 SourceLocation StartLoc, SourceLocation IdLoc, 2282 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 2283 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo); 2284} 2285 2286FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 2287 StringLiteral *Str, 2288 SourceLocation AsmLoc, 2289 SourceLocation RParenLoc) { 2290 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 2291} 2292