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