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