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