Decl.cpp revision 663b5a0be7261c29bc4c526a71cffcfa02d4153e
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/PrettyPrinter.h"
23#include "clang/Basic/Builtins.h"
24#include "clang/Basic/IdentifierTable.h"
25#include "clang/Parse/DeclSpec.h"
26#include "llvm/Support/ErrorHandling.h"
27#include <vector>
28
29using namespace clang;
30
31void Attr::Destroy(ASTContext &C) {
32  if (Next) {
33    Next->Destroy(C);
34    Next = 0;
35  }
36  this->~Attr();
37  C.Deallocate((void*)this);
38}
39
40/// \brief Return the TypeLoc wrapper for the type source info.
41TypeLoc DeclaratorInfo::getTypeLoc() const {
42  return TypeLoc(Ty, (void*)(this + 1));
43}
44
45//===----------------------------------------------------------------------===//
46// Decl Allocation/Deallocation Method Implementations
47//===----------------------------------------------------------------------===//
48
49
50TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
51  return new (C) TranslationUnitDecl(C);
52}
53
54NamespaceDecl *NamespaceDecl::Create(ASTContext &C, DeclContext *DC,
55                                     SourceLocation L, IdentifierInfo *Id) {
56  return new (C) NamespaceDecl(DC, L, Id);
57}
58
59void NamespaceDecl::Destroy(ASTContext& C) {
60  // NamespaceDecl uses "NextDeclarator" to chain namespace declarations
61  // together. They are all top-level Decls.
62
63  this->~NamespaceDecl();
64  C.Deallocate((void *)this);
65}
66
67
68ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
69    SourceLocation L, IdentifierInfo *Id, QualType T) {
70  return new (C) ImplicitParamDecl(ImplicitParam, DC, L, Id, T);
71}
72
73const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
74  switch (SC) {
75  case VarDecl::None:          break;
76  case VarDecl::Auto:          return "auto"; break;
77  case VarDecl::Extern:        return "extern"; break;
78  case VarDecl::PrivateExtern: return "__private_extern__"; break;
79  case VarDecl::Register:      return "register"; break;
80  case VarDecl::Static:        return "static"; break;
81  }
82
83  assert(0 && "Invalid storage class");
84  return 0;
85}
86
87ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
88                                 SourceLocation L, IdentifierInfo *Id,
89                                 QualType T, DeclaratorInfo *DInfo,
90                                 StorageClass S, Expr *DefArg) {
91  return new (C) ParmVarDecl(ParmVar, DC, L, Id, T, DInfo, S, DefArg);
92}
93
94QualType ParmVarDecl::getOriginalType() const {
95  if (const OriginalParmVarDecl *PVD =
96      dyn_cast<OriginalParmVarDecl>(this))
97    return PVD->OriginalType;
98  return getType();
99}
100
101SourceRange ParmVarDecl::getDefaultArgRange() const {
102  if (const Expr *E = getInit())
103    return E->getSourceRange();
104
105  if (const Expr *E = getUninstantiatedDefaultArg())
106    return E->getSourceRange();
107
108  return SourceRange();
109}
110
111void VarDecl::setInit(ASTContext &C, Expr *I) {
112  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
113    Eval->~EvaluatedStmt();
114    C.Deallocate(Eval);
115  }
116
117  Init = I;
118}
119
120bool VarDecl::isExternC() const {
121  ASTContext &Context = getASTContext();
122  if (!Context.getLangOptions().CPlusPlus)
123    return (getDeclContext()->isTranslationUnit() &&
124            getStorageClass() != Static) ||
125      (getDeclContext()->isFunctionOrMethod() && hasExternalStorage());
126
127  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
128       DC = DC->getParent()) {
129    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
130      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
131        return getStorageClass() != Static;
132
133      break;
134    }
135
136    if (DC->isFunctionOrMethod())
137      return false;
138  }
139
140  return false;
141}
142
143OriginalParmVarDecl *OriginalParmVarDecl::Create(
144                                 ASTContext &C, DeclContext *DC,
145                                 SourceLocation L, IdentifierInfo *Id,
146                                 QualType T, DeclaratorInfo *DInfo,
147                                 QualType OT, StorageClass S, Expr *DefArg) {
148  return new (C) OriginalParmVarDecl(DC, L, Id, T, DInfo, OT, S, DefArg);
149}
150
151FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
152                                   SourceLocation L,
153                                   DeclarationName N, QualType T,
154                                   DeclaratorInfo *DInfo,
155                                   StorageClass S, bool isInline,
156                                   bool hasWrittenPrototype) {
157  FunctionDecl *New
158    = new (C) FunctionDecl(Function, DC, L, N, T, DInfo, S, isInline);
159  New->HasWrittenPrototype = hasWrittenPrototype;
160  return New;
161}
162
163BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
164  return new (C) BlockDecl(DC, L);
165}
166
167FieldDecl *FieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
168                             IdentifierInfo *Id, QualType T,
169                             DeclaratorInfo *DInfo, Expr *BW, bool Mutable) {
170  return new (C) FieldDecl(Decl::Field, DC, L, Id, T, DInfo, BW, Mutable);
171}
172
173bool FieldDecl::isAnonymousStructOrUnion() const {
174  if (!isImplicit() || getDeclName())
175    return false;
176
177  if (const RecordType *Record = getType()->getAs<RecordType>())
178    return Record->getDecl()->isAnonymousStructOrUnion();
179
180  return false;
181}
182
183EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
184                                           SourceLocation L,
185                                           IdentifierInfo *Id, QualType T,
186                                           Expr *E, const llvm::APSInt &V) {
187  return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
188}
189
190void EnumConstantDecl::Destroy(ASTContext& C) {
191  if (Init) Init->Destroy(C);
192  Decl::Destroy(C);
193}
194
195TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
196                                 SourceLocation L,
197                                 IdentifierInfo *Id, QualType T) {
198  return new (C) TypedefDecl(DC, L, Id, T);
199}
200
201EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
202                           IdentifierInfo *Id, SourceLocation TKL,
203                           EnumDecl *PrevDecl) {
204  EnumDecl *Enum = new (C) EnumDecl(DC, L, Id, PrevDecl, TKL);
205  C.getTypeDeclType(Enum, PrevDecl);
206  return Enum;
207}
208
209void EnumDecl::Destroy(ASTContext& C) {
210  Decl::Destroy(C);
211}
212
213void EnumDecl::completeDefinition(ASTContext &C, QualType NewType) {
214  assert(!isDefinition() && "Cannot redefine enums!");
215  IntegerType = NewType;
216  TagDecl::completeDefinition();
217}
218
219FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
220                                           SourceLocation L,
221                                           StringLiteral *Str) {
222  return new (C) FileScopeAsmDecl(DC, L, Str);
223}
224
225//===----------------------------------------------------------------------===//
226// NamedDecl Implementation
227//===----------------------------------------------------------------------===//
228
229std::string NamedDecl::getQualifiedNameAsString() const {
230  return getQualifiedNameAsString(getASTContext().getLangOptions());
231}
232
233std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
234  std::vector<std::string> Names;
235  std::string QualName;
236  const DeclContext *Ctx = getDeclContext();
237
238  if (Ctx->isFunctionOrMethod())
239    return getNameAsString();
240
241  while (Ctx) {
242    if (Ctx->isFunctionOrMethod())
243      // FIXME: That probably will happen, when D was member of local
244      // scope class/struct/union. How do we handle this case?
245      break;
246
247    if (const ClassTemplateSpecializationDecl *Spec
248          = dyn_cast<ClassTemplateSpecializationDecl>(Ctx)) {
249      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
250      std::string TemplateArgsStr
251        = TemplateSpecializationType::PrintTemplateArgumentList(
252                                           TemplateArgs.getFlatArgumentList(),
253                                           TemplateArgs.flat_size(),
254                                           P);
255      Names.push_back(Spec->getIdentifier()->getName() + TemplateArgsStr);
256    } else if (const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx))
257      Names.push_back(ND->getNameAsString());
258    else
259      break;
260
261    Ctx = Ctx->getParent();
262  }
263
264  std::vector<std::string>::reverse_iterator
265    I = Names.rbegin(),
266    End = Names.rend();
267
268  for (; I!=End; ++I)
269    QualName += *I + "::";
270
271  QualName += getNameAsString();
272
273  return QualName;
274}
275
276bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
277  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
278
279  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
280  // We want to keep it, unless it nominates same namespace.
281  if (getKind() == Decl::UsingDirective) {
282    return cast<UsingDirectiveDecl>(this)->getNominatedNamespace() ==
283           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace();
284  }
285
286  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
287    // For function declarations, we keep track of redeclarations.
288    return FD->getPreviousDeclaration() == OldD;
289
290  // For function templates, the underlying function declarations are linked.
291  if (const FunctionTemplateDecl *FunctionTemplate
292        = dyn_cast<FunctionTemplateDecl>(this))
293    if (const FunctionTemplateDecl *OldFunctionTemplate
294          = dyn_cast<FunctionTemplateDecl>(OldD))
295      return FunctionTemplate->getTemplatedDecl()
296               ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
297
298  // For method declarations, we keep track of redeclarations.
299  if (isa<ObjCMethodDecl>(this))
300    return false;
301
302  if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
303    return true;
304
305  // For non-function declarations, if the declarations are of the
306  // same kind then this must be a redeclaration, or semantic analysis
307  // would not have given us the new declaration.
308  return this->getKind() == OldD->getKind();
309}
310
311bool NamedDecl::hasLinkage() const {
312  if (const VarDecl *VD = dyn_cast<VarDecl>(this))
313    return VD->hasExternalStorage() || VD->isFileVarDecl();
314
315  if (isa<FunctionDecl>(this) && !isa<CXXMethodDecl>(this))
316    return true;
317
318  return false;
319}
320
321NamedDecl *NamedDecl::getUnderlyingDecl() {
322  NamedDecl *ND = this;
323  while (true) {
324    if (UsingDecl *UD = dyn_cast<UsingDecl>(ND))
325      ND = UD->getTargetDecl();
326    else if (ObjCCompatibleAliasDecl *AD
327              = dyn_cast<ObjCCompatibleAliasDecl>(ND))
328      return AD->getClassInterface();
329    else
330      return ND;
331  }
332}
333
334//===----------------------------------------------------------------------===//
335// DeclaratorDecl Implementation
336//===----------------------------------------------------------------------===//
337
338SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
339  if (DeclInfo)
340    return DeclInfo->getTypeLoc().getTypeSpecRange().getBegin();
341  return SourceLocation();
342}
343
344//===----------------------------------------------------------------------===//
345// VarDecl Implementation
346//===----------------------------------------------------------------------===//
347
348VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
349                         IdentifierInfo *Id, QualType T, DeclaratorInfo *DInfo,
350                         StorageClass S) {
351  return new (C) VarDecl(Var, DC, L, Id, T, DInfo, S);
352}
353
354void VarDecl::Destroy(ASTContext& C) {
355  Expr *Init = getInit();
356  if (Init) {
357    Init->Destroy(C);
358    if (EvaluatedStmt *Eval = this->Init.dyn_cast<EvaluatedStmt *>()) {
359      Eval->~EvaluatedStmt();
360      C.Deallocate(Eval);
361    }
362  }
363  this->~VarDecl();
364  C.Deallocate((void *)this);
365}
366
367VarDecl::~VarDecl() {
368}
369
370SourceRange VarDecl::getSourceRange() const {
371  if (getInit())
372    return SourceRange(getLocation(), getInit()->getLocEnd());
373  return SourceRange(getLocation(), getLocation());
374}
375
376VarDecl *VarDecl::getInstantiatedFromStaticDataMember() {
377  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
378    return cast<VarDecl>(MSI->getInstantiatedFrom());
379
380  return 0;
381}
382
383TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
384  if (MemberSpecializationInfo *MSI
385        = getASTContext().getInstantiatedFromStaticDataMember(this))
386    return MSI->getTemplateSpecializationKind();
387
388  return TSK_Undeclared;
389}
390
391MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() {
392  return getASTContext().getInstantiatedFromStaticDataMember(this);
393}
394
395void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
396  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
397  assert(MSI && "Not an instantiated static data member?");
398  MSI->setTemplateSpecializationKind(TSK);
399}
400
401bool VarDecl::isTentativeDefinition(ASTContext &Context) const {
402  if (!isFileVarDecl() || Context.getLangOptions().CPlusPlus)
403    return false;
404
405  const VarDecl *Def = 0;
406  return (!getDefinition(Def) &&
407          (getStorageClass() == None || getStorageClass() == Static));
408}
409
410const Expr *VarDecl::getDefinition(const VarDecl *&Def) const {
411  redecl_iterator I = redecls_begin(), E = redecls_end();
412  while (I != E && !I->getInit())
413    ++I;
414
415  if (I != E) {
416    Def = *I;
417    return I->getInit();
418  }
419  return 0;
420}
421
422VarDecl *VarDecl::getCanonicalDecl() {
423  return getFirstDeclaration();
424}
425
426//===----------------------------------------------------------------------===//
427// FunctionDecl Implementation
428//===----------------------------------------------------------------------===//
429
430void FunctionDecl::Destroy(ASTContext& C) {
431  if (Body && Body.isOffset())
432    Body.get(C.getExternalSource())->Destroy(C);
433
434  for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I)
435    (*I)->Destroy(C);
436
437  FunctionTemplateSpecializationInfo *FTSInfo
438    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
439  if (FTSInfo)
440    C.Deallocate(FTSInfo);
441
442  MemberSpecializationInfo *MSInfo
443    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
444  if (MSInfo)
445    C.Deallocate(MSInfo);
446
447  C.Deallocate(ParamInfo);
448
449  Decl::Destroy(C);
450}
451
452void FunctionDecl::getNameForDiagnostic(std::string &S,
453                                        const PrintingPolicy &Policy,
454                                        bool Qualified) const {
455  NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
456  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
457  if (TemplateArgs)
458    S += TemplateSpecializationType::PrintTemplateArgumentList(
459                                         TemplateArgs->getFlatArgumentList(),
460                                         TemplateArgs->flat_size(),
461                                                               Policy);
462
463}
464
465Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
466  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
467    if (I->Body) {
468      Definition = *I;
469      return I->Body.get(getASTContext().getExternalSource());
470    }
471  }
472
473  return 0;
474}
475
476void FunctionDecl::setBody(Stmt *B) {
477  Body = B;
478  if (B)
479    EndRangeLoc = B->getLocEnd();
480}
481
482bool FunctionDecl::isMain() const {
483  ASTContext &Context = getASTContext();
484  return !Context.getLangOptions().Freestanding &&
485    getDeclContext()->getLookupContext()->isTranslationUnit() &&
486    getIdentifier() && getIdentifier()->isStr("main");
487}
488
489bool FunctionDecl::isExternC() const {
490  ASTContext &Context = getASTContext();
491  // In C, any non-static, non-overloadable function has external
492  // linkage.
493  if (!Context.getLangOptions().CPlusPlus)
494    return getStorageClass() != Static && !getAttr<OverloadableAttr>();
495
496  for (const DeclContext *DC = getDeclContext(); !DC->isTranslationUnit();
497       DC = DC->getParent()) {
498    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))  {
499      if (Linkage->getLanguage() == LinkageSpecDecl::lang_c)
500        return getStorageClass() != Static &&
501               !getAttr<OverloadableAttr>();
502
503      break;
504    }
505  }
506
507  return false;
508}
509
510bool FunctionDecl::isGlobal() const {
511  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
512    return Method->isStatic();
513
514  if (getStorageClass() == Static)
515    return false;
516
517  for (const DeclContext *DC = getDeclContext();
518       DC->isNamespace();
519       DC = DC->getParent()) {
520    if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
521      if (!Namespace->getDeclName())
522        return false;
523      break;
524    }
525  }
526
527  return true;
528}
529
530/// \brief Returns a value indicating whether this function
531/// corresponds to a builtin function.
532///
533/// The function corresponds to a built-in function if it is
534/// declared at translation scope or within an extern "C" block and
535/// its name matches with the name of a builtin. The returned value
536/// will be 0 for functions that do not correspond to a builtin, a
537/// value of type \c Builtin::ID if in the target-independent range
538/// \c [1,Builtin::First), or a target-specific builtin value.
539unsigned FunctionDecl::getBuiltinID() const {
540  ASTContext &Context = getASTContext();
541  if (!getIdentifier() || !getIdentifier()->getBuiltinID())
542    return 0;
543
544  unsigned BuiltinID = getIdentifier()->getBuiltinID();
545  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
546    return BuiltinID;
547
548  // This function has the name of a known C library
549  // function. Determine whether it actually refers to the C library
550  // function or whether it just has the same name.
551
552  // If this is a static function, it's not a builtin.
553  if (getStorageClass() == Static)
554    return 0;
555
556  // If this function is at translation-unit scope and we're not in
557  // C++, it refers to the C library function.
558  if (!Context.getLangOptions().CPlusPlus &&
559      getDeclContext()->isTranslationUnit())
560    return BuiltinID;
561
562  // If the function is in an extern "C" linkage specification and is
563  // not marked "overloadable", it's the real function.
564  if (isa<LinkageSpecDecl>(getDeclContext()) &&
565      cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
566        == LinkageSpecDecl::lang_c &&
567      !getAttr<OverloadableAttr>())
568    return BuiltinID;
569
570  // Not a builtin
571  return 0;
572}
573
574
575/// getNumParams - Return the number of parameters this function must have
576/// based on its FunctionType.  This is the length of the PararmInfo array
577/// after it has been created.
578unsigned FunctionDecl::getNumParams() const {
579  const FunctionType *FT = getType()->getAs<FunctionType>();
580  if (isa<FunctionNoProtoType>(FT))
581    return 0;
582  return cast<FunctionProtoType>(FT)->getNumArgs();
583
584}
585
586void FunctionDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo,
587                             unsigned NumParams) {
588  assert(ParamInfo == 0 && "Already has param info!");
589  assert(NumParams == getNumParams() && "Parameter count mismatch!");
590
591  // Zero params -> null pointer.
592  if (NumParams) {
593    void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams);
594    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
595    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
596
597    // Update source range. The check below allows us to set EndRangeLoc before
598    // setting the parameters.
599    if (EndRangeLoc.isInvalid() || EndRangeLoc == getLocation())
600      EndRangeLoc = NewParamInfo[NumParams-1]->getLocEnd();
601  }
602}
603
604/// getMinRequiredArguments - Returns the minimum number of arguments
605/// needed to call this function. This may be fewer than the number of
606/// function parameters, if some of the parameters have default
607/// arguments (in C++).
608unsigned FunctionDecl::getMinRequiredArguments() const {
609  unsigned NumRequiredArgs = getNumParams();
610  while (NumRequiredArgs > 0
611         && getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
612    --NumRequiredArgs;
613
614  return NumRequiredArgs;
615}
616
617/// \brief For an inline function definition in C, determine whether the
618/// definition will be externally visible.
619///
620/// Inline function definitions are always available for inlining optimizations.
621/// However, depending on the language dialect, declaration specifiers, and
622/// attributes, the definition of an inline function may or may not be
623/// "externally" visible to other translation units in the program.
624///
625/// In C99, inline definitions are not externally visible by default. However,
626/// if even one of the globa-scope declarations is marked "extern inline", the
627/// inline definition becomes externally visible (C99 6.7.4p6).
628///
629/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
630/// definition, we use the GNU semantics for inline, which are nearly the
631/// opposite of C99 semantics. In particular, "inline" by itself will create
632/// an externally visible symbol, but "extern inline" will not create an
633/// externally visible symbol.
634bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
635  assert(isThisDeclarationADefinition() && "Must have the function definition");
636  assert(isInline() && "Function must be inline");
637
638  if (!getASTContext().getLangOptions().C99 || hasAttr<GNUInlineAttr>()) {
639    // GNU inline semantics. Based on a number of examples, we came up with the
640    // following heuristic: if the "inline" keyword is present on a
641    // declaration of the function but "extern" is not present on that
642    // declaration, then the symbol is externally visible. Otherwise, the GNU
643    // "extern inline" semantics applies and the symbol is not externally
644    // visible.
645    for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
646         Redecl != RedeclEnd;
647         ++Redecl) {
648      if (Redecl->isInline() && Redecl->getStorageClass() != Extern)
649        return true;
650    }
651
652    // GNU "extern inline" semantics; no externally visible symbol.
653    return false;
654  }
655
656  // C99 6.7.4p6:
657  //   [...] If all of the file scope declarations for a function in a
658  //   translation unit include the inline function specifier without extern,
659  //   then the definition in that translation unit is an inline definition.
660  for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
661       Redecl != RedeclEnd;
662       ++Redecl) {
663    // Only consider file-scope declarations in this test.
664    if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
665      continue;
666
667    if (!Redecl->isInline() || Redecl->getStorageClass() == Extern)
668      return true; // Not an inline definition
669  }
670
671  // C99 6.7.4p6:
672  //   An inline definition does not provide an external definition for the
673  //   function, and does not forbid an external definition in another
674  //   translation unit.
675  return false;
676}
677
678void
679FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
680  redeclarable_base::setPreviousDeclaration(PrevDecl);
681
682  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
683    FunctionTemplateDecl *PrevFunTmpl
684      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
685    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
686    FunTmpl->setPreviousDeclaration(PrevFunTmpl);
687  }
688}
689
690const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
691  return getFirstDeclaration();
692}
693
694FunctionDecl *FunctionDecl::getCanonicalDecl() {
695  return getFirstDeclaration();
696}
697
698/// getOverloadedOperator - Which C++ overloaded operator this
699/// function represents, if any.
700OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
701  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
702    return getDeclName().getCXXOverloadedOperator();
703  else
704    return OO_None;
705}
706
707FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
708  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
709    return cast<FunctionDecl>(Info->getInstantiatedFrom());
710
711  return 0;
712}
713
714MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
715  return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
716}
717
718void
719FunctionDecl::setInstantiationOfMemberFunction(FunctionDecl *FD,
720                                               TemplateSpecializationKind TSK) {
721  assert(TemplateOrSpecialization.isNull() &&
722         "Member function is already a specialization");
723  MemberSpecializationInfo *Info
724    = new (getASTContext()) MemberSpecializationInfo(FD, TSK);
725  TemplateOrSpecialization = Info;
726}
727
728FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
729  if (FunctionTemplateSpecializationInfo *Info
730        = TemplateOrSpecialization
731            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
732    return Info->Template.getPointer();
733  }
734  return 0;
735}
736
737const TemplateArgumentList *
738FunctionDecl::getTemplateSpecializationArgs() const {
739  if (FunctionTemplateSpecializationInfo *Info
740        = TemplateOrSpecialization
741            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
742    return Info->TemplateArguments;
743  }
744  return 0;
745}
746
747void
748FunctionDecl::setFunctionTemplateSpecialization(ASTContext &Context,
749                                                FunctionTemplateDecl *Template,
750                                     const TemplateArgumentList *TemplateArgs,
751                                                void *InsertPos,
752                                              TemplateSpecializationKind TSK) {
753  assert(TSK != TSK_Undeclared &&
754         "Must specify the type of function template specialization");
755  FunctionTemplateSpecializationInfo *Info
756    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
757  if (!Info)
758    Info = new (Context) FunctionTemplateSpecializationInfo;
759
760  Info->Function = this;
761  Info->Template.setPointer(Template);
762  Info->Template.setInt(TSK - 1);
763  Info->TemplateArguments = TemplateArgs;
764  TemplateOrSpecialization = Info;
765
766  // Insert this function template specialization into the set of known
767  // function template specializations.
768  if (InsertPos)
769    Template->getSpecializations().InsertNode(Info, InsertPos);
770  else {
771    // Try to insert the new node. If there is an existing node, remove it
772    // first.
773    FunctionTemplateSpecializationInfo *Existing
774      = Template->getSpecializations().GetOrInsertNode(Info);
775    if (Existing) {
776      Template->getSpecializations().RemoveNode(Existing);
777      Template->getSpecializations().GetOrInsertNode(Info);
778    }
779  }
780}
781
782TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
783  // For a function template specialization, query the specialization
784  // information object.
785  FunctionTemplateSpecializationInfo *FTSInfo
786    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
787  if (FTSInfo)
788    return FTSInfo->getTemplateSpecializationKind();
789
790  MemberSpecializationInfo *MSInfo
791    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
792  if (MSInfo)
793    return MSInfo->getTemplateSpecializationKind();
794
795  return TSK_Undeclared;
796}
797
798void
799FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK) {
800  if (FunctionTemplateSpecializationInfo *FTSInfo
801        = TemplateOrSpecialization.dyn_cast<
802                                        FunctionTemplateSpecializationInfo*>())
803    FTSInfo->setTemplateSpecializationKind(TSK);
804  else if (MemberSpecializationInfo *MSInfo
805             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
806    MSInfo->setTemplateSpecializationKind(TSK);
807  else
808    assert(false && "Function cannot have a template specialization kind");
809}
810
811bool FunctionDecl::isOutOfLine() const {
812  // FIXME: Should we restrict this to member functions?
813  if (Decl::isOutOfLine())
814    return true;
815
816  // If this function was instantiated from a member function of a
817  // class template, check whether that member function was defined out-of-line.
818  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
819    const FunctionDecl *Definition;
820    if (FD->getBody(Definition))
821      return Definition->isOutOfLine();
822  }
823
824  // If this function was instantiated from a function template,
825  // check whether that function template was defined out-of-line.
826  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
827    const FunctionDecl *Definition;
828    if (FunTmpl->getTemplatedDecl()->getBody(Definition))
829      return Definition->isOutOfLine();
830  }
831
832  return false;
833}
834
835//===----------------------------------------------------------------------===//
836// TagDecl Implementation
837//===----------------------------------------------------------------------===//
838
839SourceRange TagDecl::getSourceRange() const {
840  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
841  return SourceRange(TagKeywordLoc, E);
842}
843
844TagDecl* TagDecl::getCanonicalDecl() {
845  return getFirstDeclaration();
846}
847
848void TagDecl::startDefinition() {
849  if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) {
850    TagT->decl.setPointer(this);
851    TagT->decl.setInt(1);
852  }
853}
854
855void TagDecl::completeDefinition() {
856  IsDefinition = true;
857  if (TagType *TagT = const_cast<TagType *>(TypeForDecl->getAs<TagType>())) {
858    assert(TagT->decl.getPointer() == this &&
859           "Attempt to redefine a tag definition?");
860    TagT->decl.setInt(0);
861  }
862}
863
864TagDecl* TagDecl::getDefinition(ASTContext& C) const {
865  if (isDefinition())
866    return const_cast<TagDecl *>(this);
867
868  for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
869       R != REnd; ++R)
870    if (R->isDefinition())
871      return *R;
872
873  return 0;
874}
875
876TagDecl::TagKind TagDecl::getTagKindForTypeSpec(unsigned TypeSpec) {
877  switch (TypeSpec) {
878  default: llvm::llvm_unreachable("unexpected type specifier");
879  case DeclSpec::TST_struct: return TK_struct;
880  case DeclSpec::TST_class: return TK_class;
881  case DeclSpec::TST_union: return TK_union;
882  case DeclSpec::TST_enum: return TK_enum;
883  }
884}
885
886//===----------------------------------------------------------------------===//
887// RecordDecl Implementation
888//===----------------------------------------------------------------------===//
889
890RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC, SourceLocation L,
891                       IdentifierInfo *Id, RecordDecl *PrevDecl,
892                       SourceLocation TKL)
893  : TagDecl(DK, TK, DC, L, Id, PrevDecl, TKL) {
894  HasFlexibleArrayMember = false;
895  AnonymousStructOrUnion = false;
896  HasObjectMember = false;
897  assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
898}
899
900RecordDecl *RecordDecl::Create(ASTContext &C, TagKind TK, DeclContext *DC,
901                               SourceLocation L, IdentifierInfo *Id,
902                               SourceLocation TKL, RecordDecl* PrevDecl) {
903
904  RecordDecl* R = new (C) RecordDecl(Record, TK, DC, L, Id, PrevDecl, TKL);
905  C.getTypeDeclType(R, PrevDecl);
906  return R;
907}
908
909RecordDecl::~RecordDecl() {
910}
911
912void RecordDecl::Destroy(ASTContext& C) {
913  TagDecl::Destroy(C);
914}
915
916bool RecordDecl::isInjectedClassName() const {
917  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
918    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
919}
920
921/// completeDefinition - Notes that the definition of this type is now
922/// complete.
923void RecordDecl::completeDefinition(ASTContext& C) {
924  assert(!isDefinition() && "Cannot redefine record!");
925  TagDecl::completeDefinition();
926}
927
928//===----------------------------------------------------------------------===//
929// BlockDecl Implementation
930//===----------------------------------------------------------------------===//
931
932BlockDecl::~BlockDecl() {
933}
934
935void BlockDecl::Destroy(ASTContext& C) {
936  if (Body)
937    Body->Destroy(C);
938
939  for (param_iterator I=param_begin(), E=param_end(); I!=E; ++I)
940    (*I)->Destroy(C);
941
942  C.Deallocate(ParamInfo);
943  Decl::Destroy(C);
944}
945
946void BlockDecl::setParams(ASTContext& C, ParmVarDecl **NewParamInfo,
947                          unsigned NParms) {
948  assert(ParamInfo == 0 && "Already has param info!");
949
950  // Zero params -> null pointer.
951  if (NParms) {
952    NumParams = NParms;
953    void *Mem = C.Allocate(sizeof(ParmVarDecl*)*NumParams);
954    ParamInfo = new (Mem) ParmVarDecl*[NumParams];
955    memcpy(ParamInfo, NewParamInfo, sizeof(ParmVarDecl*)*NumParams);
956  }
957}
958
959unsigned BlockDecl::getNumParams() const {
960  return NumParams;
961}
962