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