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