Decl.cpp revision a626a3d0fb74455651f742c0938902a42e6e71c8
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/Basic/Builtins.h" 25#include "clang/Basic/IdentifierTable.h" 26#include "clang/Basic/Specifiers.h" 27#include "llvm/Support/ErrorHandling.h" 28 29using namespace clang; 30 31//===----------------------------------------------------------------------===// 32// NamedDecl Implementation 33//===----------------------------------------------------------------------===// 34 35/// \brief Get the most restrictive linkage for the types in the given 36/// template parameter list. 37static Linkage 38getLinkageForTemplateParameterList(const TemplateParameterList *Params) { 39 Linkage L = ExternalLinkage; 40 for (TemplateParameterList::const_iterator P = Params->begin(), 41 PEnd = Params->end(); 42 P != PEnd; ++P) { 43 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) 44 if (!NTTP->getType()->isDependentType()) { 45 L = minLinkage(L, NTTP->getType()->getLinkage()); 46 continue; 47 } 48 49 if (TemplateTemplateParmDecl *TTP 50 = dyn_cast<TemplateTemplateParmDecl>(*P)) { 51 L = minLinkage(L, 52 getLinkageForTemplateParameterList(TTP->getTemplateParameters())); 53 } 54 } 55 56 return L; 57} 58 59/// \brief Get the most restrictive linkage for the types and 60/// declarations in the given template argument list. 61static Linkage getLinkageForTemplateArgumentList(const TemplateArgument *Args, 62 unsigned NumArgs) { 63 Linkage L = ExternalLinkage; 64 65 for (unsigned I = 0; I != NumArgs; ++I) { 66 switch (Args[I].getKind()) { 67 case TemplateArgument::Null: 68 case TemplateArgument::Integral: 69 case TemplateArgument::Expression: 70 break; 71 72 case TemplateArgument::Type: 73 L = minLinkage(L, Args[I].getAsType()->getLinkage()); 74 break; 75 76 case TemplateArgument::Declaration: 77 if (NamedDecl *ND = dyn_cast<NamedDecl>(Args[I].getAsDecl())) 78 L = minLinkage(L, ND->getLinkage()); 79 if (ValueDecl *VD = dyn_cast<ValueDecl>(Args[I].getAsDecl())) 80 L = minLinkage(L, VD->getType()->getLinkage()); 81 break; 82 83 case TemplateArgument::Template: 84 if (TemplateDecl *Template 85 = Args[I].getAsTemplate().getAsTemplateDecl()) 86 L = minLinkage(L, Template->getLinkage()); 87 break; 88 89 case TemplateArgument::Pack: 90 L = minLinkage(L, 91 getLinkageForTemplateArgumentList(Args[I].pack_begin(), 92 Args[I].pack_size())); 93 break; 94 } 95 } 96 97 return L; 98} 99 100static Linkage 101getLinkageForTemplateArgumentList(const TemplateArgumentList &TArgs) { 102 return getLinkageForTemplateArgumentList(TArgs.getFlatArgumentList(), 103 TArgs.flat_size()); 104} 105 106static Linkage getLinkageForNamespaceScopeDecl(const NamedDecl *D) { 107 assert(D->getDeclContext()->getRedeclContext()->isFileContext() && 108 "Not a name having namespace scope"); 109 ASTContext &Context = D->getASTContext(); 110 111 // C++ [basic.link]p3: 112 // A name having namespace scope (3.3.6) has internal linkage if it 113 // is the name of 114 // - an object, reference, function or function template that is 115 // explicitly declared static; or, 116 // (This bullet corresponds to C99 6.2.2p3.) 117 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 118 // Explicitly declared static. 119 if (Var->getStorageClass() == SC_Static) 120 return InternalLinkage; 121 122 // - an object or reference that is explicitly declared const 123 // and neither explicitly declared extern nor previously 124 // declared to have external linkage; or 125 // (there is no equivalent in C99) 126 if (Context.getLangOptions().CPlusPlus && 127 Var->getType().isConstant(Context) && 128 Var->getStorageClass() != SC_Extern && 129 Var->getStorageClass() != SC_PrivateExtern) { 130 bool FoundExtern = false; 131 for (const VarDecl *PrevVar = Var->getPreviousDeclaration(); 132 PrevVar && !FoundExtern; 133 PrevVar = PrevVar->getPreviousDeclaration()) 134 if (isExternalLinkage(PrevVar->getLinkage())) 135 FoundExtern = true; 136 137 if (!FoundExtern) 138 return InternalLinkage; 139 } 140 } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) { 141 // C++ [temp]p4: 142 // A non-member function template can have internal linkage; any 143 // other template name shall have external linkage. 144 const FunctionDecl *Function = 0; 145 if (const FunctionTemplateDecl *FunTmpl 146 = dyn_cast<FunctionTemplateDecl>(D)) 147 Function = FunTmpl->getTemplatedDecl(); 148 else 149 Function = cast<FunctionDecl>(D); 150 151 // Explicitly declared static. 152 if (Function->getStorageClass() == SC_Static) 153 return InternalLinkage; 154 } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) { 155 // - a data member of an anonymous union. 156 if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion()) 157 return InternalLinkage; 158 } 159 160 // C++ [basic.link]p4: 161 162 // A name having namespace scope has external linkage if it is the 163 // name of 164 // 165 // - an object or reference, unless it has internal linkage; or 166 if (const VarDecl *Var = dyn_cast<VarDecl>(D)) { 167 if (!Context.getLangOptions().CPlusPlus && 168 (Var->getStorageClass() == SC_Extern || 169 Var->getStorageClass() == SC_PrivateExtern)) { 170 // C99 6.2.2p4: 171 // For an identifier declared with the storage-class specifier 172 // extern in a scope in which a prior declaration of that 173 // identifier is visible, if the prior declaration specifies 174 // internal or external linkage, the linkage of the identifier 175 // at the later declaration is the same as the linkage 176 // specified at the prior declaration. If no prior declaration 177 // is visible, or if the prior declaration specifies no 178 // linkage, then the identifier has external linkage. 179 if (const VarDecl *PrevVar = Var->getPreviousDeclaration()) { 180 if (Linkage L = PrevVar->getLinkage()) 181 return L; 182 } 183 } 184 185 // C99 6.2.2p5: 186 // If the declaration of an identifier for an object has file 187 // scope and no storage-class specifier, its linkage is 188 // external. 189 if (Var->isInAnonymousNamespace()) 190 return UniqueExternalLinkage; 191 192 return ExternalLinkage; 193 } 194 195 // - a function, unless it has internal linkage; or 196 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) { 197 // C99 6.2.2p5: 198 // If the declaration of an identifier for a function has no 199 // storage-class specifier, its linkage is determined exactly 200 // as if it were declared with the storage-class specifier 201 // extern. 202 if (!Context.getLangOptions().CPlusPlus && 203 (Function->getStorageClass() == SC_Extern || 204 Function->getStorageClass() == SC_PrivateExtern || 205 Function->getStorageClass() == SC_None)) { 206 // C99 6.2.2p4: 207 // For an identifier declared with the storage-class specifier 208 // extern in a scope in which a prior declaration of that 209 // identifier is visible, if the prior declaration specifies 210 // internal or external linkage, the linkage of the identifier 211 // at the later declaration is the same as the linkage 212 // specified at the prior declaration. If no prior declaration 213 // is visible, or if the prior declaration specifies no 214 // linkage, then the identifier has external linkage. 215 if (const FunctionDecl *PrevFunc = Function->getPreviousDeclaration()) { 216 if (Linkage L = PrevFunc->getLinkage()) 217 return L; 218 } 219 } 220 221 if (Function->isInAnonymousNamespace()) 222 return UniqueExternalLinkage; 223 224 if (FunctionTemplateSpecializationInfo *SpecInfo 225 = Function->getTemplateSpecializationInfo()) { 226 Linkage L = SpecInfo->getTemplate()->getLinkage(); 227 const TemplateArgumentList &TemplateArgs = *SpecInfo->TemplateArguments; 228 L = minLinkage(L, getLinkageForTemplateArgumentList(TemplateArgs)); 229 return L; 230 } 231 232 return ExternalLinkage; 233 } 234 235 // - a named class (Clause 9), or an unnamed class defined in a 236 // typedef declaration in which the class has the typedef name 237 // for linkage purposes (7.1.3); or 238 // - a named enumeration (7.2), or an unnamed enumeration 239 // defined in a typedef declaration in which the enumeration 240 // has the typedef name for linkage purposes (7.1.3); or 241 if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) 242 if (Tag->getDeclName() || Tag->getTypedefForAnonDecl()) { 243 if (Tag->isInAnonymousNamespace()) 244 return UniqueExternalLinkage; 245 246 // If this is a class template specialization, consider the 247 // linkage of the template and template arguments. 248 if (const ClassTemplateSpecializationDecl *Spec 249 = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) { 250 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 251 Linkage L = getLinkageForTemplateArgumentList(TemplateArgs); 252 return minLinkage(L, Spec->getSpecializedTemplate()->getLinkage()); 253 } 254 255 return ExternalLinkage; 256 } 257 258 // - an enumerator belonging to an enumeration with external linkage; 259 if (isa<EnumConstantDecl>(D)) { 260 Linkage L = cast<NamedDecl>(D->getDeclContext())->getLinkage(); 261 if (isExternalLinkage(L)) 262 return L; 263 } 264 265 // - a template, unless it is a function template that has 266 // internal linkage (Clause 14); 267 if (const TemplateDecl *Template = dyn_cast<TemplateDecl>(D)) { 268 if (D->isInAnonymousNamespace()) 269 return UniqueExternalLinkage; 270 271 return getLinkageForTemplateParameterList( 272 Template->getTemplateParameters()); 273 } 274 275 // - a namespace (7.3), unless it is declared within an unnamed 276 // namespace. 277 if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) 278 return ExternalLinkage; 279 280 return NoLinkage; 281} 282 283static Linkage getLinkageForClassMember(const NamedDecl *D) { 284 if (!(isa<CXXMethodDecl>(D) || 285 isa<VarDecl>(D) || 286 (isa<TagDecl>(D) && 287 (D->getDeclName() || cast<TagDecl>(D)->getTypedefForAnonDecl())))) 288 return NoLinkage; 289 290 // Class members only have linkage if their class has external linkage. 291 Linkage L = cast<RecordDecl>(D->getDeclContext())->getLinkage(); 292 if (!isExternalLinkage(L)) return NoLinkage; 293 294 // If the class already has unique-external linkage, we can't improve. 295 if (L == UniqueExternalLinkage) return UniqueExternalLinkage; 296 297 // If this is a method template specialization, use the linkage for 298 // the template parameters and arguments. 299 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) { 300 if (FunctionTemplateSpecializationInfo *SpecInfo 301 = MD->getTemplateSpecializationInfo()) { 302 Linkage ArgLinkage = 303 getLinkageForTemplateArgumentList(*SpecInfo->TemplateArguments); 304 Linkage ParamLinkage = 305 getLinkageForTemplateParameterList( 306 SpecInfo->getTemplate()->getTemplateParameters()); 307 return minLinkage(ArgLinkage, ParamLinkage); 308 } 309 310 // Similarly for member class template specializations. 311 } else if (const ClassTemplateSpecializationDecl *Spec 312 = dyn_cast<ClassTemplateSpecializationDecl>(D)) { 313 Linkage ArgLinkage = 314 getLinkageForTemplateArgumentList(Spec->getTemplateArgs()); 315 Linkage ParamLinkage = 316 getLinkageForTemplateParameterList( 317 Spec->getSpecializedTemplate()->getTemplateParameters()); 318 return minLinkage(ArgLinkage, ParamLinkage); 319 } 320 321 return ExternalLinkage; 322} 323 324Linkage NamedDecl::getLinkage() const { 325 326 // Objective-C: treat all Objective-C declarations as having external 327 // linkage. 328 switch (getKind()) { 329 default: 330 break; 331 case Decl::ObjCAtDefsField: 332 case Decl::ObjCCategory: 333 case Decl::ObjCCategoryImpl: 334 case Decl::ObjCClass: 335 case Decl::ObjCCompatibleAlias: 336 case Decl::ObjCForwardProtocol: 337 case Decl::ObjCImplementation: 338 case Decl::ObjCInterface: 339 case Decl::ObjCIvar: 340 case Decl::ObjCMethod: 341 case Decl::ObjCProperty: 342 case Decl::ObjCPropertyImpl: 343 case Decl::ObjCProtocol: 344 return ExternalLinkage; 345 } 346 347 // Handle linkage for namespace-scope names. 348 if (getDeclContext()->getRedeclContext()->isFileContext()) 349 if (Linkage L = getLinkageForNamespaceScopeDecl(this)) 350 return L; 351 352 // C++ [basic.link]p5: 353 // In addition, a member function, static data member, a named 354 // class or enumeration of class scope, or an unnamed class or 355 // enumeration defined in a class-scope typedef declaration such 356 // that the class or enumeration has the typedef name for linkage 357 // purposes (7.1.3), has external linkage if the name of the class 358 // has external linkage. 359 if (getDeclContext()->isRecord()) 360 return getLinkageForClassMember(this); 361 362 // C++ [basic.link]p6: 363 // The name of a function declared in block scope and the name of 364 // an object declared by a block scope extern declaration have 365 // linkage. If there is a visible declaration of an entity with 366 // linkage having the same name and type, ignoring entities 367 // declared outside the innermost enclosing namespace scope, the 368 // block scope declaration declares that same entity and receives 369 // the linkage of the previous declaration. If there is more than 370 // one such matching entity, the program is ill-formed. Otherwise, 371 // if no matching entity is found, the block scope entity receives 372 // external linkage. 373 if (getLexicalDeclContext()->isFunctionOrMethod()) { 374 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(this)) { 375 if (Function->getPreviousDeclaration()) 376 if (Linkage L = Function->getPreviousDeclaration()->getLinkage()) 377 return L; 378 379 if (Function->isInAnonymousNamespace()) 380 return UniqueExternalLinkage; 381 382 return ExternalLinkage; 383 } 384 385 if (const VarDecl *Var = dyn_cast<VarDecl>(this)) 386 if (Var->getStorageClass() == SC_Extern || 387 Var->getStorageClass() == SC_PrivateExtern) { 388 if (Var->getPreviousDeclaration()) 389 if (Linkage L = Var->getPreviousDeclaration()->getLinkage()) 390 return L; 391 392 if (Var->isInAnonymousNamespace()) 393 return UniqueExternalLinkage; 394 395 return ExternalLinkage; 396 } 397 } 398 399 // C++ [basic.link]p6: 400 // Names not covered by these rules have no linkage. 401 return NoLinkage; 402 } 403 404std::string NamedDecl::getQualifiedNameAsString() const { 405 return getQualifiedNameAsString(getASTContext().getLangOptions()); 406} 407 408std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const { 409 const DeclContext *Ctx = getDeclContext(); 410 411 if (Ctx->isFunctionOrMethod()) 412 return getNameAsString(); 413 414 typedef llvm::SmallVector<const DeclContext *, 8> ContextsTy; 415 ContextsTy Contexts; 416 417 // Collect contexts. 418 while (Ctx && isa<NamedDecl>(Ctx)) { 419 Contexts.push_back(Ctx); 420 Ctx = Ctx->getParent(); 421 }; 422 423 std::string QualName; 424 llvm::raw_string_ostream OS(QualName); 425 426 for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend(); 427 I != E; ++I) { 428 if (const ClassTemplateSpecializationDecl *Spec 429 = dyn_cast<ClassTemplateSpecializationDecl>(*I)) { 430 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs(); 431 std::string TemplateArgsStr 432 = TemplateSpecializationType::PrintTemplateArgumentList( 433 TemplateArgs.getFlatArgumentList(), 434 TemplateArgs.flat_size(), 435 P); 436 OS << Spec->getName() << TemplateArgsStr; 437 } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) { 438 if (ND->isAnonymousNamespace()) 439 OS << "<anonymous namespace>"; 440 else 441 OS << ND; 442 } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) { 443 if (!RD->getIdentifier()) 444 OS << "<anonymous " << RD->getKindName() << '>'; 445 else 446 OS << RD; 447 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) { 448 const FunctionProtoType *FT = 0; 449 if (FD->hasWrittenPrototype()) 450 FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 451 452 OS << FD << '('; 453 if (FT) { 454 unsigned NumParams = FD->getNumParams(); 455 for (unsigned i = 0; i < NumParams; ++i) { 456 if (i) 457 OS << ", "; 458 std::string Param; 459 FD->getParamDecl(i)->getType().getAsStringInternal(Param, P); 460 OS << Param; 461 } 462 463 if (FT->isVariadic()) { 464 if (NumParams > 0) 465 OS << ", "; 466 OS << "..."; 467 } 468 } 469 OS << ')'; 470 } else { 471 OS << cast<NamedDecl>(*I); 472 } 473 OS << "::"; 474 } 475 476 if (getDeclName()) 477 OS << this; 478 else 479 OS << "<anonymous>"; 480 481 return OS.str(); 482} 483 484bool NamedDecl::declarationReplaces(NamedDecl *OldD) const { 485 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch"); 486 487 // UsingDirectiveDecl's are not really NamedDecl's, and all have same name. 488 // We want to keep it, unless it nominates same namespace. 489 if (getKind() == Decl::UsingDirective) { 490 return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() == 491 cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace(); 492 } 493 494 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this)) 495 // For function declarations, we keep track of redeclarations. 496 return FD->getPreviousDeclaration() == OldD; 497 498 // For function templates, the underlying function declarations are linked. 499 if (const FunctionTemplateDecl *FunctionTemplate 500 = dyn_cast<FunctionTemplateDecl>(this)) 501 if (const FunctionTemplateDecl *OldFunctionTemplate 502 = dyn_cast<FunctionTemplateDecl>(OldD)) 503 return FunctionTemplate->getTemplatedDecl() 504 ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl()); 505 506 // For method declarations, we keep track of redeclarations. 507 if (isa<ObjCMethodDecl>(this)) 508 return false; 509 510 if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD)) 511 return true; 512 513 if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD)) 514 return cast<UsingShadowDecl>(this)->getTargetDecl() == 515 cast<UsingShadowDecl>(OldD)->getTargetDecl(); 516 517 // For non-function declarations, if the declarations are of the 518 // same kind then this must be a redeclaration, or semantic analysis 519 // would not have given us the new declaration. 520 return this->getKind() == OldD->getKind(); 521} 522 523bool NamedDecl::hasLinkage() const { 524 return getLinkage() != NoLinkage; 525} 526 527NamedDecl *NamedDecl::getUnderlyingDecl() { 528 NamedDecl *ND = this; 529 while (true) { 530 if (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND)) 531 ND = UD->getTargetDecl(); 532 else if (ObjCCompatibleAliasDecl *AD 533 = dyn_cast<ObjCCompatibleAliasDecl>(ND)) 534 return AD->getClassInterface(); 535 else 536 return ND; 537 } 538} 539 540bool NamedDecl::isCXXInstanceMember() const { 541 assert(isCXXClassMember() && 542 "checking whether non-member is instance member"); 543 544 const NamedDecl *D = this; 545 if (isa<UsingShadowDecl>(D)) 546 D = cast<UsingShadowDecl>(D)->getTargetDecl(); 547 548 if (isa<FieldDecl>(D)) 549 return true; 550 if (isa<CXXMethodDecl>(D)) 551 return cast<CXXMethodDecl>(D)->isInstance(); 552 if (isa<FunctionTemplateDecl>(D)) 553 return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D) 554 ->getTemplatedDecl())->isInstance(); 555 return false; 556} 557 558//===----------------------------------------------------------------------===// 559// DeclaratorDecl Implementation 560//===----------------------------------------------------------------------===// 561 562template <typename DeclT> 563static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) { 564 if (decl->getNumTemplateParameterLists() > 0) 565 return decl->getTemplateParameterList(0)->getTemplateLoc(); 566 else 567 return decl->getInnerLocStart(); 568} 569 570SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const { 571 TypeSourceInfo *TSI = getTypeSourceInfo(); 572 if (TSI) return TSI->getTypeLoc().getBeginLoc(); 573 return SourceLocation(); 574} 575 576void DeclaratorDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 577 SourceRange QualifierRange) { 578 if (Qualifier) { 579 // Make sure the extended decl info is allocated. 580 if (!hasExtInfo()) { 581 // Save (non-extended) type source info pointer. 582 TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>(); 583 // Allocate external info struct. 584 DeclInfo = new (getASTContext()) ExtInfo; 585 // Restore savedTInfo into (extended) decl info. 586 getExtInfo()->TInfo = savedTInfo; 587 } 588 // Set qualifier info. 589 getExtInfo()->NNS = Qualifier; 590 getExtInfo()->NNSRange = QualifierRange; 591 } 592 else { 593 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 594 assert(QualifierRange.isInvalid()); 595 if (hasExtInfo()) { 596 // Save type source info pointer. 597 TypeSourceInfo *savedTInfo = getExtInfo()->TInfo; 598 // Deallocate the extended decl info. 599 getASTContext().Deallocate(getExtInfo()); 600 // Restore savedTInfo into (non-extended) decl info. 601 DeclInfo = savedTInfo; 602 } 603 } 604} 605 606SourceLocation DeclaratorDecl::getOuterLocStart() const { 607 return getTemplateOrInnerLocStart(this); 608} 609 610void 611QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context, 612 unsigned NumTPLists, 613 TemplateParameterList **TPLists) { 614 assert((NumTPLists == 0 || TPLists != 0) && 615 "Empty array of template parameters with positive size!"); 616 assert((NumTPLists == 0 || NNS) && 617 "Nonempty array of template parameters with no qualifier!"); 618 619 // Free previous template parameters (if any). 620 if (NumTemplParamLists > 0) { 621 Context.Deallocate(TemplParamLists); 622 TemplParamLists = 0; 623 NumTemplParamLists = 0; 624 } 625 // Set info on matched template parameter lists (if any). 626 if (NumTPLists > 0) { 627 TemplParamLists = new (Context) TemplateParameterList*[NumTPLists]; 628 NumTemplParamLists = NumTPLists; 629 for (unsigned i = NumTPLists; i-- > 0; ) 630 TemplParamLists[i] = TPLists[i]; 631 } 632} 633 634//===----------------------------------------------------------------------===// 635// VarDecl Implementation 636//===----------------------------------------------------------------------===// 637 638const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) { 639 switch (SC) { 640 case SC_None: break; 641 case SC_Auto: return "auto"; break; 642 case SC_Extern: return "extern"; break; 643 case SC_PrivateExtern: return "__private_extern__"; break; 644 case SC_Register: return "register"; break; 645 case SC_Static: return "static"; break; 646 } 647 648 assert(0 && "Invalid storage class"); 649 return 0; 650} 651 652VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 653 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, 654 StorageClass S, StorageClass SCAsWritten) { 655 return new (C) VarDecl(Var, DC, L, Id, T, TInfo, S, SCAsWritten); 656} 657 658SourceLocation VarDecl::getInnerLocStart() const { 659 SourceLocation Start = getTypeSpecStartLoc(); 660 if (Start.isInvalid()) 661 Start = getLocation(); 662 return Start; 663} 664 665SourceRange VarDecl::getSourceRange() const { 666 if (getInit()) 667 return SourceRange(getOuterLocStart(), getInit()->getLocEnd()); 668 return SourceRange(getOuterLocStart(), getLocation()); 669} 670 671bool VarDecl::isExternC() const { 672 ASTContext &Context = getASTContext(); 673 if (!Context.getLangOptions().CPlusPlus) 674 return (getDeclContext()->isTranslationUnit() && 675 getStorageClass() != SC_Static) || 676 (getDeclContext()->isFunctionOrMethod() && hasExternalStorage()); 677 678 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 679 DC = DC->getParent()) { 680 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 681 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 682 return getStorageClass() != SC_Static; 683 684 break; 685 } 686 687 if (DC->isFunctionOrMethod()) 688 return false; 689 } 690 691 return false; 692} 693 694VarDecl *VarDecl::getCanonicalDecl() { 695 return getFirstDeclaration(); 696} 697 698VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition() const { 699 // C++ [basic.def]p2: 700 // A declaration is a definition unless [...] it contains the 'extern' 701 // specifier or a linkage-specification and neither an initializer [...], 702 // it declares a static data member in a class declaration [...]. 703 // C++ [temp.expl.spec]p15: 704 // An explicit specialization of a static data member of a template is a 705 // definition if the declaration includes an initializer; otherwise, it is 706 // a declaration. 707 if (isStaticDataMember()) { 708 if (isOutOfLine() && (hasInit() || 709 getTemplateSpecializationKind() != TSK_ExplicitSpecialization)) 710 return Definition; 711 else 712 return DeclarationOnly; 713 } 714 // C99 6.7p5: 715 // A definition of an identifier is a declaration for that identifier that 716 // [...] causes storage to be reserved for that object. 717 // Note: that applies for all non-file-scope objects. 718 // C99 6.9.2p1: 719 // If the declaration of an identifier for an object has file scope and an 720 // initializer, the declaration is an external definition for the identifier 721 if (hasInit()) 722 return Definition; 723 // AST for 'extern "C" int foo;' is annotated with 'extern'. 724 if (hasExternalStorage()) 725 return DeclarationOnly; 726 727 if (getStorageClassAsWritten() == SC_Extern || 728 getStorageClassAsWritten() == SC_PrivateExtern) { 729 for (const VarDecl *PrevVar = getPreviousDeclaration(); 730 PrevVar; PrevVar = PrevVar->getPreviousDeclaration()) { 731 if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit()) 732 return DeclarationOnly; 733 } 734 } 735 // C99 6.9.2p2: 736 // A declaration of an object that has file scope without an initializer, 737 // and without a storage class specifier or the scs 'static', constitutes 738 // a tentative definition. 739 // No such thing in C++. 740 if (!getASTContext().getLangOptions().CPlusPlus && isFileVarDecl()) 741 return TentativeDefinition; 742 743 // What's left is (in C, block-scope) declarations without initializers or 744 // external storage. These are definitions. 745 return Definition; 746} 747 748VarDecl *VarDecl::getActingDefinition() { 749 DefinitionKind Kind = isThisDeclarationADefinition(); 750 if (Kind != TentativeDefinition) 751 return 0; 752 753 VarDecl *LastTentative = 0; 754 VarDecl *First = getFirstDeclaration(); 755 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 756 I != E; ++I) { 757 Kind = (*I)->isThisDeclarationADefinition(); 758 if (Kind == Definition) 759 return 0; 760 else if (Kind == TentativeDefinition) 761 LastTentative = *I; 762 } 763 return LastTentative; 764} 765 766bool VarDecl::isTentativeDefinitionNow() const { 767 DefinitionKind Kind = isThisDeclarationADefinition(); 768 if (Kind != TentativeDefinition) 769 return false; 770 771 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 772 if ((*I)->isThisDeclarationADefinition() == Definition) 773 return false; 774 } 775 return true; 776} 777 778VarDecl *VarDecl::getDefinition() { 779 VarDecl *First = getFirstDeclaration(); 780 for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end(); 781 I != E; ++I) { 782 if ((*I)->isThisDeclarationADefinition() == Definition) 783 return *I; 784 } 785 return 0; 786} 787 788const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const { 789 redecl_iterator I = redecls_begin(), E = redecls_end(); 790 while (I != E && !I->getInit()) 791 ++I; 792 793 if (I != E) { 794 D = *I; 795 return I->getInit(); 796 } 797 return 0; 798} 799 800bool VarDecl::isOutOfLine() const { 801 if (Decl::isOutOfLine()) 802 return true; 803 804 if (!isStaticDataMember()) 805 return false; 806 807 // If this static data member was instantiated from a static data member of 808 // a class template, check whether that static data member was defined 809 // out-of-line. 810 if (VarDecl *VD = getInstantiatedFromStaticDataMember()) 811 return VD->isOutOfLine(); 812 813 return false; 814} 815 816VarDecl *VarDecl::getOutOfLineDefinition() { 817 if (!isStaticDataMember()) 818 return 0; 819 820 for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end(); 821 RD != RDEnd; ++RD) { 822 if (RD->getLexicalDeclContext()->isFileContext()) 823 return *RD; 824 } 825 826 return 0; 827} 828 829void VarDecl::setInit(Expr *I) { 830 if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) { 831 Eval->~EvaluatedStmt(); 832 getASTContext().Deallocate(Eval); 833 } 834 835 Init = I; 836} 837 838VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const { 839 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 840 return cast<VarDecl>(MSI->getInstantiatedFrom()); 841 842 return 0; 843} 844 845TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const { 846 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) 847 return MSI->getTemplateSpecializationKind(); 848 849 return TSK_Undeclared; 850} 851 852MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const { 853 return getASTContext().getInstantiatedFromStaticDataMember(this); 854} 855 856void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 857 SourceLocation PointOfInstantiation) { 858 MemberSpecializationInfo *MSI = getMemberSpecializationInfo(); 859 assert(MSI && "Not an instantiated static data member?"); 860 MSI->setTemplateSpecializationKind(TSK); 861 if (TSK != TSK_ExplicitSpecialization && 862 PointOfInstantiation.isValid() && 863 MSI->getPointOfInstantiation().isInvalid()) 864 MSI->setPointOfInstantiation(PointOfInstantiation); 865} 866 867//===----------------------------------------------------------------------===// 868// ParmVarDecl Implementation 869//===----------------------------------------------------------------------===// 870 871ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC, 872 SourceLocation L, IdentifierInfo *Id, 873 QualType T, TypeSourceInfo *TInfo, 874 StorageClass S, StorageClass SCAsWritten, 875 Expr *DefArg) { 876 return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, TInfo, 877 S, SCAsWritten, DefArg); 878} 879 880Expr *ParmVarDecl::getDefaultArg() { 881 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"); 882 assert(!hasUninstantiatedDefaultArg() && 883 "Default argument is not yet instantiated!"); 884 885 Expr *Arg = getInit(); 886 if (CXXExprWithTemporaries *E = dyn_cast_or_null<CXXExprWithTemporaries>(Arg)) 887 return E->getSubExpr(); 888 889 return Arg; 890} 891 892unsigned ParmVarDecl::getNumDefaultArgTemporaries() const { 893 if (const CXXExprWithTemporaries *E = 894 dyn_cast<CXXExprWithTemporaries>(getInit())) 895 return E->getNumTemporaries(); 896 897 return 0; 898} 899 900CXXTemporary *ParmVarDecl::getDefaultArgTemporary(unsigned i) { 901 assert(getNumDefaultArgTemporaries() && 902 "Default arguments does not have any temporaries!"); 903 904 CXXExprWithTemporaries *E = cast<CXXExprWithTemporaries>(getInit()); 905 return E->getTemporary(i); 906} 907 908SourceRange ParmVarDecl::getDefaultArgRange() const { 909 if (const Expr *E = getInit()) 910 return E->getSourceRange(); 911 912 if (hasUninstantiatedDefaultArg()) 913 return getUninstantiatedDefaultArg()->getSourceRange(); 914 915 return SourceRange(); 916} 917 918//===----------------------------------------------------------------------===// 919// FunctionDecl Implementation 920//===----------------------------------------------------------------------===// 921 922void FunctionDecl::getNameForDiagnostic(std::string &S, 923 const PrintingPolicy &Policy, 924 bool Qualified) const { 925 NamedDecl::getNameForDiagnostic(S, Policy, Qualified); 926 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs(); 927 if (TemplateArgs) 928 S += TemplateSpecializationType::PrintTemplateArgumentList( 929 TemplateArgs->getFlatArgumentList(), 930 TemplateArgs->flat_size(), 931 Policy); 932 933} 934 935bool FunctionDecl::isVariadic() const { 936 if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>()) 937 return FT->isVariadic(); 938 return false; 939} 940 941bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const { 942 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 943 if (I->Body) { 944 Definition = *I; 945 return true; 946 } 947 } 948 949 return false; 950} 951 952Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const { 953 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) { 954 if (I->Body) { 955 Definition = *I; 956 return I->Body.get(getASTContext().getExternalSource()); 957 } 958 } 959 960 return 0; 961} 962 963void FunctionDecl::setBody(Stmt *B) { 964 Body = B; 965 if (B) 966 EndRangeLoc = B->getLocEnd(); 967} 968 969bool FunctionDecl::isMain() const { 970 ASTContext &Context = getASTContext(); 971 return !Context.getLangOptions().Freestanding && 972 getDeclContext()->getRedeclContext()->isTranslationUnit() && 973 getIdentifier() && getIdentifier()->isStr("main"); 974} 975 976bool FunctionDecl::isExternC() const { 977 ASTContext &Context = getASTContext(); 978 // In C, any non-static, non-overloadable function has external 979 // linkage. 980 if (!Context.getLangOptions().CPlusPlus) 981 return getStorageClass() != SC_Static && !getAttr<OverloadableAttr>(); 982 983 for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit(); 984 DC = DC->getParent()) { 985 if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC)) { 986 if (Linkage->getLanguage() == LinkageSpecDecl::lang_c) 987 return getStorageClass() != SC_Static && 988 !getAttr<OverloadableAttr>(); 989 990 break; 991 } 992 993 if (DC->isRecord()) 994 break; 995 } 996 997 return false; 998} 999 1000bool FunctionDecl::isGlobal() const { 1001 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this)) 1002 return Method->isStatic(); 1003 1004 if (getStorageClass() == SC_Static) 1005 return false; 1006 1007 for (const DeclContext *DC = getDeclContext(); 1008 DC->isNamespace(); 1009 DC = DC->getParent()) { 1010 if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) { 1011 if (!Namespace->getDeclName()) 1012 return false; 1013 break; 1014 } 1015 } 1016 1017 return true; 1018} 1019 1020void 1021FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) { 1022 redeclarable_base::setPreviousDeclaration(PrevDecl); 1023 1024 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) { 1025 FunctionTemplateDecl *PrevFunTmpl 1026 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0; 1027 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"); 1028 FunTmpl->setPreviousDeclaration(PrevFunTmpl); 1029 } 1030} 1031 1032const FunctionDecl *FunctionDecl::getCanonicalDecl() const { 1033 return getFirstDeclaration(); 1034} 1035 1036FunctionDecl *FunctionDecl::getCanonicalDecl() { 1037 return getFirstDeclaration(); 1038} 1039 1040/// \brief Returns a value indicating whether this function 1041/// corresponds to a builtin function. 1042/// 1043/// The function corresponds to a built-in function if it is 1044/// declared at translation scope or within an extern "C" block and 1045/// its name matches with the name of a builtin. The returned value 1046/// will be 0 for functions that do not correspond to a builtin, a 1047/// value of type \c Builtin::ID if in the target-independent range 1048/// \c [1,Builtin::First), or a target-specific builtin value. 1049unsigned FunctionDecl::getBuiltinID() const { 1050 ASTContext &Context = getASTContext(); 1051 if (!getIdentifier() || !getIdentifier()->getBuiltinID()) 1052 return 0; 1053 1054 unsigned BuiltinID = getIdentifier()->getBuiltinID(); 1055 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) 1056 return BuiltinID; 1057 1058 // This function has the name of a known C library 1059 // function. Determine whether it actually refers to the C library 1060 // function or whether it just has the same name. 1061 1062 // If this is a static function, it's not a builtin. 1063 if (getStorageClass() == SC_Static) 1064 return 0; 1065 1066 // If this function is at translation-unit scope and we're not in 1067 // C++, it refers to the C library function. 1068 if (!Context.getLangOptions().CPlusPlus && 1069 getDeclContext()->isTranslationUnit()) 1070 return BuiltinID; 1071 1072 // If the function is in an extern "C" linkage specification and is 1073 // not marked "overloadable", it's the real function. 1074 if (isa<LinkageSpecDecl>(getDeclContext()) && 1075 cast<LinkageSpecDecl>(getDeclContext())->getLanguage() 1076 == LinkageSpecDecl::lang_c && 1077 !getAttr<OverloadableAttr>()) 1078 return BuiltinID; 1079 1080 // Not a builtin 1081 return 0; 1082} 1083 1084 1085/// getNumParams - Return the number of parameters this function must have 1086/// based on its FunctionType. This is the length of the PararmInfo array 1087/// after it has been created. 1088unsigned FunctionDecl::getNumParams() const { 1089 const FunctionType *FT = getType()->getAs<FunctionType>(); 1090 if (isa<FunctionNoProtoType>(FT)) 1091 return 0; 1092 return cast<FunctionProtoType>(FT)->getNumArgs(); 1093 1094} 1095 1096void FunctionDecl::setParams(ASTContext &C, 1097 ParmVarDecl **NewParamInfo, unsigned NumParams) { 1098 assert(ParamInfo == 0 && "Already has param info!"); 1099 assert(NumParams == getNumParams() && "Parameter count mismatch!"); 1100 1101 // Zero params -> null pointer. 1102 if (NumParams) { 1103 void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams); 1104 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1105 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1106 1107 // Update source range. The check below allows us to set EndRangeLoc before 1108 // setting the parameters. 1109 if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation()) 1110 EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd(); 1111 } 1112} 1113 1114/// getMinRequiredArguments - Returns the minimum number of arguments 1115/// needed to call this function. This may be fewer than the number of 1116/// function parameters, if some of the parameters have default 1117/// arguments (in C++). 1118unsigned FunctionDecl::getMinRequiredArguments() const { 1119 unsigned NumRequiredArgs = getNumParams(); 1120 while (NumRequiredArgs > 0 1121 && getParamDecl(NumRequiredArgs-1)->hasDefaultArg()) 1122 --NumRequiredArgs; 1123 1124 return NumRequiredArgs; 1125} 1126 1127bool FunctionDecl::isInlined() const { 1128 // FIXME: This is not enough. Consider: 1129 // 1130 // inline void f(); 1131 // void f() { } 1132 // 1133 // f is inlined, but does not have inline specified. 1134 // To fix this we should add an 'inline' flag to FunctionDecl. 1135 if (isInlineSpecified()) 1136 return true; 1137 1138 if (isa<CXXMethodDecl>(this)) { 1139 if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified()) 1140 return true; 1141 } 1142 1143 switch (getTemplateSpecializationKind()) { 1144 case TSK_Undeclared: 1145 case TSK_ExplicitSpecialization: 1146 return false; 1147 1148 case TSK_ImplicitInstantiation: 1149 case TSK_ExplicitInstantiationDeclaration: 1150 case TSK_ExplicitInstantiationDefinition: 1151 // Handle below. 1152 break; 1153 } 1154 1155 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1156 bool HasPattern = false; 1157 if (PatternDecl) 1158 HasPattern = PatternDecl->hasBody(PatternDecl); 1159 1160 if (HasPattern && PatternDecl) 1161 return PatternDecl->isInlined(); 1162 1163 return false; 1164} 1165 1166/// \brief For an inline function definition in C or C++, determine whether the 1167/// definition will be externally visible. 1168/// 1169/// Inline function definitions are always available for inlining optimizations. 1170/// However, depending on the language dialect, declaration specifiers, and 1171/// attributes, the definition of an inline function may or may not be 1172/// "externally" visible to other translation units in the program. 1173/// 1174/// In C99, inline definitions are not externally visible by default. However, 1175/// if even one of the global-scope declarations is marked "extern inline", the 1176/// inline definition becomes externally visible (C99 6.7.4p6). 1177/// 1178/// In GNU89 mode, or if the gnu_inline attribute is attached to the function 1179/// definition, we use the GNU semantics for inline, which are nearly the 1180/// opposite of C99 semantics. In particular, "inline" by itself will create 1181/// an externally visible symbol, but "extern inline" will not create an 1182/// externally visible symbol. 1183bool FunctionDecl::isInlineDefinitionExternallyVisible() const { 1184 assert(isThisDeclarationADefinition() && "Must have the function definition"); 1185 assert(isInlined() && "Function must be inline"); 1186 ASTContext &Context = getASTContext(); 1187 1188 if (!Context.getLangOptions().C99 || hasAttr<GNUInlineAttr>()) { 1189 // GNU inline semantics. Based on a number of examples, we came up with the 1190 // following heuristic: if the "inline" keyword is present on a 1191 // declaration of the function but "extern" is not present on that 1192 // declaration, then the symbol is externally visible. Otherwise, the GNU 1193 // "extern inline" semantics applies and the symbol is not externally 1194 // visible. 1195 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1196 Redecl != RedeclEnd; 1197 ++Redecl) { 1198 if (Redecl->isInlineSpecified() && Redecl->getStorageClass() != SC_Extern) 1199 return true; 1200 } 1201 1202 // GNU "extern inline" semantics; no externally visible symbol. 1203 return false; 1204 } 1205 1206 // C99 6.7.4p6: 1207 // [...] If all of the file scope declarations for a function in a 1208 // translation unit include the inline function specifier without extern, 1209 // then the definition in that translation unit is an inline definition. 1210 for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end(); 1211 Redecl != RedeclEnd; 1212 ++Redecl) { 1213 // Only consider file-scope declarations in this test. 1214 if (!Redecl->getLexicalDeclContext()->isTranslationUnit()) 1215 continue; 1216 1217 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern) 1218 return true; // Not an inline definition 1219 } 1220 1221 // C99 6.7.4p6: 1222 // An inline definition does not provide an external definition for the 1223 // function, and does not forbid an external definition in another 1224 // translation unit. 1225 return false; 1226} 1227 1228/// getOverloadedOperator - Which C++ overloaded operator this 1229/// function represents, if any. 1230OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const { 1231 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName) 1232 return getDeclName().getCXXOverloadedOperator(); 1233 else 1234 return OO_None; 1235} 1236 1237/// getLiteralIdentifier - The literal suffix identifier this function 1238/// represents, if any. 1239const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const { 1240 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName) 1241 return getDeclName().getCXXLiteralIdentifier(); 1242 else 1243 return 0; 1244} 1245 1246FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const { 1247 if (TemplateOrSpecialization.isNull()) 1248 return TK_NonTemplate; 1249 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>()) 1250 return TK_FunctionTemplate; 1251 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>()) 1252 return TK_MemberSpecialization; 1253 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>()) 1254 return TK_FunctionTemplateSpecialization; 1255 if (TemplateOrSpecialization.is 1256 <DependentFunctionTemplateSpecializationInfo*>()) 1257 return TK_DependentFunctionTemplateSpecialization; 1258 1259 assert(false && "Did we miss a TemplateOrSpecialization type?"); 1260 return TK_NonTemplate; 1261} 1262 1263FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const { 1264 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) 1265 return cast<FunctionDecl>(Info->getInstantiatedFrom()); 1266 1267 return 0; 1268} 1269 1270MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const { 1271 return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1272} 1273 1274void 1275FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C, 1276 FunctionDecl *FD, 1277 TemplateSpecializationKind TSK) { 1278 assert(TemplateOrSpecialization.isNull() && 1279 "Member function is already a specialization"); 1280 MemberSpecializationInfo *Info 1281 = new (C) MemberSpecializationInfo(FD, TSK); 1282 TemplateOrSpecialization = Info; 1283} 1284 1285bool FunctionDecl::isImplicitlyInstantiable() const { 1286 // If the function is invalid, it can't be implicitly instantiated. 1287 if (isInvalidDecl()) 1288 return false; 1289 1290 switch (getTemplateSpecializationKind()) { 1291 case TSK_Undeclared: 1292 case TSK_ExplicitSpecialization: 1293 case TSK_ExplicitInstantiationDefinition: 1294 return false; 1295 1296 case TSK_ImplicitInstantiation: 1297 return true; 1298 1299 case TSK_ExplicitInstantiationDeclaration: 1300 // Handled below. 1301 break; 1302 } 1303 1304 // Find the actual template from which we will instantiate. 1305 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern(); 1306 bool HasPattern = false; 1307 if (PatternDecl) 1308 HasPattern = PatternDecl->hasBody(PatternDecl); 1309 1310 // C++0x [temp.explicit]p9: 1311 // Except for inline functions, other explicit instantiation declarations 1312 // have the effect of suppressing the implicit instantiation of the entity 1313 // to which they refer. 1314 if (!HasPattern || !PatternDecl) 1315 return true; 1316 1317 return PatternDecl->isInlined(); 1318} 1319 1320FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const { 1321 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) { 1322 while (Primary->getInstantiatedFromMemberTemplate()) { 1323 // If we have hit a point where the user provided a specialization of 1324 // this template, we're done looking. 1325 if (Primary->isMemberSpecialization()) 1326 break; 1327 1328 Primary = Primary->getInstantiatedFromMemberTemplate(); 1329 } 1330 1331 return Primary->getTemplatedDecl(); 1332 } 1333 1334 return getInstantiatedFromMemberFunction(); 1335} 1336 1337FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const { 1338 if (FunctionTemplateSpecializationInfo *Info 1339 = TemplateOrSpecialization 1340 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1341 return Info->Template.getPointer(); 1342 } 1343 return 0; 1344} 1345 1346const TemplateArgumentList * 1347FunctionDecl::getTemplateSpecializationArgs() const { 1348 if (FunctionTemplateSpecializationInfo *Info 1349 = TemplateOrSpecialization 1350 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1351 return Info->TemplateArguments; 1352 } 1353 return 0; 1354} 1355 1356const TemplateArgumentListInfo * 1357FunctionDecl::getTemplateSpecializationArgsAsWritten() const { 1358 if (FunctionTemplateSpecializationInfo *Info 1359 = TemplateOrSpecialization 1360 .dyn_cast<FunctionTemplateSpecializationInfo*>()) { 1361 return Info->TemplateArgumentsAsWritten; 1362 } 1363 return 0; 1364} 1365 1366void 1367FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C, 1368 FunctionTemplateDecl *Template, 1369 const TemplateArgumentList *TemplateArgs, 1370 void *InsertPos, 1371 TemplateSpecializationKind TSK, 1372 const TemplateArgumentListInfo *TemplateArgsAsWritten, 1373 SourceLocation PointOfInstantiation) { 1374 assert(TSK != TSK_Undeclared && 1375 "Must specify the type of function template specialization"); 1376 FunctionTemplateSpecializationInfo *Info 1377 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1378 if (!Info) 1379 Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK, 1380 TemplateArgs, 1381 TemplateArgsAsWritten, 1382 PointOfInstantiation); 1383 TemplateOrSpecialization = Info; 1384 1385 // Insert this function template specialization into the set of known 1386 // function template specializations. 1387 if (InsertPos) 1388 Template->getSpecializations().InsertNode(Info, InsertPos); 1389 else { 1390 // Try to insert the new node. If there is an existing node, leave it, the 1391 // set will contain the canonical decls while 1392 // FunctionTemplateDecl::findSpecialization will return 1393 // the most recent redeclarations. 1394 FunctionTemplateSpecializationInfo *Existing 1395 = Template->getSpecializations().GetOrInsertNode(Info); 1396 (void)Existing; 1397 assert((!Existing || Existing->Function->isCanonicalDecl()) && 1398 "Set is supposed to only contain canonical decls"); 1399 } 1400} 1401 1402void 1403FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context, 1404 const UnresolvedSetImpl &Templates, 1405 const TemplateArgumentListInfo &TemplateArgs) { 1406 assert(TemplateOrSpecialization.isNull()); 1407 size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo); 1408 Size += Templates.size() * sizeof(FunctionTemplateDecl*); 1409 Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc); 1410 void *Buffer = Context.Allocate(Size); 1411 DependentFunctionTemplateSpecializationInfo *Info = 1412 new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates, 1413 TemplateArgs); 1414 TemplateOrSpecialization = Info; 1415} 1416 1417DependentFunctionTemplateSpecializationInfo:: 1418DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts, 1419 const TemplateArgumentListInfo &TArgs) 1420 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) { 1421 1422 d.NumTemplates = Ts.size(); 1423 d.NumArgs = TArgs.size(); 1424 1425 FunctionTemplateDecl **TsArray = 1426 const_cast<FunctionTemplateDecl**>(getTemplates()); 1427 for (unsigned I = 0, E = Ts.size(); I != E; ++I) 1428 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl()); 1429 1430 TemplateArgumentLoc *ArgsArray = 1431 const_cast<TemplateArgumentLoc*>(getTemplateArgs()); 1432 for (unsigned I = 0, E = TArgs.size(); I != E; ++I) 1433 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]); 1434} 1435 1436TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const { 1437 // For a function template specialization, query the specialization 1438 // information object. 1439 FunctionTemplateSpecializationInfo *FTSInfo 1440 = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>(); 1441 if (FTSInfo) 1442 return FTSInfo->getTemplateSpecializationKind(); 1443 1444 MemberSpecializationInfo *MSInfo 1445 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>(); 1446 if (MSInfo) 1447 return MSInfo->getTemplateSpecializationKind(); 1448 1449 return TSK_Undeclared; 1450} 1451 1452void 1453FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK, 1454 SourceLocation PointOfInstantiation) { 1455 if (FunctionTemplateSpecializationInfo *FTSInfo 1456 = TemplateOrSpecialization.dyn_cast< 1457 FunctionTemplateSpecializationInfo*>()) { 1458 FTSInfo->setTemplateSpecializationKind(TSK); 1459 if (TSK != TSK_ExplicitSpecialization && 1460 PointOfInstantiation.isValid() && 1461 FTSInfo->getPointOfInstantiation().isInvalid()) 1462 FTSInfo->setPointOfInstantiation(PointOfInstantiation); 1463 } else if (MemberSpecializationInfo *MSInfo 1464 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) { 1465 MSInfo->setTemplateSpecializationKind(TSK); 1466 if (TSK != TSK_ExplicitSpecialization && 1467 PointOfInstantiation.isValid() && 1468 MSInfo->getPointOfInstantiation().isInvalid()) 1469 MSInfo->setPointOfInstantiation(PointOfInstantiation); 1470 } else 1471 assert(false && "Function cannot have a template specialization kind"); 1472} 1473 1474SourceLocation FunctionDecl::getPointOfInstantiation() const { 1475 if (FunctionTemplateSpecializationInfo *FTSInfo 1476 = TemplateOrSpecialization.dyn_cast< 1477 FunctionTemplateSpecializationInfo*>()) 1478 return FTSInfo->getPointOfInstantiation(); 1479 else if (MemberSpecializationInfo *MSInfo 1480 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) 1481 return MSInfo->getPointOfInstantiation(); 1482 1483 return SourceLocation(); 1484} 1485 1486bool FunctionDecl::isOutOfLine() const { 1487 if (Decl::isOutOfLine()) 1488 return true; 1489 1490 // If this function was instantiated from a member function of a 1491 // class template, check whether that member function was defined out-of-line. 1492 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) { 1493 const FunctionDecl *Definition; 1494 if (FD->hasBody(Definition)) 1495 return Definition->isOutOfLine(); 1496 } 1497 1498 // If this function was instantiated from a function template, 1499 // check whether that function template was defined out-of-line. 1500 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) { 1501 const FunctionDecl *Definition; 1502 if (FunTmpl->getTemplatedDecl()->hasBody(Definition)) 1503 return Definition->isOutOfLine(); 1504 } 1505 1506 return false; 1507} 1508 1509//===----------------------------------------------------------------------===// 1510// FieldDecl Implementation 1511//===----------------------------------------------------------------------===// 1512 1513FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 1514 IdentifierInfo *Id, QualType T, 1515 TypeSourceInfo *TInfo, Expr *BW, bool Mutable) { 1516 return new (C) FieldDecl(Decl::Field, DC, L, Id, T, TInfo, BW, Mutable); 1517} 1518 1519bool FieldDecl::isAnonymousStructOrUnion() const { 1520 if (!isImplicit() || getDeclName()) 1521 return false; 1522 1523 if (const RecordType *Record = getType()->getAs<RecordType>()) 1524 return Record->getDecl()->isAnonymousStructOrUnion(); 1525 1526 return false; 1527} 1528 1529//===----------------------------------------------------------------------===// 1530// TagDecl Implementation 1531//===----------------------------------------------------------------------===// 1532 1533SourceLocation TagDecl::getOuterLocStart() const { 1534 return getTemplateOrInnerLocStart(this); 1535} 1536 1537SourceRange TagDecl::getSourceRange() const { 1538 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation(); 1539 return SourceRange(getOuterLocStart(), E); 1540} 1541 1542TagDecl* TagDecl::getCanonicalDecl() { 1543 return getFirstDeclaration(); 1544} 1545 1546void TagDecl::setTypedefForAnonDecl(TypedefDecl *TDD) { 1547 TypedefDeclOrQualifier = TDD; 1548 if (TypeForDecl) 1549 TypeForDecl->ClearLinkageCache(); 1550} 1551 1552void TagDecl::startDefinition() { 1553 IsBeingDefined = true; 1554 1555 if (isa<CXXRecordDecl>(this)) { 1556 CXXRecordDecl *D = cast<CXXRecordDecl>(this); 1557 struct CXXRecordDecl::DefinitionData *Data = 1558 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D); 1559 for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) 1560 cast<CXXRecordDecl>(*I)->DefinitionData = Data; 1561 } 1562} 1563 1564void TagDecl::completeDefinition() { 1565 assert((!isa<CXXRecordDecl>(this) || 1566 cast<CXXRecordDecl>(this)->hasDefinition()) && 1567 "definition completed but not started"); 1568 1569 IsDefinition = true; 1570 IsBeingDefined = false; 1571} 1572 1573TagDecl* TagDecl::getDefinition() const { 1574 if (isDefinition()) 1575 return const_cast<TagDecl *>(this); 1576 1577 for (redecl_iterator R = redecls_begin(), REnd = redecls_end(); 1578 R != REnd; ++R) 1579 if (R->isDefinition()) 1580 return *R; 1581 1582 return 0; 1583} 1584 1585void TagDecl::setQualifierInfo(NestedNameSpecifier *Qualifier, 1586 SourceRange QualifierRange) { 1587 if (Qualifier) { 1588 // Make sure the extended qualifier info is allocated. 1589 if (!hasExtInfo()) 1590 TypedefDeclOrQualifier = new (getASTContext()) ExtInfo; 1591 // Set qualifier info. 1592 getExtInfo()->NNS = Qualifier; 1593 getExtInfo()->NNSRange = QualifierRange; 1594 } 1595 else { 1596 // Here Qualifier == 0, i.e., we are removing the qualifier (if any). 1597 assert(QualifierRange.isInvalid()); 1598 if (hasExtInfo()) { 1599 getASTContext().Deallocate(getExtInfo()); 1600 TypedefDeclOrQualifier = (TypedefDecl*) 0; 1601 } 1602 } 1603} 1604 1605//===----------------------------------------------------------------------===// 1606// EnumDecl Implementation 1607//===----------------------------------------------------------------------===// 1608 1609EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L, 1610 IdentifierInfo *Id, SourceLocation TKL, 1611 EnumDecl *PrevDecl) { 1612 EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL); 1613 C.getTypeDeclType(Enum, PrevDecl); 1614 return Enum; 1615} 1616 1617EnumDecl *EnumDecl::Create(ASTContext &C, EmptyShell Empty) { 1618 return new (C) EnumDecl(0, SourceLocation(), 0, 0, SourceLocation()); 1619} 1620 1621void EnumDecl::completeDefinition(QualType NewType, 1622 QualType NewPromotionType, 1623 unsigned NumPositiveBits, 1624 unsigned NumNegativeBits) { 1625 assert(!isDefinition() && "Cannot redefine enums!"); 1626 IntegerType = NewType; 1627 PromotionType = NewPromotionType; 1628 setNumPositiveBits(NumPositiveBits); 1629 setNumNegativeBits(NumNegativeBits); 1630 TagDecl::completeDefinition(); 1631} 1632 1633//===----------------------------------------------------------------------===// 1634// RecordDecl Implementation 1635//===----------------------------------------------------------------------===// 1636 1637RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L, 1638 IdentifierInfo *Id, RecordDecl *PrevDecl, 1639 SourceLocation TKL) 1640 : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) { 1641 HasFlexibleArrayMember = false; 1642 AnonymousStructOrUnion = false; 1643 HasObjectMember = false; 1644 assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!"); 1645} 1646 1647RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC, 1648 SourceLocation L, IdentifierInfo *Id, 1649 SourceLocation TKL, RecordDecl* PrevDecl) { 1650 1651 RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL); 1652 C.getTypeDeclType(R, PrevDecl); 1653 return R; 1654} 1655 1656RecordDecl *RecordDecl::Create(ASTContext &C, EmptyShell Empty) { 1657 return new (C) RecordDecl(Record, TTK_Struct, 0, SourceLocation(), 0, 0, 1658 SourceLocation()); 1659} 1660 1661bool RecordDecl::isInjectedClassName() const { 1662 return isImplicit() && getDeclName() && getDeclContext()->isRecord() && 1663 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName(); 1664} 1665 1666/// completeDefinition - Notes that the definition of this type is now 1667/// complete. 1668void RecordDecl::completeDefinition() { 1669 assert(!isDefinition() && "Cannot redefine record!"); 1670 TagDecl::completeDefinition(); 1671} 1672 1673ValueDecl *RecordDecl::getAnonymousStructOrUnionObject() { 1674 // Force the decl chain to come into existence properly. 1675 if (!getNextDeclInContext()) getParent()->decls_begin(); 1676 1677 assert(isAnonymousStructOrUnion()); 1678 ValueDecl *D = cast<ValueDecl>(getNextDeclInContext()); 1679 assert(D->getType()->isRecordType()); 1680 assert(D->getType()->getAs<RecordType>()->getDecl() == this); 1681 return D; 1682} 1683 1684//===----------------------------------------------------------------------===// 1685// BlockDecl Implementation 1686//===----------------------------------------------------------------------===// 1687 1688void BlockDecl::setParams(ParmVarDecl **NewParamInfo, 1689 unsigned NParms) { 1690 assert(ParamInfo == 0 && "Already has param info!"); 1691 1692 // Zero params -> null pointer. 1693 if (NParms) { 1694 NumParams = NParms; 1695 void *Mem = getASTContext().Allocate(sizeof(ParmVarDecl*)*NumParams); 1696 ParamInfo = new (Mem) ParmVarDecl*[NumParams]; 1697 memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams); 1698 } 1699} 1700 1701unsigned BlockDecl::getNumParams() const { 1702 return NumParams; 1703} 1704 1705 1706//===----------------------------------------------------------------------===// 1707// Other Decl Allocation/Deallocation Method Implementations 1708//===----------------------------------------------------------------------===// 1709 1710TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) { 1711 return new (C) TranslationUnitDecl(C); 1712} 1713 1714NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC, 1715 SourceLocation L, IdentifierInfo *Id) { 1716 return new (C) NamespaceDecl(DC, L, Id); 1717} 1718 1719ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC, 1720 SourceLocation L, IdentifierInfo *Id, QualType T) { 1721 return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T); 1722} 1723 1724FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC, 1725 const DeclarationNameInfo &NameInfo, 1726 QualType T, TypeSourceInfo *TInfo, 1727 StorageClass S, StorageClass SCAsWritten, 1728 bool isInline, bool hasWrittenPrototype) { 1729 FunctionDecl *New = new (C) FunctionDecl(Function, DC, NameInfo, T, TInfo, 1730 S, SCAsWritten, isInline); 1731 New->HasWrittenPrototype = hasWrittenPrototype; 1732 return New; 1733} 1734 1735BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) { 1736 return new (C) BlockDecl(DC, L); 1737} 1738 1739EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD, 1740 SourceLocation L, 1741 IdentifierInfo *Id, QualType T, 1742 Expr *E, const llvm::APSInt &V) { 1743 return new (C) EnumConstantDecl(CD, L, Id, T, E, V); 1744} 1745 1746SourceRange EnumConstantDecl::getSourceRange() const { 1747 SourceLocation End = getLocation(); 1748 if (Init) 1749 End = Init->getLocEnd(); 1750 return SourceRange(getLocation(), End); 1751} 1752 1753TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC, 1754 SourceLocation L, IdentifierInfo *Id, 1755 TypeSourceInfo *TInfo) { 1756 return new (C) TypedefDecl(DC, L, Id, TInfo); 1757} 1758 1759FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC, 1760 SourceLocation L, 1761 StringLiteral *Str) { 1762 return new (C) FileScopeAsmDecl(DC, L, Str); 1763} 1764