Decl.cpp revision 62d9f110b83dfa5dcd4a945e3b5f2e9c73d3aa4a
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/Module.h"
28#include "clang/Basic/Specifiers.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/Support/ErrorHandling.h"
31
32#include <algorithm>
33
34using namespace clang;
35
36//===----------------------------------------------------------------------===//
37// NamedDecl Implementation
38//===----------------------------------------------------------------------===//
39
40static llvm::Optional<Visibility> getVisibilityOf(const Decl *D) {
41  // If this declaration has an explicit visibility attribute, use it.
42  if (const VisibilityAttr *A = D->getAttr<VisibilityAttr>()) {
43    switch (A->getVisibility()) {
44    case VisibilityAttr::Default:
45      return DefaultVisibility;
46    case VisibilityAttr::Hidden:
47      return HiddenVisibility;
48    case VisibilityAttr::Protected:
49      return ProtectedVisibility;
50    }
51  }
52
53  // If we're on Mac OS X, an 'availability' for Mac OS X attribute
54  // implies visibility(default).
55  if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
56    for (specific_attr_iterator<AvailabilityAttr>
57              A = D->specific_attr_begin<AvailabilityAttr>(),
58           AEnd = D->specific_attr_end<AvailabilityAttr>();
59         A != AEnd; ++A)
60      if ((*A)->getPlatform()->getName().equals("macosx"))
61        return DefaultVisibility;
62  }
63
64  return llvm::Optional<Visibility>();
65}
66
67typedef NamedDecl::LinkageInfo LinkageInfo;
68
69namespace {
70/// Flags controlling the computation of linkage and visibility.
71struct LVFlags {
72  bool ConsiderGlobalVisibility;
73  bool ConsiderVisibilityAttributes;
74  bool ConsiderTemplateParameterTypes;
75
76  LVFlags() : ConsiderGlobalVisibility(true),
77              ConsiderVisibilityAttributes(true),
78              ConsiderTemplateParameterTypes(true) {
79  }
80
81  LVFlags(bool Global, bool Attributes, bool Parameters) :
82    ConsiderGlobalVisibility(Global),
83    ConsiderVisibilityAttributes(Attributes),
84    ConsiderTemplateParameterTypes(Parameters) {
85  }
86
87  /// \brief Returns a set of flags that is only useful for computing the
88  /// linkage, not the visibility, of a declaration.
89  static LVFlags CreateOnlyDeclLinkage() {
90    return LVFlags(false, false, false);
91  }
92};
93} // end anonymous namespace
94
95static LinkageInfo getLVForType(QualType T) {
96  std::pair<Linkage,Visibility> P = T->getLinkageAndVisibility();
97  return LinkageInfo(P.first, P.second, T->isVisibilityExplicit());
98}
99
100/// \brief Get the most restrictive linkage for the types in the given
101/// template parameter list.
102static LinkageInfo
103getLVForTemplateParameterList(const TemplateParameterList *Params) {
104  LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
105  for (TemplateParameterList::const_iterator P = Params->begin(),
106                                          PEnd = Params->end();
107       P != PEnd; ++P) {
108    if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(*P)) {
109      if (NTTP->isExpandedParameterPack()) {
110        for (unsigned I = 0, N = NTTP->getNumExpansionTypes(); I != N; ++I) {
111          QualType T = NTTP->getExpansionType(I);
112          if (!T->isDependentType())
113            LV.merge(getLVForType(T));
114        }
115        continue;
116      }
117
118      if (!NTTP->getType()->isDependentType()) {
119        LV.merge(getLVForType(NTTP->getType()));
120        continue;
121      }
122    }
123
124    if (TemplateTemplateParmDecl *TTP
125                                   = dyn_cast<TemplateTemplateParmDecl>(*P)) {
126      LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters()));
127    }
128  }
129
130  return LV;
131}
132
133/// getLVForDecl - Get the linkage and visibility for the given declaration.
134static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags F);
135
136/// \brief Get the most restrictive linkage for the types and
137/// declarations in the given template argument list.
138static LinkageInfo getLVForTemplateArgumentList(const TemplateArgument *Args,
139                                                unsigned NumArgs,
140                                                LVFlags &F) {
141  LinkageInfo LV(ExternalLinkage, DefaultVisibility, false);
142
143  for (unsigned I = 0; I != NumArgs; ++I) {
144    switch (Args[I].getKind()) {
145    case TemplateArgument::Null:
146    case TemplateArgument::Integral:
147    case TemplateArgument::Expression:
148      break;
149
150    case TemplateArgument::Type:
151      LV.merge(getLVForType(Args[I].getAsType()));
152      break;
153
154    case TemplateArgument::Declaration:
155      // The decl can validly be null as the representation of nullptr
156      // arguments, valid only in C++0x.
157      if (Decl *D = Args[I].getAsDecl()) {
158        if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
159          LV = merge(LV, getLVForDecl(ND, F));
160      }
161      break;
162
163    case TemplateArgument::Template:
164    case TemplateArgument::TemplateExpansion:
165      if (TemplateDecl *Template
166                = Args[I].getAsTemplateOrTemplatePattern().getAsTemplateDecl())
167        LV.merge(getLVForDecl(Template, F));
168      break;
169
170    case TemplateArgument::Pack:
171      LV.mergeWithMin(getLVForTemplateArgumentList(Args[I].pack_begin(),
172                                                   Args[I].pack_size(),
173                                                   F));
174      break;
175    }
176  }
177
178  return LV;
179}
180
181static LinkageInfo
182getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
183                             LVFlags &F) {
184  return getLVForTemplateArgumentList(TArgs.data(), TArgs.size(), F);
185}
186
187static bool shouldConsiderTemplateLV(const FunctionDecl *fn,
188                               const FunctionTemplateSpecializationInfo *spec) {
189  return !(spec->isExplicitSpecialization() &&
190           fn->hasAttr<VisibilityAttr>());
191}
192
193static bool shouldConsiderTemplateLV(const ClassTemplateSpecializationDecl *d) {
194  return !(d->isExplicitSpecialization() && d->hasAttr<VisibilityAttr>());
195}
196
197static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D, LVFlags F) {
198  assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
199         "Not a name having namespace scope");
200  ASTContext &Context = D->getASTContext();
201
202  // C++ [basic.link]p3:
203  //   A name having namespace scope (3.3.6) has internal linkage if it
204  //   is the name of
205  //     - an object, reference, function or function template that is
206  //       explicitly declared static; or,
207  // (This bullet corresponds to C99 6.2.2p3.)
208  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
209    // Explicitly declared static.
210    if (Var->getStorageClass() == SC_Static)
211      return LinkageInfo::internal();
212
213    // - an object or reference that is explicitly declared const
214    //   and neither explicitly declared extern nor previously
215    //   declared to have external linkage; or
216    // (there is no equivalent in C99)
217    if (Context.getLangOpts().CPlusPlus &&
218        Var->getType().isConstant(Context) &&
219        Var->getStorageClass() != SC_Extern &&
220        Var->getStorageClass() != SC_PrivateExtern) {
221      bool FoundExtern = false;
222      for (const VarDecl *PrevVar = Var->getPreviousDecl();
223           PrevVar && !FoundExtern;
224           PrevVar = PrevVar->getPreviousDecl())
225        if (isExternalLinkage(PrevVar->getLinkage()))
226          FoundExtern = true;
227
228      if (!FoundExtern)
229        return LinkageInfo::internal();
230    }
231    if (Var->getStorageClass() == SC_None) {
232      const VarDecl *PrevVar = Var->getPreviousDecl();
233      for (; PrevVar; PrevVar = PrevVar->getPreviousDecl())
234        if (PrevVar->getStorageClass() == SC_PrivateExtern)
235          break;
236        if (PrevVar)
237          return PrevVar->getLinkageAndVisibility();
238    }
239  } else if (isa<FunctionDecl>(D) || isa<FunctionTemplateDecl>(D)) {
240    // C++ [temp]p4:
241    //   A non-member function template can have internal linkage; any
242    //   other template name shall have external linkage.
243    const FunctionDecl *Function = 0;
244    if (const FunctionTemplateDecl *FunTmpl
245                                        = dyn_cast<FunctionTemplateDecl>(D))
246      Function = FunTmpl->getTemplatedDecl();
247    else
248      Function = cast<FunctionDecl>(D);
249
250    // Explicitly declared static.
251    if (Function->getStorageClass() == SC_Static)
252      return LinkageInfo(InternalLinkage, DefaultVisibility, false);
253  } else if (const FieldDecl *Field = dyn_cast<FieldDecl>(D)) {
254    //   - a data member of an anonymous union.
255    if (cast<RecordDecl>(Field->getDeclContext())->isAnonymousStructOrUnion())
256      return LinkageInfo::internal();
257  }
258
259  if (D->isInAnonymousNamespace()) {
260    const VarDecl *Var = dyn_cast<VarDecl>(D);
261    const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
262    if ((!Var || !Var->getDeclContext()->isExternCContext()) &&
263        (!Func || !Func->getDeclContext()->isExternCContext()))
264      return LinkageInfo::uniqueExternal();
265  }
266
267  // Set up the defaults.
268
269  // C99 6.2.2p5:
270  //   If the declaration of an identifier for an object has file
271  //   scope and no storage-class specifier, its linkage is
272  //   external.
273  LinkageInfo LV;
274  LV.mergeVisibility(Context.getLangOpts().getVisibilityMode());
275
276  // C++ [basic.link]p4:
277
278  //   A name having namespace scope has external linkage if it is the
279  //   name of
280  //
281  //     - an object or reference, unless it has internal linkage; or
282  if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
283    // GCC applies the following optimization to variables and static
284    // data members, but not to functions:
285    //
286    // Modify the variable's LV by the LV of its type unless this is
287    // C or extern "C".  This follows from [basic.link]p9:
288    //   A type without linkage shall not be used as the type of a
289    //   variable or function with external linkage unless
290    //    - the entity has C language linkage, or
291    //    - the entity is declared within an unnamed namespace, or
292    //    - the entity is not used or is defined in the same
293    //      translation unit.
294    // and [basic.link]p10:
295    //   ...the types specified by all declarations referring to a
296    //   given variable or function shall be identical...
297    // C does not have an equivalent rule.
298    //
299    // Ignore this if we've got an explicit attribute;  the user
300    // probably knows what they're doing.
301    //
302    // Note that we don't want to make the variable non-external
303    // because of this, but unique-external linkage suits us.
304    if (Context.getLangOpts().CPlusPlus &&
305        !Var->getDeclContext()->isExternCContext()) {
306      LinkageInfo TypeLV = getLVForType(Var->getType());
307      if (TypeLV.linkage() != ExternalLinkage)
308        return LinkageInfo::uniqueExternal();
309      LV.mergeVisibilityWithMin(TypeLV.visibility(),
310                                TypeLV.visibilityExplicit());
311    }
312
313    if (Var->getStorageClass() == SC_PrivateExtern)
314      LV.setVisibility(HiddenVisibility, true);
315
316    if (!Context.getLangOpts().CPlusPlus &&
317        (Var->getStorageClass() == SC_Extern ||
318         Var->getStorageClass() == SC_PrivateExtern)) {
319
320      // C99 6.2.2p4:
321      //   For an identifier declared with the storage-class specifier
322      //   extern in a scope in which a prior declaration of that
323      //   identifier is visible, if the prior declaration specifies
324      //   internal or external linkage, the linkage of the identifier
325      //   at the later declaration is the same as the linkage
326      //   specified at the prior declaration. If no prior declaration
327      //   is visible, or if the prior declaration specifies no
328      //   linkage, then the identifier has external linkage.
329      if (const VarDecl *PrevVar = Var->getPreviousDecl()) {
330        LinkageInfo PrevLV = getLVForDecl(PrevVar, F);
331        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
332        LV.mergeVisibility(PrevLV);
333      }
334    }
335
336  //     - a function, unless it has internal linkage; or
337  } else if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
338    // In theory, we can modify the function's LV by the LV of its
339    // type unless it has C linkage (see comment above about variables
340    // for justification).  In practice, GCC doesn't do this, so it's
341    // just too painful to make work.
342
343    if (Function->getStorageClass() == SC_PrivateExtern)
344      LV.setVisibility(HiddenVisibility, true);
345
346    // C99 6.2.2p5:
347    //   If the declaration of an identifier for a function has no
348    //   storage-class specifier, its linkage is determined exactly
349    //   as if it were declared with the storage-class specifier
350    //   extern.
351    if (!Context.getLangOpts().CPlusPlus &&
352        (Function->getStorageClass() == SC_Extern ||
353         Function->getStorageClass() == SC_PrivateExtern ||
354         Function->getStorageClass() == SC_None)) {
355      // C99 6.2.2p4:
356      //   For an identifier declared with the storage-class specifier
357      //   extern in a scope in which a prior declaration of that
358      //   identifier is visible, if the prior declaration specifies
359      //   internal or external linkage, the linkage of the identifier
360      //   at the later declaration is the same as the linkage
361      //   specified at the prior declaration. If no prior declaration
362      //   is visible, or if the prior declaration specifies no
363      //   linkage, then the identifier has external linkage.
364      if (const FunctionDecl *PrevFunc = Function->getPreviousDecl()) {
365        LinkageInfo PrevLV = getLVForDecl(PrevFunc, F);
366        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
367        LV.mergeVisibility(PrevLV);
368      }
369    }
370
371    // In C++, then if the type of the function uses a type with
372    // unique-external linkage, it's not legally usable from outside
373    // this translation unit.  However, we should use the C linkage
374    // rules instead for extern "C" declarations.
375    if (Context.getLangOpts().CPlusPlus &&
376        !Function->getDeclContext()->isExternCContext() &&
377        Function->getType()->getLinkage() == UniqueExternalLinkage)
378      return LinkageInfo::uniqueExternal();
379
380    // Consider LV from the template and the template arguments unless
381    // this is an explicit specialization with a visibility attribute.
382    if (FunctionTemplateSpecializationInfo *specInfo
383                               = Function->getTemplateSpecializationInfo()) {
384      if (shouldConsiderTemplateLV(Function, specInfo)) {
385        LV.merge(getLVForDecl(specInfo->getTemplate(),
386                              LVFlags::CreateOnlyDeclLinkage()));
387        const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
388        LV.mergeWithMin(getLVForTemplateArgumentList(templateArgs, F));
389      }
390    }
391
392  //     - a named class (Clause 9), or an unnamed class defined in a
393  //       typedef declaration in which the class has the typedef name
394  //       for linkage purposes (7.1.3); or
395  //     - a named enumeration (7.2), or an unnamed enumeration
396  //       defined in a typedef declaration in which the enumeration
397  //       has the typedef name for linkage purposes (7.1.3); or
398  } else if (const TagDecl *Tag = dyn_cast<TagDecl>(D)) {
399    // Unnamed tags have no linkage.
400    if (!Tag->getDeclName() && !Tag->getTypedefNameForAnonDecl())
401      return LinkageInfo::none();
402
403    // If this is a class template specialization, consider the
404    // linkage of the template and template arguments.
405    if (const ClassTemplateSpecializationDecl *spec
406          = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
407      if (shouldConsiderTemplateLV(spec)) {
408        // From the template.
409        LV.merge(getLVForDecl(spec->getSpecializedTemplate(),
410                              LVFlags::CreateOnlyDeclLinkage()));
411
412        // The arguments at which the template was instantiated.
413        const TemplateArgumentList &TemplateArgs = spec->getTemplateArgs();
414        LV.mergeWithMin(getLVForTemplateArgumentList(TemplateArgs, F));
415      }
416    }
417
418    // Consider -fvisibility unless the type has C linkage.
419    if (F.ConsiderGlobalVisibility)
420      F.ConsiderGlobalVisibility =
421        (Context.getLangOpts().CPlusPlus &&
422         !Tag->getDeclContext()->isExternCContext());
423
424  //     - an enumerator belonging to an enumeration with external linkage;
425  } else if (isa<EnumConstantDecl>(D)) {
426    LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()), F);
427    if (!isExternalLinkage(EnumLV.linkage()))
428      return LinkageInfo::none();
429    LV.merge(EnumLV);
430
431  //     - a template, unless it is a function template that has
432  //       internal linkage (Clause 14);
433  } else if (const TemplateDecl *temp = dyn_cast<TemplateDecl>(D)) {
434    if (F.ConsiderTemplateParameterTypes)
435      LV.merge(getLVForTemplateParameterList(temp->getTemplateParameters()));
436
437  //     - a namespace (7.3), unless it is declared within an unnamed
438  //       namespace.
439  } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
440    return LV;
441
442  // By extension, we assign external linkage to Objective-C
443  // interfaces.
444  } else if (isa<ObjCInterfaceDecl>(D)) {
445    // fallout
446
447  // Everything not covered here has no linkage.
448  } else {
449    return LinkageInfo::none();
450  }
451
452  if (F.ConsiderVisibilityAttributes) {
453    if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
454      LV.setVisibility(*Vis, true);
455      F.ConsiderGlobalVisibility = false;
456    } else {
457      // If we're declared in a namespace with a visibility attribute,
458      // use that namespace's visibility, but don't call it explicit.
459      for (const DeclContext *DC = D->getDeclContext();
460           !isa<TranslationUnitDecl>(DC);
461           DC = DC->getParent()) {
462        const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC);
463        if (!ND) continue;
464        if (llvm::Optional<Visibility> Vis = ND->getExplicitVisibility()) {
465          LV.setVisibility(*Vis, true);
466          F.ConsiderGlobalVisibility = false;
467          break;
468        }
469      }
470    }
471  }
472
473  // If we ended up with non-external linkage, visibility should
474  // always be default.
475  if (LV.linkage() != ExternalLinkage)
476    return LinkageInfo(LV.linkage(), DefaultVisibility, false);
477
478  return LV;
479}
480
481static LinkageInfo getLVForClassMember(const NamedDecl *D, LVFlags F) {
482  // Only certain class members have linkage.  Note that fields don't
483  // really have linkage, but it's convenient to say they do for the
484  // purposes of calculating linkage of pointer-to-data-member
485  // template arguments.
486  if (!(isa<CXXMethodDecl>(D) ||
487        isa<VarDecl>(D) ||
488        isa<FieldDecl>(D) ||
489        (isa<TagDecl>(D) &&
490         (D->getDeclName() || cast<TagDecl>(D)->getTypedefNameForAnonDecl()))))
491    return LinkageInfo::none();
492
493  LinkageInfo LV;
494  LV.mergeVisibility(D->getASTContext().getLangOpts().getVisibilityMode());
495
496  // The flags we're going to use to compute the class's visibility.
497  LVFlags ClassF = F;
498
499  // If we have an explicit visibility attribute, merge that in.
500  if (F.ConsiderVisibilityAttributes) {
501    if (llvm::Optional<Visibility> Vis = D->getExplicitVisibility()) {
502      LV.mergeVisibility(*Vis, true);
503
504      // Ignore global visibility later, but not this attribute.
505      F.ConsiderGlobalVisibility = false;
506
507      // Ignore both global visibility and attributes when computing our
508      // parent's visibility.
509      ClassF = LVFlags::CreateOnlyDeclLinkage();
510    }
511  }
512
513  // Class members only have linkage if their class has external
514  // linkage.
515  LV.merge(getLVForDecl(cast<RecordDecl>(D->getDeclContext()), ClassF));
516  if (!isExternalLinkage(LV.linkage()))
517    return LinkageInfo::none();
518
519  // If the class already has unique-external linkage, we can't improve.
520  if (LV.linkage() == UniqueExternalLinkage)
521    return LinkageInfo::uniqueExternal();
522
523  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
524    // If the type of the function uses a type with unique-external
525    // linkage, it's not legally usable from outside this translation unit.
526    if (MD->getType()->getLinkage() == UniqueExternalLinkage)
527      return LinkageInfo::uniqueExternal();
528
529    TemplateSpecializationKind TSK = TSK_Undeclared;
530
531    // If this is a method template specialization, use the linkage for
532    // the template parameters and arguments.
533    if (FunctionTemplateSpecializationInfo *spec
534           = MD->getTemplateSpecializationInfo()) {
535      if (shouldConsiderTemplateLV(MD, spec)) {
536        LV.mergeWithMin(getLVForTemplateArgumentList(*spec->TemplateArguments,
537                                                     F));
538        if (F.ConsiderTemplateParameterTypes)
539          LV.merge(getLVForTemplateParameterList(
540                              spec->getTemplate()->getTemplateParameters()));
541      }
542
543      TSK = spec->getTemplateSpecializationKind();
544    } else if (MemberSpecializationInfo *MSI =
545                 MD->getMemberSpecializationInfo()) {
546      TSK = MSI->getTemplateSpecializationKind();
547    }
548
549    // If we're paying attention to global visibility, apply
550    // -finline-visibility-hidden if this is an inline method.
551    //
552    // Note that ConsiderGlobalVisibility doesn't yet have information
553    // about whether containing classes have visibility attributes,
554    // and that's intentional.
555    if (TSK != TSK_ExplicitInstantiationDeclaration &&
556        TSK != TSK_ExplicitInstantiationDefinition &&
557        F.ConsiderGlobalVisibility &&
558        MD->getASTContext().getLangOpts().InlineVisibilityHidden) {
559      // InlineVisibilityHidden only applies to definitions, and
560      // isInlined() only gives meaningful answers on definitions
561      // anyway.
562      const FunctionDecl *Def = 0;
563      if (MD->hasBody(Def) && Def->isInlined())
564        LV.setVisibility(HiddenVisibility);
565    }
566
567    // Note that in contrast to basically every other situation, we
568    // *do* apply -fvisibility to method declarations.
569
570  } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
571    if (const ClassTemplateSpecializationDecl *spec
572        = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
573      if (shouldConsiderTemplateLV(spec)) {
574        // Merge template argument/parameter information for member
575        // class template specializations.
576        LV.mergeWithMin(getLVForTemplateArgumentList(spec->getTemplateArgs(),
577                                                     F));
578      if (F.ConsiderTemplateParameterTypes)
579        LV.merge(getLVForTemplateParameterList(
580                    spec->getSpecializedTemplate()->getTemplateParameters()));
581      }
582    }
583
584  // Static data members.
585  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
586    // Modify the variable's linkage by its type, but ignore the
587    // type's visibility unless it's a definition.
588    LinkageInfo TypeLV = getLVForType(VD->getType());
589    if (TypeLV.linkage() != ExternalLinkage)
590      LV.mergeLinkage(UniqueExternalLinkage);
591    if (!LV.visibilityExplicit())
592      LV.mergeVisibility(TypeLV.visibility(), TypeLV.visibilityExplicit());
593  }
594
595  return LV;
596}
597
598static void clearLinkageForClass(const CXXRecordDecl *record) {
599  for (CXXRecordDecl::decl_iterator
600         i = record->decls_begin(), e = record->decls_end(); i != e; ++i) {
601    Decl *child = *i;
602    if (isa<NamedDecl>(child))
603      cast<NamedDecl>(child)->ClearLinkageCache();
604  }
605}
606
607void NamedDecl::anchor() { }
608
609void NamedDecl::ClearLinkageCache() {
610  // Note that we can't skip clearing the linkage of children just
611  // because the parent doesn't have cached linkage:  we don't cache
612  // when computing linkage for parent contexts.
613
614  HasCachedLinkage = 0;
615
616  // If we're changing the linkage of a class, we need to reset the
617  // linkage of child declarations, too.
618  if (const CXXRecordDecl *record = dyn_cast<CXXRecordDecl>(this))
619    clearLinkageForClass(record);
620
621  if (ClassTemplateDecl *temp =
622        dyn_cast<ClassTemplateDecl>(const_cast<NamedDecl*>(this))) {
623    // Clear linkage for the template pattern.
624    CXXRecordDecl *record = temp->getTemplatedDecl();
625    record->HasCachedLinkage = 0;
626    clearLinkageForClass(record);
627
628    // We need to clear linkage for specializations, too.
629    for (ClassTemplateDecl::spec_iterator
630           i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
631      i->ClearLinkageCache();
632  }
633
634  // Clear cached linkage for function template decls, too.
635  if (FunctionTemplateDecl *temp =
636        dyn_cast<FunctionTemplateDecl>(const_cast<NamedDecl*>(this))) {
637    temp->getTemplatedDecl()->ClearLinkageCache();
638    for (FunctionTemplateDecl::spec_iterator
639           i = temp->spec_begin(), e = temp->spec_end(); i != e; ++i)
640      i->ClearLinkageCache();
641  }
642
643}
644
645Linkage NamedDecl::getLinkage() const {
646  if (HasCachedLinkage) {
647    assert(Linkage(CachedLinkage) ==
648             getLVForDecl(this, LVFlags::CreateOnlyDeclLinkage()).linkage());
649    return Linkage(CachedLinkage);
650  }
651
652  CachedLinkage = getLVForDecl(this,
653                               LVFlags::CreateOnlyDeclLinkage()).linkage();
654  HasCachedLinkage = 1;
655  return Linkage(CachedLinkage);
656}
657
658LinkageInfo NamedDecl::getLinkageAndVisibility() const {
659  LinkageInfo LI = getLVForDecl(this, LVFlags());
660  assert(!HasCachedLinkage || Linkage(CachedLinkage) == LI.linkage());
661  HasCachedLinkage = 1;
662  CachedLinkage = LI.linkage();
663  return LI;
664}
665
666llvm::Optional<Visibility> NamedDecl::getExplicitVisibility() const {
667  // Use the most recent declaration of a variable.
668  if (const VarDecl *var = dyn_cast<VarDecl>(this))
669    return getVisibilityOf(var->getMostRecentDecl());
670
671  // Use the most recent declaration of a function, and also handle
672  // function template specializations.
673  if (const FunctionDecl *fn = dyn_cast<FunctionDecl>(this)) {
674    if (llvm::Optional<Visibility> V
675                            = getVisibilityOf(fn->getMostRecentDecl()))
676      return V;
677
678    // If the function is a specialization of a template with an
679    // explicit visibility attribute, use that.
680    if (FunctionTemplateSpecializationInfo *templateInfo
681          = fn->getTemplateSpecializationInfo())
682      return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl());
683
684    // If the function is a member of a specialization of a class template
685    // and the corresponding decl has explicit visibility, use that.
686    FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
687    if (InstantiatedFrom)
688      return getVisibilityOf(InstantiatedFrom);
689
690    return llvm::Optional<Visibility>();
691  }
692
693  // Otherwise, just check the declaration itself first.
694  if (llvm::Optional<Visibility> V = getVisibilityOf(this))
695    return V;
696
697  // If there wasn't explicit visibility there, and this is a
698  // specialization of a class template, check for visibility
699  // on the pattern.
700  if (const ClassTemplateSpecializationDecl *spec
701        = dyn_cast<ClassTemplateSpecializationDecl>(this))
702    return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl());
703
704  // If this is a member class of a specialization of a class template
705  // and the corresponding decl has explicit visibility, use that.
706  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(this)) {
707    CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
708    if (InstantiatedFrom)
709      return getVisibilityOf(InstantiatedFrom);
710  }
711
712  return llvm::Optional<Visibility>();
713}
714
715static LinkageInfo getLVForDecl(const NamedDecl *D, LVFlags Flags) {
716  // Objective-C: treat all Objective-C declarations as having external
717  // linkage.
718  switch (D->getKind()) {
719    default:
720      break;
721    case Decl::ParmVar:
722      return LinkageInfo::none();
723    case Decl::TemplateTemplateParm: // count these as external
724    case Decl::NonTypeTemplateParm:
725    case Decl::ObjCAtDefsField:
726    case Decl::ObjCCategory:
727    case Decl::ObjCCategoryImpl:
728    case Decl::ObjCCompatibleAlias:
729    case Decl::ObjCImplementation:
730    case Decl::ObjCMethod:
731    case Decl::ObjCProperty:
732    case Decl::ObjCPropertyImpl:
733    case Decl::ObjCProtocol:
734      return LinkageInfo::external();
735
736    case Decl::CXXRecord: {
737      const CXXRecordDecl *Record = cast<CXXRecordDecl>(D);
738      if (Record->isLambda()) {
739        if (!Record->getLambdaManglingNumber()) {
740          // This lambda has no mangling number, so it's internal.
741          return LinkageInfo::internal();
742        }
743
744        // This lambda has its linkage/visibility determined by its owner.
745        const DeclContext *DC = D->getDeclContext()->getRedeclContext();
746        if (Decl *ContextDecl = Record->getLambdaContextDecl()) {
747          if (isa<ParmVarDecl>(ContextDecl))
748            DC = ContextDecl->getDeclContext()->getRedeclContext();
749          else
750            return getLVForDecl(cast<NamedDecl>(ContextDecl), Flags);
751        }
752
753        if (const NamedDecl *ND = dyn_cast<NamedDecl>(DC))
754          return getLVForDecl(ND, Flags);
755
756        return LinkageInfo::external();
757      }
758
759      break;
760    }
761  }
762
763  // Handle linkage for namespace-scope names.
764  if (D->getDeclContext()->getRedeclContext()->isFileContext())
765    return getLVForNamespaceScopeDecl(D, Flags);
766
767  // C++ [basic.link]p5:
768  //   In addition, a member function, static data member, a named
769  //   class or enumeration of class scope, or an unnamed class or
770  //   enumeration defined in a class-scope typedef declaration such
771  //   that the class or enumeration has the typedef name for linkage
772  //   purposes (7.1.3), has external linkage if the name of the class
773  //   has external linkage.
774  if (D->getDeclContext()->isRecord())
775    return getLVForClassMember(D, Flags);
776
777  // C++ [basic.link]p6:
778  //   The name of a function declared in block scope and the name of
779  //   an object declared by a block scope extern declaration have
780  //   linkage. If there is a visible declaration of an entity with
781  //   linkage having the same name and type, ignoring entities
782  //   declared outside the innermost enclosing namespace scope, the
783  //   block scope declaration declares that same entity and receives
784  //   the linkage of the previous declaration. If there is more than
785  //   one such matching entity, the program is ill-formed. Otherwise,
786  //   if no matching entity is found, the block scope entity receives
787  //   external linkage.
788  if (D->getLexicalDeclContext()->isFunctionOrMethod()) {
789    if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
790      if (Function->isInAnonymousNamespace() &&
791          !Function->getDeclContext()->isExternCContext())
792        return LinkageInfo::uniqueExternal();
793
794      LinkageInfo LV;
795      if (Flags.ConsiderVisibilityAttributes) {
796        if (llvm::Optional<Visibility> Vis = Function->getExplicitVisibility())
797          LV.setVisibility(*Vis);
798      }
799
800      if (const FunctionDecl *Prev = Function->getPreviousDecl()) {
801        LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
802        if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
803        LV.mergeVisibility(PrevLV);
804      }
805
806      return LV;
807    }
808
809    if (const VarDecl *Var = dyn_cast<VarDecl>(D))
810      if (Var->getStorageClass() == SC_Extern ||
811          Var->getStorageClass() == SC_PrivateExtern) {
812        if (Var->isInAnonymousNamespace() &&
813            !Var->getDeclContext()->isExternCContext())
814          return LinkageInfo::uniqueExternal();
815
816        LinkageInfo LV;
817        if (Var->getStorageClass() == SC_PrivateExtern)
818          LV.setVisibility(HiddenVisibility);
819        else if (Flags.ConsiderVisibilityAttributes) {
820          if (llvm::Optional<Visibility> Vis = Var->getExplicitVisibility())
821            LV.setVisibility(*Vis);
822        }
823
824        if (const VarDecl *Prev = Var->getPreviousDecl()) {
825          LinkageInfo PrevLV = getLVForDecl(Prev, Flags);
826          if (PrevLV.linkage()) LV.setLinkage(PrevLV.linkage());
827          LV.mergeVisibility(PrevLV);
828        }
829
830        return LV;
831      }
832  }
833
834  // C++ [basic.link]p6:
835  //   Names not covered by these rules have no linkage.
836  return LinkageInfo::none();
837}
838
839std::string NamedDecl::getQualifiedNameAsString() const {
840  return getQualifiedNameAsString(getASTContext().getPrintingPolicy());
841}
842
843std::string NamedDecl::getQualifiedNameAsString(const PrintingPolicy &P) const {
844  const DeclContext *Ctx = getDeclContext();
845
846  if (Ctx->isFunctionOrMethod())
847    return getNameAsString();
848
849  typedef SmallVector<const DeclContext *, 8> ContextsTy;
850  ContextsTy Contexts;
851
852  // Collect contexts.
853  while (Ctx && isa<NamedDecl>(Ctx)) {
854    Contexts.push_back(Ctx);
855    Ctx = Ctx->getParent();
856  };
857
858  std::string QualName;
859  llvm::raw_string_ostream OS(QualName);
860
861  for (ContextsTy::reverse_iterator I = Contexts.rbegin(), E = Contexts.rend();
862       I != E; ++I) {
863    if (const ClassTemplateSpecializationDecl *Spec
864          = dyn_cast<ClassTemplateSpecializationDecl>(*I)) {
865      const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
866      std::string TemplateArgsStr
867        = TemplateSpecializationType::PrintTemplateArgumentList(
868                                           TemplateArgs.data(),
869                                           TemplateArgs.size(),
870                                           P);
871      OS << Spec->getName() << TemplateArgsStr;
872    } else if (const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(*I)) {
873      if (ND->isAnonymousNamespace())
874        OS << "<anonymous namespace>";
875      else
876        OS << *ND;
877    } else if (const RecordDecl *RD = dyn_cast<RecordDecl>(*I)) {
878      if (!RD->getIdentifier())
879        OS << "<anonymous " << RD->getKindName() << '>';
880      else
881        OS << *RD;
882    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
883      const FunctionProtoType *FT = 0;
884      if (FD->hasWrittenPrototype())
885        FT = dyn_cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
886
887      OS << *FD << '(';
888      if (FT) {
889        unsigned NumParams = FD->getNumParams();
890        for (unsigned i = 0; i < NumParams; ++i) {
891          if (i)
892            OS << ", ";
893          std::string Param;
894          FD->getParamDecl(i)->getType().getAsStringInternal(Param, P);
895          OS << Param;
896        }
897
898        if (FT->isVariadic()) {
899          if (NumParams > 0)
900            OS << ", ";
901          OS << "...";
902        }
903      }
904      OS << ')';
905    } else {
906      OS << *cast<NamedDecl>(*I);
907    }
908    OS << "::";
909  }
910
911  if (getDeclName())
912    OS << *this;
913  else
914    OS << "<anonymous>";
915
916  return OS.str();
917}
918
919bool NamedDecl::declarationReplaces(NamedDecl *OldD) const {
920  assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
921
922  // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
923  // We want to keep it, unless it nominates same namespace.
924  if (getKind() == Decl::UsingDirective) {
925    return cast<UsingDirectiveDecl>(this)->getNominatedNamespace()
926             ->getOriginalNamespace() ==
927           cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
928             ->getOriginalNamespace();
929  }
930
931  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(this))
932    // For function declarations, we keep track of redeclarations.
933    return FD->getPreviousDecl() == OldD;
934
935  // For function templates, the underlying function declarations are linked.
936  if (const FunctionTemplateDecl *FunctionTemplate
937        = dyn_cast<FunctionTemplateDecl>(this))
938    if (const FunctionTemplateDecl *OldFunctionTemplate
939          = dyn_cast<FunctionTemplateDecl>(OldD))
940      return FunctionTemplate->getTemplatedDecl()
941               ->declarationReplaces(OldFunctionTemplate->getTemplatedDecl());
942
943  // For method declarations, we keep track of redeclarations.
944  if (isa<ObjCMethodDecl>(this))
945    return false;
946
947  if (isa<ObjCInterfaceDecl>(this) && isa<ObjCCompatibleAliasDecl>(OldD))
948    return true;
949
950  if (isa<UsingShadowDecl>(this) && isa<UsingShadowDecl>(OldD))
951    return cast<UsingShadowDecl>(this)->getTargetDecl() ==
952           cast<UsingShadowDecl>(OldD)->getTargetDecl();
953
954  if (isa<UsingDecl>(this) && isa<UsingDecl>(OldD)) {
955    ASTContext &Context = getASTContext();
956    return Context.getCanonicalNestedNameSpecifier(
957                                     cast<UsingDecl>(this)->getQualifier()) ==
958           Context.getCanonicalNestedNameSpecifier(
959                                        cast<UsingDecl>(OldD)->getQualifier());
960  }
961
962  // A typedef of an Objective-C class type can replace an Objective-C class
963  // declaration or definition, and vice versa.
964  if ((isa<TypedefNameDecl>(this) && isa<ObjCInterfaceDecl>(OldD)) ||
965      (isa<ObjCInterfaceDecl>(this) && isa<TypedefNameDecl>(OldD)))
966    return true;
967
968  // For non-function declarations, if the declarations are of the
969  // same kind then this must be a redeclaration, or semantic analysis
970  // would not have given us the new declaration.
971  return this->getKind() == OldD->getKind();
972}
973
974bool NamedDecl::hasLinkage() const {
975  return getLinkage() != NoLinkage;
976}
977
978NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
979  NamedDecl *ND = this;
980  while (UsingShadowDecl *UD = dyn_cast<UsingShadowDecl>(ND))
981    ND = UD->getTargetDecl();
982
983  if (ObjCCompatibleAliasDecl *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
984    return AD->getClassInterface();
985
986  return ND;
987}
988
989bool NamedDecl::isCXXInstanceMember() const {
990  if (!isCXXClassMember())
991    return false;
992
993  const NamedDecl *D = this;
994  if (isa<UsingShadowDecl>(D))
995    D = cast<UsingShadowDecl>(D)->getTargetDecl();
996
997  if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
998    return true;
999  if (isa<CXXMethodDecl>(D))
1000    return cast<CXXMethodDecl>(D)->isInstance();
1001  if (isa<FunctionTemplateDecl>(D))
1002    return cast<CXXMethodDecl>(cast<FunctionTemplateDecl>(D)
1003                                 ->getTemplatedDecl())->isInstance();
1004  return false;
1005}
1006
1007//===----------------------------------------------------------------------===//
1008// DeclaratorDecl Implementation
1009//===----------------------------------------------------------------------===//
1010
1011template <typename DeclT>
1012static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1013  if (decl->getNumTemplateParameterLists() > 0)
1014    return decl->getTemplateParameterList(0)->getTemplateLoc();
1015  else
1016    return decl->getInnerLocStart();
1017}
1018
1019SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1020  TypeSourceInfo *TSI = getTypeSourceInfo();
1021  if (TSI) return TSI->getTypeLoc().getBeginLoc();
1022  return SourceLocation();
1023}
1024
1025void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1026  if (QualifierLoc) {
1027    // Make sure the extended decl info is allocated.
1028    if (!hasExtInfo()) {
1029      // Save (non-extended) type source info pointer.
1030      TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1031      // Allocate external info struct.
1032      DeclInfo = new (getASTContext()) ExtInfo;
1033      // Restore savedTInfo into (extended) decl info.
1034      getExtInfo()->TInfo = savedTInfo;
1035    }
1036    // Set qualifier info.
1037    getExtInfo()->QualifierLoc = QualifierLoc;
1038  } else {
1039    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1040    if (hasExtInfo()) {
1041      if (getExtInfo()->NumTemplParamLists == 0) {
1042        // Save type source info pointer.
1043        TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1044        // Deallocate the extended decl info.
1045        getASTContext().Deallocate(getExtInfo());
1046        // Restore savedTInfo into (non-extended) decl info.
1047        DeclInfo = savedTInfo;
1048      }
1049      else
1050        getExtInfo()->QualifierLoc = QualifierLoc;
1051    }
1052  }
1053}
1054
1055void
1056DeclaratorDecl::setTemplateParameterListsInfo(ASTContext &Context,
1057                                              unsigned NumTPLists,
1058                                              TemplateParameterList **TPLists) {
1059  assert(NumTPLists > 0);
1060  // Make sure the extended decl info is allocated.
1061  if (!hasExtInfo()) {
1062    // Save (non-extended) type source info pointer.
1063    TypeSourceInfo *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1064    // Allocate external info struct.
1065    DeclInfo = new (getASTContext()) ExtInfo;
1066    // Restore savedTInfo into (extended) decl info.
1067    getExtInfo()->TInfo = savedTInfo;
1068  }
1069  // Set the template parameter lists info.
1070  getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
1071}
1072
1073SourceLocation DeclaratorDecl::getOuterLocStart() const {
1074  return getTemplateOrInnerLocStart(this);
1075}
1076
1077namespace {
1078
1079// Helper function: returns true if QT is or contains a type
1080// having a postfix component.
1081bool typeIsPostfix(clang::QualType QT) {
1082  while (true) {
1083    const Type* T = QT.getTypePtr();
1084    switch (T->getTypeClass()) {
1085    default:
1086      return false;
1087    case Type::Pointer:
1088      QT = cast<PointerType>(T)->getPointeeType();
1089      break;
1090    case Type::BlockPointer:
1091      QT = cast<BlockPointerType>(T)->getPointeeType();
1092      break;
1093    case Type::MemberPointer:
1094      QT = cast<MemberPointerType>(T)->getPointeeType();
1095      break;
1096    case Type::LValueReference:
1097    case Type::RValueReference:
1098      QT = cast<ReferenceType>(T)->getPointeeType();
1099      break;
1100    case Type::PackExpansion:
1101      QT = cast<PackExpansionType>(T)->getPattern();
1102      break;
1103    case Type::Paren:
1104    case Type::ConstantArray:
1105    case Type::DependentSizedArray:
1106    case Type::IncompleteArray:
1107    case Type::VariableArray:
1108    case Type::FunctionProto:
1109    case Type::FunctionNoProto:
1110      return true;
1111    }
1112  }
1113}
1114
1115} // namespace
1116
1117SourceRange DeclaratorDecl::getSourceRange() const {
1118  SourceLocation RangeEnd = getLocation();
1119  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1120    if (typeIsPostfix(TInfo->getType()))
1121      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1122  }
1123  return SourceRange(getOuterLocStart(), RangeEnd);
1124}
1125
1126void
1127QualifierInfo::setTemplateParameterListsInfo(ASTContext &Context,
1128                                             unsigned NumTPLists,
1129                                             TemplateParameterList **TPLists) {
1130  assert((NumTPLists == 0 || TPLists != 0) &&
1131         "Empty array of template parameters with positive size!");
1132
1133  // Free previous template parameters (if any).
1134  if (NumTemplParamLists > 0) {
1135    Context.Deallocate(TemplParamLists);
1136    TemplParamLists = 0;
1137    NumTemplParamLists = 0;
1138  }
1139  // Set info on matched template parameter lists (if any).
1140  if (NumTPLists > 0) {
1141    TemplParamLists = new (Context) TemplateParameterList*[NumTPLists];
1142    NumTemplParamLists = NumTPLists;
1143    for (unsigned i = NumTPLists; i-- > 0; )
1144      TemplParamLists[i] = TPLists[i];
1145  }
1146}
1147
1148//===----------------------------------------------------------------------===//
1149// VarDecl Implementation
1150//===----------------------------------------------------------------------===//
1151
1152const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1153  switch (SC) {
1154  case SC_None:                 break;
1155  case SC_Auto:                 return "auto";
1156  case SC_Extern:               return "extern";
1157  case SC_OpenCLWorkGroupLocal: return "<<work-group-local>>";
1158  case SC_PrivateExtern:        return "__private_extern__";
1159  case SC_Register:             return "register";
1160  case SC_Static:               return "static";
1161  }
1162
1163  llvm_unreachable("Invalid storage class");
1164}
1165
1166VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1167                         SourceLocation StartL, SourceLocation IdL,
1168                         IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1169                         StorageClass S, StorageClass SCAsWritten) {
1170  return new (C) VarDecl(Var, DC, StartL, IdL, Id, T, TInfo, S, SCAsWritten);
1171}
1172
1173VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1174  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(VarDecl));
1175  return new (Mem) VarDecl(Var, 0, SourceLocation(), SourceLocation(), 0,
1176                           QualType(), 0, SC_None, SC_None);
1177}
1178
1179void VarDecl::setStorageClass(StorageClass SC) {
1180  assert(isLegalForVariable(SC));
1181  if (getStorageClass() != SC)
1182    ClearLinkageCache();
1183
1184  VarDeclBits.SClass = SC;
1185}
1186
1187SourceRange VarDecl::getSourceRange() const {
1188  if (getInit())
1189    return SourceRange(getOuterLocStart(), getInit()->getLocEnd());
1190  return DeclaratorDecl::getSourceRange();
1191}
1192
1193bool VarDecl::isExternC() const {
1194  if (getLinkage() != ExternalLinkage)
1195    return false;
1196
1197  const DeclContext *DC = getDeclContext();
1198  if (DC->isRecord())
1199    return false;
1200
1201  ASTContext &Context = getASTContext();
1202  if (!Context.getLangOpts().CPlusPlus)
1203    return true;
1204  return DC->isExternCContext();
1205}
1206
1207VarDecl *VarDecl::getCanonicalDecl() {
1208  return getFirstDeclaration();
1209}
1210
1211VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
1212  ASTContext &C) const
1213{
1214  // C++ [basic.def]p2:
1215  //   A declaration is a definition unless [...] it contains the 'extern'
1216  //   specifier or a linkage-specification and neither an initializer [...],
1217  //   it declares a static data member in a class declaration [...].
1218  // C++ [temp.expl.spec]p15:
1219  //   An explicit specialization of a static data member of a template is a
1220  //   definition if the declaration includes an initializer; otherwise, it is
1221  //   a declaration.
1222  if (isStaticDataMember()) {
1223    if (isOutOfLine() && (hasInit() ||
1224          getTemplateSpecializationKind() != TSK_ExplicitSpecialization))
1225      return Definition;
1226    else
1227      return DeclarationOnly;
1228  }
1229  // C99 6.7p5:
1230  //   A definition of an identifier is a declaration for that identifier that
1231  //   [...] causes storage to be reserved for that object.
1232  // Note: that applies for all non-file-scope objects.
1233  // C99 6.9.2p1:
1234  //   If the declaration of an identifier for an object has file scope and an
1235  //   initializer, the declaration is an external definition for the identifier
1236  if (hasInit())
1237    return Definition;
1238  // AST for 'extern "C" int foo;' is annotated with 'extern'.
1239  if (hasExternalStorage())
1240    return DeclarationOnly;
1241
1242  if (getStorageClassAsWritten() == SC_Extern ||
1243       getStorageClassAsWritten() == SC_PrivateExtern) {
1244    for (const VarDecl *PrevVar = getPreviousDecl();
1245         PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
1246      if (PrevVar->getLinkage() == InternalLinkage && PrevVar->hasInit())
1247        return DeclarationOnly;
1248    }
1249  }
1250  // C99 6.9.2p2:
1251  //   A declaration of an object that has file scope without an initializer,
1252  //   and without a storage class specifier or the scs 'static', constitutes
1253  //   a tentative definition.
1254  // No such thing in C++.
1255  if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1256    return TentativeDefinition;
1257
1258  // What's left is (in C, block-scope) declarations without initializers or
1259  // external storage. These are definitions.
1260  return Definition;
1261}
1262
1263VarDecl *VarDecl::getActingDefinition() {
1264  DefinitionKind Kind = isThisDeclarationADefinition();
1265  if (Kind != TentativeDefinition)
1266    return 0;
1267
1268  VarDecl *LastTentative = 0;
1269  VarDecl *First = getFirstDeclaration();
1270  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1271       I != E; ++I) {
1272    Kind = (*I)->isThisDeclarationADefinition();
1273    if (Kind == Definition)
1274      return 0;
1275    else if (Kind == TentativeDefinition)
1276      LastTentative = *I;
1277  }
1278  return LastTentative;
1279}
1280
1281bool VarDecl::isTentativeDefinitionNow() const {
1282  DefinitionKind Kind = isThisDeclarationADefinition();
1283  if (Kind != TentativeDefinition)
1284    return false;
1285
1286  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1287    if ((*I)->isThisDeclarationADefinition() == Definition)
1288      return false;
1289  }
1290  return true;
1291}
1292
1293VarDecl *VarDecl::getDefinition(ASTContext &C) {
1294  VarDecl *First = getFirstDeclaration();
1295  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1296       I != E; ++I) {
1297    if ((*I)->isThisDeclarationADefinition(C) == Definition)
1298      return *I;
1299  }
1300  return 0;
1301}
1302
1303VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
1304  DefinitionKind Kind = DeclarationOnly;
1305
1306  const VarDecl *First = getFirstDeclaration();
1307  for (redecl_iterator I = First->redecls_begin(), E = First->redecls_end();
1308       I != E; ++I) {
1309    Kind = std::max(Kind, (*I)->isThisDeclarationADefinition(C));
1310    if (Kind == Definition)
1311      break;
1312  }
1313
1314  return Kind;
1315}
1316
1317const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
1318  redecl_iterator I = redecls_begin(), E = redecls_end();
1319  while (I != E && !I->getInit())
1320    ++I;
1321
1322  if (I != E) {
1323    D = *I;
1324    return I->getInit();
1325  }
1326  return 0;
1327}
1328
1329bool VarDecl::isOutOfLine() const {
1330  if (Decl::isOutOfLine())
1331    return true;
1332
1333  if (!isStaticDataMember())
1334    return false;
1335
1336  // If this static data member was instantiated from a static data member of
1337  // a class template, check whether that static data member was defined
1338  // out-of-line.
1339  if (VarDecl *VD = getInstantiatedFromStaticDataMember())
1340    return VD->isOutOfLine();
1341
1342  return false;
1343}
1344
1345VarDecl *VarDecl::getOutOfLineDefinition() {
1346  if (!isStaticDataMember())
1347    return 0;
1348
1349  for (VarDecl::redecl_iterator RD = redecls_begin(), RDEnd = redecls_end();
1350       RD != RDEnd; ++RD) {
1351    if (RD->getLexicalDeclContext()->isFileContext())
1352      return *RD;
1353  }
1354
1355  return 0;
1356}
1357
1358void VarDecl::setInit(Expr *I) {
1359  if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
1360    Eval->~EvaluatedStmt();
1361    getASTContext().Deallocate(Eval);
1362  }
1363
1364  Init = I;
1365}
1366
1367bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
1368  const LangOptions &Lang = C.getLangOpts();
1369
1370  if (!Lang.CPlusPlus)
1371    return false;
1372
1373  // In C++11, any variable of reference type can be used in a constant
1374  // expression if it is initialized by a constant expression.
1375  if (Lang.CPlusPlus0x && getType()->isReferenceType())
1376    return true;
1377
1378  // Only const objects can be used in constant expressions in C++. C++98 does
1379  // not require the variable to be non-volatile, but we consider this to be a
1380  // defect.
1381  if (!getType().isConstQualified() || getType().isVolatileQualified())
1382    return false;
1383
1384  // In C++, const, non-volatile variables of integral or enumeration types
1385  // can be used in constant expressions.
1386  if (getType()->isIntegralOrEnumerationType())
1387    return true;
1388
1389  // Additionally, in C++11, non-volatile constexpr variables can be used in
1390  // constant expressions.
1391  return Lang.CPlusPlus0x && isConstexpr();
1392}
1393
1394/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
1395/// form, which contains extra information on the evaluated value of the
1396/// initializer.
1397EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
1398  EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>();
1399  if (!Eval) {
1400    Stmt *S = Init.get<Stmt *>();
1401    Eval = new (getASTContext()) EvaluatedStmt;
1402    Eval->Value = S;
1403    Init = Eval;
1404  }
1405  return Eval;
1406}
1407
1408APValue *VarDecl::evaluateValue() const {
1409  llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1410  return evaluateValue(Notes);
1411}
1412
1413APValue *VarDecl::evaluateValue(
1414    llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
1415  EvaluatedStmt *Eval = ensureEvaluatedStmt();
1416
1417  // We only produce notes indicating why an initializer is non-constant the
1418  // first time it is evaluated. FIXME: The notes won't always be emitted the
1419  // first time we try evaluation, so might not be produced at all.
1420  if (Eval->WasEvaluated)
1421    return Eval->Evaluated.isUninit() ? 0 : &Eval->Evaluated;
1422
1423  const Expr *Init = cast<Expr>(Eval->Value);
1424  assert(!Init->isValueDependent());
1425
1426  if (Eval->IsEvaluating) {
1427    // FIXME: Produce a diagnostic for self-initialization.
1428    Eval->CheckedICE = true;
1429    Eval->IsICE = false;
1430    return 0;
1431  }
1432
1433  Eval->IsEvaluating = true;
1434
1435  bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
1436                                            this, Notes);
1437
1438  // Ensure the result is an uninitialized APValue if evaluation fails.
1439  if (!Result)
1440    Eval->Evaluated = APValue();
1441
1442  Eval->IsEvaluating = false;
1443  Eval->WasEvaluated = true;
1444
1445  // In C++11, we have determined whether the initializer was a constant
1446  // expression as a side-effect.
1447  if (getASTContext().getLangOpts().CPlusPlus0x && !Eval->CheckedICE) {
1448    Eval->CheckedICE = true;
1449    Eval->IsICE = Result && Notes.empty();
1450  }
1451
1452  return Result ? &Eval->Evaluated : 0;
1453}
1454
1455bool VarDecl::checkInitIsICE() const {
1456  // Initializers of weak variables are never ICEs.
1457  if (isWeak())
1458    return false;
1459
1460  EvaluatedStmt *Eval = ensureEvaluatedStmt();
1461  if (Eval->CheckedICE)
1462    // We have already checked whether this subexpression is an
1463    // integral constant expression.
1464    return Eval->IsICE;
1465
1466  const Expr *Init = cast<Expr>(Eval->Value);
1467  assert(!Init->isValueDependent());
1468
1469  // In C++11, evaluate the initializer to check whether it's a constant
1470  // expression.
1471  if (getASTContext().getLangOpts().CPlusPlus0x) {
1472    llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1473    evaluateValue(Notes);
1474    return Eval->IsICE;
1475  }
1476
1477  // It's an ICE whether or not the definition we found is
1478  // out-of-line.  See DR 721 and the discussion in Clang PR
1479  // 6206 for details.
1480
1481  if (Eval->CheckingICE)
1482    return false;
1483  Eval->CheckingICE = true;
1484
1485  Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
1486  Eval->CheckingICE = false;
1487  Eval->CheckedICE = true;
1488  return Eval->IsICE;
1489}
1490
1491bool VarDecl::extendsLifetimeOfTemporary() const {
1492  assert(getType()->isReferenceType() &&"Non-references never extend lifetime");
1493
1494  const Expr *E = getInit();
1495  if (!E)
1496    return false;
1497
1498  if (const ExprWithCleanups *Cleanups = dyn_cast<ExprWithCleanups>(E))
1499    E = Cleanups->getSubExpr();
1500
1501  return isa<MaterializeTemporaryExpr>(E);
1502}
1503
1504VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
1505  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1506    return cast<VarDecl>(MSI->getInstantiatedFrom());
1507
1508  return 0;
1509}
1510
1511TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
1512  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
1513    return MSI->getTemplateSpecializationKind();
1514
1515  return TSK_Undeclared;
1516}
1517
1518MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
1519  return getASTContext().getInstantiatedFromStaticDataMember(this);
1520}
1521
1522void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
1523                                         SourceLocation PointOfInstantiation) {
1524  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
1525  assert(MSI && "Not an instantiated static data member?");
1526  MSI->setTemplateSpecializationKind(TSK);
1527  if (TSK != TSK_ExplicitSpecialization &&
1528      PointOfInstantiation.isValid() &&
1529      MSI->getPointOfInstantiation().isInvalid())
1530    MSI->setPointOfInstantiation(PointOfInstantiation);
1531}
1532
1533//===----------------------------------------------------------------------===//
1534// ParmVarDecl Implementation
1535//===----------------------------------------------------------------------===//
1536
1537ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
1538                                 SourceLocation StartLoc,
1539                                 SourceLocation IdLoc, IdentifierInfo *Id,
1540                                 QualType T, TypeSourceInfo *TInfo,
1541                                 StorageClass S, StorageClass SCAsWritten,
1542                                 Expr *DefArg) {
1543  return new (C) ParmVarDecl(ParmVar, DC, StartLoc, IdLoc, Id, T, TInfo,
1544                             S, SCAsWritten, DefArg);
1545}
1546
1547ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1548  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ParmVarDecl));
1549  return new (Mem) ParmVarDecl(ParmVar, 0, SourceLocation(), SourceLocation(),
1550                               0, QualType(), 0, SC_None, SC_None, 0);
1551}
1552
1553SourceRange ParmVarDecl::getSourceRange() const {
1554  if (!hasInheritedDefaultArg()) {
1555    SourceRange ArgRange = getDefaultArgRange();
1556    if (ArgRange.isValid())
1557      return SourceRange(getOuterLocStart(), ArgRange.getEnd());
1558  }
1559
1560  return DeclaratorDecl::getSourceRange();
1561}
1562
1563Expr *ParmVarDecl::getDefaultArg() {
1564  assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
1565  assert(!hasUninstantiatedDefaultArg() &&
1566         "Default argument is not yet instantiated!");
1567
1568  Expr *Arg = getInit();
1569  if (ExprWithCleanups *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
1570    return E->getSubExpr();
1571
1572  return Arg;
1573}
1574
1575SourceRange ParmVarDecl::getDefaultArgRange() const {
1576  if (const Expr *E = getInit())
1577    return E->getSourceRange();
1578
1579  if (hasUninstantiatedDefaultArg())
1580    return getUninstantiatedDefaultArg()->getSourceRange();
1581
1582  return SourceRange();
1583}
1584
1585bool ParmVarDecl::isParameterPack() const {
1586  return isa<PackExpansionType>(getType());
1587}
1588
1589void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
1590  getASTContext().setParameterIndex(this, parameterIndex);
1591  ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
1592}
1593
1594unsigned ParmVarDecl::getParameterIndexLarge() const {
1595  return getASTContext().getParameterIndex(this);
1596}
1597
1598//===----------------------------------------------------------------------===//
1599// FunctionDecl Implementation
1600//===----------------------------------------------------------------------===//
1601
1602void FunctionDecl::getNameForDiagnostic(std::string &S,
1603                                        const PrintingPolicy &Policy,
1604                                        bool Qualified) const {
1605  NamedDecl::getNameForDiagnostic(S, Policy, Qualified);
1606  const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
1607  if (TemplateArgs)
1608    S += TemplateSpecializationType::PrintTemplateArgumentList(
1609                                                         TemplateArgs->data(),
1610                                                         TemplateArgs->size(),
1611                                                               Policy);
1612
1613}
1614
1615bool FunctionDecl::isVariadic() const {
1616  if (const FunctionProtoType *FT = getType()->getAs<FunctionProtoType>())
1617    return FT->isVariadic();
1618  return false;
1619}
1620
1621bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
1622  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1623    if (I->Body || I->IsLateTemplateParsed) {
1624      Definition = *I;
1625      return true;
1626    }
1627  }
1628
1629  return false;
1630}
1631
1632bool FunctionDecl::hasTrivialBody() const
1633{
1634  Stmt *S = getBody();
1635  if (!S) {
1636    // Since we don't have a body for this function, we don't know if it's
1637    // trivial or not.
1638    return false;
1639  }
1640
1641  if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
1642    return true;
1643  return false;
1644}
1645
1646bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
1647  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1648    if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed) {
1649      Definition = I->IsDeleted ? I->getCanonicalDecl() : *I;
1650      return true;
1651    }
1652  }
1653
1654  return false;
1655}
1656
1657Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
1658  for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I) {
1659    if (I->Body) {
1660      Definition = *I;
1661      return I->Body.get(getASTContext().getExternalSource());
1662    } else if (I->IsLateTemplateParsed) {
1663      Definition = *I;
1664      return 0;
1665    }
1666  }
1667
1668  return 0;
1669}
1670
1671void FunctionDecl::setBody(Stmt *B) {
1672  Body = B;
1673  if (B)
1674    EndRangeLoc = B->getLocEnd();
1675}
1676
1677void FunctionDecl::setPure(bool P) {
1678  IsPure = P;
1679  if (P)
1680    if (CXXRecordDecl *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
1681      Parent->markedVirtualFunctionPure();
1682}
1683
1684bool FunctionDecl::isMain() const {
1685  const TranslationUnitDecl *tunit =
1686    dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
1687  return tunit &&
1688         !tunit->getASTContext().getLangOpts().Freestanding &&
1689         getIdentifier() &&
1690         getIdentifier()->isStr("main");
1691}
1692
1693bool FunctionDecl::isReservedGlobalPlacementOperator() const {
1694  assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
1695  assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
1696         getDeclName().getCXXOverloadedOperator() == OO_Delete ||
1697         getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
1698         getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
1699
1700  if (isa<CXXRecordDecl>(getDeclContext())) return false;
1701  assert(getDeclContext()->getRedeclContext()->isTranslationUnit());
1702
1703  const FunctionProtoType *proto = getType()->castAs<FunctionProtoType>();
1704  if (proto->getNumArgs() != 2 || proto->isVariadic()) return false;
1705
1706  ASTContext &Context =
1707    cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
1708      ->getASTContext();
1709
1710  // The result type and first argument type are constant across all
1711  // these operators.  The second argument must be exactly void*.
1712  return (proto->getArgType(1).getCanonicalType() == Context.VoidPtrTy);
1713}
1714
1715bool FunctionDecl::isExternC() const {
1716  if (getLinkage() != ExternalLinkage)
1717    return false;
1718
1719  if (getAttr<OverloadableAttr>())
1720    return false;
1721
1722  const DeclContext *DC = getDeclContext();
1723  if (DC->isRecord())
1724    return false;
1725
1726  ASTContext &Context = getASTContext();
1727  if (!Context.getLangOpts().CPlusPlus)
1728    return true;
1729
1730  return isMain() || DC->isExternCContext();
1731}
1732
1733bool FunctionDecl::isGlobal() const {
1734  if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
1735    return Method->isStatic();
1736
1737  if (getStorageClass() == SC_Static)
1738    return false;
1739
1740  for (const DeclContext *DC = getDeclContext();
1741       DC->isNamespace();
1742       DC = DC->getParent()) {
1743    if (const NamespaceDecl *Namespace = cast<NamespaceDecl>(DC)) {
1744      if (!Namespace->getDeclName())
1745        return false;
1746      break;
1747    }
1748  }
1749
1750  return true;
1751}
1752
1753void
1754FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
1755  redeclarable_base::setPreviousDeclaration(PrevDecl);
1756
1757  if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
1758    FunctionTemplateDecl *PrevFunTmpl
1759      = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : 0;
1760    assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
1761    FunTmpl->setPreviousDeclaration(PrevFunTmpl);
1762  }
1763
1764  if (PrevDecl && PrevDecl->IsInline)
1765    IsInline = true;
1766}
1767
1768const FunctionDecl *FunctionDecl::getCanonicalDecl() const {
1769  return getFirstDeclaration();
1770}
1771
1772FunctionDecl *FunctionDecl::getCanonicalDecl() {
1773  return getFirstDeclaration();
1774}
1775
1776void FunctionDecl::setStorageClass(StorageClass SC) {
1777  assert(isLegalForFunction(SC));
1778  if (getStorageClass() != SC)
1779    ClearLinkageCache();
1780
1781  SClass = SC;
1782}
1783
1784/// \brief Returns a value indicating whether this function
1785/// corresponds to a builtin function.
1786///
1787/// The function corresponds to a built-in function if it is
1788/// declared at translation scope or within an extern "C" block and
1789/// its name matches with the name of a builtin. The returned value
1790/// will be 0 for functions that do not correspond to a builtin, a
1791/// value of type \c Builtin::ID if in the target-independent range
1792/// \c [1,Builtin::First), or a target-specific builtin value.
1793unsigned FunctionDecl::getBuiltinID() const {
1794  if (!getIdentifier())
1795    return 0;
1796
1797  unsigned BuiltinID = getIdentifier()->getBuiltinID();
1798  if (!BuiltinID)
1799    return 0;
1800
1801  ASTContext &Context = getASTContext();
1802  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
1803    return BuiltinID;
1804
1805  // This function has the name of a known C library
1806  // function. Determine whether it actually refers to the C library
1807  // function or whether it just has the same name.
1808
1809  // If this is a static function, it's not a builtin.
1810  if (getStorageClass() == SC_Static)
1811    return 0;
1812
1813  // If this function is at translation-unit scope and we're not in
1814  // C++, it refers to the C library function.
1815  if (!Context.getLangOpts().CPlusPlus &&
1816      getDeclContext()->isTranslationUnit())
1817    return BuiltinID;
1818
1819  // If the function is in an extern "C" linkage specification and is
1820  // not marked "overloadable", it's the real function.
1821  if (isa<LinkageSpecDecl>(getDeclContext()) &&
1822      cast<LinkageSpecDecl>(getDeclContext())->getLanguage()
1823        == LinkageSpecDecl::lang_c &&
1824      !getAttr<OverloadableAttr>())
1825    return BuiltinID;
1826
1827  // Not a builtin
1828  return 0;
1829}
1830
1831
1832/// getNumParams - Return the number of parameters this function must have
1833/// based on its FunctionType.  This is the length of the ParamInfo array
1834/// after it has been created.
1835unsigned FunctionDecl::getNumParams() const {
1836  const FunctionType *FT = getType()->getAs<FunctionType>();
1837  if (isa<FunctionNoProtoType>(FT))
1838    return 0;
1839  return cast<FunctionProtoType>(FT)->getNumArgs();
1840
1841}
1842
1843void FunctionDecl::setParams(ASTContext &C,
1844                             llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
1845  assert(ParamInfo == 0 && "Already has param info!");
1846  assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
1847
1848  // Zero params -> null pointer.
1849  if (!NewParamInfo.empty()) {
1850    ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
1851    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
1852  }
1853}
1854
1855void FunctionDecl::setDeclsInPrototypeScope(llvm::ArrayRef<NamedDecl *> NewDecls) {
1856  assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
1857
1858  if (!NewDecls.empty()) {
1859    NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
1860    std::copy(NewDecls.begin(), NewDecls.end(), A);
1861    DeclsInPrototypeScope = llvm::ArrayRef<NamedDecl*>(A, NewDecls.size());
1862  }
1863}
1864
1865/// getMinRequiredArguments - Returns the minimum number of arguments
1866/// needed to call this function. This may be fewer than the number of
1867/// function parameters, if some of the parameters have default
1868/// arguments (in C++) or the last parameter is a parameter pack.
1869unsigned FunctionDecl::getMinRequiredArguments() const {
1870  if (!getASTContext().getLangOpts().CPlusPlus)
1871    return getNumParams();
1872
1873  unsigned NumRequiredArgs = getNumParams();
1874
1875  // If the last parameter is a parameter pack, we don't need an argument for
1876  // it.
1877  if (NumRequiredArgs > 0 &&
1878      getParamDecl(NumRequiredArgs - 1)->isParameterPack())
1879    --NumRequiredArgs;
1880
1881  // If this parameter has a default argument, we don't need an argument for
1882  // it.
1883  while (NumRequiredArgs > 0 &&
1884         getParamDecl(NumRequiredArgs-1)->hasDefaultArg())
1885    --NumRequiredArgs;
1886
1887  // We might have parameter packs before the end. These can't be deduced,
1888  // but they can still handle multiple arguments.
1889  unsigned ArgIdx = NumRequiredArgs;
1890  while (ArgIdx > 0) {
1891    if (getParamDecl(ArgIdx - 1)->isParameterPack())
1892      NumRequiredArgs = ArgIdx;
1893
1894    --ArgIdx;
1895  }
1896
1897  return NumRequiredArgs;
1898}
1899
1900bool FunctionDecl::isInlined() const {
1901  if (IsInline)
1902    return true;
1903
1904  if (isa<CXXMethodDecl>(this)) {
1905    if (!isOutOfLine() || getCanonicalDecl()->isInlineSpecified())
1906      return true;
1907  }
1908
1909  switch (getTemplateSpecializationKind()) {
1910  case TSK_Undeclared:
1911  case TSK_ExplicitSpecialization:
1912    return false;
1913
1914  case TSK_ImplicitInstantiation:
1915  case TSK_ExplicitInstantiationDeclaration:
1916  case TSK_ExplicitInstantiationDefinition:
1917    // Handle below.
1918    break;
1919  }
1920
1921  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
1922  bool HasPattern = false;
1923  if (PatternDecl)
1924    HasPattern = PatternDecl->hasBody(PatternDecl);
1925
1926  if (HasPattern && PatternDecl)
1927    return PatternDecl->isInlined();
1928
1929  return false;
1930}
1931
1932static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
1933  // Only consider file-scope declarations in this test.
1934  if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
1935    return false;
1936
1937  // Only consider explicit declarations; the presence of a builtin for a
1938  // libcall shouldn't affect whether a definition is externally visible.
1939  if (Redecl->isImplicit())
1940    return false;
1941
1942  if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
1943    return true; // Not an inline definition
1944
1945  return false;
1946}
1947
1948/// \brief For a function declaration in C or C++, determine whether this
1949/// declaration causes the definition to be externally visible.
1950///
1951/// Specifically, this determines if adding the current declaration to the set
1952/// of redeclarations of the given functions causes
1953/// isInlineDefinitionExternallyVisible to change from false to true.
1954bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
1955  assert(!doesThisDeclarationHaveABody() &&
1956         "Must have a declaration without a body.");
1957
1958  ASTContext &Context = getASTContext();
1959
1960  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
1961    // With GNU inlining, a declaration with 'inline' but not 'extern', forces
1962    // an externally visible definition.
1963    //
1964    // FIXME: What happens if gnu_inline gets added on after the first
1965    // declaration?
1966    if (!isInlineSpecified() || getStorageClassAsWritten() == SC_Extern)
1967      return false;
1968
1969    const FunctionDecl *Prev = this;
1970    bool FoundBody = false;
1971    while ((Prev = Prev->getPreviousDecl())) {
1972      FoundBody |= Prev->Body;
1973
1974      if (Prev->Body) {
1975        // If it's not the case that both 'inline' and 'extern' are
1976        // specified on the definition, then it is always externally visible.
1977        if (!Prev->isInlineSpecified() ||
1978            Prev->getStorageClassAsWritten() != SC_Extern)
1979          return false;
1980      } else if (Prev->isInlineSpecified() &&
1981                 Prev->getStorageClassAsWritten() != SC_Extern) {
1982        return false;
1983      }
1984    }
1985    return FoundBody;
1986  }
1987
1988  if (Context.getLangOpts().CPlusPlus)
1989    return false;
1990
1991  // C99 6.7.4p6:
1992  //   [...] If all of the file scope declarations for a function in a
1993  //   translation unit include the inline function specifier without extern,
1994  //   then the definition in that translation unit is an inline definition.
1995  if (isInlineSpecified() && getStorageClass() != SC_Extern)
1996    return false;
1997  const FunctionDecl *Prev = this;
1998  bool FoundBody = false;
1999  while ((Prev = Prev->getPreviousDecl())) {
2000    FoundBody |= Prev->Body;
2001    if (RedeclForcesDefC99(Prev))
2002      return false;
2003  }
2004  return FoundBody;
2005}
2006
2007/// \brief For an inline function definition in C or C++, determine whether the
2008/// definition will be externally visible.
2009///
2010/// Inline function definitions are always available for inlining optimizations.
2011/// However, depending on the language dialect, declaration specifiers, and
2012/// attributes, the definition of an inline function may or may not be
2013/// "externally" visible to other translation units in the program.
2014///
2015/// In C99, inline definitions are not externally visible by default. However,
2016/// if even one of the global-scope declarations is marked "extern inline", the
2017/// inline definition becomes externally visible (C99 6.7.4p6).
2018///
2019/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2020/// definition, we use the GNU semantics for inline, which are nearly the
2021/// opposite of C99 semantics. In particular, "inline" by itself will create
2022/// an externally visible symbol, but "extern inline" will not create an
2023/// externally visible symbol.
2024bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2025  assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2026  assert(isInlined() && "Function must be inline");
2027  ASTContext &Context = getASTContext();
2028
2029  if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2030    // Note: If you change the logic here, please change
2031    // doesDeclarationForceExternallyVisibleDefinition as well.
2032    //
2033    // If it's not the case that both 'inline' and 'extern' are
2034    // specified on the definition, then this inline definition is
2035    // externally visible.
2036    if (!(isInlineSpecified() && getStorageClassAsWritten() == SC_Extern))
2037      return true;
2038
2039    // If any declaration is 'inline' but not 'extern', then this definition
2040    // is externally visible.
2041    for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2042         Redecl != RedeclEnd;
2043         ++Redecl) {
2044      if (Redecl->isInlineSpecified() &&
2045          Redecl->getStorageClassAsWritten() != SC_Extern)
2046        return true;
2047    }
2048
2049    return false;
2050  }
2051
2052  // C99 6.7.4p6:
2053  //   [...] If all of the file scope declarations for a function in a
2054  //   translation unit include the inline function specifier without extern,
2055  //   then the definition in that translation unit is an inline definition.
2056  for (redecl_iterator Redecl = redecls_begin(), RedeclEnd = redecls_end();
2057       Redecl != RedeclEnd;
2058       ++Redecl) {
2059    if (RedeclForcesDefC99(*Redecl))
2060      return true;
2061  }
2062
2063  // C99 6.7.4p6:
2064  //   An inline definition does not provide an external definition for the
2065  //   function, and does not forbid an external definition in another
2066  //   translation unit.
2067  return false;
2068}
2069
2070/// getOverloadedOperator - Which C++ overloaded operator this
2071/// function represents, if any.
2072OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
2073  if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
2074    return getDeclName().getCXXOverloadedOperator();
2075  else
2076    return OO_None;
2077}
2078
2079/// getLiteralIdentifier - The literal suffix identifier this function
2080/// represents, if any.
2081const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
2082  if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
2083    return getDeclName().getCXXLiteralIdentifier();
2084  else
2085    return 0;
2086}
2087
2088FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
2089  if (TemplateOrSpecialization.isNull())
2090    return TK_NonTemplate;
2091  if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
2092    return TK_FunctionTemplate;
2093  if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
2094    return TK_MemberSpecialization;
2095  if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
2096    return TK_FunctionTemplateSpecialization;
2097  if (TemplateOrSpecialization.is
2098                               <DependentFunctionTemplateSpecializationInfo*>())
2099    return TK_DependentFunctionTemplateSpecialization;
2100
2101  llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
2102}
2103
2104FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
2105  if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
2106    return cast<FunctionDecl>(Info->getInstantiatedFrom());
2107
2108  return 0;
2109}
2110
2111MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
2112  return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2113}
2114
2115void
2116FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
2117                                               FunctionDecl *FD,
2118                                               TemplateSpecializationKind TSK) {
2119  assert(TemplateOrSpecialization.isNull() &&
2120         "Member function is already a specialization");
2121  MemberSpecializationInfo *Info
2122    = new (C) MemberSpecializationInfo(FD, TSK);
2123  TemplateOrSpecialization = Info;
2124}
2125
2126bool FunctionDecl::isImplicitlyInstantiable() const {
2127  // If the function is invalid, it can't be implicitly instantiated.
2128  if (isInvalidDecl())
2129    return false;
2130
2131  switch (getTemplateSpecializationKind()) {
2132  case TSK_Undeclared:
2133  case TSK_ExplicitInstantiationDefinition:
2134    return false;
2135
2136  case TSK_ImplicitInstantiation:
2137    return true;
2138
2139  // It is possible to instantiate TSK_ExplicitSpecialization kind
2140  // if the FunctionDecl has a class scope specialization pattern.
2141  case TSK_ExplicitSpecialization:
2142    return getClassScopeSpecializationPattern() != 0;
2143
2144  case TSK_ExplicitInstantiationDeclaration:
2145    // Handled below.
2146    break;
2147  }
2148
2149  // Find the actual template from which we will instantiate.
2150  const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
2151  bool HasPattern = false;
2152  if (PatternDecl)
2153    HasPattern = PatternDecl->hasBody(PatternDecl);
2154
2155  // C++0x [temp.explicit]p9:
2156  //   Except for inline functions, other explicit instantiation declarations
2157  //   have the effect of suppressing the implicit instantiation of the entity
2158  //   to which they refer.
2159  if (!HasPattern || !PatternDecl)
2160    return true;
2161
2162  return PatternDecl->isInlined();
2163}
2164
2165bool FunctionDecl::isTemplateInstantiation() const {
2166  switch (getTemplateSpecializationKind()) {
2167    case TSK_Undeclared:
2168    case TSK_ExplicitSpecialization:
2169      return false;
2170    case TSK_ImplicitInstantiation:
2171    case TSK_ExplicitInstantiationDeclaration:
2172    case TSK_ExplicitInstantiationDefinition:
2173      return true;
2174  }
2175  llvm_unreachable("All TSK values handled.");
2176}
2177
2178FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
2179  // Handle class scope explicit specialization special case.
2180  if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
2181    return getClassScopeSpecializationPattern();
2182
2183  if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
2184    while (Primary->getInstantiatedFromMemberTemplate()) {
2185      // If we have hit a point where the user provided a specialization of
2186      // this template, we're done looking.
2187      if (Primary->isMemberSpecialization())
2188        break;
2189
2190      Primary = Primary->getInstantiatedFromMemberTemplate();
2191    }
2192
2193    return Primary->getTemplatedDecl();
2194  }
2195
2196  return getInstantiatedFromMemberFunction();
2197}
2198
2199FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
2200  if (FunctionTemplateSpecializationInfo *Info
2201        = TemplateOrSpecialization
2202            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2203    return Info->Template.getPointer();
2204  }
2205  return 0;
2206}
2207
2208FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
2209    return getASTContext().getClassScopeSpecializationPattern(this);
2210}
2211
2212const TemplateArgumentList *
2213FunctionDecl::getTemplateSpecializationArgs() const {
2214  if (FunctionTemplateSpecializationInfo *Info
2215        = TemplateOrSpecialization
2216            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2217    return Info->TemplateArguments;
2218  }
2219  return 0;
2220}
2221
2222const ASTTemplateArgumentListInfo *
2223FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
2224  if (FunctionTemplateSpecializationInfo *Info
2225        = TemplateOrSpecialization
2226            .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
2227    return Info->TemplateArgumentsAsWritten;
2228  }
2229  return 0;
2230}
2231
2232void
2233FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
2234                                                FunctionTemplateDecl *Template,
2235                                     const TemplateArgumentList *TemplateArgs,
2236                                                void *InsertPos,
2237                                                TemplateSpecializationKind TSK,
2238                        const TemplateArgumentListInfo *TemplateArgsAsWritten,
2239                                          SourceLocation PointOfInstantiation) {
2240  assert(TSK != TSK_Undeclared &&
2241         "Must specify the type of function template specialization");
2242  FunctionTemplateSpecializationInfo *Info
2243    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2244  if (!Info)
2245    Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
2246                                                      TemplateArgs,
2247                                                      TemplateArgsAsWritten,
2248                                                      PointOfInstantiation);
2249  TemplateOrSpecialization = Info;
2250  Template->addSpecialization(Info, InsertPos);
2251}
2252
2253void
2254FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
2255                                    const UnresolvedSetImpl &Templates,
2256                             const TemplateArgumentListInfo &TemplateArgs) {
2257  assert(TemplateOrSpecialization.isNull());
2258  size_t Size = sizeof(DependentFunctionTemplateSpecializationInfo);
2259  Size += Templates.size() * sizeof(FunctionTemplateDecl*);
2260  Size += TemplateArgs.size() * sizeof(TemplateArgumentLoc);
2261  void *Buffer = Context.Allocate(Size);
2262  DependentFunctionTemplateSpecializationInfo *Info =
2263    new (Buffer) DependentFunctionTemplateSpecializationInfo(Templates,
2264                                                             TemplateArgs);
2265  TemplateOrSpecialization = Info;
2266}
2267
2268DependentFunctionTemplateSpecializationInfo::
2269DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
2270                                      const TemplateArgumentListInfo &TArgs)
2271  : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
2272
2273  d.NumTemplates = Ts.size();
2274  d.NumArgs = TArgs.size();
2275
2276  FunctionTemplateDecl **TsArray =
2277    const_cast<FunctionTemplateDecl**>(getTemplates());
2278  for (unsigned I = 0, E = Ts.size(); I != E; ++I)
2279    TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
2280
2281  TemplateArgumentLoc *ArgsArray =
2282    const_cast<TemplateArgumentLoc*>(getTemplateArgs());
2283  for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
2284    new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
2285}
2286
2287TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
2288  // For a function template specialization, query the specialization
2289  // information object.
2290  FunctionTemplateSpecializationInfo *FTSInfo
2291    = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
2292  if (FTSInfo)
2293    return FTSInfo->getTemplateSpecializationKind();
2294
2295  MemberSpecializationInfo *MSInfo
2296    = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
2297  if (MSInfo)
2298    return MSInfo->getTemplateSpecializationKind();
2299
2300  return TSK_Undeclared;
2301}
2302
2303void
2304FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2305                                          SourceLocation PointOfInstantiation) {
2306  if (FunctionTemplateSpecializationInfo *FTSInfo
2307        = TemplateOrSpecialization.dyn_cast<
2308                                    FunctionTemplateSpecializationInfo*>()) {
2309    FTSInfo->setTemplateSpecializationKind(TSK);
2310    if (TSK != TSK_ExplicitSpecialization &&
2311        PointOfInstantiation.isValid() &&
2312        FTSInfo->getPointOfInstantiation().isInvalid())
2313      FTSInfo->setPointOfInstantiation(PointOfInstantiation);
2314  } else if (MemberSpecializationInfo *MSInfo
2315             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
2316    MSInfo->setTemplateSpecializationKind(TSK);
2317    if (TSK != TSK_ExplicitSpecialization &&
2318        PointOfInstantiation.isValid() &&
2319        MSInfo->getPointOfInstantiation().isInvalid())
2320      MSInfo->setPointOfInstantiation(PointOfInstantiation);
2321  } else
2322    llvm_unreachable("Function cannot have a template specialization kind");
2323}
2324
2325SourceLocation FunctionDecl::getPointOfInstantiation() const {
2326  if (FunctionTemplateSpecializationInfo *FTSInfo
2327        = TemplateOrSpecialization.dyn_cast<
2328                                        FunctionTemplateSpecializationInfo*>())
2329    return FTSInfo->getPointOfInstantiation();
2330  else if (MemberSpecializationInfo *MSInfo
2331             = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
2332    return MSInfo->getPointOfInstantiation();
2333
2334  return SourceLocation();
2335}
2336
2337bool FunctionDecl::isOutOfLine() const {
2338  if (Decl::isOutOfLine())
2339    return true;
2340
2341  // If this function was instantiated from a member function of a
2342  // class template, check whether that member function was defined out-of-line.
2343  if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
2344    const FunctionDecl *Definition;
2345    if (FD->hasBody(Definition))
2346      return Definition->isOutOfLine();
2347  }
2348
2349  // If this function was instantiated from a function template,
2350  // check whether that function template was defined out-of-line.
2351  if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
2352    const FunctionDecl *Definition;
2353    if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
2354      return Definition->isOutOfLine();
2355  }
2356
2357  return false;
2358}
2359
2360SourceRange FunctionDecl::getSourceRange() const {
2361  return SourceRange(getOuterLocStart(), EndRangeLoc);
2362}
2363
2364unsigned FunctionDecl::getMemoryFunctionKind() const {
2365  IdentifierInfo *FnInfo = getIdentifier();
2366
2367  if (!FnInfo)
2368    return 0;
2369
2370  // Builtin handling.
2371  switch (getBuiltinID()) {
2372  case Builtin::BI__builtin_memset:
2373  case Builtin::BI__builtin___memset_chk:
2374  case Builtin::BImemset:
2375    return Builtin::BImemset;
2376
2377  case Builtin::BI__builtin_memcpy:
2378  case Builtin::BI__builtin___memcpy_chk:
2379  case Builtin::BImemcpy:
2380    return Builtin::BImemcpy;
2381
2382  case Builtin::BI__builtin_memmove:
2383  case Builtin::BI__builtin___memmove_chk:
2384  case Builtin::BImemmove:
2385    return Builtin::BImemmove;
2386
2387  case Builtin::BIstrlcpy:
2388    return Builtin::BIstrlcpy;
2389  case Builtin::BIstrlcat:
2390    return Builtin::BIstrlcat;
2391
2392  case Builtin::BI__builtin_memcmp:
2393  case Builtin::BImemcmp:
2394    return Builtin::BImemcmp;
2395
2396  case Builtin::BI__builtin_strncpy:
2397  case Builtin::BI__builtin___strncpy_chk:
2398  case Builtin::BIstrncpy:
2399    return Builtin::BIstrncpy;
2400
2401  case Builtin::BI__builtin_strncmp:
2402  case Builtin::BIstrncmp:
2403    return Builtin::BIstrncmp;
2404
2405  case Builtin::BI__builtin_strncasecmp:
2406  case Builtin::BIstrncasecmp:
2407    return Builtin::BIstrncasecmp;
2408
2409  case Builtin::BI__builtin_strncat:
2410  case Builtin::BI__builtin___strncat_chk:
2411  case Builtin::BIstrncat:
2412    return Builtin::BIstrncat;
2413
2414  case Builtin::BI__builtin_strndup:
2415  case Builtin::BIstrndup:
2416    return Builtin::BIstrndup;
2417
2418  case Builtin::BI__builtin_strlen:
2419  case Builtin::BIstrlen:
2420    return Builtin::BIstrlen;
2421
2422  default:
2423    if (isExternC()) {
2424      if (FnInfo->isStr("memset"))
2425        return Builtin::BImemset;
2426      else if (FnInfo->isStr("memcpy"))
2427        return Builtin::BImemcpy;
2428      else if (FnInfo->isStr("memmove"))
2429        return Builtin::BImemmove;
2430      else if (FnInfo->isStr("memcmp"))
2431        return Builtin::BImemcmp;
2432      else if (FnInfo->isStr("strncpy"))
2433        return Builtin::BIstrncpy;
2434      else if (FnInfo->isStr("strncmp"))
2435        return Builtin::BIstrncmp;
2436      else if (FnInfo->isStr("strncasecmp"))
2437        return Builtin::BIstrncasecmp;
2438      else if (FnInfo->isStr("strncat"))
2439        return Builtin::BIstrncat;
2440      else if (FnInfo->isStr("strndup"))
2441        return Builtin::BIstrndup;
2442      else if (FnInfo->isStr("strlen"))
2443        return Builtin::BIstrlen;
2444    }
2445    break;
2446  }
2447  return 0;
2448}
2449
2450//===----------------------------------------------------------------------===//
2451// FieldDecl Implementation
2452//===----------------------------------------------------------------------===//
2453
2454FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
2455                             SourceLocation StartLoc, SourceLocation IdLoc,
2456                             IdentifierInfo *Id, QualType T,
2457                             TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
2458                             bool HasInit) {
2459  return new (C) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
2460                           BW, Mutable, HasInit);
2461}
2462
2463FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2464  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FieldDecl));
2465  return new (Mem) FieldDecl(Field, 0, SourceLocation(), SourceLocation(),
2466                             0, QualType(), 0, 0, false, false);
2467}
2468
2469bool FieldDecl::isAnonymousStructOrUnion() const {
2470  if (!isImplicit() || getDeclName())
2471    return false;
2472
2473  if (const RecordType *Record = getType()->getAs<RecordType>())
2474    return Record->getDecl()->isAnonymousStructOrUnion();
2475
2476  return false;
2477}
2478
2479unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
2480  assert(isBitField() && "not a bitfield");
2481  Expr *BitWidth = InitializerOrBitWidth.getPointer();
2482  return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
2483}
2484
2485unsigned FieldDecl::getFieldIndex() const {
2486  if (CachedFieldIndex) return CachedFieldIndex - 1;
2487
2488  unsigned Index = 0;
2489  const RecordDecl *RD = getParent();
2490  const FieldDecl *LastFD = 0;
2491  bool IsMsStruct = RD->hasAttr<MsStructAttr>();
2492
2493  for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
2494       I != E; ++I, ++Index) {
2495    (*I)->CachedFieldIndex = Index + 1;
2496
2497    if (IsMsStruct) {
2498      // Zero-length bitfields following non-bitfield members are ignored.
2499      if (getASTContext().ZeroBitfieldFollowsNonBitfield((*I), LastFD)) {
2500        --Index;
2501        continue;
2502      }
2503      LastFD = (*I);
2504    }
2505  }
2506
2507  assert(CachedFieldIndex && "failed to find field in parent");
2508  return CachedFieldIndex - 1;
2509}
2510
2511SourceRange FieldDecl::getSourceRange() const {
2512  if (const Expr *E = InitializerOrBitWidth.getPointer())
2513    return SourceRange(getInnerLocStart(), E->getLocEnd());
2514  return DeclaratorDecl::getSourceRange();
2515}
2516
2517void FieldDecl::setInClassInitializer(Expr *Init) {
2518  assert(!InitializerOrBitWidth.getPointer() &&
2519         "bit width or initializer already set");
2520  InitializerOrBitWidth.setPointer(Init);
2521  InitializerOrBitWidth.setInt(0);
2522}
2523
2524//===----------------------------------------------------------------------===//
2525// TagDecl Implementation
2526//===----------------------------------------------------------------------===//
2527
2528SourceLocation TagDecl::getOuterLocStart() const {
2529  return getTemplateOrInnerLocStart(this);
2530}
2531
2532SourceRange TagDecl::getSourceRange() const {
2533  SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
2534  return SourceRange(getOuterLocStart(), E);
2535}
2536
2537TagDecl* TagDecl::getCanonicalDecl() {
2538  return getFirstDeclaration();
2539}
2540
2541void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
2542  TypedefNameDeclOrQualifier = TDD;
2543  if (TypeForDecl)
2544    const_cast<Type*>(TypeForDecl)->ClearLinkageCache();
2545  ClearLinkageCache();
2546}
2547
2548void TagDecl::startDefinition() {
2549  IsBeingDefined = true;
2550
2551  if (isa<CXXRecordDecl>(this)) {
2552    CXXRecordDecl *D = cast<CXXRecordDecl>(this);
2553    struct CXXRecordDecl::DefinitionData *Data =
2554      new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
2555    for (redecl_iterator I = redecls_begin(), E = redecls_end(); I != E; ++I)
2556      cast<CXXRecordDecl>(*I)->DefinitionData = Data;
2557  }
2558}
2559
2560void TagDecl::completeDefinition() {
2561  assert((!isa<CXXRecordDecl>(this) ||
2562          cast<CXXRecordDecl>(this)->hasDefinition()) &&
2563         "definition completed but not started");
2564
2565  IsCompleteDefinition = true;
2566  IsBeingDefined = false;
2567
2568  if (ASTMutationListener *L = getASTMutationListener())
2569    L->CompletedTagDefinition(this);
2570}
2571
2572TagDecl *TagDecl::getDefinition() const {
2573  if (isCompleteDefinition())
2574    return const_cast<TagDecl *>(this);
2575  if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(this))
2576    return CXXRD->getDefinition();
2577
2578  for (redecl_iterator R = redecls_begin(), REnd = redecls_end();
2579       R != REnd; ++R)
2580    if (R->isCompleteDefinition())
2581      return *R;
2582
2583  return 0;
2584}
2585
2586void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
2587  if (QualifierLoc) {
2588    // Make sure the extended qualifier info is allocated.
2589    if (!hasExtInfo())
2590      TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2591    // Set qualifier info.
2592    getExtInfo()->QualifierLoc = QualifierLoc;
2593  } else {
2594    // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
2595    if (hasExtInfo()) {
2596      if (getExtInfo()->NumTemplParamLists == 0) {
2597        getASTContext().Deallocate(getExtInfo());
2598        TypedefNameDeclOrQualifier = (TypedefNameDecl*) 0;
2599      }
2600      else
2601        getExtInfo()->QualifierLoc = QualifierLoc;
2602    }
2603  }
2604}
2605
2606void TagDecl::setTemplateParameterListsInfo(ASTContext &Context,
2607                                            unsigned NumTPLists,
2608                                            TemplateParameterList **TPLists) {
2609  assert(NumTPLists > 0);
2610  // Make sure the extended decl info is allocated.
2611  if (!hasExtInfo())
2612    // Allocate external info struct.
2613    TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
2614  // Set the template parameter lists info.
2615  getExtInfo()->setTemplateParameterListsInfo(Context, NumTPLists, TPLists);
2616}
2617
2618//===----------------------------------------------------------------------===//
2619// EnumDecl Implementation
2620//===----------------------------------------------------------------------===//
2621
2622void EnumDecl::anchor() { }
2623
2624EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
2625                           SourceLocation StartLoc, SourceLocation IdLoc,
2626                           IdentifierInfo *Id,
2627                           EnumDecl *PrevDecl, bool IsScoped,
2628                           bool IsScopedUsingClassTag, bool IsFixed) {
2629  EnumDecl *Enum = new (C) EnumDecl(DC, StartLoc, IdLoc, Id, PrevDecl,
2630                                    IsScoped, IsScopedUsingClassTag, IsFixed);
2631  C.getTypeDeclType(Enum, PrevDecl);
2632  return Enum;
2633}
2634
2635EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2636  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumDecl));
2637  return new (Mem) EnumDecl(0, SourceLocation(), SourceLocation(), 0, 0,
2638                            false, false, false);
2639}
2640
2641void EnumDecl::completeDefinition(QualType NewType,
2642                                  QualType NewPromotionType,
2643                                  unsigned NumPositiveBits,
2644                                  unsigned NumNegativeBits) {
2645  assert(!isCompleteDefinition() && "Cannot redefine enums!");
2646  if (!IntegerType)
2647    IntegerType = NewType.getTypePtr();
2648  PromotionType = NewPromotionType;
2649  setNumPositiveBits(NumPositiveBits);
2650  setNumNegativeBits(NumNegativeBits);
2651  TagDecl::completeDefinition();
2652}
2653
2654TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
2655  if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2656    return MSI->getTemplateSpecializationKind();
2657
2658  return TSK_Undeclared;
2659}
2660
2661void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2662                                         SourceLocation PointOfInstantiation) {
2663  MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
2664  assert(MSI && "Not an instantiated member enumeration?");
2665  MSI->setTemplateSpecializationKind(TSK);
2666  if (TSK != TSK_ExplicitSpecialization &&
2667      PointOfInstantiation.isValid() &&
2668      MSI->getPointOfInstantiation().isInvalid())
2669    MSI->setPointOfInstantiation(PointOfInstantiation);
2670}
2671
2672EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
2673  if (SpecializationInfo)
2674    return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
2675
2676  return 0;
2677}
2678
2679void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
2680                                            TemplateSpecializationKind TSK) {
2681  assert(!SpecializationInfo && "Member enum is already a specialization");
2682  SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
2683}
2684
2685//===----------------------------------------------------------------------===//
2686// RecordDecl Implementation
2687//===----------------------------------------------------------------------===//
2688
2689RecordDecl::RecordDecl(Kind DK, TagKind TK, DeclContext *DC,
2690                       SourceLocation StartLoc, SourceLocation IdLoc,
2691                       IdentifierInfo *Id, RecordDecl *PrevDecl)
2692  : TagDecl(DK, TK, DC, IdLoc, Id, PrevDecl, StartLoc) {
2693  HasFlexibleArrayMember = false;
2694  AnonymousStructOrUnion = false;
2695  HasObjectMember = false;
2696  LoadedFieldsFromExternalStorage = false;
2697  assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
2698}
2699
2700RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
2701                               SourceLocation StartLoc, SourceLocation IdLoc,
2702                               IdentifierInfo *Id, RecordDecl* PrevDecl) {
2703  RecordDecl* R = new (C) RecordDecl(Record, TK, DC, StartLoc, IdLoc, Id,
2704                                     PrevDecl);
2705  C.getTypeDeclType(R, PrevDecl);
2706  return R;
2707}
2708
2709RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
2710  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(RecordDecl));
2711  return new (Mem) RecordDecl(Record, TTK_Struct, 0, SourceLocation(),
2712                              SourceLocation(), 0, 0);
2713}
2714
2715bool RecordDecl::isInjectedClassName() const {
2716  return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
2717    cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
2718}
2719
2720RecordDecl::field_iterator RecordDecl::field_begin() const {
2721  if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
2722    LoadFieldsFromExternalStorage();
2723
2724  return field_iterator(decl_iterator(FirstDecl));
2725}
2726
2727/// completeDefinition - Notes that the definition of this type is now
2728/// complete.
2729void RecordDecl::completeDefinition() {
2730  assert(!isCompleteDefinition() && "Cannot redefine record!");
2731  TagDecl::completeDefinition();
2732}
2733
2734void RecordDecl::LoadFieldsFromExternalStorage() const {
2735  ExternalASTSource *Source = getASTContext().getExternalSource();
2736  assert(hasExternalLexicalStorage() && Source && "No external storage?");
2737
2738  // Notify that we have a RecordDecl doing some initialization.
2739  ExternalASTSource::Deserializing TheFields(Source);
2740
2741  SmallVector<Decl*, 64> Decls;
2742  LoadedFieldsFromExternalStorage = true;
2743  switch (Source->FindExternalLexicalDeclsBy<FieldDecl>(this, Decls)) {
2744  case ELR_Success:
2745    break;
2746
2747  case ELR_AlreadyLoaded:
2748  case ELR_Failure:
2749    return;
2750  }
2751
2752#ifndef NDEBUG
2753  // Check that all decls we got were FieldDecls.
2754  for (unsigned i=0, e=Decls.size(); i != e; ++i)
2755    assert(isa<FieldDecl>(Decls[i]));
2756#endif
2757
2758  if (Decls.empty())
2759    return;
2760
2761  llvm::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
2762                                                 /*FieldsAlreadyLoaded=*/false);
2763}
2764
2765//===----------------------------------------------------------------------===//
2766// BlockDecl Implementation
2767//===----------------------------------------------------------------------===//
2768
2769void BlockDecl::setParams(llvm::ArrayRef<ParmVarDecl *> NewParamInfo) {
2770  assert(ParamInfo == 0 && "Already has param info!");
2771
2772  // Zero params -> null pointer.
2773  if (!NewParamInfo.empty()) {
2774    NumParams = NewParamInfo.size();
2775    ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
2776    std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2777  }
2778}
2779
2780void BlockDecl::setCaptures(ASTContext &Context,
2781                            const Capture *begin,
2782                            const Capture *end,
2783                            bool capturesCXXThis) {
2784  CapturesCXXThis = capturesCXXThis;
2785
2786  if (begin == end) {
2787    NumCaptures = 0;
2788    Captures = 0;
2789    return;
2790  }
2791
2792  NumCaptures = end - begin;
2793
2794  // Avoid new Capture[] because we don't want to provide a default
2795  // constructor.
2796  size_t allocationSize = NumCaptures * sizeof(Capture);
2797  void *buffer = Context.Allocate(allocationSize, /*alignment*/sizeof(void*));
2798  memcpy(buffer, begin, allocationSize);
2799  Captures = static_cast<Capture*>(buffer);
2800}
2801
2802bool BlockDecl::capturesVariable(const VarDecl *variable) const {
2803  for (capture_const_iterator
2804         i = capture_begin(), e = capture_end(); i != e; ++i)
2805    // Only auto vars can be captured, so no redeclaration worries.
2806    if (i->getVariable() == variable)
2807      return true;
2808
2809  return false;
2810}
2811
2812SourceRange BlockDecl::getSourceRange() const {
2813  return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
2814}
2815
2816//===----------------------------------------------------------------------===//
2817// Other Decl Allocation/Deallocation Method Implementations
2818//===----------------------------------------------------------------------===//
2819
2820void TranslationUnitDecl::anchor() { }
2821
2822TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
2823  return new (C) TranslationUnitDecl(C);
2824}
2825
2826void LabelDecl::anchor() { }
2827
2828LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2829                             SourceLocation IdentL, IdentifierInfo *II) {
2830  return new (C) LabelDecl(DC, IdentL, II, 0, IdentL);
2831}
2832
2833LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
2834                             SourceLocation IdentL, IdentifierInfo *II,
2835                             SourceLocation GnuLabelL) {
2836  assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
2837  return new (C) LabelDecl(DC, IdentL, II, 0, GnuLabelL);
2838}
2839
2840LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2841  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LabelDecl));
2842  return new (Mem) LabelDecl(0, SourceLocation(), 0, 0, SourceLocation());
2843}
2844
2845void ValueDecl::anchor() { }
2846
2847void ImplicitParamDecl::anchor() { }
2848
2849ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
2850                                             SourceLocation IdLoc,
2851                                             IdentifierInfo *Id,
2852                                             QualType Type) {
2853  return new (C) ImplicitParamDecl(DC, IdLoc, Id, Type);
2854}
2855
2856ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
2857                                                         unsigned ID) {
2858  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(ImplicitParamDecl));
2859  return new (Mem) ImplicitParamDecl(0, SourceLocation(), 0, QualType());
2860}
2861
2862FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
2863                                   SourceLocation StartLoc,
2864                                   const DeclarationNameInfo &NameInfo,
2865                                   QualType T, TypeSourceInfo *TInfo,
2866                                   StorageClass SC, StorageClass SCAsWritten,
2867                                   bool isInlineSpecified,
2868                                   bool hasWrittenPrototype,
2869                                   bool isConstexprSpecified) {
2870  FunctionDecl *New = new (C) FunctionDecl(Function, DC, StartLoc, NameInfo,
2871                                           T, TInfo, SC, SCAsWritten,
2872                                           isInlineSpecified,
2873                                           isConstexprSpecified);
2874  New->HasWrittenPrototype = hasWrittenPrototype;
2875  return New;
2876}
2877
2878FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2879  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FunctionDecl));
2880  return new (Mem) FunctionDecl(Function, 0, SourceLocation(),
2881                                DeclarationNameInfo(), QualType(), 0,
2882                                SC_None, SC_None, false, false);
2883}
2884
2885BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
2886  return new (C) BlockDecl(DC, L);
2887}
2888
2889BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2890  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(BlockDecl));
2891  return new (Mem) BlockDecl(0, SourceLocation());
2892}
2893
2894EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
2895                                           SourceLocation L,
2896                                           IdentifierInfo *Id, QualType T,
2897                                           Expr *E, const llvm::APSInt &V) {
2898  return new (C) EnumConstantDecl(CD, L, Id, T, E, V);
2899}
2900
2901EnumConstantDecl *
2902EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2903  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(EnumConstantDecl));
2904  return new (Mem) EnumConstantDecl(0, SourceLocation(), 0, QualType(), 0,
2905                                    llvm::APSInt());
2906}
2907
2908void IndirectFieldDecl::anchor() { }
2909
2910IndirectFieldDecl *
2911IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
2912                          IdentifierInfo *Id, QualType T, NamedDecl **CH,
2913                          unsigned CHS) {
2914  return new (C) IndirectFieldDecl(DC, L, Id, T, CH, CHS);
2915}
2916
2917IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
2918                                                         unsigned ID) {
2919  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(IndirectFieldDecl));
2920  return new (Mem) IndirectFieldDecl(0, SourceLocation(), DeclarationName(),
2921                                     QualType(), 0, 0);
2922}
2923
2924SourceRange EnumConstantDecl::getSourceRange() const {
2925  SourceLocation End = getLocation();
2926  if (Init)
2927    End = Init->getLocEnd();
2928  return SourceRange(getLocation(), End);
2929}
2930
2931void TypeDecl::anchor() { }
2932
2933TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
2934                                 SourceLocation StartLoc, SourceLocation IdLoc,
2935                                 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
2936  return new (C) TypedefDecl(DC, StartLoc, IdLoc, Id, TInfo);
2937}
2938
2939void TypedefNameDecl::anchor() { }
2940
2941TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2942  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypedefDecl));
2943  return new (Mem) TypedefDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2944}
2945
2946TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
2947                                     SourceLocation StartLoc,
2948                                     SourceLocation IdLoc, IdentifierInfo *Id,
2949                                     TypeSourceInfo *TInfo) {
2950  return new (C) TypeAliasDecl(DC, StartLoc, IdLoc, Id, TInfo);
2951}
2952
2953TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2954  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(TypeAliasDecl));
2955  return new (Mem) TypeAliasDecl(0, SourceLocation(), SourceLocation(), 0, 0);
2956}
2957
2958SourceRange TypedefDecl::getSourceRange() const {
2959  SourceLocation RangeEnd = getLocation();
2960  if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2961    if (typeIsPostfix(TInfo->getType()))
2962      RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2963  }
2964  return SourceRange(getLocStart(), RangeEnd);
2965}
2966
2967SourceRange TypeAliasDecl::getSourceRange() const {
2968  SourceLocation RangeEnd = getLocStart();
2969  if (TypeSourceInfo *TInfo = getTypeSourceInfo())
2970    RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2971  return SourceRange(getLocStart(), RangeEnd);
2972}
2973
2974void FileScopeAsmDecl::anchor() { }
2975
2976FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
2977                                           StringLiteral *Str,
2978                                           SourceLocation AsmLoc,
2979                                           SourceLocation RParenLoc) {
2980  return new (C) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
2981}
2982
2983FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
2984                                                       unsigned ID) {
2985  void *Mem = AllocateDeserializedDecl(C, ID, sizeof(FileScopeAsmDecl));
2986  return new (Mem) FileScopeAsmDecl(0, 0, SourceLocation(), SourceLocation());
2987}
2988
2989//===----------------------------------------------------------------------===//
2990// ImportDecl Implementation
2991//===----------------------------------------------------------------------===//
2992
2993/// \brief Retrieve the number of module identifiers needed to name the given
2994/// module.
2995static unsigned getNumModuleIdentifiers(Module *Mod) {
2996  unsigned Result = 1;
2997  while (Mod->Parent) {
2998    Mod = Mod->Parent;
2999    ++Result;
3000  }
3001  return Result;
3002}
3003
3004ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3005                       Module *Imported,
3006                       ArrayRef<SourceLocation> IdentifierLocs)
3007  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
3008    NextLocalImport()
3009{
3010  assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
3011  SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(this + 1);
3012  memcpy(StoredLocs, IdentifierLocs.data(),
3013         IdentifierLocs.size() * sizeof(SourceLocation));
3014}
3015
3016ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
3017                       Module *Imported, SourceLocation EndLoc)
3018  : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
3019    NextLocalImport()
3020{
3021  *reinterpret_cast<SourceLocation *>(this + 1) = EndLoc;
3022}
3023
3024ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
3025                               SourceLocation StartLoc, Module *Imported,
3026                               ArrayRef<SourceLocation> IdentifierLocs) {
3027  void *Mem = C.Allocate(sizeof(ImportDecl) +
3028                         IdentifierLocs.size() * sizeof(SourceLocation));
3029  return new (Mem) ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
3030}
3031
3032ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
3033                                       SourceLocation StartLoc,
3034                                       Module *Imported,
3035                                       SourceLocation EndLoc) {
3036  void *Mem = C.Allocate(sizeof(ImportDecl) + sizeof(SourceLocation));
3037  ImportDecl *Import = new (Mem) ImportDecl(DC, StartLoc, Imported, EndLoc);
3038  Import->setImplicit();
3039  return Import;
3040}
3041
3042ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3043                                           unsigned NumLocations) {
3044  void *Mem = AllocateDeserializedDecl(C, ID,
3045                                       (sizeof(ImportDecl) +
3046                                        NumLocations * sizeof(SourceLocation)));
3047  return new (Mem) ImportDecl(EmptyShell());
3048}
3049
3050ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
3051  if (!ImportedAndComplete.getInt())
3052    return ArrayRef<SourceLocation>();
3053
3054  const SourceLocation *StoredLocs
3055    = reinterpret_cast<const SourceLocation *>(this + 1);
3056  return ArrayRef<SourceLocation>(StoredLocs,
3057                                  getNumModuleIdentifiers(getImportedModule()));
3058}
3059
3060SourceRange ImportDecl::getSourceRange() const {
3061  if (!ImportedAndComplete.getInt())
3062    return SourceRange(getLocation(),
3063                       *reinterpret_cast<const SourceLocation *>(this + 1));
3064
3065  return SourceRange(getLocation(), getIdentifierLocs().back());
3066}
3067