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