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