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