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/ASTContext.h" 16 #include "clang/AST/ASTMutationListener.h" 17 #include "clang/AST/Attr.h" 18 #include "clang/AST/DeclCXX.h" 19 #include "clang/AST/DeclObjC.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/Expr.h" 22 #include "clang/AST/ExprCXX.h" 23 #include "clang/AST/PrettyPrinter.h" 24 #include "clang/AST/Stmt.h" 25 #include "clang/AST/TypeLoc.h" 26 #include "clang/Basic/Builtins.h" 27 #include "clang/Basic/IdentifierTable.h" 28 #include "clang/Basic/Module.h" 29 #include "clang/Basic/Specifiers.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/Support/ErrorHandling.h" 32 #include "llvm/Support/type_traits.h" 33 #include <algorithm> 34 35 using namespace clang; 36 37 //===----------------------------------------------------------------------===// 38 // NamedDecl Implementation 39 //===----------------------------------------------------------------------===// 40 41 // Visibility rules aren't rigorously externally specified, but here 42 // are the basic principles behind what we implement: 43 // 44 // 1. An explicit visibility attribute is generally a direct expression 45 // of the user's intent and should be honored. Only the innermost 46 // visibility attribute applies. If no visibility attribute applies, 47 // global visibility settings are considered. 48 // 49 // 2. There is one caveat to the above: on or in a template pattern, 50 // an explicit visibility attribute is just a default rule, and 51 // visibility can be decreased by the visibility of template 52 // arguments. But this, too, has an exception: an attribute on an 53 // explicit specialization or instantiation causes all the visibility 54 // restrictions of the template arguments to be ignored. 55 // 56 // 3. A variable that does not otherwise have explicit visibility can 57 // be restricted by the visibility of its type. 58 // 59 // 4. A visibility restriction is explicit if it comes from an 60 // attribute (or something like it), not a global visibility setting. 61 // When emitting a reference to an external symbol, visibility 62 // restrictions are ignored unless they are explicit. 63 // 64 // 5. When computing the visibility of a non-type, including a 65 // non-type member of a class, only non-type visibility restrictions 66 // are considered: the 'visibility' attribute, global value-visibility 67 // settings, and a few special cases like __private_extern. 68 // 69 // 6. When computing the visibility of a type, including a type member 70 // of a class, only type visibility restrictions are considered: 71 // the 'type_visibility' attribute and global type-visibility settings. 72 // However, a 'visibility' attribute counts as a 'type_visibility' 73 // attribute on any declaration that only has the former. 74 // 75 // The visibility of a "secondary" entity, like a template argument, 76 // is computed using the kind of that entity, not the kind of the 77 // primary entity for which we are computing visibility. For example, 78 // the visibility of a specialization of either of these templates: 79 // template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X); 80 // template <class T, bool (&compare)(T, X)> class matcher; 81 // is restricted according to the type visibility of the argument 'T', 82 // the type visibility of 'bool(&)(T,X)', and the value visibility of 83 // the argument function 'compare'. That 'has_match' is a value 84 // and 'matcher' is a type only matters when looking for attributes 85 // and settings from the immediate context. 86 87 const unsigned IgnoreExplicitVisibilityBit = 2; 88 89 /// Kinds of LV computation. The linkage side of the computation is 90 /// always the same, but different things can change how visibility is 91 /// computed. 92 enum LVComputationKind { 93 /// Do an LV computation for, ultimately, a type. 94 /// Visibility may be restricted by type visibility settings and 95 /// the visibility of template arguments. 96 LVForType = NamedDecl::VisibilityForType, 97 98 /// Do an LV computation for, ultimately, a non-type declaration. 99 /// Visibility may be restricted by value visibility settings and 100 /// the visibility of template arguments. 101 LVForValue = NamedDecl::VisibilityForValue, 102 103 /// Do an LV computation for, ultimately, a type that already has 104 /// some sort of explicit visibility. Visibility may only be 105 /// restricted by the visibility of template arguments. 106 LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit), 107 108 /// Do an LV computation for, ultimately, a non-type declaration 109 /// that already has some sort of explicit visibility. Visibility 110 /// may only be restricted by the visibility of template arguments. 111 LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit) 112 }; 113 114 /// Does this computation kind permit us to consider additional 115 /// visibility settings from attributes and the like? 116 static bool hasExplicitVisibilityAlready(LVComputationKind computation) { 117 return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0); 118 } 119 120 /// Given an LVComputationKind, return one of the same type/value sort 121 /// that records that it already has explicit visibility. 122 static LVComputationKind 123 withExplicitVisibilityAlready(LVComputationKind oldKind) { 124 LVComputationKind newKind = 125 static_cast<LVComputationKind>(unsigned(oldKind) | 126 IgnoreExplicitVisibilityBit); 127 assert(oldKind != LVForType || newKind == LVForExplicitType); 128 assert(oldKind != LVForValue || newKind == LVForExplicitValue); 129 assert(oldKind != LVForExplicitType || newKind == LVForExplicitType); 130 assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue); 131 return newKind; 132 } 133 134 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D, 135 LVComputationKind kind) { 136 assert(!hasExplicitVisibilityAlready(kind) && 137 "asking for explicit visibility when we shouldn't be"); 138 return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind); 139 } 140 141 /// Is the given declaration a "type" or a "value" for the purposes of 142 /// visibility computation? 143 static bool usesTypeVisibility(const NamedDecl *D) { 144 return isa<TypeDecl>(D) || 145 isa<ClassTemplateDecl>(D) || 146 isa<ObjCInterfaceDecl>(D); 147 } 148 149 /// Does the given declaration have member specialization information, 150 /// and if so, is it an explicit specialization? 151 template <class T> static typename 152 llvm::enable_if_c<!llvm::is_base_of<RedeclarableTemplateDecl, T>::value, 153 bool>::type 154 isExplicitMemberSpecialization(const T *D) { 155 if (const MemberSpecializationInfo *member = 156 D->getMemberSpecializationInfo()) { 157 return member->isExplicitSpecialization(); 158 } 159 return false; 160 } 161 162 /// For templates, this question is easier: a member template can't be 163 /// explicitly instantiated, so there's a single bit indicating whether 164 /// or not this is an explicit member specialization. 165 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) { 166 return D->isMemberSpecialization(); 167 } 168 169 /// Given a visibility attribute, return the explicit visibility 170 /// associated with it. 171 template <class T> 172 static Visibility getVisibilityFromAttr(const T *attr) { 173 switch (attr->getVisibility()) { 174 case T::Default: 175 return DefaultVisibility; 176 case T::Hidden: 177 return HiddenVisibility; 178 case T::Protected: 179 return ProtectedVisibility; 180 } 181 llvm_unreachable("bad visibility kind"); 182 } 183 184 /// Return the explicit visibility of the given declaration. 185 static Optional<Visibility> getVisibilityOf(const NamedDecl *D, 186 NamedDecl::ExplicitVisibilityKind kind) { 187 // If we're ultimately computing the visibility of a type, look for 188 // a 'type_visibility' attribute before looking for 'visibility'. 189 if (kind == NamedDecl::VisibilityForType) { 190 if (const TypeVisibilityAttr *A = D->getAttr<TypeVisibilityAttr>()) { 191 return getVisibilityFromAttr(A); 192 } 193 } 194 195 // If this declaration has an explicit visibility attribute, use it. 196 if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) { 197 return getVisibilityFromAttr(A); 198 } 199 200 // If we're on Mac OS X, an 'availability' for Mac OS X attribute 201 // implies visibility(default). 202 if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) { 203 for (specific_attr_iterator<AvailabilityAttr> 204 A = D->specific_attr_begin<AvailabilityAttr>(), 205 AEnd = D->specific_attr_end<AvailabilityAttr>(); 206 A != AEnd; ++A) 207 if ((*A)->getPlatform()->getName().equals("macosx")) 208 return DefaultVisibility; 209 } 210 211 return None; 212 } 213 214 /// \brief Get the most restrictive linkage for the types in the given 215 /// template parameter list. For visibility purposes, template 216 /// parameters are part of the signature of a template. 217 static LinkageInfo 218 getLVForTemplateParameterList(const TemplateParameterList *params) { 219 LinkageInfo LV; 220 for (TemplateParameterList::const_iterator P = params->begin(), 221 PEnd = params->end(); 222 P != PEnd; ++P) { 223 224 // Template type parameters are the most common and never 225 // contribute to visibility, pack or not. 226 if (isa<TemplateTypeParmDecl>(*P)) 227 continue; 228 229 // Non-type template parameters can be restricted by the value type, e.g. 230 // template <enum X> class A { ... }; 231 // We have to be careful here, though, because we can be dealing with 232 // dependent types. 233 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) { 234 // Handle the non-pack case first. 235 if (!NTTP->isExpandedParameterPack()) { 236 if (!NTTP->getType()->isDependentType()) { 237 LV.merge(NTTP->getType()->getLinkageAndVisibility()); 238 } 239 continue; 240 } 241 242 // Look at all the types in an expanded pack. 243 for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) { 244 QualType type = NTTP->getExpansionType(i); 245 if (!type->isDependentType()) 246 LV.merge(type->getLinkageAndVisibility()); 247 } 248 continue; 249 } 250 251 // Template template parameters can be restricted by their 252 // template parameters, recursively. 253 TemplateTemplateParmDecl *TTP = cast<TemplateTemplateParmDecl>(*P); 254 255 // Handle the non-pack case first. 256 if (!TTP->isExpandedParameterPack()) { 257 LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters())); 258 continue; 259 } 260 261 // Look at all expansions in an expanded pack. 262 for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters(); 263 i != n; ++i) { 264 LV.merge(getLVForTemplateParameterList( 265 TTP->getExpansionTemplateParameters(i))); 266 } 267 } 268 269 return LV; 270 } 271 272 /// getLVForDecl - Get the linkage and visibility for the given declaration. 273 static LinkageInfo getLVForDecl(const NamedDecl *D, 274 LVComputationKind computation); 275 276 /// \brief Get the most restrictive linkage for the types and 277 /// declarations in the given template argument list. 278 /// 279 /// Note that we don't take an LVComputationKind because we always 280 /// want to honor the visibility of template arguments in the same way. 281 static LinkageInfo 282 getLVForTemplateArgumentList(ArrayRef<TemplateArgument> args) { 283 LinkageInfo LV; 284 285 for (unsigned i = 0, e = args.size(); i != e; ++i) { 286 const TemplateArgument &arg = args[i]; 287 switch (arg.getKind()) { 288 case TemplateArgument::Null: 289 case TemplateArgument::Integral: 290 case TemplateArgument::Expression: 291 continue; 292 293 case TemplateArgument::Type: 294 LV.merge(arg.getAsType()->getLinkageAndVisibility()); 295 continue; 296 297 case TemplateArgument::Declaration: 298 if (NamedDecl *ND = dyn_cast<NamedDecl>(arg.getAsDecl())) { 299 assert(!usesTypeVisibility(ND)); 300 LV.merge(getLVForDecl(ND, LVForValue)); 301 } 302 continue; 303 304 case TemplateArgument::NullPtr: 305 LV.merge(arg.getNullPtrType()->getLinkageAndVisibility()); 306 continue; 307 308 case TemplateArgument::Template: 309 case TemplateArgument::TemplateExpansion: 310 if (TemplateDecl *Template 311 = arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl()) 312 LV.merge(getLVForDecl(Template, LVForValue)); 313 continue; 314 315 case TemplateArgument::Pack: 316 LV.merge(getLVForTemplateArgumentList(arg.getPackAsArray())); 317 continue; 318 } 319 llvm_unreachable("bad template argument kind"); 320 } 321 322 return LV; 323 } 324 325 static LinkageInfo 326 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs) { 327 return getLVForTemplateArgumentList(TArgs.asArray()); 328 } 329 330 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn, 331 const FunctionTemplateSpecializationInfo *specInfo) { 332 // Include visibility from the template parameters and arguments 333 // only if this is not an explicit instantiation or specialization 334 // with direct explicit visibility. (Implicit instantiations won't 335 // have a direct attribute.) 336 if (!specInfo->isExplicitInstantiationOrSpecialization()) 337 return true; 338 339 return !fn->hasAttr<VisibilityAttr>(); 340 } 341 342 /// Merge in template-related linkage and visibility for the given 343 /// function template specialization. 344 /// 345 /// We don't need a computation kind here because we can assume 346 /// LVForValue. 347 /// 348 /// \param[out] LV the computation to use for the parent 349 static void 350 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn, 351 const FunctionTemplateSpecializationInfo *specInfo) { 352 bool considerVisibility = 353 shouldConsiderTemplateVisibility(fn, specInfo); 354 355 // Merge information from the template parameters. 356 FunctionTemplateDecl *temp = specInfo->getTemplate(); 357 LinkageInfo tempLV = 358 getLVForTemplateParameterList(temp->getTemplateParameters()); 359 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 360 361 // Merge information from the template arguments. 362 const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments; 363 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs); 364 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 365 } 366 367 /// Does the given declaration have a direct visibility attribute 368 /// that would match the given rules? 369 static bool hasDirectVisibilityAttribute(const NamedDecl *D, 370 LVComputationKind computation) { 371 switch (computation) { 372 case LVForType: 373 case LVForExplicitType: 374 if (D->hasAttr<TypeVisibilityAttr>()) 375 return true; 376 // fallthrough 377 case LVForValue: 378 case LVForExplicitValue: 379 if (D->hasAttr<VisibilityAttr>()) 380 return true; 381 return false; 382 } 383 llvm_unreachable("bad visibility computation kind"); 384 } 385 386 /// Should we consider visibility associated with the template 387 /// arguments and parameters of the given class template specialization? 388 static bool shouldConsiderTemplateVisibility( 389 const ClassTemplateSpecializationDecl *spec, 390 LVComputationKind computation) { 391 // Include visibility from the template parameters and arguments 392 // only if this is not an explicit instantiation or specialization 393 // with direct explicit visibility (and note that implicit 394 // instantiations won't have a direct attribute). 395 // 396 // Furthermore, we want to ignore template parameters and arguments 397 // for an explicit specialization when computing the visibility of a 398 // member thereof with explicit visibility. 399 // 400 // This is a bit complex; let's unpack it. 401 // 402 // An explicit class specialization is an independent, top-level 403 // declaration. As such, if it or any of its members has an 404 // explicit visibility attribute, that must directly express the 405 // user's intent, and we should honor it. The same logic applies to 406 // an explicit instantiation of a member of such a thing. 407 408 // Fast path: if this is not an explicit instantiation or 409 // specialization, we always want to consider template-related 410 // visibility restrictions. 411 if (!spec->isExplicitInstantiationOrSpecialization()) 412 return true; 413 414 // This is the 'member thereof' check. 415 if (spec->isExplicitSpecialization() && 416 hasExplicitVisibilityAlready(computation)) 417 return false; 418 419 return !hasDirectVisibilityAttribute(spec, computation); 420 } 421 422 /// Merge in template-related linkage and visibility for the given 423 /// class template specialization. 424 static void mergeTemplateLV(LinkageInfo &LV, 425 const ClassTemplateSpecializationDecl *spec, 426 LVComputationKind computation) { 427 bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation); 428 429 // Merge information from the template parameters, but ignore 430 // visibility if we're only considering template arguments. 431 432 ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 433 LinkageInfo tempLV = 434 getLVForTemplateParameterList(temp->getTemplateParameters()); 435 LV.mergeMaybeWithVisibility(tempLV, 436 considerVisibility && !hasExplicitVisibilityAlready(computation)); 437 438 // Merge information from the template arguments. We ignore 439 // template-argument visibility if we've got an explicit 440 // instantiation with a visibility attribute. 441 const TemplateArgumentList &templateArgs = spec->getTemplateArgs(); 442 LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs); 443 LV.mergeMaybeWithVisibility(argsLV, considerVisibility); 444 } 445 446 static bool useInlineVisibilityHidden(const NamedDecl *D) { 447 // FIXME: we should warn if -fvisibility-inlines-hidden is used with c. 448 const LangOptions &Opts = D->getASTContext().getLangOpts(); 449 if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden) 450 return false; 451 452 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 453 if (!FD) 454 return false; 455 456 TemplateSpecializationKind TSK = TSK_Undeclared; 457 if (FunctionTemplateSpecializationInfo *spec 458 = FD->getTemplateSpecializationInfo()) { 459 TSK = spec->getTemplateSpecializationKind(); 460 } else if (MemberSpecializationInfo *MSI = 461 FD->getMemberSpecializationInfo()) { 462 TSK = MSI->getTemplateSpecializationKind(); 463 } 464 465 const FunctionDecl *Def = 0; 466 // InlineVisibilityHidden only applies to definitions, and 467 // isInlined() only gives meaningful answers on definitions 468 // anyway. 469 return TSK != TSK_ExplicitInstantiationDeclaration && 470 TSK != TSK_ExplicitInstantiationDefinition && 471 FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>(); 472 } 473 474 template <typename T> static bool isFirstInExternCContext(T *D) { 475 const T *First = D->getFirstDeclaration(); 476 return First->isInExternCContext(); 477 } 478 479 static bool isSingleLineExternC(const Decl &D) { 480 if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext())) 481 if (SD->getLanguage() == LinkageSpecDecl::lang_c && !SD->hasBraces()) 482 return true; 483 return false; 484 } 485 486 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, 487 LVComputationKind computation) { 488 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 489 "Not a name having namespace scope"); 490 ASTContext &Context = D->getASTContext(); 491 492 // C++ [basic.link]p3: 493 // A name having namespace scope (3.3.6) has internal linkage if it 494 // is the name of 495 // - an object, reference, function or function template that is 496 // explicitly declared static; or, 497 // (This bullet corresponds to C99 6.2.2p3.) 498 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 499 // Explicitly declared static. 500 if (Var->getStorageClass() == SC_Static) 501 return LinkageInfo::internal(); 502 503 // - a non-volatile object or reference that is explicitly declared const 504 // or constexpr and neither explicitly declared extern nor previously 505 // declared to have external linkage; or (there is no equivalent in C99) 506 if (Context.getLangOpts().CPlusPlus && 507 Var->getType().isConstQualified() && 508 !Var->getType().isVolatileQualified()) { 509 const VarDecl *PrevVar = Var->getPreviousDecl(); 510 if (PrevVar) 511 return PrevVar->getLinkageAndVisibility(); 512 513 if (Var->getStorageClass() != SC_Extern && 514 Var->getStorageClass() != SC_PrivateExtern && 515 !isSingleLineExternC(*Var)) 516 return LinkageInfo::internal(); 517 } 518 519 for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar; 520 PrevVar = PrevVar->getPreviousDecl()) { 521 if (PrevVar->getStorageClass() == SC_PrivateExtern && 522 Var->getStorageClass() == SC_None) 523 return PrevVar->getLinkageAndVisibility(); 524 // Explicitly declared static. 525 if (PrevVar->getStorageClass() == SC_Static) 526 return LinkageInfo::internal(); 527 } 528 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 529 // C++ [temp]p4: 530 // A non-member function template can have internal linkage; any 531 // other template name shall have external linkage. 532 const FunctionDecl *Function = 0; 533 if (const FunctionTemplateDecl *FunTmpl 534 = dyn_cast<FunctionTemplateDecl>(D)) 535 Function = FunTmpl->getTemplatedDecl(); 536 else 537 Function = cast<FunctionDecl>(D); 538 539 // Explicitly declared static. 540 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 541 return LinkageInfo(InternalLinkage, DefaultVisibility, false); 542 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 543 // - a data member of an anonymous union. 544 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 545 return LinkageInfo::internal(); 546 } 547 548 if (D->isInAnonymousNamespace()) { 549 const VarDecl *Var = dyn_cast<VarDecl>(D); 550 const FunctionDecl *Func = dyn_cast<FunctionDecl>(D); 551 if ((!Var || !isFirstInExternCContext(Var)) && 552 (!Func || !isFirstInExternCContext(Func))) 553 return LinkageInfo::uniqueExternal(); 554 } 555 556 // Set up the defaults. 557 558 // C99 6.2.2p5: 559 // If the declaration of an identifier for an object has file 560 // scope and no storage-class specifier, its linkage is 561 // external. 562 LinkageInfo LV; 563 564 if (!hasExplicitVisibilityAlready(computation)) { 565 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) { 566 LV.mergeVisibility(*Vis, true); 567 } else { 568 // If we're declared in a namespace with a visibility attribute, 569 // use that namespace's visibility, and it still counts as explicit. 570 for (const DeclContext *DC = D->getDeclContext(); 571 !isa<TranslationUnitDecl>(DC); 572 DC = DC->getParent()) { 573 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC); 574 if (!ND) continue; 575 if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) { 576 LV.mergeVisibility(*Vis, true); 577 break; 578 } 579 } 580 } 581 582 // Add in global settings if the above didn't give us direct visibility. 583 if (!LV.isVisibilityExplicit()) { 584 // Use global type/value visibility as appropriate. 585 Visibility globalVisibility; 586 if (computation == LVForValue) { 587 globalVisibility = Context.getLangOpts().getValueVisibilityMode(); 588 } else { 589 assert(computation == LVForType); 590 globalVisibility = Context.getLangOpts().getTypeVisibilityMode(); 591 } 592 LV.mergeVisibility(globalVisibility, /*explicit*/ false); 593 594 // If we're paying attention to global visibility, apply 595 // -finline-visibility-hidden if this is an inline method. 596 if (useInlineVisibilityHidden(D)) 597 LV.mergeVisibility(HiddenVisibility, true); 598 } 599 } 600 601 // C++ [basic.link]p4: 602 603 // A name having namespace scope has external linkage if it is the 604 // name of 605 // 606 // - an object or reference, unless it has internal linkage; or 607 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 608 // GCC applies the following optimization to variables and static 609 // data members, but not to functions: 610 // 611 // Modify the variable's LV by the LV of its type unless this is 612 // C or extern "C". This follows from [basic.link]p9: 613 // A type without linkage shall not be used as the type of a 614 // variable or function with external linkage unless 615 // - the entity has C language linkage, or 616 // - the entity is declared within an unnamed namespace, or 617 // - the entity is not used or is defined in the same 618 // translation unit. 619 // and [basic.link]p10: 620 // ...the types specified by all declarations referring to a 621 // given variable or function shall be identical... 622 // C does not have an equivalent rule. 623 // 624 // Ignore this if we've got an explicit attribute; the user 625 // probably knows what they're doing. 626 // 627 // Note that we don't want to make the variable non-external 628 // because of this, but unique-external linkage suits us. 629 if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) { 630 LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility(); 631 if (TypeLV.getLinkage() != ExternalLinkage) 632 return LinkageInfo::uniqueExternal(); 633 if (!LV.isVisibilityExplicit()) 634 LV.mergeVisibility(TypeLV); 635 } 636 637 if (Var->getStorageClass() == SC_PrivateExtern) 638 LV.mergeVisibility(HiddenVisibility, true); 639 640 // Note that Sema::MergeVarDecl already takes care of implementing 641 // C99 6.2.2p4 and propagating the visibility attribute, so we don't have 642 // to do it here. 643 644 // - a function, unless it has internal linkage; or 645 } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 646 // In theory, we can modify the function's LV by the LV of its 647 // type unless it has C linkage (see comment above about variables 648 // for justification). In practice, GCC doesn't do this, so it's 649 // just too painful to make work. 650 651 if (Function->getStorageClass() == SC_PrivateExtern) 652 LV.mergeVisibility(HiddenVisibility, true); 653 654 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 655 // merging storage classes and visibility attributes, so we don't have to 656 // look at previous decls in here. 657 658 // In C++, then if the type of the function uses a type with 659 // unique-external linkage, it's not legally usable from outside 660 // this translation unit. However, we should use the C linkage 661 // rules instead for extern "C" declarations. 662 if (Context.getLangOpts().CPlusPlus && 663 !Function->isInExternCContext() && 664 Function->getType()->getLinkage() == UniqueExternalLinkage) 665 return LinkageInfo::uniqueExternal(); 666 667 // Consider LV from the template and the template arguments. 668 // We're at file scope, so we do not need to worry about nested 669 // specializations. 670 if (FunctionTemplateSpecializationInfo *specInfo 671 = Function->getTemplateSpecializationInfo()) { 672 mergeTemplateLV(LV, Function, specInfo); 673 } 674 675 // - a named class (Clause 9), or an unnamed class defined in a 676 // typedef declaration in which the class has the typedef name 677 // for linkage purposes (7.1.3); or 678 // - a named enumeration (7.2), or an unnamed enumeration 679 // defined in a typedef declaration in which the enumeration 680 // has the typedef name for linkage purposes (7.1.3); or 681 } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) { 682 // Unnamed tags have no linkage. 683 if (!Tag->hasNameForLinkage()) 684 return LinkageInfo::none(); 685 686 // If this is a class template specialization, consider the 687 // linkage of the template and template arguments. We're at file 688 // scope, so we do not need to worry about nested specializations. 689 if (const ClassTemplateSpecializationDecl *spec 690 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 691 mergeTemplateLV(LV, spec, computation); 692 } 693 694 // - an enumerator belonging to an enumeration with external linkage; 695 } else if (isa<EnumConstantDecl>(D)) { 696 LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), 697 computation); 698 if (!isExternalLinkage(EnumLV.getLinkage())) 699 return LinkageInfo::none(); 700 LV.merge(EnumLV); 701 702 // - a template, unless it is a function template that has 703 // internal linkage (Clause 14); 704 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) { 705 bool considerVisibility = !hasExplicitVisibilityAlready(computation); 706 LinkageInfo tempLV = 707 getLVForTemplateParameterList(temp->getTemplateParameters()); 708 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 709 710 // - a namespace (7.3), unless it is declared within an unnamed 711 // namespace. 712 } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) { 713 return LV; 714 715 // By extension, we assign external linkage to Objective-C 716 // interfaces. 717 } else if (isa<ObjCInterfaceDecl>(D)) { 718 // fallout 719 720 // Everything not covered here has no linkage. 721 } else { 722 return LinkageInfo::none(); 723 } 724 725 // If we ended up with non-external linkage, visibility should 726 // always be default. 727 if (LV.getLinkage() != ExternalLinkage) 728 return LinkageInfo(LV.getLinkage(), DefaultVisibility, false); 729 730 return LV; 731 } 732 733 static LinkageInfo getLVForClassMember(const NamedDecl *D, 734 LVComputationKind computation) { 735 // Only certain class members have linkage. Note that fields don't 736 // really have linkage, but it's convenient to say they do for the 737 // purposes of calculating linkage of pointer-to-data-member 738 // template arguments. 739 if (!(isa<CXXMethodDecl>(D) || 740 isa<VarDecl>(D) || 741 isa<FieldDecl>(D) || 742 isa<TagDecl>(D))) 743 return LinkageInfo::none(); 744 745 LinkageInfo LV; 746 747 // If we have an explicit visibility attribute, merge that in. 748 if (!hasExplicitVisibilityAlready(computation)) { 749 if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) 750 LV.mergeVisibility(*Vis, true); 751 // If we're paying attention to global visibility, apply 752 // -finline-visibility-hidden if this is an inline method. 753 // 754 // Note that we do this before merging information about 755 // the class visibility. 756 if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D)) 757 LV.mergeVisibility(HiddenVisibility, true); 758 } 759 760 // If this class member has an explicit visibility attribute, the only 761 // thing that can change its visibility is the template arguments, so 762 // only look for them when processing the class. 763 LVComputationKind classComputation = computation; 764 if (LV.isVisibilityExplicit()) 765 classComputation = withExplicitVisibilityAlready(computation); 766 767 LinkageInfo classLV = 768 getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation); 769 if (!isExternalLinkage(classLV.getLinkage())) 770 return LinkageInfo::none(); 771 772 // If the class already has unique-external linkage, we can't improve. 773 if (classLV.getLinkage() == UniqueExternalLinkage) 774 return LinkageInfo::uniqueExternal(); 775 776 // Otherwise, don't merge in classLV yet, because in certain cases 777 // we need to completely ignore the visibility from it. 778 779 // Specifically, if this decl exists and has an explicit attribute. 780 const NamedDecl *explicitSpecSuppressor = 0; 781 782 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 783 // If the type of the function uses a type with unique-external 784 // linkage, it's not legally usable from outside this translation unit. 785 if (MD->getType()->getLinkage() == UniqueExternalLinkage) 786 return LinkageInfo::uniqueExternal(); 787 788 // If this is a method template specialization, use the linkage for 789 // the template parameters and arguments. 790 if (FunctionTemplateSpecializationInfo *spec 791 = MD->getTemplateSpecializationInfo()) { 792 mergeTemplateLV(LV, MD, spec); 793 if (spec->isExplicitSpecialization()) { 794 explicitSpecSuppressor = MD; 795 } else if (isExplicitMemberSpecialization(spec->getTemplate())) { 796 explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl(); 797 } 798 } else if (isExplicitMemberSpecialization(MD)) { 799 explicitSpecSuppressor = MD; 800 } 801 802 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 803 if (const ClassTemplateSpecializationDecl *spec 804 = dyn_cast<ClassTemplateSpecializationDecl>(RD)) { 805 mergeTemplateLV(LV, spec, computation); 806 if (spec->isExplicitSpecialization()) { 807 explicitSpecSuppressor = spec; 808 } else { 809 const ClassTemplateDecl *temp = spec->getSpecializedTemplate(); 810 if (isExplicitMemberSpecialization(temp)) { 811 explicitSpecSuppressor = temp->getTemplatedDecl(); 812 } 813 } 814 } else if (isExplicitMemberSpecialization(RD)) { 815 explicitSpecSuppressor = RD; 816 } 817 818 // Static data members. 819 } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) { 820 // Modify the variable's linkage by its type, but ignore the 821 // type's visibility unless it's a definition. 822 LinkageInfo typeLV = VD->getType()->getLinkageAndVisibility(); 823 LV.mergeMaybeWithVisibility(typeLV, 824 !LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit()); 825 826 if (isExplicitMemberSpecialization(VD)) { 827 explicitSpecSuppressor = VD; 828 } 829 830 // Template members. 831 } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) { 832 bool considerVisibility = 833 (!LV.isVisibilityExplicit() && 834 !classLV.isVisibilityExplicit() && 835 !hasExplicitVisibilityAlready(computation)); 836 LinkageInfo tempLV = 837 getLVForTemplateParameterList(temp->getTemplateParameters()); 838 LV.mergeMaybeWithVisibility(tempLV, considerVisibility); 839 840 if (const RedeclarableTemplateDecl *redeclTemp = 841 dyn_cast<RedeclarableTemplateDecl>(temp)) { 842 if (isExplicitMemberSpecialization(redeclTemp)) { 843 explicitSpecSuppressor = temp->getTemplatedDecl(); 844 } 845 } 846 } 847 848 // We should never be looking for an attribute directly on a template. 849 assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)); 850 851 // If this member is an explicit member specialization, and it has 852 // an explicit attribute, ignore visibility from the parent. 853 bool considerClassVisibility = true; 854 if (explicitSpecSuppressor && 855 // optimization: hasDVA() is true only with explicit visibility. 856 LV.isVisibilityExplicit() && 857 classLV.getVisibility() != DefaultVisibility && 858 hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) { 859 considerClassVisibility = false; 860 } 861 862 // Finally, merge in information from the class. 863 LV.mergeMaybeWithVisibility(classLV, considerClassVisibility); 864 return LV; 865 } 866 867 void NamedDecl::anchor() { } 868 869 bool NamedDecl::isLinkageValid() const { 870 if (!HasCachedLinkage) 871 return true; 872 873 return getLVForDecl(this, LVForExplicitValue).getLinkage() == 874 Linkage(CachedLinkage); 875 } 876 877 Linkage NamedDecl::getLinkage() const { 878 if (HasCachedLinkage) 879 return Linkage(CachedLinkage); 880 881 // We don't care about visibility here, so ask for the cheapest 882 // possible visibility analysis. 883 CachedLinkage = getLVForDecl(this, LVForExplicitValue).getLinkage(); 884 HasCachedLinkage = 1; 885 886 #ifndef NDEBUG 887 verifyLinkage(); 888 #endif 889 890 return Linkage(CachedLinkage); 891 } 892 893 LinkageInfo NamedDecl::getLinkageAndVisibility() const { 894 LVComputationKind computation = 895 (usesTypeVisibility(this) ? LVForType : LVForValue); 896 LinkageInfo LI = getLVForDecl(this, computation); 897 if (HasCachedLinkage) { 898 assert(Linkage(CachedLinkage) == LI.getLinkage()); 899 return LI; 900 } 901 HasCachedLinkage = 1; 902 CachedLinkage = LI.getLinkage(); 903 904 #ifndef NDEBUG 905 verifyLinkage(); 906 #endif 907 908 return LI; 909 } 910 911 void NamedDecl::verifyLinkage() const { 912 // In C (because of gnu inline) and in c++ with microsoft extensions an 913 // static can follow an extern, so we can have two decls with different 914 // linkages. 915 const LangOptions &Opts = getASTContext().getLangOpts(); 916 if (!Opts.CPlusPlus || Opts.MicrosoftExt) 917 return; 918 919 // We have just computed the linkage for this decl. By induction we know 920 // that all other computed linkages match, check that the one we just computed 921 // also does. 922 NamedDecl *D = NULL; 923 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 924 NamedDecl *T = cast<NamedDecl>(*I); 925 if (T == this) 926 continue; 927 if (T->HasCachedLinkage != 0) { 928 D = T; 929 break; 930 } 931 } 932 assert(!D || D->CachedLinkage == CachedLinkage); 933 } 934 935 Optional<Visibility> 936 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const { 937 // Check the declaration itself first. 938 if (Optional<Visibility> V = getVisibilityOf(this, kind)) 939 return V; 940 941 // If this is a member class of a specialization of a class template 942 // and the corresponding decl has explicit visibility, use that. 943 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) { 944 CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass(); 945 if (InstantiatedFrom) 946 return getVisibilityOf(InstantiatedFrom, kind); 947 } 948 949 // If there wasn't explicit visibility there, and this is a 950 // specialization of a class template, check for visibility 951 // on the pattern. 952 if (const ClassTemplateSpecializationDecl *spec 953 = dyn_cast<ClassTemplateSpecializationDecl>(this)) 954 return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(), 955 kind); 956 957 // Use the most recent declaration. 958 const NamedDecl *MostRecent = cast<NamedDecl>(this->getMostRecentDecl()); 959 if (MostRecent != this) 960 return MostRecent->getExplicitVisibility(kind); 961 962 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) { 963 if (Var->isStaticDataMember()) { 964 VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember(); 965 if (InstantiatedFrom) 966 return getVisibilityOf(InstantiatedFrom, kind); 967 } 968 969 return None; 970 } 971 // Also handle function template specializations. 972 if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) { 973 // If the function is a specialization of a template with an 974 // explicit visibility attribute, use that. 975 if (FunctionTemplateSpecializationInfo *templateInfo 976 = fn->getTemplateSpecializationInfo()) 977 return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(), 978 kind); 979 980 // If the function is a member of a specialization of a class template 981 // and the corresponding decl has explicit visibility, use that. 982 FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction(); 983 if (InstantiatedFrom) 984 return getVisibilityOf(InstantiatedFrom, kind); 985 986 return None; 987 } 988 989 // The visibility of a template is stored in the templated decl. 990 if (const TemplateDecl *TD = dyn_cast<TemplateDecl>(this)) 991 return getVisibilityOf(TD->getTemplatedDecl(), kind); 992 993 return None; 994 } 995 996 static LinkageInfo getLVForLocalDecl(const NamedDecl *D, 997 LVComputationKind computation) { 998 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 999 if (Function->isInAnonymousNamespace() && 1000 !Function->isInExternCContext()) 1001 return LinkageInfo::uniqueExternal(); 1002 1003 // This is a "void f();" which got merged with a file static. 1004 if (Function->getCanonicalDecl()->getStorageClass() == SC_Static) 1005 return LinkageInfo::internal(); 1006 1007 LinkageInfo LV; 1008 if (!hasExplicitVisibilityAlready(computation)) { 1009 if (Optional<Visibility> Vis = 1010 getExplicitVisibility(Function, computation)) 1011 LV.mergeVisibility(*Vis, true); 1012 } 1013 1014 // Note that Sema::MergeCompatibleFunctionDecls already takes care of 1015 // merging storage classes and visibility attributes, so we don't have to 1016 // look at previous decls in here. 1017 1018 return LV; 1019 } 1020 1021 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 1022 if (Var->hasExternalStorage()) { 1023 if (Var->isInAnonymousNamespace() && !Var->isInExternCContext()) 1024 return LinkageInfo::uniqueExternal(); 1025 1026 LinkageInfo LV; 1027 if (Var->getStorageClass() == SC_PrivateExtern) 1028 LV.mergeVisibility(HiddenVisibility, true); 1029 else if (!hasExplicitVisibilityAlready(computation)) { 1030 if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation)) 1031 LV.mergeVisibility(*Vis, true); 1032 } 1033 1034 if (const VarDecl *Prev = Var->getPreviousDecl()) { 1035 LinkageInfo PrevLV = getLVForDecl(Prev, computation); 1036 if (PrevLV.getLinkage()) 1037 LV.setLinkage(PrevLV.getLinkage()); 1038 LV.mergeVisibility(PrevLV); 1039 } 1040 1041 return LV; 1042 } 1043 } 1044 1045 return LinkageInfo::none(); 1046 } 1047 1048 static LinkageInfo getLVForDecl(const NamedDecl *D, 1049 LVComputationKind computation) { 1050 // Objective-C: treat all Objective-C declarations as having external 1051 // linkage. 1052 switch (D->getKind()) { 1053 default: 1054 break; 1055 case Decl::ParmVar: 1056 return LinkageInfo::none(); 1057 case Decl::TemplateTemplateParm: // count these as external 1058 case Decl::NonTypeTemplateParm: 1059 case Decl::ObjCAtDefsField: 1060 case Decl::ObjCCategory: 1061 case Decl::ObjCCategoryImpl: 1062 case Decl::ObjCCompatibleAlias: 1063 case Decl::ObjCImplementation: 1064 case Decl::ObjCMethod: 1065 case Decl::ObjCProperty: 1066 case Decl::ObjCPropertyImpl: 1067 case Decl::ObjCProtocol: 1068 return LinkageInfo::external(); 1069 1070 case Decl::CXXRecord: { 1071 const CXXRecordDecl *Record = cast<CXXRecordDecl>(D); 1072 if (Record->isLambda()) { 1073 if (!Record->getLambdaManglingNumber()) { 1074 // This lambda has no mangling number, so it's internal. 1075 return LinkageInfo::internal(); 1076 } 1077 1078 // This lambda has its linkage/visibility determined by its owner. 1079 const DeclContext *DC = D->getDeclContext()->getRedeclContext(); 1080 if (Decl *ContextDecl = Record->getLambdaContextDecl()) { 1081 if (isa<ParmVarDecl>(ContextDecl)) 1082 DC = ContextDecl->getDeclContext()->getRedeclContext(); 1083 else 1084 return getLVForDecl(cast<NamedDecl>(ContextDecl), computation); 1085 } 1086 1087 if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC)) 1088 return getLVForDecl(ND, computation); 1089 1090 return LinkageInfo::external(); 1091 } 1092 1093 break; 1094 } 1095 } 1096 1097 // Handle linkage for namespace-scope names. 1098 if (D->getDeclContext()->getRedeclContext()->isFileContext()) 1099 return getLVForNamespaceScopeDecl(D, computation); 1100 1101 // C++ [basic.link]p5: 1102 // In addition, a member function, static data member, a named 1103 // class or enumeration of class scope, or an unnamed class or 1104 // enumeration defined in a class-scope typedef declaration such 1105 // that the class or enumeration has the typedef name for linkage 1106 // purposes (7.1.3), has external linkage if the name of the class 1107 // has external linkage. 1108 if (D->getDeclContext()->isRecord()) 1109 return getLVForClassMember(D, computation); 1110 1111 // C++ [basic.link]p6: 1112 // The name of a function declared in block scope and the name of 1113 // an object declared by a block scope extern declaration have 1114 // linkage. If there is a visible declaration of an entity with 1115 // linkage having the same name and type, ignoring entities 1116 // declared outside the innermost enclosing namespace scope, the 1117 // block scope declaration declares that same entity and receives 1118 // the linkage of the previous declaration. If there is more than 1119 // one such matching entity, the program is ill-formed. Otherwise, 1120 // if no matching entity is found, the block scope entity receives 1121 // external linkage. 1122 if (D->getDeclContext()->isFunctionOrMethod()) 1123 return getLVForLocalDecl(D, computation); 1124 1125 // C++ [basic.link]p6: 1126 // Names not covered by these rules have no linkage. 1127 return LinkageInfo::none(); 1128 } 1129 1130 std::string NamedDecl::getQualifiedNameAsString() const { 1131 return getQualifiedNameAsString(getASTContext().getPrintingPolicy()); 1132 } 1133 1134 std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 1135 std::string QualName; 1136 llvm::raw_string_ostream OS(QualName); 1137 printQualifiedName(OS, P); 1138 return OS.str(); 1139 } 1140 1141 void NamedDecl::printQualifiedName(raw_ostream &OS) const { 1142 printQualifiedName(OS, getASTContext().getPrintingPolicy()); 1143 } 1144 1145 void NamedDecl::printQualifiedName(raw_ostream &OS, 1146 const PrintingPolicy &P) const { 1147 const DeclContext *Ctx = getDeclContext(); 1148 1149 if (Ctx->isFunctionOrMethod()) { 1150 printName(OS); 1151 return; 1152 } 1153 1154 typedef SmallVector<const DeclContext *, 8> ContextsTy; 1155 ContextsTy Contexts; 1156 1157 // Collect contexts. 1158 while (Ctx && isa<NamedDecl>(Ctx)) { 1159 Contexts.push_back(Ctx); 1160 Ctx = Ctx->getParent(); 1161 } 1162 1163 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 1164 I != E; ++I) { 1165 if (const ClassTemplateSpecializationDecl *Spec 1166 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 1167 OS << Spec->getName(); 1168 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 1169 TemplateSpecializationType::PrintTemplateArgumentList(OS, 1170 TemplateArgs.data(), 1171 TemplateArgs.size(), 1172 P); 1173 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 1174 if (ND->isAnonymousNamespace()) 1175 OS << "<anonymous namespace>"; 1176 else 1177 OS << *ND; 1178 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 1179 if (!RD->getIdentifier()) 1180 OS << "<anonymous " << RD->getKindName() << '>'; 1181 else 1182 OS << *RD; 1183 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 1184 const FunctionProtoType *FT = 0; 1185 if (FD->hasWrittenPrototype()) 1186 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>()); 1187 1188 OS << *FD << '('; 1189 if (FT) { 1190 unsigned NumParams = FD->getNumParams(); 1191 for (unsigned i = 0; i < NumParams; ++i) { 1192 if (i) 1193 OS << ", "; 1194 OS << FD->getParamDecl(i)->getType().stream(P); 1195 } 1196 1197 if (FT->isVariadic()) { 1198 if (NumParams > 0) 1199 OS << ", "; 1200 OS << "..."; 1201 } 1202 } 1203 OS << ')'; 1204 } else { 1205 OS << *cast<NamedDecl>(*I); 1206 } 1207 OS << "::"; 1208 } 1209 1210 if (getDeclName()) 1211 OS << *this; 1212 else 1213 OS << "<anonymous>"; 1214 } 1215 1216 void NamedDecl::getNameForDiagnostic(raw_ostream &OS, 1217 const PrintingPolicy &Policy, 1218 bool Qualified) const { 1219 if (Qualified) 1220 printQualifiedName(OS, Policy); 1221 else 1222 printName(OS); 1223 } 1224 1225 bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 1226 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 1227 1228 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 1229 // We want to keep it, unless it nominates same namespace. 1230 if (getKind() == Decl::UsingDirective) { 1231 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() 1232 ->getOriginalNamespace() == 1233 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace() 1234 ->getOriginalNamespace(); 1235 } 1236 1237 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 1238 // For function declarations, we keep track of redeclarations. 1239 return FD->getPreviousDecl() == OldD; 1240 1241 // For function templates, the underlying function declarations are linked. 1242 if (const FunctionTemplateDecl *FunctionTemplate 1243 = dyn_cast<FunctionTemplateDecl>(this)) 1244 if (const FunctionTemplateDecl *OldFunctionTemplate 1245 = dyn_cast<FunctionTemplateDecl>(OldD)) 1246 return FunctionTemplate->getTemplatedDecl() 1247 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 1248 1249 // For method declarations, we keep track of redeclarations. 1250 if (isa<ObjCMethodDecl>(this)) 1251 return false; 1252 1253 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 1254 return true; 1255 1256 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 1257 return cast<UsingShadowDecl>(this)->getTargetDecl() == 1258 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 1259 1260 if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) { 1261 ASTContext &Context = getASTContext(); 1262 return Context.getCanonicalNestedNameSpecifier( 1263 cast<UsingDecl>(this)->getQualifier()) == 1264 Context.getCanonicalNestedNameSpecifier( 1265 cast<UsingDecl>(OldD)->getQualifier()); 1266 } 1267 1268 // A typedef of an Objective-C class type can replace an Objective-C class 1269 // declaration or definition, and vice versa. 1270 if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) || 1271 (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD))) 1272 return true; 1273 1274 // For non-function declarations, if the declarations are of the 1275 // same kind then this must be a redeclaration, or semantic analysis 1276 // would not have given us the new declaration. 1277 return this->getKind() == OldD->getKind(); 1278 } 1279 1280 bool NamedDecl::hasLinkage() const { 1281 return getLinkage() != NoLinkage; 1282 } 1283 1284 NamedDecl *NamedDecl::getUnderlyingDeclImpl() { 1285 NamedDecl *ND = this; 1286 while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 1287 ND = UD->getTargetDecl(); 1288 1289 if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 1290 return AD->getClassInterface(); 1291 1292 return ND; 1293 } 1294 1295 bool NamedDecl::isCXXInstanceMember() const { 1296 if (!isCXXClassMember()) 1297 return false; 1298 1299 const NamedDecl *D = this; 1300 if (isa<UsingShadowDecl>(D)) 1301 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 1302 1303 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D)) 1304 return true; 1305 if (isa<CXXMethodDecl>(D)) 1306 return cast<CXXMethodDecl>(D)->isInstance(); 1307 if (isa<FunctionTemplateDecl>(D)) 1308 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 1309 ->getTemplatedDecl())->isInstance(); 1310 return false; 1311 } 1312 1313 //===----------------------------------------------------------------------===// 1314 // DeclaratorDecl Implementation 1315 //===----------------------------------------------------------------------===// 1316 1317 template <typename DeclT> 1318 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 1319 if (decl->getNumTemplateParameterLists() > 0) 1320 return decl->getTemplateParameterList(0)->getTemplateLoc(); 1321 else 1322 return decl->getInnerLocStart(); 1323 } 1324 1325 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 1326 TypeSourceInfo *TSI = getTypeSourceInfo(); 1327 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 1328 return SourceLocation(); 1329 } 1330 1331 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 1332 if (QualifierLoc) { 1333 // Make sure the extended decl info is allocated. 1334 if (!hasExtInfo()) { 1335 // Save (non-extended) type source info pointer. 1336 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1337 // Allocate external info struct. 1338 DeclInfo = new (getASTContext()) ExtInfo; 1339 // Restore savedTInfo into (extended) decl info. 1340 getExtInfo()->TInfo = savedTInfo; 1341 } 1342 // Set qualifier info. 1343 getExtInfo()->QualifierLoc = QualifierLoc; 1344 } else { 1345 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1346 if (hasExtInfo()) { 1347 if (getExtInfo()->NumTemplParamLists == 0) { 1348 // Save type source info pointer. 1349 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 1350 // Deallocate the extended decl info. 1351 getASTContext().Deallocate(getExtInfo()); 1352 // Restore savedTInfo into (non-extended) decl info. 1353 DeclInfo = savedTInfo; 1354 } 1355 else 1356 getExtInfo()->QualifierLoc = QualifierLoc; 1357 } 1358 } 1359 } 1360 1361 void 1362 DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context, 1363 unsigned NumTPLists, 1364 TemplateParameterList **TPLists) { 1365 assert(NumTPLists > 0); 1366 // Make sure the extended decl info is allocated. 1367 if (!hasExtInfo()) { 1368 // Save (non-extended) type source info pointer. 1369 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 1370 // Allocate external info struct. 1371 DeclInfo = new (getASTContext()) ExtInfo; 1372 // Restore savedTInfo into (extended) decl info. 1373 getExtInfo()->TInfo = savedTInfo; 1374 } 1375 // Set the template parameter lists info. 1376 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 1377 } 1378 1379 SourceLocation DeclaratorDecl::getOuterLocStart() const { 1380 return getTemplateOrInnerLocStart(this); 1381 } 1382 1383 namespace { 1384 1385 // Helper function: returns true if QT is or contains a type 1386 // having a postfix component. 1387 bool typeIsPostfix(clang::QualType QT) { 1388 while (true) { 1389 const Type* T = QT.getTypePtr(); 1390 switch (T->getTypeClass()) { 1391 default: 1392 return false; 1393 case Type::Pointer: 1394 QT = cast<PointerType>(T)->getPointeeType(); 1395 break; 1396 case Type::BlockPointer: 1397 QT = cast<BlockPointerType>(T)->getPointeeType(); 1398 break; 1399 case Type::MemberPointer: 1400 QT = cast<MemberPointerType>(T)->getPointeeType(); 1401 break; 1402 case Type::LValueReference: 1403 case Type::RValueReference: 1404 QT = cast<ReferenceType>(T)->getPointeeType(); 1405 break; 1406 case Type::PackExpansion: 1407 QT = cast<PackExpansionType>(T)->getPattern(); 1408 break; 1409 case Type::Paren: 1410 case Type::ConstantArray: 1411 case Type::DependentSizedArray: 1412 case Type::IncompleteArray: 1413 case Type::VariableArray: 1414 case Type::FunctionProto: 1415 case Type::FunctionNoProto: 1416 return true; 1417 } 1418 } 1419 } 1420 1421 } // namespace 1422 1423 SourceRange DeclaratorDecl::getSourceRange() const { 1424 SourceLocation RangeEnd = getLocation(); 1425 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 1426 if (typeIsPostfix(TInfo->getType())) 1427 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 1428 } 1429 return SourceRange(getOuterLocStart(), RangeEnd); 1430 } 1431 1432 void 1433 QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 1434 unsigned NumTPLists, 1435 TemplateParameterList **TPLists) { 1436 assert((NumTPLists == 0 || TPLists != 0) && 1437 "Empty array of template parameters with positive size!"); 1438 1439 // Free previous template parameters (if any). 1440 if (NumTemplParamLists > 0) { 1441 Context.Deallocate(TemplParamLists); 1442 TemplParamLists = 0; 1443 NumTemplParamLists = 0; 1444 } 1445 // Set info on matched template parameter lists (if any). 1446 if (NumTPLists > 0) { 1447 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 1448 NumTemplParamLists = NumTPLists; 1449 for (unsigned i = NumTPLists; i-- > 0; ) 1450 TemplParamLists[i] = TPLists[i]; 1451 } 1452 } 1453 1454 //===----------------------------------------------------------------------===// 1455 // VarDecl Implementation 1456 //===----------------------------------------------------------------------===// 1457 1458 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 1459 switch (SC) { 1460 case SC_None: break; 1461 case SC_Auto: return "auto"; 1462 case SC_Extern: return "extern"; 1463 case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>"; 1464 case SC_PrivateExtern: return "__private_extern__"; 1465 case SC_Register: return "register"; 1466 case SC_Static: return "static"; 1467 } 1468 1469 llvm_unreachable("Invalid storage class"); 1470 } 1471 1472 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, 1473 SourceLocation StartL, SourceLocation IdL, 1474 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 1475 StorageClass S) { 1476 return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S); 1477 } 1478 1479 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1480 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl)); 1481 return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0, 1482 QualType(), 0, SC_None); 1483 } 1484 1485 void VarDecl::setStorageClass(StorageClass SC) { 1486 assert(isLegalForVariable(SC)); 1487 VarDeclBits.SClass = SC; 1488 } 1489 1490 SourceRange VarDecl::getSourceRange() const { 1491 if (const Expr *Init = getInit()) { 1492 SourceLocation InitEnd = Init->getLocEnd(); 1493 // If Init is implicit, ignore its source range and fallback on 1494 // DeclaratorDecl::getSourceRange() to handle postfix elements. 1495 if (InitEnd.isValid() && InitEnd != getLocation()) 1496 return SourceRange(getOuterLocStart(), InitEnd); 1497 } 1498 return DeclaratorDecl::getSourceRange(); 1499 } 1500 1501 template<typename T> 1502 static LanguageLinkage getLanguageLinkageTemplate(const T &D) { 1503 // C++ [dcl.link]p1: All function types, function names with external linkage, 1504 // and variable names with external linkage have a language linkage. 1505 if (!isExternalLinkage(D.getLinkage())) 1506 return NoLanguageLinkage; 1507 1508 // Language linkage is a C++ concept, but saying that everything else in C has 1509 // C language linkage fits the implementation nicely. 1510 ASTContext &Context = D.getASTContext(); 1511 if (!Context.getLangOpts().CPlusPlus) 1512 return CLanguageLinkage; 1513 1514 // C++ [dcl.link]p4: A C language linkage is ignored in determining the 1515 // language linkage of the names of class members and the function type of 1516 // class member functions. 1517 const DeclContext *DC = D.getDeclContext(); 1518 if (DC->isRecord()) 1519 return CXXLanguageLinkage; 1520 1521 // If the first decl is in an extern "C" context, any other redeclaration 1522 // will have C language linkage. If the first one is not in an extern "C" 1523 // context, we would have reported an error for any other decl being in one. 1524 if (isFirstInExternCContext(&D)) 1525 return CLanguageLinkage; 1526 return CXXLanguageLinkage; 1527 } 1528 1529 template<typename T> 1530 static bool isExternCTemplate(const T &D) { 1531 // Since the context is ignored for class members, they can only have C++ 1532 // language linkage or no language linkage. 1533 const DeclContext *DC = D.getDeclContext(); 1534 if (DC->isRecord()) { 1535 assert(D.getASTContext().getLangOpts().CPlusPlus); 1536 return false; 1537 } 1538 1539 return D.getLanguageLinkage() == CLanguageLinkage; 1540 } 1541 1542 LanguageLinkage VarDecl::getLanguageLinkage() const { 1543 return getLanguageLinkageTemplate(*this); 1544 } 1545 1546 bool VarDecl::isExternC() const { 1547 return isExternCTemplate(*this); 1548 } 1549 1550 static bool isLinkageSpecContext(const DeclContext *DC, 1551 LinkageSpecDecl::LanguageIDs ID) { 1552 while (DC->getDeclKind() != Decl::TranslationUnit) { 1553 if (DC->getDeclKind() == Decl::LinkageSpec) 1554 return cast<LinkageSpecDecl>(DC)->getLanguage() == ID; 1555 DC = DC->getParent(); 1556 } 1557 return false; 1558 } 1559 1560 template <typename T> 1561 static bool isInLanguageSpecContext(T *D, LinkageSpecDecl::LanguageIDs ID) { 1562 return isLinkageSpecContext(D->getLexicalDeclContext(), ID); 1563 } 1564 1565 bool VarDecl::isInExternCContext() const { 1566 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c); 1567 } 1568 1569 bool VarDecl::isInExternCXXContext() const { 1570 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx); 1571 } 1572 1573 VarDecl *VarDecl::getCanonicalDecl() { 1574 return getFirstDeclaration(); 1575 } 1576 1577 VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition( 1578 ASTContext &C) const 1579 { 1580 // C++ [basic.def]p2: 1581 // A declaration is a definition unless [...] it contains the 'extern' 1582 // specifier or a linkage-specification and neither an initializer [...], 1583 // it declares a static data member in a class declaration [...]. 1584 // C++ [temp.expl.spec]p15: 1585 // An explicit specialization of a static data member of a template is a 1586 // definition if the declaration includes an initializer; otherwise, it is 1587 // a declaration. 1588 if (isStaticDataMember()) { 1589 if (isOutOfLine() && (hasInit() || 1590 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 1591 return Definition; 1592 else 1593 return DeclarationOnly; 1594 } 1595 // C99 6.7p5: 1596 // A definition of an identifier is a declaration for that identifier that 1597 // [...] causes storage to be reserved for that object. 1598 // Note: that applies for all non-file-scope objects. 1599 // C99 6.9.2p1: 1600 // If the declaration of an identifier for an object has file scope and an 1601 // initializer, the declaration is an external definition for the identifier 1602 if (hasInit()) 1603 return Definition; 1604 1605 if (hasExternalStorage()) 1606 return DeclarationOnly; 1607 1608 // [dcl.link] p7: 1609 // A declaration directly contained in a linkage-specification is treated 1610 // as if it contains the extern specifier for the purpose of determining 1611 // the linkage of the declared name and whether it is a definition. 1612 if (isSingleLineExternC(*this)) 1613 return DeclarationOnly; 1614 1615 // C99 6.9.2p2: 1616 // A declaration of an object that has file scope without an initializer, 1617 // and without a storage class specifier or the scs 'static', constitutes 1618 // a tentative definition. 1619 // No such thing in C++. 1620 if (!C.getLangOpts().CPlusPlus && isFileVarDecl()) 1621 return TentativeDefinition; 1622 1623 // What's left is (in C, block-scope) declarations without initializers or 1624 // external storage. These are definitions. 1625 return Definition; 1626 } 1627 1628 VarDecl *VarDecl::getActingDefinition() { 1629 DefinitionKind Kind = isThisDeclarationADefinition(); 1630 if (Kind != TentativeDefinition) 1631 return 0; 1632 1633 VarDecl *LastTentative = 0; 1634 VarDecl *First = getFirstDeclaration(); 1635 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1636 I != E; ++I) { 1637 Kind = (*I)->isThisDeclarationADefinition(); 1638 if (Kind == Definition) 1639 return 0; 1640 else if (Kind == TentativeDefinition) 1641 LastTentative = *I; 1642 } 1643 return LastTentative; 1644 } 1645 1646 bool VarDecl::isTentativeDefinitionNow() const { 1647 DefinitionKind Kind = isThisDeclarationADefinition(); 1648 if (Kind != TentativeDefinition) 1649 return false; 1650 1651 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1652 if ((*I)->isThisDeclarationADefinition() == Definition) 1653 return false; 1654 } 1655 return true; 1656 } 1657 1658 VarDecl *VarDecl::getDefinition(ASTContext &C) { 1659 VarDecl *First = getFirstDeclaration(); 1660 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1661 I != E; ++I) { 1662 if ((*I)->isThisDeclarationADefinition(C) == Definition) 1663 return *I; 1664 } 1665 return 0; 1666 } 1667 1668 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const { 1669 DefinitionKind Kind = DeclarationOnly; 1670 1671 const VarDecl *First = getFirstDeclaration(); 1672 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 1673 I != E; ++I) { 1674 Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C)); 1675 if (Kind == Definition) 1676 break; 1677 } 1678 1679 return Kind; 1680 } 1681 1682 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 1683 redecl_iterator I = redecls_begin(), E = redecls_end(); 1684 while (I != E && !I->getInit()) 1685 ++I; 1686 1687 if (I != E) { 1688 D = *I; 1689 return I->getInit(); 1690 } 1691 return 0; 1692 } 1693 1694 bool VarDecl::isOutOfLine() const { 1695 if (Decl::isOutOfLine()) 1696 return true; 1697 1698 if (!isStaticDataMember()) 1699 return false; 1700 1701 // If this static data member was instantiated from a static data member of 1702 // a class template, check whether that static data member was defined 1703 // out-of-line. 1704 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 1705 return VD->isOutOfLine(); 1706 1707 return false; 1708 } 1709 1710 VarDecl *VarDecl::getOutOfLineDefinition() { 1711 if (!isStaticDataMember()) 1712 return 0; 1713 1714 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 1715 RD != RDEnd; ++RD) { 1716 if (RD->getLexicalDeclContext()->isFileContext()) 1717 return *RD; 1718 } 1719 1720 return 0; 1721 } 1722 1723 void VarDecl::setInit(Expr *I) { 1724 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 1725 Eval->~EvaluatedStmt(); 1726 getASTContext().Deallocate(Eval); 1727 } 1728 1729 Init = I; 1730 } 1731 1732 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const { 1733 const LangOptions &Lang = C.getLangOpts(); 1734 1735 if (!Lang.CPlusPlus) 1736 return false; 1737 1738 // In C++11, any variable of reference type can be used in a constant 1739 // expression if it is initialized by a constant expression. 1740 if (Lang.CPlusPlus11 && getType()->isReferenceType()) 1741 return true; 1742 1743 // Only const objects can be used in constant expressions in C++. C++98 does 1744 // not require the variable to be non-volatile, but we consider this to be a 1745 // defect. 1746 if (!getType().isConstQualified() || getType().isVolatileQualified()) 1747 return false; 1748 1749 // In C++, const, non-volatile variables of integral or enumeration types 1750 // can be used in constant expressions. 1751 if (getType()->isIntegralOrEnumerationType()) 1752 return true; 1753 1754 // Additionally, in C++11, non-volatile constexpr variables can be used in 1755 // constant expressions. 1756 return Lang.CPlusPlus11 && isConstexpr(); 1757 } 1758 1759 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt 1760 /// form, which contains extra information on the evaluated value of the 1761 /// initializer. 1762 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const { 1763 EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>(); 1764 if (!Eval) { 1765 Stmt *S = Init.get<Stmt *>(); 1766 Eval = new (getASTContext()) EvaluatedStmt; 1767 Eval->Value = S; 1768 Init = Eval; 1769 } 1770 return Eval; 1771 } 1772 1773 APValue *VarDecl::evaluateValue() const { 1774 SmallVector<PartialDiagnosticAt, 8> Notes; 1775 return evaluateValue(Notes); 1776 } 1777 1778 APValue *VarDecl::evaluateValue( 1779 SmallVectorImpl<PartialDiagnosticAt> &Notes) const { 1780 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 1781 1782 // We only produce notes indicating why an initializer is non-constant the 1783 // first time it is evaluated. FIXME: The notes won't always be emitted the 1784 // first time we try evaluation, so might not be produced at all. 1785 if (Eval->WasEvaluated) 1786 return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated; 1787 1788 const Expr *Init = cast<Expr>(Eval->Value); 1789 assert(!Init->isValueDependent()); 1790 1791 if (Eval->IsEvaluating) { 1792 // FIXME: Produce a diagnostic for self-initialization. 1793 Eval->CheckedICE = true; 1794 Eval->IsICE = false; 1795 return 0; 1796 } 1797 1798 Eval->IsEvaluating = true; 1799 1800 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(), 1801 this, Notes); 1802 1803 // Ensure the result is an uninitialized APValue if evaluation fails. 1804 if (!Result) 1805 Eval->Evaluated = APValue(); 1806 1807 Eval->IsEvaluating = false; 1808 Eval->WasEvaluated = true; 1809 1810 // In C++11, we have determined whether the initializer was a constant 1811 // expression as a side-effect. 1812 if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) { 1813 Eval->CheckedICE = true; 1814 Eval->IsICE = Result && Notes.empty(); 1815 } 1816 1817 return Result ? &Eval->Evaluated : 0; 1818 } 1819 1820 bool VarDecl::checkInitIsICE() const { 1821 // Initializers of weak variables are never ICEs. 1822 if (isWeak()) 1823 return false; 1824 1825 EvaluatedStmt *Eval = ensureEvaluatedStmt(); 1826 if (Eval->CheckedICE) 1827 // We have already checked whether this subexpression is an 1828 // integral constant expression. 1829 return Eval->IsICE; 1830 1831 const Expr *Init = cast<Expr>(Eval->Value); 1832 assert(!Init->isValueDependent()); 1833 1834 // In C++11, evaluate the initializer to check whether it's a constant 1835 // expression. 1836 if (getASTContext().getLangOpts().CPlusPlus11) { 1837 SmallVector<PartialDiagnosticAt, 8> Notes; 1838 evaluateValue(Notes); 1839 return Eval->IsICE; 1840 } 1841 1842 // It's an ICE whether or not the definition we found is 1843 // out-of-line. See DR 721 and the discussion in Clang PR 1844 // 6206 for details. 1845 1846 if (Eval->CheckingICE) 1847 return false; 1848 Eval->CheckingICE = true; 1849 1850 Eval->IsICE = Init->isIntegerConstantExpr(getASTContext()); 1851 Eval->CheckingICE = false; 1852 Eval->CheckedICE = true; 1853 return Eval->IsICE; 1854 } 1855 1856 bool VarDecl::extendsLifetimeOfTemporary() const { 1857 assert(getType()->isReferenceType() &&"Non-references never extend lifetime"); 1858 1859 const Expr *E = getInit(); 1860 if (!E) 1861 return false; 1862 1863 if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E)) 1864 E = Cleanups->getSubExpr(); 1865 1866 return isa<MaterializeTemporaryExpr>(E); 1867 } 1868 1869 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 1870 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1871 return cast<VarDecl>(MSI->getInstantiatedFrom()); 1872 1873 return 0; 1874 } 1875 1876 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 1877 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 1878 return MSI->getTemplateSpecializationKind(); 1879 1880 return TSK_Undeclared; 1881 } 1882 1883 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 1884 return getASTContext().getInstantiatedFromStaticDataMember(this); 1885 } 1886 1887 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1888 SourceLocation PointOfInstantiation) { 1889 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 1890 assert(MSI && "Not an instantiated static data member?"); 1891 MSI->setTemplateSpecializationKind(TSK); 1892 if (TSK != TSK_ExplicitSpecialization && 1893 PointOfInstantiation.isValid() && 1894 MSI->getPointOfInstantiation().isInvalid()) 1895 MSI->setPointOfInstantiation(PointOfInstantiation); 1896 } 1897 1898 //===----------------------------------------------------------------------===// 1899 // ParmVarDecl Implementation 1900 //===----------------------------------------------------------------------===// 1901 1902 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 1903 SourceLocation StartLoc, 1904 SourceLocation IdLoc, IdentifierInfo *Id, 1905 QualType T, TypeSourceInfo *TInfo, 1906 StorageClass S, Expr *DefArg) { 1907 return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo, 1908 S, DefArg); 1909 } 1910 1911 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 1912 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl)); 1913 return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(), 1914 0, QualType(), 0, SC_None, 0); 1915 } 1916 1917 SourceRange ParmVarDecl::getSourceRange() const { 1918 if (!hasInheritedDefaultArg()) { 1919 SourceRange ArgRange = getDefaultArgRange(); 1920 if (ArgRange.isValid()) 1921 return SourceRange(getOuterLocStart(), ArgRange.getEnd()); 1922 } 1923 1924 // DeclaratorDecl considers the range of postfix types as overlapping with the 1925 // declaration name, but this is not the case with parameters in ObjC methods. 1926 if (isa<ObjCMethodDecl>(getDeclContext())) 1927 return SourceRange(DeclaratorDecl::getLocStart(), getLocation()); 1928 1929 return DeclaratorDecl::getSourceRange(); 1930 } 1931 1932 Expr *ParmVarDecl::getDefaultArg() { 1933 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 1934 assert(!hasUninstantiatedDefaultArg() && 1935 "Default argument is not yet instantiated!"); 1936 1937 Expr *Arg = getInit(); 1938 if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg)) 1939 return E->getSubExpr(); 1940 1941 return Arg; 1942 } 1943 1944 SourceRange ParmVarDecl::getDefaultArgRange() const { 1945 if (const Expr *E = getInit()) 1946 return E->getSourceRange(); 1947 1948 if (hasUninstantiatedDefaultArg()) 1949 return getUninstantiatedDefaultArg()->getSourceRange(); 1950 1951 return SourceRange(); 1952 } 1953 1954 bool ParmVarDecl::isParameterPack() const { 1955 return isa<PackExpansionType>(getType()); 1956 } 1957 1958 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) { 1959 getASTContext().setParameterIndex(this, parameterIndex); 1960 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel; 1961 } 1962 1963 unsigned ParmVarDecl::getParameterIndexLarge() const { 1964 return getASTContext().getParameterIndex(this); 1965 } 1966 1967 //===----------------------------------------------------------------------===// 1968 // FunctionDecl Implementation 1969 //===----------------------------------------------------------------------===// 1970 1971 void FunctionDecl::getNameForDiagnostic( 1972 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const { 1973 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified); 1974 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 1975 if (TemplateArgs) 1976 TemplateSpecializationType::PrintTemplateArgumentList( 1977 OS, TemplateArgs->data(), TemplateArgs->size(), Policy); 1978 } 1979 1980 bool FunctionDecl::isVariadic() const { 1981 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 1982 return FT->isVariadic(); 1983 return false; 1984 } 1985 1986 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 1987 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 1988 if (I->Body || I->IsLateTemplateParsed) { 1989 Definition = *I; 1990 return true; 1991 } 1992 } 1993 1994 return false; 1995 } 1996 1997 bool FunctionDecl::hasTrivialBody() const 1998 { 1999 Stmt *S = getBody(); 2000 if (!S) { 2001 // Since we don't have a body for this function, we don't know if it's 2002 // trivial or not. 2003 return false; 2004 } 2005 2006 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 2007 return true; 2008 return false; 2009 } 2010 2011 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const { 2012 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 2013 if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) { 2014 Definition = I->IsDeleted ? I->getCanonicalDecl() : *I; 2015 return true; 2016 } 2017 } 2018 2019 return false; 2020 } 2021 2022 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 2023 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 2024 if (I->Body) { 2025 Definition = *I; 2026 return I->Body.get(getASTContext().getExternalSource()); 2027 } else if (I->IsLateTemplateParsed) { 2028 Definition = *I; 2029 return 0; 2030 } 2031 } 2032 2033 return 0; 2034 } 2035 2036 void FunctionDecl::setBody(Stmt *B) { 2037 Body = B; 2038 if (B) 2039 EndRangeLoc = B->getLocEnd(); 2040 } 2041 2042 void FunctionDecl::setPure(bool P) { 2043 IsPure = P; 2044 if (P) 2045 if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext())) 2046 Parent->markedVirtualFunctionPure(); 2047 } 2048 2049 bool FunctionDecl::isMain() const { 2050 const TranslationUnitDecl *tunit = 2051 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()); 2052 return tunit && 2053 !tunit->getASTContext().getLangOpts().Freestanding && 2054 getIdentifier() && 2055 getIdentifier()->isStr("main"); 2056 } 2057 2058 bool FunctionDecl::isReservedGlobalPlacementOperator() const { 2059 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName); 2060 assert(getDeclName().getCXXOverloadedOperator() == OO_New || 2061 getDeclName().getCXXOverloadedOperator() == OO_Delete || 2062 getDeclName().getCXXOverloadedOperator() == OO_Array_New || 2063 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete); 2064 2065 if (isa<CXXRecordDecl>(getDeclContext())) return false; 2066 assert(getDeclContext()->getRedeclContext()->isTranslationUnit()); 2067 2068 const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>(); 2069 if (proto->getNumArgs() != 2 || proto->isVariadic()) return false; 2070 2071 ASTContext &Context = 2072 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext()) 2073 ->getASTContext(); 2074 2075 // The result type and first argument type are constant across all 2076 // these operators. The second argument must be exactly void*. 2077 return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy); 2078 } 2079 2080 LanguageLinkage FunctionDecl::getLanguageLinkage() const { 2081 // Users expect to be able to write 2082 // extern "C" void *__builtin_alloca (size_t); 2083 // so consider builtins as having C language linkage. 2084 if (getBuiltinID()) 2085 return CLanguageLinkage; 2086 2087 return getLanguageLinkageTemplate(*this); 2088 } 2089 2090 bool FunctionDecl::isExternC() const { 2091 return isExternCTemplate(*this); 2092 } 2093 2094 bool FunctionDecl::isInExternCContext() const { 2095 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c); 2096 } 2097 2098 bool FunctionDecl::isInExternCXXContext() const { 2099 return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx); 2100 } 2101 2102 bool FunctionDecl::isGlobal() const { 2103 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 2104 return Method->isStatic(); 2105 2106 if (getCanonicalDecl()->getStorageClass() == SC_Static) 2107 return false; 2108 2109 for (const DeclContext *DC = getDeclContext(); 2110 DC->isNamespace(); 2111 DC = DC->getParent()) { 2112 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 2113 if (!Namespace->getDeclName()) 2114 return false; 2115 break; 2116 } 2117 } 2118 2119 return true; 2120 } 2121 2122 bool FunctionDecl::isNoReturn() const { 2123 return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() || 2124 hasAttr<C11NoReturnAttr>() || 2125 getType()->getAs<FunctionType>()->getNoReturnAttr(); 2126 } 2127 2128 void 2129 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 2130 redeclarable_base::setPreviousDeclaration(PrevDecl); 2131 2132 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 2133 FunctionTemplateDecl *PrevFunTmpl 2134 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 2135 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 2136 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 2137 } 2138 2139 if (PrevDecl && PrevDecl->IsInline) 2140 IsInline = true; 2141 } 2142 2143 const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 2144 return getFirstDeclaration(); 2145 } 2146 2147 FunctionDecl *FunctionDecl::getCanonicalDecl() { 2148 return getFirstDeclaration(); 2149 } 2150 2151 /// \brief Returns a value indicating whether this function 2152 /// corresponds to a builtin function. 2153 /// 2154 /// The function corresponds to a built-in function if it is 2155 /// declared at translation scope or within an extern "C" block and 2156 /// its name matches with the name of a builtin. The returned value 2157 /// will be 0 for functions that do not correspond to a builtin, a 2158 /// value of type \c Builtin::ID if in the target-independent range 2159 /// \c [1,Builtin::First), or a target-specific builtin value. 2160 unsigned FunctionDecl::getBuiltinID() const { 2161 if (!getIdentifier()) 2162 return 0; 2163 2164 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 2165 if (!BuiltinID) 2166 return 0; 2167 2168 ASTContext &Context = getASTContext(); 2169 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 2170 return BuiltinID; 2171 2172 // This function has the name of a known C library 2173 // function. Determine whether it actually refers to the C library 2174 // function or whether it just has the same name. 2175 2176 // If this is a static function, it's not a builtin. 2177 if (getStorageClass() == SC_Static) 2178 return 0; 2179 2180 // If this function is at translation-unit scope and we're not in 2181 // C++, it refers to the C library function. 2182 if (!Context.getLangOpts().CPlusPlus && 2183 getDeclContext()->isTranslationUnit()) 2184 return BuiltinID; 2185 2186 // If the function is in an extern "C" linkage specification and is 2187 // not marked "overloadable", it's the real function. 2188 if (isa<LinkageSpecDecl>(getDeclContext()) && 2189 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 2190 == LinkageSpecDecl::lang_c && 2191 !getAttr<OverloadableAttr>()) 2192 return BuiltinID; 2193 2194 // Not a builtin 2195 return 0; 2196 } 2197 2198 2199 /// getNumParams - Return the number of parameters this function must have 2200 /// based on its FunctionType. This is the length of the ParamInfo array 2201 /// after it has been created. 2202 unsigned FunctionDecl::getNumParams() const { 2203 const FunctionType *FT = getType()->castAs<FunctionType>(); 2204 if (isa<FunctionNoProtoType>(FT)) 2205 return 0; 2206 return cast<FunctionProtoType>(FT)->getNumArgs(); 2207 2208 } 2209 2210 void FunctionDecl::setParams(ASTContext &C, 2211 ArrayRef<ParmVarDecl *> NewParamInfo) { 2212 assert(ParamInfo == 0 && "Already has param info!"); 2213 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"); 2214 2215 // Zero params -> null pointer. 2216 if (!NewParamInfo.empty()) { 2217 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()]; 2218 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 2219 } 2220 } 2221 2222 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) { 2223 assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!"); 2224 2225 if (!NewDecls.empty()) { 2226 NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()]; 2227 std::copy(NewDecls.begin(), NewDecls.end(), A); 2228 DeclsInPrototypeScope = ArrayRef<NamedDecl *>(A, NewDecls.size()); 2229 } 2230 } 2231 2232 /// getMinRequiredArguments - Returns the minimum number of arguments 2233 /// needed to call this function. This may be fewer than the number of 2234 /// function parameters, if some of the parameters have default 2235 /// arguments (in C++) or the last parameter is a parameter pack. 2236 unsigned FunctionDecl::getMinRequiredArguments() const { 2237 if (!getASTContext().getLangOpts().CPlusPlus) 2238 return getNumParams(); 2239 2240 unsigned NumRequiredArgs = getNumParams(); 2241 2242 // If the last parameter is a parameter pack, we don't need an argument for 2243 // it. 2244 if (NumRequiredArgs > 0 && 2245 getParamDecl(NumRequiredArgs - 1)->isParameterPack()) 2246 --NumRequiredArgs; 2247 2248 // If this parameter has a default argument, we don't need an argument for 2249 // it. 2250 while (NumRequiredArgs > 0 && 2251 getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 2252 --NumRequiredArgs; 2253 2254 // We might have parameter packs before the end. These can't be deduced, 2255 // but they can still handle multiple arguments. 2256 unsigned ArgIdx = NumRequiredArgs; 2257 while (ArgIdx > 0) { 2258 if (getParamDecl(ArgIdx - 1)->isParameterPack()) 2259 NumRequiredArgs = ArgIdx; 2260 2261 --ArgIdx; 2262 } 2263 2264 return NumRequiredArgs; 2265 } 2266 2267 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) { 2268 // Only consider file-scope declarations in this test. 2269 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 2270 return false; 2271 2272 // Only consider explicit declarations; the presence of a builtin for a 2273 // libcall shouldn't affect whether a definition is externally visible. 2274 if (Redecl->isImplicit()) 2275 return false; 2276 2277 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 2278 return true; // Not an inline definition 2279 2280 return false; 2281 } 2282 2283 /// \brief For a function declaration in C or C++, determine whether this 2284 /// declaration causes the definition to be externally visible. 2285 /// 2286 /// Specifically, this determines if adding the current declaration to the set 2287 /// of redeclarations of the given functions causes 2288 /// isInlineDefinitionExternallyVisible to change from false to true. 2289 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const { 2290 assert(!doesThisDeclarationHaveABody() && 2291 "Must have a declaration without a body."); 2292 2293 ASTContext &Context = getASTContext(); 2294 2295 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 2296 // With GNU inlining, a declaration with 'inline' but not 'extern', forces 2297 // an externally visible definition. 2298 // 2299 // FIXME: What happens if gnu_inline gets added on after the first 2300 // declaration? 2301 if (!isInlineSpecified() || getStorageClass() == SC_Extern) 2302 return false; 2303 2304 const FunctionDecl *Prev = this; 2305 bool FoundBody = false; 2306 while ((Prev = Prev->getPreviousDecl())) { 2307 FoundBody |= Prev->Body; 2308 2309 if (Prev->Body) { 2310 // If it's not the case that both 'inline' and 'extern' are 2311 // specified on the definition, then it is always externally visible. 2312 if (!Prev->isInlineSpecified() || 2313 Prev->getStorageClass() != SC_Extern) 2314 return false; 2315 } else if (Prev->isInlineSpecified() && 2316 Prev->getStorageClass() != SC_Extern) { 2317 return false; 2318 } 2319 } 2320 return FoundBody; 2321 } 2322 2323 if (Context.getLangOpts().CPlusPlus) 2324 return false; 2325 2326 // C99 6.7.4p6: 2327 // [...] If all of the file scope declarations for a function in a 2328 // translation unit include the inline function specifier without extern, 2329 // then the definition in that translation unit is an inline definition. 2330 if (isInlineSpecified() && getStorageClass() != SC_Extern) 2331 return false; 2332 const FunctionDecl *Prev = this; 2333 bool FoundBody = false; 2334 while ((Prev = Prev->getPreviousDecl())) { 2335 FoundBody |= Prev->Body; 2336 if (RedeclForcesDefC99(Prev)) 2337 return false; 2338 } 2339 return FoundBody; 2340 } 2341 2342 /// \brief For an inline function definition in C, or for a gnu_inline function 2343 /// in C++, determine whether the definition will be externally visible. 2344 /// 2345 /// Inline function definitions are always available for inlining optimizations. 2346 /// However, depending on the language dialect, declaration specifiers, and 2347 /// attributes, the definition of an inline function may or may not be 2348 /// "externally" visible to other translation units in the program. 2349 /// 2350 /// In C99, inline definitions are not externally visible by default. However, 2351 /// if even one of the global-scope declarations is marked "extern inline", the 2352 /// inline definition becomes externally visible (C99 6.7.4p6). 2353 /// 2354 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function 2355 /// definition, we use the GNU semantics for inline, which are nearly the 2356 /// opposite of C99 semantics. In particular, "inline" by itself will create 2357 /// an externally visible symbol, but "extern inline" will not create an 2358 /// externally visible symbol. 2359 bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 2360 assert(doesThisDeclarationHaveABody() && "Must have the function definition"); 2361 assert(isInlined() && "Function must be inline"); 2362 ASTContext &Context = getASTContext(); 2363 2364 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) { 2365 // Note: If you change the logic here, please change 2366 // doesDeclarationForceExternallyVisibleDefinition as well. 2367 // 2368 // If it's not the case that both 'inline' and 'extern' are 2369 // specified on the definition, then this inline definition is 2370 // externally visible. 2371 if (!(isInlineSpecified() && getStorageClass() == SC_Extern)) 2372 return true; 2373 2374 // If any declaration is 'inline' but not 'extern', then this definition 2375 // is externally visible. 2376 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 2377 Redecl != RedeclEnd; 2378 ++Redecl) { 2379 if (Redecl->isInlineSpecified() && 2380 Redecl->getStorageClass() != SC_Extern) 2381 return true; 2382 } 2383 2384 return false; 2385 } 2386 2387 // The rest of this function is C-only. 2388 assert(!Context.getLangOpts().CPlusPlus && 2389 "should not use C inline rules in C++"); 2390 2391 // C99 6.7.4p6: 2392 // [...] If all of the file scope declarations for a function in a 2393 // translation unit include the inline function specifier without extern, 2394 // then the definition in that translation unit is an inline definition. 2395 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 2396 Redecl != RedeclEnd; 2397 ++Redecl) { 2398 if (RedeclForcesDefC99(*Redecl)) 2399 return true; 2400 } 2401 2402 // C99 6.7.4p6: 2403 // An inline definition does not provide an external definition for the 2404 // function, and does not forbid an external definition in another 2405 // translation unit. 2406 return false; 2407 } 2408 2409 /// getOverloadedOperator - Which C++ overloaded operator this 2410 /// function represents, if any. 2411 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 2412 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 2413 return getDeclName().getCXXOverloadedOperator(); 2414 else 2415 return OO_None; 2416 } 2417 2418 /// getLiteralIdentifier - The literal suffix identifier this function 2419 /// represents, if any. 2420 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 2421 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 2422 return getDeclName().getCXXLiteralIdentifier(); 2423 else 2424 return 0; 2425 } 2426 2427 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 2428 if (TemplateOrSpecialization.isNull()) 2429 return TK_NonTemplate; 2430 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 2431 return TK_FunctionTemplate; 2432 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 2433 return TK_MemberSpecialization; 2434 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 2435 return TK_FunctionTemplateSpecialization; 2436 if (TemplateOrSpecialization.is 2437 <DependentFunctionTemplateSpecializationInfo*>()) 2438 return TK_DependentFunctionTemplateSpecialization; 2439 2440 llvm_unreachable("Did we miss a TemplateOrSpecialization type?"); 2441 } 2442 2443 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 2444 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 2445 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 2446 2447 return 0; 2448 } 2449 2450 void 2451 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 2452 FunctionDecl *FD, 2453 TemplateSpecializationKind TSK) { 2454 assert(TemplateOrSpecialization.isNull() && 2455 "Member function is already a specialization"); 2456 MemberSpecializationInfo *Info 2457 = new (C) MemberSpecializationInfo(FD, TSK); 2458 TemplateOrSpecialization = Info; 2459 } 2460 2461 bool FunctionDecl::isImplicitlyInstantiable() const { 2462 // If the function is invalid, it can't be implicitly instantiated. 2463 if (isInvalidDecl()) 2464 return false; 2465 2466 switch (getTemplateSpecializationKind()) { 2467 case TSK_Undeclared: 2468 case TSK_ExplicitInstantiationDefinition: 2469 return false; 2470 2471 case TSK_ImplicitInstantiation: 2472 return true; 2473 2474 // It is possible to instantiate TSK_ExplicitSpecialization kind 2475 // if the FunctionDecl has a class scope specialization pattern. 2476 case TSK_ExplicitSpecialization: 2477 return getClassScopeSpecializationPattern() != 0; 2478 2479 case TSK_ExplicitInstantiationDeclaration: 2480 // Handled below. 2481 break; 2482 } 2483 2484 // Find the actual template from which we will instantiate. 2485 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 2486 bool HasPattern = false; 2487 if (PatternDecl) 2488 HasPattern = PatternDecl->hasBody(PatternDecl); 2489 2490 // C++0x [temp.explicit]p9: 2491 // Except for inline functions, other explicit instantiation declarations 2492 // have the effect of suppressing the implicit instantiation of the entity 2493 // to which they refer. 2494 if (!HasPattern || !PatternDecl) 2495 return true; 2496 2497 return PatternDecl->isInlined(); 2498 } 2499 2500 bool FunctionDecl::isTemplateInstantiation() const { 2501 switch (getTemplateSpecializationKind()) { 2502 case TSK_Undeclared: 2503 case TSK_ExplicitSpecialization: 2504 return false; 2505 case TSK_ImplicitInstantiation: 2506 case TSK_ExplicitInstantiationDeclaration: 2507 case TSK_ExplicitInstantiationDefinition: 2508 return true; 2509 } 2510 llvm_unreachable("All TSK values handled."); 2511 } 2512 2513 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 2514 // Handle class scope explicit specialization special case. 2515 if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization) 2516 return getClassScopeSpecializationPattern(); 2517 2518 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 2519 while (Primary->getInstantiatedFromMemberTemplate()) { 2520 // If we have hit a point where the user provided a specialization of 2521 // this template, we're done looking. 2522 if (Primary->isMemberSpecialization()) 2523 break; 2524 2525 Primary = Primary->getInstantiatedFromMemberTemplate(); 2526 } 2527 2528 return Primary->getTemplatedDecl(); 2529 } 2530 2531 return getInstantiatedFromMemberFunction(); 2532 } 2533 2534 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 2535 if (FunctionTemplateSpecializationInfo *Info 2536 = TemplateOrSpecialization 2537 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2538 return Info->Template.getPointer(); 2539 } 2540 return 0; 2541 } 2542 2543 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const { 2544 return getASTContext().getClassScopeSpecializationPattern(this); 2545 } 2546 2547 const TemplateArgumentList * 2548 FunctionDecl::getTemplateSpecializationArgs() const { 2549 if (FunctionTemplateSpecializationInfo *Info 2550 = TemplateOrSpecialization 2551 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2552 return Info->TemplateArguments; 2553 } 2554 return 0; 2555 } 2556 2557 const ASTTemplateArgumentListInfo * 2558 FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 2559 if (FunctionTemplateSpecializationInfo *Info 2560 = TemplateOrSpecialization 2561 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 2562 return Info->TemplateArgumentsAsWritten; 2563 } 2564 return 0; 2565 } 2566 2567 void 2568 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 2569 FunctionTemplateDecl *Template, 2570 const TemplateArgumentList *TemplateArgs, 2571 void *InsertPos, 2572 TemplateSpecializationKind TSK, 2573 const TemplateArgumentListInfo *TemplateArgsAsWritten, 2574 SourceLocation PointOfInstantiation) { 2575 assert(TSK != TSK_Undeclared && 2576 "Must specify the type of function template specialization"); 2577 FunctionTemplateSpecializationInfo *Info 2578 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 2579 if (!Info) 2580 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 2581 TemplateArgs, 2582 TemplateArgsAsWritten, 2583 PointOfInstantiation); 2584 TemplateOrSpecialization = Info; 2585 Template->addSpecialization(Info, InsertPos); 2586 } 2587 2588 void 2589 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 2590 const UnresolvedSetImpl &Templates, 2591 const TemplateArgumentListInfo &TemplateArgs) { 2592 assert(TemplateOrSpecialization.isNull()); 2593 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 2594 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 2595 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 2596 void *Buffer = Context.Allocate(Size); 2597 DependentFunctionTemplateSpecializationInfo *Info = 2598 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 2599 TemplateArgs); 2600 TemplateOrSpecialization = Info; 2601 } 2602 2603 DependentFunctionTemplateSpecializationInfo:: 2604 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 2605 const TemplateArgumentListInfo &TArgs) 2606 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 2607 2608 d.NumTemplates = Ts.size(); 2609 d.NumArgs = TArgs.size(); 2610 2611 FunctionTemplateDecl **TsArray = 2612 const_cast<FunctionTemplateDecl**>(getTemplates()); 2613 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 2614 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 2615 2616 TemplateArgumentLoc *ArgsArray = 2617 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 2618 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 2619 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 2620 } 2621 2622 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 2623 // For a function template specialization, query the specialization 2624 // information object. 2625 FunctionTemplateSpecializationInfo *FTSInfo 2626 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 2627 if (FTSInfo) 2628 return FTSInfo->getTemplateSpecializationKind(); 2629 2630 MemberSpecializationInfo *MSInfo 2631 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 2632 if (MSInfo) 2633 return MSInfo->getTemplateSpecializationKind(); 2634 2635 return TSK_Undeclared; 2636 } 2637 2638 void 2639 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 2640 SourceLocation PointOfInstantiation) { 2641 if (FunctionTemplateSpecializationInfo *FTSInfo 2642 = TemplateOrSpecialization.dyn_cast< 2643 FunctionTemplateSpecializationInfo*>()) { 2644 FTSInfo->setTemplateSpecializationKind(TSK); 2645 if (TSK != TSK_ExplicitSpecialization && 2646 PointOfInstantiation.isValid() && 2647 FTSInfo->getPointOfInstantiation().isInvalid()) 2648 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 2649 } else if (MemberSpecializationInfo *MSInfo 2650 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 2651 MSInfo->setTemplateSpecializationKind(TSK); 2652 if (TSK != TSK_ExplicitSpecialization && 2653 PointOfInstantiation.isValid() && 2654 MSInfo->getPointOfInstantiation().isInvalid()) 2655 MSInfo->setPointOfInstantiation(PointOfInstantiation); 2656 } else 2657 llvm_unreachable("Function cannot have a template specialization kind"); 2658 } 2659 2660 SourceLocation FunctionDecl::getPointOfInstantiation() const { 2661 if (FunctionTemplateSpecializationInfo *FTSInfo 2662 = TemplateOrSpecialization.dyn_cast< 2663 FunctionTemplateSpecializationInfo*>()) 2664 return FTSInfo->getPointOfInstantiation(); 2665 else if (MemberSpecializationInfo *MSInfo 2666 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 2667 return MSInfo->getPointOfInstantiation(); 2668 2669 return SourceLocation(); 2670 } 2671 2672 bool FunctionDecl::isOutOfLine() const { 2673 if (Decl::isOutOfLine()) 2674 return true; 2675 2676 // If this function was instantiated from a member function of a 2677 // class template, check whether that member function was defined out-of-line. 2678 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 2679 const FunctionDecl *Definition; 2680 if (FD->hasBody(Definition)) 2681 return Definition->isOutOfLine(); 2682 } 2683 2684 // If this function was instantiated from a function template, 2685 // check whether that function template was defined out-of-line. 2686 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 2687 const FunctionDecl *Definition; 2688 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 2689 return Definition->isOutOfLine(); 2690 } 2691 2692 return false; 2693 } 2694 2695 SourceRange FunctionDecl::getSourceRange() const { 2696 return SourceRange(getOuterLocStart(), EndRangeLoc); 2697 } 2698 2699 unsigned FunctionDecl::getMemoryFunctionKind() const { 2700 IdentifierInfo *FnInfo = getIdentifier(); 2701 2702 if (!FnInfo) 2703 return 0; 2704 2705 // Builtin handling. 2706 switch (getBuiltinID()) { 2707 case Builtin::BI__builtin_memset: 2708 case Builtin::BI__builtin___memset_chk: 2709 case Builtin::BImemset: 2710 return Builtin::BImemset; 2711 2712 case Builtin::BI__builtin_memcpy: 2713 case Builtin::BI__builtin___memcpy_chk: 2714 case Builtin::BImemcpy: 2715 return Builtin::BImemcpy; 2716 2717 case Builtin::BI__builtin_memmove: 2718 case Builtin::BI__builtin___memmove_chk: 2719 case Builtin::BImemmove: 2720 return Builtin::BImemmove; 2721 2722 case Builtin::BIstrlcpy: 2723 return Builtin::BIstrlcpy; 2724 case Builtin::BIstrlcat: 2725 return Builtin::BIstrlcat; 2726 2727 case Builtin::BI__builtin_memcmp: 2728 case Builtin::BImemcmp: 2729 return Builtin::BImemcmp; 2730 2731 case Builtin::BI__builtin_strncpy: 2732 case Builtin::BI__builtin___strncpy_chk: 2733 case Builtin::BIstrncpy: 2734 return Builtin::BIstrncpy; 2735 2736 case Builtin::BI__builtin_strncmp: 2737 case Builtin::BIstrncmp: 2738 return Builtin::BIstrncmp; 2739 2740 case Builtin::BI__builtin_strncasecmp: 2741 case Builtin::BIstrncasecmp: 2742 return Builtin::BIstrncasecmp; 2743 2744 case Builtin::BI__builtin_strncat: 2745 case Builtin::BI__builtin___strncat_chk: 2746 case Builtin::BIstrncat: 2747 return Builtin::BIstrncat; 2748 2749 case Builtin::BI__builtin_strndup: 2750 case Builtin::BIstrndup: 2751 return Builtin::BIstrndup; 2752 2753 case Builtin::BI__builtin_strlen: 2754 case Builtin::BIstrlen: 2755 return Builtin::BIstrlen; 2756 2757 default: 2758 if (isExternC()) { 2759 if (FnInfo->isStr("memset")) 2760 return Builtin::BImemset; 2761 else if (FnInfo->isStr("memcpy")) 2762 return Builtin::BImemcpy; 2763 else if (FnInfo->isStr("memmove")) 2764 return Builtin::BImemmove; 2765 else if (FnInfo->isStr("memcmp")) 2766 return Builtin::BImemcmp; 2767 else if (FnInfo->isStr("strncpy")) 2768 return Builtin::BIstrncpy; 2769 else if (FnInfo->isStr("strncmp")) 2770 return Builtin::BIstrncmp; 2771 else if (FnInfo->isStr("strncasecmp")) 2772 return Builtin::BIstrncasecmp; 2773 else if (FnInfo->isStr("strncat")) 2774 return Builtin::BIstrncat; 2775 else if (FnInfo->isStr("strndup")) 2776 return Builtin::BIstrndup; 2777 else if (FnInfo->isStr("strlen")) 2778 return Builtin::BIstrlen; 2779 } 2780 break; 2781 } 2782 return 0; 2783 } 2784 2785 //===----------------------------------------------------------------------===// 2786 // FieldDecl Implementation 2787 //===----------------------------------------------------------------------===// 2788 2789 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC, 2790 SourceLocation StartLoc, SourceLocation IdLoc, 2791 IdentifierInfo *Id, QualType T, 2792 TypeSourceInfo *TInfo, Expr *BW, bool Mutable, 2793 InClassInitStyle InitStyle) { 2794 return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo, 2795 BW, Mutable, InitStyle); 2796 } 2797 2798 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2799 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl)); 2800 return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(), 2801 0, QualType(), 0, 0, false, ICIS_NoInit); 2802 } 2803 2804 bool FieldDecl::isAnonymousStructOrUnion() const { 2805 if (!isImplicit() || getDeclName()) 2806 return false; 2807 2808 if (const RecordType *Record = getType()->getAs<RecordType>()) 2809 return Record->getDecl()->isAnonymousStructOrUnion(); 2810 2811 return false; 2812 } 2813 2814 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const { 2815 assert(isBitField() && "not a bitfield"); 2816 Expr *BitWidth = InitializerOrBitWidth.getPointer(); 2817 return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue(); 2818 } 2819 2820 unsigned FieldDecl::getFieldIndex() const { 2821 if (CachedFieldIndex) return CachedFieldIndex - 1; 2822 2823 unsigned Index = 0; 2824 const RecordDecl *RD = getParent(); 2825 const FieldDecl *LastFD = 0; 2826 bool IsMsStruct = RD->isMsStruct(getASTContext()); 2827 2828 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end(); 2829 I != E; ++I, ++Index) { 2830 I->CachedFieldIndex = Index + 1; 2831 2832 if (IsMsStruct) { 2833 // Zero-length bitfields following non-bitfield members are ignored. 2834 if (getASTContext().ZeroBitfieldFollowsNonBitfield(*I, LastFD)) { 2835 --Index; 2836 continue; 2837 } 2838 LastFD = *I; 2839 } 2840 } 2841 2842 assert(CachedFieldIndex && "failed to find field in parent"); 2843 return CachedFieldIndex - 1; 2844 } 2845 2846 SourceRange FieldDecl::getSourceRange() const { 2847 if (const Expr *E = InitializerOrBitWidth.getPointer()) 2848 return SourceRange(getInnerLocStart(), E->getLocEnd()); 2849 return DeclaratorDecl::getSourceRange(); 2850 } 2851 2852 void FieldDecl::setBitWidth(Expr *Width) { 2853 assert(!InitializerOrBitWidth.getPointer() && !hasInClassInitializer() && 2854 "bit width or initializer already set"); 2855 InitializerOrBitWidth.setPointer(Width); 2856 } 2857 2858 void FieldDecl::setInClassInitializer(Expr *Init) { 2859 assert(!InitializerOrBitWidth.getPointer() && hasInClassInitializer() && 2860 "bit width or initializer already set"); 2861 InitializerOrBitWidth.setPointer(Init); 2862 } 2863 2864 //===----------------------------------------------------------------------===// 2865 // TagDecl Implementation 2866 //===----------------------------------------------------------------------===// 2867 2868 SourceLocation TagDecl::getOuterLocStart() const { 2869 return getTemplateOrInnerLocStart(this); 2870 } 2871 2872 SourceRange TagDecl::getSourceRange() const { 2873 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 2874 return SourceRange(getOuterLocStart(), E); 2875 } 2876 2877 TagDecl* TagDecl::getCanonicalDecl() { 2878 return getFirstDeclaration(); 2879 } 2880 2881 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) { 2882 TypedefNameDeclOrQualifier = TDD; 2883 if (TypeForDecl) 2884 assert(TypeForDecl->isLinkageValid()); 2885 assert(isLinkageValid()); 2886 } 2887 2888 void TagDecl::startDefinition() { 2889 IsBeingDefined = true; 2890 2891 if (CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(this)) { 2892 struct CXXRecordDecl::DefinitionData *Data = 2893 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 2894 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 2895 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 2896 } 2897 } 2898 2899 void TagDecl::completeDefinition() { 2900 assert((!isa<CXXRecordDecl>(this) || 2901 cast<CXXRecordDecl>(this)->hasDefinition()) && 2902 "definition completed but not started"); 2903 2904 IsCompleteDefinition = true; 2905 IsBeingDefined = false; 2906 2907 if (ASTMutationListener *L = getASTMutationListener()) 2908 L->CompletedTagDefinition(this); 2909 } 2910 2911 TagDecl *TagDecl::getDefinition() const { 2912 if (isCompleteDefinition()) 2913 return const_cast<TagDecl *>(this); 2914 2915 // If it's possible for us to have an out-of-date definition, check now. 2916 if (MayHaveOutOfDateDef) { 2917 if (IdentifierInfo *II = getIdentifier()) { 2918 if (II->isOutOfDate()) { 2919 updateOutOfDate(*II); 2920 } 2921 } 2922 } 2923 2924 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this)) 2925 return CXXRD->getDefinition(); 2926 2927 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 2928 R != REnd; ++R) 2929 if (R->isCompleteDefinition()) 2930 return *R; 2931 2932 return 0; 2933 } 2934 2935 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) { 2936 if (QualifierLoc) { 2937 // Make sure the extended qualifier info is allocated. 2938 if (!hasExtInfo()) 2939 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 2940 // Set qualifier info. 2941 getExtInfo()->QualifierLoc = QualifierLoc; 2942 } else { 2943 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 2944 if (hasExtInfo()) { 2945 if (getExtInfo()->NumTemplParamLists == 0) { 2946 getASTContext().Deallocate(getExtInfo()); 2947 TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0; 2948 } 2949 else 2950 getExtInfo()->QualifierLoc = QualifierLoc; 2951 } 2952 } 2953 } 2954 2955 void TagDecl::setTemplateParameterListsInfo(ASTContext &Context, 2956 unsigned NumTPLists, 2957 TemplateParameterList **TPLists) { 2958 assert(NumTPLists > 0); 2959 // Make sure the extended decl info is allocated. 2960 if (!hasExtInfo()) 2961 // Allocate external info struct. 2962 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo; 2963 // Set the template parameter lists info. 2964 getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists); 2965 } 2966 2967 //===----------------------------------------------------------------------===// 2968 // EnumDecl Implementation 2969 //===----------------------------------------------------------------------===// 2970 2971 void EnumDecl::anchor() { } 2972 2973 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, 2974 SourceLocation StartLoc, SourceLocation IdLoc, 2975 IdentifierInfo *Id, 2976 EnumDecl *PrevDecl, bool IsScoped, 2977 bool IsScopedUsingClassTag, bool IsFixed) { 2978 EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl, 2979 IsScoped, IsScopedUsingClassTag, IsFixed); 2980 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 2981 C.getTypeDeclType(Enum, PrevDecl); 2982 return Enum; 2983 } 2984 2985 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 2986 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl)); 2987 EnumDecl *Enum = new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 2988 0, 0, false, false, false); 2989 Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules; 2990 return Enum; 2991 } 2992 2993 void EnumDecl::completeDefinition(QualType NewType, 2994 QualType NewPromotionType, 2995 unsigned NumPositiveBits, 2996 unsigned NumNegativeBits) { 2997 assert(!isCompleteDefinition() && "Cannot redefine enums!"); 2998 if (!IntegerType) 2999 IntegerType = NewType.getTypePtr(); 3000 PromotionType = NewPromotionType; 3001 setNumPositiveBits(NumPositiveBits); 3002 setNumNegativeBits(NumNegativeBits); 3003 TagDecl::completeDefinition(); 3004 } 3005 3006 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const { 3007 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 3008 return MSI->getTemplateSpecializationKind(); 3009 3010 return TSK_Undeclared; 3011 } 3012 3013 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 3014 SourceLocation PointOfInstantiation) { 3015 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 3016 assert(MSI && "Not an instantiated member enumeration?"); 3017 MSI->setTemplateSpecializationKind(TSK); 3018 if (TSK != TSK_ExplicitSpecialization && 3019 PointOfInstantiation.isValid() && 3020 MSI->getPointOfInstantiation().isInvalid()) 3021 MSI->setPointOfInstantiation(PointOfInstantiation); 3022 } 3023 3024 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const { 3025 if (SpecializationInfo) 3026 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom()); 3027 3028 return 0; 3029 } 3030 3031 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED, 3032 TemplateSpecializationKind TSK) { 3033 assert(!SpecializationInfo && "Member enum is already a specialization"); 3034 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK); 3035 } 3036 3037 //===----------------------------------------------------------------------===// 3038 // RecordDecl Implementation 3039 //===----------------------------------------------------------------------===// 3040 3041 RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, 3042 SourceLocation StartLoc, SourceLocation IdLoc, 3043 IdentifierInfo *Id, RecordDecl *PrevDecl) 3044 : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) { 3045 HasFlexibleArrayMember = false; 3046 AnonymousStructOrUnion = false; 3047 HasObjectMember = false; 3048 HasVolatileMember = false; 3049 LoadedFieldsFromExternalStorage = false; 3050 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 3051 } 3052 3053 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC, 3054 SourceLocation StartLoc, SourceLocation IdLoc, 3055 IdentifierInfo *Id, RecordDecl* PrevDecl) { 3056 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id, 3057 PrevDecl); 3058 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3059 3060 C.getTypeDeclType(R, PrevDecl); 3061 return R; 3062 } 3063 3064 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) { 3065 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl)); 3066 RecordDecl *R = new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 3067 SourceLocation(), 0, 0); 3068 R->MayHaveOutOfDateDef = C.getLangOpts().Modules; 3069 return R; 3070 } 3071 3072 bool RecordDecl::isInjectedClassName() const { 3073 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 3074 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 3075 } 3076 3077 RecordDecl::field_iterator RecordDecl::field_begin() const { 3078 if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage) 3079 LoadFieldsFromExternalStorage(); 3080 3081 return field_iterator(decl_iterator(FirstDecl)); 3082 } 3083 3084 /// completeDefinition - Notes that the definition of this type is now 3085 /// complete. 3086 void RecordDecl::completeDefinition() { 3087 assert(!isCompleteDefinition() && "Cannot redefine record!"); 3088 TagDecl::completeDefinition(); 3089 } 3090 3091 /// isMsStruct - Get whether or not this record uses ms_struct layout. 3092 /// This which can be turned on with an attribute, pragma, or the 3093 /// -mms-bitfields command-line option. 3094 bool RecordDecl::isMsStruct(const ASTContext &C) const { 3095 return hasAttr<MsStructAttr>() || C.getLangOpts().MSBitfields == 1; 3096 } 3097 3098 static bool isFieldOrIndirectField(Decl::Kind K) { 3099 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K); 3100 } 3101 3102 void RecordDecl::LoadFieldsFromExternalStorage() const { 3103 ExternalASTSource *Source = getASTContext().getExternalSource(); 3104 assert(hasExternalLexicalStorage() && Source && "No external storage?"); 3105 3106 // Notify that we have a RecordDecl doing some initialization. 3107 ExternalASTSource::Deserializing TheFields(Source); 3108 3109 SmallVector<Decl*, 64> Decls; 3110 LoadedFieldsFromExternalStorage = true; 3111 switch (Source->FindExternalLexicalDecls(this, isFieldOrIndirectField, 3112 Decls)) { 3113 case ELR_Success: 3114 break; 3115 3116 case ELR_AlreadyLoaded: 3117 case ELR_Failure: 3118 return; 3119 } 3120 3121 #ifndef NDEBUG 3122 // Check that all decls we got were FieldDecls. 3123 for (unsigned i=0, e=Decls.size(); i != e; ++i) 3124 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])); 3125 #endif 3126 3127 if (Decls.empty()) 3128 return; 3129 3130 llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls, 3131 /*FieldsAlreadyLoaded=*/false); 3132 } 3133 3134 //===----------------------------------------------------------------------===// 3135 // BlockDecl Implementation 3136 //===----------------------------------------------------------------------===// 3137 3138 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) { 3139 assert(ParamInfo == 0 && "Already has param info!"); 3140 3141 // Zero params -> null pointer. 3142 if (!NewParamInfo.empty()) { 3143 NumParams = NewParamInfo.size(); 3144 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()]; 3145 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo); 3146 } 3147 } 3148 3149 void BlockDecl::setCaptures(ASTContext &Context, 3150 const Capture *begin, 3151 const Capture *end, 3152 bool capturesCXXThis) { 3153 CapturesCXXThis = capturesCXXThis; 3154 3155 if (begin == end) { 3156 NumCaptures = 0; 3157 Captures = 0; 3158 return; 3159 } 3160 3161 NumCaptures = end - begin; 3162 3163 // Avoid new Capture[] because we don't want to provide a default 3164 // constructor. 3165 size_t allocationSize = NumCaptures * sizeof(Capture); 3166 void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*)); 3167 memcpy(buffer, begin, allocationSize); 3168 Captures = static_cast<Capture*>(buffer); 3169 } 3170 3171 bool BlockDecl::capturesVariable(const VarDecl *variable) const { 3172 for (capture_const_iterator 3173 i = capture_begin(), e = capture_end(); i != e; ++i) 3174 // Only auto vars can be captured, so no redeclaration worries. 3175 if (i->getVariable() == variable) 3176 return true; 3177 3178 return false; 3179 } 3180 3181 SourceRange BlockDecl::getSourceRange() const { 3182 return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation()); 3183 } 3184 3185 //===----------------------------------------------------------------------===// 3186 // Other Decl Allocation/Deallocation Method Implementations 3187 //===----------------------------------------------------------------------===// 3188 3189 void TranslationUnitDecl::anchor() { } 3190 3191 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 3192 return new (C) TranslationUnitDecl(C); 3193 } 3194 3195 void LabelDecl::anchor() { } 3196 3197 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 3198 SourceLocation IdentL, IdentifierInfo *II) { 3199 return new (C) LabelDecl(DC, IdentL, II, 0, IdentL); 3200 } 3201 3202 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC, 3203 SourceLocation IdentL, IdentifierInfo *II, 3204 SourceLocation GnuLabelL) { 3205 assert(GnuLabelL != IdentL && "Use this only for GNU local labels"); 3206 return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL); 3207 } 3208 3209 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3210 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl)); 3211 return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation()); 3212 } 3213 3214 void ValueDecl::anchor() { } 3215 3216 bool ValueDecl::isWeak() const { 3217 for (attr_iterator I = attr_begin(), E = attr_end(); I != E; ++I) 3218 if (isa<WeakAttr>(*I) || isa<WeakRefAttr>(*I)) 3219 return true; 3220 3221 return isWeakImported(); 3222 } 3223 3224 void ImplicitParamDecl::anchor() { } 3225 3226 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 3227 SourceLocation IdLoc, 3228 IdentifierInfo *Id, 3229 QualType Type) { 3230 return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type); 3231 } 3232 3233 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C, 3234 unsigned ID) { 3235 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl)); 3236 return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType()); 3237 } 3238 3239 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 3240 SourceLocation StartLoc, 3241 const DeclarationNameInfo &NameInfo, 3242 QualType T, TypeSourceInfo *TInfo, 3243 StorageClass SC, 3244 bool isInlineSpecified, 3245 bool hasWrittenPrototype, 3246 bool isConstexprSpecified) { 3247 FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo, 3248 T, TInfo, SC, 3249 isInlineSpecified, 3250 isConstexprSpecified); 3251 New->HasWrittenPrototype = hasWrittenPrototype; 3252 return New; 3253 } 3254 3255 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3256 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl)); 3257 return new (Mem) FunctionDecl(Function, 0, SourceLocation(), 3258 DeclarationNameInfo(), QualType(), 0, 3259 SC_None, false, false); 3260 } 3261 3262 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 3263 return new (C) BlockDecl(DC, L); 3264 } 3265 3266 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3267 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl)); 3268 return new (Mem) BlockDecl(0, SourceLocation()); 3269 } 3270 3271 MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C, 3272 unsigned ID) { 3273 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(MSPropertyDecl)); 3274 return new (Mem) MSPropertyDecl(0, SourceLocation(), DeclarationName(), 3275 QualType(), 0, SourceLocation(), 3276 0, 0); 3277 } 3278 3279 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC, 3280 unsigned NumParams) { 3281 unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*); 3282 return new (C.Allocate(Size)) CapturedDecl(DC, NumParams); 3283 } 3284 3285 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3286 unsigned NumParams) { 3287 unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*); 3288 void *Mem = AllocateDeserializedDecl(C, ID, Size); 3289 return new (Mem) CapturedDecl(0, NumParams); 3290 } 3291 3292 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 3293 SourceLocation L, 3294 IdentifierInfo *Id, QualType T, 3295 Expr *E, const llvm::APSInt &V) { 3296 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 3297 } 3298 3299 EnumConstantDecl * 3300 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3301 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl)); 3302 return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0, 3303 llvm::APSInt()); 3304 } 3305 3306 void IndirectFieldDecl::anchor() { } 3307 3308 IndirectFieldDecl * 3309 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 3310 IdentifierInfo *Id, QualType T, NamedDecl **CH, 3311 unsigned CHS) { 3312 return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS); 3313 } 3314 3315 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C, 3316 unsigned ID) { 3317 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl)); 3318 return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(), 3319 QualType(), 0, 0); 3320 } 3321 3322 SourceRange EnumConstantDecl::getSourceRange() const { 3323 SourceLocation End = getLocation(); 3324 if (Init) 3325 End = Init->getLocEnd(); 3326 return SourceRange(getLocation(), End); 3327 } 3328 3329 void TypeDecl::anchor() { } 3330 3331 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 3332 SourceLocation StartLoc, SourceLocation IdLoc, 3333 IdentifierInfo *Id, TypeSourceInfo *TInfo) { 3334 return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo); 3335 } 3336 3337 void TypedefNameDecl::anchor() { } 3338 3339 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3340 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl)); 3341 return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0); 3342 } 3343 3344 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC, 3345 SourceLocation StartLoc, 3346 SourceLocation IdLoc, IdentifierInfo *Id, 3347 TypeSourceInfo *TInfo) { 3348 return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo); 3349 } 3350 3351 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3352 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl)); 3353 return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0); 3354 } 3355 3356 SourceRange TypedefDecl::getSourceRange() const { 3357 SourceLocation RangeEnd = getLocation(); 3358 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) { 3359 if (typeIsPostfix(TInfo->getType())) 3360 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3361 } 3362 return SourceRange(getLocStart(), RangeEnd); 3363 } 3364 3365 SourceRange TypeAliasDecl::getSourceRange() const { 3366 SourceLocation RangeEnd = getLocStart(); 3367 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) 3368 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd(); 3369 return SourceRange(getLocStart(), RangeEnd); 3370 } 3371 3372 void FileScopeAsmDecl::anchor() { } 3373 3374 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 3375 StringLiteral *Str, 3376 SourceLocation AsmLoc, 3377 SourceLocation RParenLoc) { 3378 return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc); 3379 } 3380 3381 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C, 3382 unsigned ID) { 3383 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl)); 3384 return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation()); 3385 } 3386 3387 void EmptyDecl::anchor() {} 3388 3389 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 3390 return new (C) EmptyDecl(DC, L); 3391 } 3392 3393 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) { 3394 void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EmptyDecl)); 3395 return new (Mem) EmptyDecl(0, SourceLocation()); 3396 } 3397 3398 //===----------------------------------------------------------------------===// 3399 // ImportDecl Implementation 3400 //===----------------------------------------------------------------------===// 3401 3402 /// \brief Retrieve the number of module identifiers needed to name the given 3403 /// module. 3404 static unsigned getNumModuleIdentifiers(Module *Mod) { 3405 unsigned Result = 1; 3406 while (Mod->Parent) { 3407 Mod = Mod->Parent; 3408 ++Result; 3409 } 3410 return Result; 3411 } 3412 3413 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 3414 Module *Imported, 3415 ArrayRef<SourceLocation> IdentifierLocs) 3416 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true), 3417 NextLocalImport() 3418 { 3419 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size()); 3420 SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1); 3421 memcpy(StoredLocs, IdentifierLocs.data(), 3422 IdentifierLocs.size() * sizeof(SourceLocation)); 3423 } 3424 3425 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc, 3426 Module *Imported, SourceLocation EndLoc) 3427 : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false), 3428 NextLocalImport() 3429 { 3430 *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc; 3431 } 3432 3433 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC, 3434 SourceLocation StartLoc, Module *Imported, 3435 ArrayRef<SourceLocation> IdentifierLocs) { 3436 void *Mem = C.Allocate(sizeof(ImportDecl) + 3437 IdentifierLocs.size() * sizeof(SourceLocation)); 3438 return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs); 3439 } 3440 3441 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC, 3442 SourceLocation StartLoc, 3443 Module *Imported, 3444 SourceLocation EndLoc) { 3445 void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation)); 3446 ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc); 3447 Import->setImplicit(); 3448 return Import; 3449 } 3450 3451 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID, 3452 unsigned NumLocations) { 3453 void *Mem = AllocateDeserializedDecl(C, ID, 3454 (sizeof(ImportDecl) + 3455 NumLocations * sizeof(SourceLocation))); 3456 return new (Mem) ImportDecl(EmptyShell()); 3457 } 3458 3459 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const { 3460 if (!ImportedAndComplete.getInt()) 3461 return None; 3462 3463 const SourceLocation *StoredLocs 3464 = reinterpret_cast<const SourceLocation *>(this + 1); 3465 return ArrayRef<SourceLocation>(StoredLocs, 3466 getNumModuleIdentifiers(getImportedModule())); 3467 } 3468 3469 SourceRange ImportDecl::getSourceRange() const { 3470 if (!ImportedAndComplete.getInt()) 3471 return SourceRange(getLocation(), 3472 *reinterpret_cast<const SourceLocation *>(this + 1)); 3473 3474 return SourceRange(getLocation(), getIdentifierLocs().back()); 3475 } 3476