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