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