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