xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 2976e014)
1 //===--- Decl.cpp - Declaration AST Node Implementation -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the Decl subclasses.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/Attr.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclOpenMP.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/PrettyPrinter.h"
26 #include "clang/AST/Stmt.h"
27 #include "clang/AST/TypeLoc.h"
28 #include "clang/Basic/Builtins.h"
29 #include "clang/Basic/IdentifierTable.h"
30 #include "clang/Basic/Module.h"
31 #include "clang/Basic/Specifiers.h"
32 #include "clang/Basic/TargetInfo.h"
33 #include "clang/Frontend/FrontendDiagnostic.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include <algorithm>
36 
37 using namespace clang;
38 
39 Decl *clang::getPrimaryMergedDecl(Decl *D) {
40   return D->getASTContext().getPrimaryMergedDecl(D);
41 }
42 
43 // Defined here so that it can be inlined into its direct callers.
44 bool Decl::isOutOfLine() const {
45   return !getLexicalDeclContext()->Equals(getDeclContext());
46 }
47 
48 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
49     : Decl(TranslationUnit, nullptr, SourceLocation()),
50       DeclContext(TranslationUnit), Ctx(ctx), AnonymousNamespace(nullptr) {
51   Hidden = Ctx.getLangOpts().ModulesLocalVisibility;
52 }
53 
54 //===----------------------------------------------------------------------===//
55 // NamedDecl Implementation
56 //===----------------------------------------------------------------------===//
57 
58 // Visibility rules aren't rigorously externally specified, but here
59 // are the basic principles behind what we implement:
60 //
61 // 1. An explicit visibility attribute is generally a direct expression
62 // of the user's intent and should be honored.  Only the innermost
63 // visibility attribute applies.  If no visibility attribute applies,
64 // global visibility settings are considered.
65 //
66 // 2. There is one caveat to the above: on or in a template pattern,
67 // an explicit visibility attribute is just a default rule, and
68 // visibility can be decreased by the visibility of template
69 // arguments.  But this, too, has an exception: an attribute on an
70 // explicit specialization or instantiation causes all the visibility
71 // restrictions of the template arguments to be ignored.
72 //
73 // 3. A variable that does not otherwise have explicit visibility can
74 // be restricted by the visibility of its type.
75 //
76 // 4. A visibility restriction is explicit if it comes from an
77 // attribute (or something like it), not a global visibility setting.
78 // When emitting a reference to an external symbol, visibility
79 // restrictions are ignored unless they are explicit.
80 //
81 // 5. When computing the visibility of a non-type, including a
82 // non-type member of a class, only non-type visibility restrictions
83 // are considered: the 'visibility' attribute, global value-visibility
84 // settings, and a few special cases like __private_extern.
85 //
86 // 6. When computing the visibility of a type, including a type member
87 // of a class, only type visibility restrictions are considered:
88 // the 'type_visibility' attribute and global type-visibility settings.
89 // However, a 'visibility' attribute counts as a 'type_visibility'
90 // attribute on any declaration that only has the former.
91 //
92 // The visibility of a "secondary" entity, like a template argument,
93 // is computed using the kind of that entity, not the kind of the
94 // primary entity for which we are computing visibility.  For example,
95 // the visibility of a specialization of either of these templates:
96 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
97 //   template <class T, bool (&compare)(T, X)> class matcher;
98 // is restricted according to the type visibility of the argument 'T',
99 // the type visibility of 'bool(&)(T,X)', and the value visibility of
100 // the argument function 'compare'.  That 'has_match' is a value
101 // and 'matcher' is a type only matters when looking for attributes
102 // and settings from the immediate context.
103 
104 const unsigned IgnoreExplicitVisibilityBit = 2;
105 const unsigned IgnoreAllVisibilityBit = 4;
106 
107 /// Kinds of LV computation.  The linkage side of the computation is
108 /// always the same, but different things can change how visibility is
109 /// computed.
110 enum LVComputationKind {
111   /// Do an LV computation for, ultimately, a type.
112   /// Visibility may be restricted by type visibility settings and
113   /// the visibility of template arguments.
114   LVForType = NamedDecl::VisibilityForType,
115 
116   /// Do an LV computation for, ultimately, a non-type declaration.
117   /// Visibility may be restricted by value visibility settings and
118   /// the visibility of template arguments.
119   LVForValue = NamedDecl::VisibilityForValue,
120 
121   /// Do an LV computation for, ultimately, a type that already has
122   /// some sort of explicit visibility.  Visibility may only be
123   /// restricted by the visibility of template arguments.
124   LVForExplicitType = (LVForType | IgnoreExplicitVisibilityBit),
125 
126   /// Do an LV computation for, ultimately, a non-type declaration
127   /// that already has some sort of explicit visibility.  Visibility
128   /// may only be restricted by the visibility of template arguments.
129   LVForExplicitValue = (LVForValue | IgnoreExplicitVisibilityBit),
130 
131   /// Do an LV computation when we only care about the linkage.
132   LVForLinkageOnly =
133       LVForValue | IgnoreExplicitVisibilityBit | IgnoreAllVisibilityBit
134 };
135 
136 /// Does this computation kind permit us to consider additional
137 /// visibility settings from attributes and the like?
138 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
139   return ((unsigned(computation) & IgnoreExplicitVisibilityBit) != 0);
140 }
141 
142 /// Given an LVComputationKind, return one of the same type/value sort
143 /// that records that it already has explicit visibility.
144 static LVComputationKind
145 withExplicitVisibilityAlready(LVComputationKind oldKind) {
146   LVComputationKind newKind =
147     static_cast<LVComputationKind>(unsigned(oldKind) |
148                                    IgnoreExplicitVisibilityBit);
149   assert(oldKind != LVForType          || newKind == LVForExplicitType);
150   assert(oldKind != LVForValue         || newKind == LVForExplicitValue);
151   assert(oldKind != LVForExplicitType  || newKind == LVForExplicitType);
152   assert(oldKind != LVForExplicitValue || newKind == LVForExplicitValue);
153   return newKind;
154 }
155 
156 static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
157                                                   LVComputationKind kind) {
158   assert(!hasExplicitVisibilityAlready(kind) &&
159          "asking for explicit visibility when we shouldn't be");
160   return D->getExplicitVisibility((NamedDecl::ExplicitVisibilityKind) kind);
161 }
162 
163 /// Is the given declaration a "type" or a "value" for the purposes of
164 /// visibility computation?
165 static bool usesTypeVisibility(const NamedDecl *D) {
166   return isa<TypeDecl>(D) ||
167          isa<ClassTemplateDecl>(D) ||
168          isa<ObjCInterfaceDecl>(D);
169 }
170 
171 /// Does the given declaration have member specialization information,
172 /// and if so, is it an explicit specialization?
173 template <class T> static typename
174 std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
175 isExplicitMemberSpecialization(const T *D) {
176   if (const MemberSpecializationInfo *member =
177         D->getMemberSpecializationInfo()) {
178     return member->isExplicitSpecialization();
179   }
180   return false;
181 }
182 
183 /// For templates, this question is easier: a member template can't be
184 /// explicitly instantiated, so there's a single bit indicating whether
185 /// or not this is an explicit member specialization.
186 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
187   return D->isMemberSpecialization();
188 }
189 
190 /// Given a visibility attribute, return the explicit visibility
191 /// associated with it.
192 template <class T>
193 static Visibility getVisibilityFromAttr(const T *attr) {
194   switch (attr->getVisibility()) {
195   case T::Default:
196     return DefaultVisibility;
197   case T::Hidden:
198     return HiddenVisibility;
199   case T::Protected:
200     return ProtectedVisibility;
201   }
202   llvm_unreachable("bad visibility kind");
203 }
204 
205 /// Return the explicit visibility of the given declaration.
206 static Optional<Visibility> getVisibilityOf(const NamedDecl *D,
207                                     NamedDecl::ExplicitVisibilityKind kind) {
208   // If we're ultimately computing the visibility of a type, look for
209   // a 'type_visibility' attribute before looking for 'visibility'.
210   if (kind == NamedDecl::VisibilityForType) {
211     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
212       return getVisibilityFromAttr(A);
213     }
214   }
215 
216   // If this declaration has an explicit visibility attribute, use it.
217   if (const auto *A = D->getAttr<VisibilityAttr>()) {
218     return getVisibilityFromAttr(A);
219   }
220 
221   // If we're on Mac OS X, an 'availability' for Mac OS X attribute
222   // implies visibility(default).
223   if (D->getASTContext().getTargetInfo().getTriple().isOSDarwin()) {
224     for (const auto *A : D->specific_attrs<AvailabilityAttr>())
225       if (A->getPlatform()->getName().equals("macos"))
226         return DefaultVisibility;
227   }
228 
229   return None;
230 }
231 
232 static LinkageInfo
233 getLVForType(const Type &T, LVComputationKind computation) {
234   if (computation == LVForLinkageOnly)
235     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
236   return T.getLinkageAndVisibility();
237 }
238 
239 /// \brief Get the most restrictive linkage for the types in the given
240 /// template parameter list.  For visibility purposes, template
241 /// parameters are part of the signature of a template.
242 static LinkageInfo
243 getLVForTemplateParameterList(const TemplateParameterList *Params,
244                               LVComputationKind computation) {
245   LinkageInfo LV;
246   for (const NamedDecl *P : *Params) {
247     // Template type parameters are the most common and never
248     // contribute to visibility, pack or not.
249     if (isa<TemplateTypeParmDecl>(P))
250       continue;
251 
252     // Non-type template parameters can be restricted by the value type, e.g.
253     //   template <enum X> class A { ... };
254     // We have to be careful here, though, because we can be dealing with
255     // dependent types.
256     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
257       // Handle the non-pack case first.
258       if (!NTTP->isExpandedParameterPack()) {
259         if (!NTTP->getType()->isDependentType()) {
260           LV.merge(getLVForType(*NTTP->getType(), computation));
261         }
262         continue;
263       }
264 
265       // Look at all the types in an expanded pack.
266       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
267         QualType type = NTTP->getExpansionType(i);
268         if (!type->isDependentType())
269           LV.merge(type->getLinkageAndVisibility());
270       }
271       continue;
272     }
273 
274     // Template template parameters can be restricted by their
275     // template parameters, recursively.
276     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
277 
278     // Handle the non-pack case first.
279     if (!TTP->isExpandedParameterPack()) {
280       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
281                                              computation));
282       continue;
283     }
284 
285     // Look at all expansions in an expanded pack.
286     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
287            i != n; ++i) {
288       LV.merge(getLVForTemplateParameterList(
289           TTP->getExpansionTemplateParameters(i), computation));
290     }
291   }
292 
293   return LV;
294 }
295 
296 /// getLVForDecl - Get the linkage and visibility for the given declaration.
297 static LinkageInfo getLVForDecl(const NamedDecl *D,
298                                 LVComputationKind computation);
299 
300 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
301   const Decl *Ret = nullptr;
302   const DeclContext *DC = D->getDeclContext();
303   while (DC->getDeclKind() != Decl::TranslationUnit) {
304     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
305       Ret = cast<Decl>(DC);
306     DC = DC->getParent();
307   }
308   return Ret;
309 }
310 
311 /// \brief Get the most restrictive linkage for the types and
312 /// declarations in the given template argument list.
313 ///
314 /// Note that we don't take an LVComputationKind because we always
315 /// want to honor the visibility of template arguments in the same way.
316 static LinkageInfo getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
317                                                 LVComputationKind computation) {
318   LinkageInfo LV;
319 
320   for (const TemplateArgument &Arg : Args) {
321     switch (Arg.getKind()) {
322     case TemplateArgument::Null:
323     case TemplateArgument::Integral:
324     case TemplateArgument::Expression:
325       continue;
326 
327     case TemplateArgument::Type:
328       LV.merge(getLVForType(*Arg.getAsType(), computation));
329       continue;
330 
331     case TemplateArgument::Declaration:
332       if (const auto *ND = dyn_cast<NamedDecl>(Arg.getAsDecl())) {
333         assert(!usesTypeVisibility(ND));
334         LV.merge(getLVForDecl(ND, computation));
335       }
336       continue;
337 
338     case TemplateArgument::NullPtr:
339       LV.merge(Arg.getNullPtrType()->getLinkageAndVisibility());
340       continue;
341 
342     case TemplateArgument::Template:
343     case TemplateArgument::TemplateExpansion:
344       if (TemplateDecl *Template =
345               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
346         LV.merge(getLVForDecl(Template, computation));
347       continue;
348 
349     case TemplateArgument::Pack:
350       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
351       continue;
352     }
353     llvm_unreachable("bad template argument kind");
354   }
355 
356   return LV;
357 }
358 
359 static LinkageInfo
360 getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
361                              LVComputationKind computation) {
362   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
363 }
364 
365 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
366                         const FunctionTemplateSpecializationInfo *specInfo) {
367   // Include visibility from the template parameters and arguments
368   // only if this is not an explicit instantiation or specialization
369   // with direct explicit visibility.  (Implicit instantiations won't
370   // have a direct attribute.)
371   if (!specInfo->isExplicitInstantiationOrSpecialization())
372     return true;
373 
374   return !fn->hasAttr<VisibilityAttr>();
375 }
376 
377 /// Merge in template-related linkage and visibility for the given
378 /// function template specialization.
379 ///
380 /// We don't need a computation kind here because we can assume
381 /// LVForValue.
382 ///
383 /// \param[out] LV the computation to use for the parent
384 static void
385 mergeTemplateLV(LinkageInfo &LV, const FunctionDecl *fn,
386                 const FunctionTemplateSpecializationInfo *specInfo,
387                 LVComputationKind computation) {
388   bool considerVisibility =
389     shouldConsiderTemplateVisibility(fn, specInfo);
390 
391   // Merge information from the template parameters.
392   FunctionTemplateDecl *temp = specInfo->getTemplate();
393   LinkageInfo tempLV =
394     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
395   LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
396 
397   // Merge information from the template arguments.
398   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
399   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
400   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
401 }
402 
403 /// Does the given declaration have a direct visibility attribute
404 /// that would match the given rules?
405 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
406                                          LVComputationKind computation) {
407   switch (computation) {
408   case LVForType:
409   case LVForExplicitType:
410     if (D->hasAttr<TypeVisibilityAttr>())
411       return true;
412     // fallthrough
413   case LVForValue:
414   case LVForExplicitValue:
415     if (D->hasAttr<VisibilityAttr>())
416       return true;
417     return false;
418   case LVForLinkageOnly:
419     return false;
420   }
421   llvm_unreachable("bad visibility computation kind");
422 }
423 
424 /// Should we consider visibility associated with the template
425 /// arguments and parameters of the given class template specialization?
426 static bool shouldConsiderTemplateVisibility(
427                                  const ClassTemplateSpecializationDecl *spec,
428                                  LVComputationKind computation) {
429   // Include visibility from the template parameters and arguments
430   // only if this is not an explicit instantiation or specialization
431   // with direct explicit visibility (and note that implicit
432   // instantiations won't have a direct attribute).
433   //
434   // Furthermore, we want to ignore template parameters and arguments
435   // for an explicit specialization when computing the visibility of a
436   // member thereof with explicit visibility.
437   //
438   // This is a bit complex; let's unpack it.
439   //
440   // An explicit class specialization is an independent, top-level
441   // declaration.  As such, if it or any of its members has an
442   // explicit visibility attribute, that must directly express the
443   // user's intent, and we should honor it.  The same logic applies to
444   // an explicit instantiation of a member of such a thing.
445 
446   // Fast path: if this is not an explicit instantiation or
447   // specialization, we always want to consider template-related
448   // visibility restrictions.
449   if (!spec->isExplicitInstantiationOrSpecialization())
450     return true;
451 
452   // This is the 'member thereof' check.
453   if (spec->isExplicitSpecialization() &&
454       hasExplicitVisibilityAlready(computation))
455     return false;
456 
457   return !hasDirectVisibilityAttribute(spec, computation);
458 }
459 
460 /// Merge in template-related linkage and visibility for the given
461 /// class template specialization.
462 static void mergeTemplateLV(LinkageInfo &LV,
463                             const ClassTemplateSpecializationDecl *spec,
464                             LVComputationKind computation) {
465   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
466 
467   // Merge information from the template parameters, but ignore
468   // visibility if we're only considering template arguments.
469 
470   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
471   LinkageInfo tempLV =
472     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
473   LV.mergeMaybeWithVisibility(tempLV,
474            considerVisibility && !hasExplicitVisibilityAlready(computation));
475 
476   // Merge information from the template arguments.  We ignore
477   // template-argument visibility if we've got an explicit
478   // instantiation with a visibility attribute.
479   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
480   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
481   if (considerVisibility)
482     LV.mergeVisibility(argsLV);
483   LV.mergeExternalVisibility(argsLV);
484 }
485 
486 /// Should we consider visibility associated with the template
487 /// arguments and parameters of the given variable template
488 /// specialization? As usual, follow class template specialization
489 /// logic up to initialization.
490 static bool shouldConsiderTemplateVisibility(
491                                  const VarTemplateSpecializationDecl *spec,
492                                  LVComputationKind computation) {
493   // Include visibility from the template parameters and arguments
494   // only if this is not an explicit instantiation or specialization
495   // with direct explicit visibility (and note that implicit
496   // instantiations won't have a direct attribute).
497   if (!spec->isExplicitInstantiationOrSpecialization())
498     return true;
499 
500   // An explicit variable specialization is an independent, top-level
501   // declaration.  As such, if it has an explicit visibility attribute,
502   // that must directly express the user's intent, and we should honor
503   // it.
504   if (spec->isExplicitSpecialization() &&
505       hasExplicitVisibilityAlready(computation))
506     return false;
507 
508   return !hasDirectVisibilityAttribute(spec, computation);
509 }
510 
511 /// Merge in template-related linkage and visibility for the given
512 /// variable template specialization. As usual, follow class template
513 /// specialization logic up to initialization.
514 static void mergeTemplateLV(LinkageInfo &LV,
515                             const VarTemplateSpecializationDecl *spec,
516                             LVComputationKind computation) {
517   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
518 
519   // Merge information from the template parameters, but ignore
520   // visibility if we're only considering template arguments.
521 
522   VarTemplateDecl *temp = spec->getSpecializedTemplate();
523   LinkageInfo tempLV =
524     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
525   LV.mergeMaybeWithVisibility(tempLV,
526            considerVisibility && !hasExplicitVisibilityAlready(computation));
527 
528   // Merge information from the template arguments.  We ignore
529   // template-argument visibility if we've got an explicit
530   // instantiation with a visibility attribute.
531   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
532   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
533   if (considerVisibility)
534     LV.mergeVisibility(argsLV);
535   LV.mergeExternalVisibility(argsLV);
536 }
537 
538 static bool useInlineVisibilityHidden(const NamedDecl *D) {
539   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
540   const LangOptions &Opts = D->getASTContext().getLangOpts();
541   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
542     return false;
543 
544   const auto *FD = dyn_cast<FunctionDecl>(D);
545   if (!FD)
546     return false;
547 
548   TemplateSpecializationKind TSK = TSK_Undeclared;
549   if (FunctionTemplateSpecializationInfo *spec
550       = FD->getTemplateSpecializationInfo()) {
551     TSK = spec->getTemplateSpecializationKind();
552   } else if (MemberSpecializationInfo *MSI =
553              FD->getMemberSpecializationInfo()) {
554     TSK = MSI->getTemplateSpecializationKind();
555   }
556 
557   const FunctionDecl *Def = nullptr;
558   // InlineVisibilityHidden only applies to definitions, and
559   // isInlined() only gives meaningful answers on definitions
560   // anyway.
561   return TSK != TSK_ExplicitInstantiationDeclaration &&
562     TSK != TSK_ExplicitInstantiationDefinition &&
563     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
564 }
565 
566 template <typename T> static bool isFirstInExternCContext(T *D) {
567   const T *First = D->getFirstDecl();
568   return First->isInExternCContext();
569 }
570 
571 static bool isSingleLineLanguageLinkage(const Decl &D) {
572   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
573     if (!SD->hasBraces())
574       return true;
575   return false;
576 }
577 
578 static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
579                                               LVComputationKind computation) {
580   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
581          "Not a name having namespace scope");
582   ASTContext &Context = D->getASTContext();
583 
584   // C++ [basic.link]p3:
585   //   A name having namespace scope (3.3.6) has internal linkage if it
586   //   is the name of
587   //     - an object, reference, function or function template that is
588   //       explicitly declared static; or,
589   // (This bullet corresponds to C99 6.2.2p3.)
590   if (const auto *Var = dyn_cast<VarDecl>(D)) {
591     // Explicitly declared static.
592     if (Var->getStorageClass() == SC_Static)
593       return LinkageInfo::internal();
594 
595     // - a non-inline, non-volatile object or reference that is explicitly
596     //   declared const or constexpr and neither explicitly declared extern
597     //   nor previously declared to have external linkage; or (there is no
598     //   equivalent in C99)
599     if (Context.getLangOpts().CPlusPlus &&
600         Var->getType().isConstQualified() &&
601         !Var->getType().isVolatileQualified() &&
602         !Var->isInline()) {
603       const VarDecl *PrevVar = Var->getPreviousDecl();
604       if (PrevVar)
605         return getLVForDecl(PrevVar, computation);
606 
607       if (Var->getStorageClass() != SC_Extern &&
608           Var->getStorageClass() != SC_PrivateExtern &&
609           !isSingleLineLanguageLinkage(*Var))
610         return LinkageInfo::internal();
611     }
612 
613     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
614          PrevVar = PrevVar->getPreviousDecl()) {
615       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
616           Var->getStorageClass() == SC_None)
617         return PrevVar->getLinkageAndVisibility();
618       // Explicitly declared static.
619       if (PrevVar->getStorageClass() == SC_Static)
620         return LinkageInfo::internal();
621     }
622   } else if (const FunctionDecl *Function = D->getAsFunction()) {
623     // C++ [temp]p4:
624     //   A non-member function template can have internal linkage; any
625     //   other template name shall have external linkage.
626 
627     // Explicitly declared static.
628     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
629       return LinkageInfo(InternalLinkage, DefaultVisibility, false);
630   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
631     //   - a data member of an anonymous union.
632     const VarDecl *VD = IFD->getVarDecl();
633     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
634     return getLVForNamespaceScopeDecl(VD, computation);
635   }
636   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
637 
638   if (D->isInAnonymousNamespace()) {
639     const auto *Var = dyn_cast<VarDecl>(D);
640     const auto *Func = dyn_cast<FunctionDecl>(D);
641     // FIXME: In C++11 onwards, anonymous namespaces should give decls
642     // within them internal linkage, not unique external linkage.
643     if ((!Var || !isFirstInExternCContext(Var)) &&
644         (!Func || !isFirstInExternCContext(Func)))
645       return LinkageInfo::uniqueExternal();
646   }
647 
648   // Set up the defaults.
649 
650   // C99 6.2.2p5:
651   //   If the declaration of an identifier for an object has file
652   //   scope and no storage-class specifier, its linkage is
653   //   external.
654   LinkageInfo LV;
655 
656   if (!hasExplicitVisibilityAlready(computation)) {
657     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
658       LV.mergeVisibility(*Vis, true);
659     } else {
660       // If we're declared in a namespace with a visibility attribute,
661       // use that namespace's visibility, and it still counts as explicit.
662       for (const DeclContext *DC = D->getDeclContext();
663            !isa<TranslationUnitDecl>(DC);
664            DC = DC->getParent()) {
665         const auto *ND = dyn_cast<NamespaceDecl>(DC);
666         if (!ND) continue;
667         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
668           LV.mergeVisibility(*Vis, true);
669           break;
670         }
671       }
672     }
673 
674     // Add in global settings if the above didn't give us direct visibility.
675     if (!LV.isVisibilityExplicit()) {
676       // Use global type/value visibility as appropriate.
677       Visibility globalVisibility;
678       if (computation == LVForValue) {
679         globalVisibility = Context.getLangOpts().getValueVisibilityMode();
680       } else {
681         assert(computation == LVForType);
682         globalVisibility = Context.getLangOpts().getTypeVisibilityMode();
683       }
684       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
685 
686       // If we're paying attention to global visibility, apply
687       // -finline-visibility-hidden if this is an inline method.
688       if (useInlineVisibilityHidden(D))
689         LV.mergeVisibility(HiddenVisibility, true);
690     }
691   }
692 
693   // C++ [basic.link]p4:
694 
695   //   A name having namespace scope has external linkage if it is the
696   //   name of
697   //
698   //     - an object or reference, unless it has internal linkage; or
699   if (const auto *Var = dyn_cast<VarDecl>(D)) {
700     // GCC applies the following optimization to variables and static
701     // data members, but not to functions:
702     //
703     // Modify the variable's LV by the LV of its type unless this is
704     // C or extern "C".  This follows from [basic.link]p9:
705     //   A type without linkage shall not be used as the type of a
706     //   variable or function with external linkage unless
707     //    - the entity has C language linkage, or
708     //    - the entity is declared within an unnamed namespace, or
709     //    - the entity is not used or is defined in the same
710     //      translation unit.
711     // and [basic.link]p10:
712     //   ...the types specified by all declarations referring to a
713     //   given variable or function shall be identical...
714     // C does not have an equivalent rule.
715     //
716     // Ignore this if we've got an explicit attribute;  the user
717     // probably knows what they're doing.
718     //
719     // Note that we don't want to make the variable non-external
720     // because of this, but unique-external linkage suits us.
721     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
722       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
723       if (TypeLV.getLinkage() != ExternalLinkage)
724         return LinkageInfo::uniqueExternal();
725       if (!LV.isVisibilityExplicit())
726         LV.mergeVisibility(TypeLV);
727     }
728 
729     if (Var->getStorageClass() == SC_PrivateExtern)
730       LV.mergeVisibility(HiddenVisibility, true);
731 
732     // Note that Sema::MergeVarDecl already takes care of implementing
733     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
734     // to do it here.
735 
736     // As per function and class template specializations (below),
737     // consider LV for the template and template arguments.  We're at file
738     // scope, so we do not need to worry about nested specializations.
739     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
740       mergeTemplateLV(LV, spec, computation);
741     }
742 
743   //     - a function, unless it has internal linkage; or
744   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
745     // In theory, we can modify the function's LV by the LV of its
746     // type unless it has C linkage (see comment above about variables
747     // for justification).  In practice, GCC doesn't do this, so it's
748     // just too painful to make work.
749 
750     if (Function->getStorageClass() == SC_PrivateExtern)
751       LV.mergeVisibility(HiddenVisibility, true);
752 
753     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
754     // merging storage classes and visibility attributes, so we don't have to
755     // look at previous decls in here.
756 
757     // In C++, then if the type of the function uses a type with
758     // unique-external linkage, it's not legally usable from outside
759     // this translation unit.  However, we should use the C linkage
760     // rules instead for extern "C" declarations.
761     if (Context.getLangOpts().CPlusPlus &&
762         !Function->isInExternCContext()) {
763       // Only look at the type-as-written. If this function has an auto-deduced
764       // return type, we can't compute the linkage of that type because it could
765       // require looking at the linkage of this function, and we don't need this
766       // for correctness because the type is not part of the function's
767       // signature.
768       // FIXME: This is a hack. We should be able to solve this circularity and
769       // the one in getLVForClassMember for Functions some other way.
770       QualType TypeAsWritten = Function->getType();
771       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
772         TypeAsWritten = TSI->getType();
773       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
774         return LinkageInfo::uniqueExternal();
775     }
776 
777     // Consider LV from the template and the template arguments.
778     // We're at file scope, so we do not need to worry about nested
779     // specializations.
780     if (FunctionTemplateSpecializationInfo *specInfo
781                                = Function->getTemplateSpecializationInfo()) {
782       mergeTemplateLV(LV, Function, specInfo, computation);
783     }
784 
785   //     - a named class (Clause 9), or an unnamed class defined in a
786   //       typedef declaration in which the class has the typedef name
787   //       for linkage purposes (7.1.3); or
788   //     - a named enumeration (7.2), or an unnamed enumeration
789   //       defined in a typedef declaration in which the enumeration
790   //       has the typedef name for linkage purposes (7.1.3); or
791   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
792     // Unnamed tags have no linkage.
793     if (!Tag->hasNameForLinkage())
794       return LinkageInfo::none();
795 
796     // If this is a class template specialization, consider the
797     // linkage of the template and template arguments.  We're at file
798     // scope, so we do not need to worry about nested specializations.
799     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
800       mergeTemplateLV(LV, spec, computation);
801     }
802 
803   //     - an enumerator belonging to an enumeration with external linkage;
804   } else if (isa<EnumConstantDecl>(D)) {
805     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
806                                       computation);
807     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
808       return LinkageInfo::none();
809     LV.merge(EnumLV);
810 
811   //     - a template, unless it is a function template that has
812   //       internal linkage (Clause 14);
813   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
814     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
815     LinkageInfo tempLV =
816       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
817     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
818 
819   //     - a namespace (7.3), unless it is declared within an unnamed
820   //       namespace.
821   } else if (isa<NamespaceDecl>(D) && !D->isInAnonymousNamespace()) {
822     return LV;
823 
824   // By extension, we assign external linkage to Objective-C
825   // interfaces.
826   } else if (isa<ObjCInterfaceDecl>(D)) {
827     // fallout
828 
829   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
830     // A typedef declaration has linkage if it gives a type a name for
831     // linkage purposes.
832     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
833       return LinkageInfo::none();
834 
835   // Everything not covered here has no linkage.
836   } else {
837     return LinkageInfo::none();
838   }
839 
840   // If we ended up with non-external linkage, visibility should
841   // always be default.
842   if (LV.getLinkage() != ExternalLinkage)
843     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
844 
845   return LV;
846 }
847 
848 static LinkageInfo getLVForClassMember(const NamedDecl *D,
849                                        LVComputationKind computation) {
850   // Only certain class members have linkage.  Note that fields don't
851   // really have linkage, but it's convenient to say they do for the
852   // purposes of calculating linkage of pointer-to-data-member
853   // template arguments.
854   //
855   // Templates also don't officially have linkage, but since we ignore
856   // the C++ standard and look at template arguments when determining
857   // linkage and visibility of a template specialization, we might hit
858   // a template template argument that way. If we do, we need to
859   // consider its linkage.
860   if (!(isa<CXXMethodDecl>(D) ||
861         isa<VarDecl>(D) ||
862         isa<FieldDecl>(D) ||
863         isa<IndirectFieldDecl>(D) ||
864         isa<TagDecl>(D) ||
865         isa<TemplateDecl>(D)))
866     return LinkageInfo::none();
867 
868   LinkageInfo LV;
869 
870   // If we have an explicit visibility attribute, merge that in.
871   if (!hasExplicitVisibilityAlready(computation)) {
872     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
873       LV.mergeVisibility(*Vis, true);
874     // If we're paying attention to global visibility, apply
875     // -finline-visibility-hidden if this is an inline method.
876     //
877     // Note that we do this before merging information about
878     // the class visibility.
879     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
880       LV.mergeVisibility(HiddenVisibility, true);
881   }
882 
883   // If this class member has an explicit visibility attribute, the only
884   // thing that can change its visibility is the template arguments, so
885   // only look for them when processing the class.
886   LVComputationKind classComputation = computation;
887   if (LV.isVisibilityExplicit())
888     classComputation = withExplicitVisibilityAlready(computation);
889 
890   LinkageInfo classLV =
891     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
892   // If the class already has unique-external linkage, we can't improve.
893   if (classLV.getLinkage() == UniqueExternalLinkage)
894     return LinkageInfo::uniqueExternal();
895 
896   if (!isExternallyVisible(classLV.getLinkage()))
897     return LinkageInfo::none();
898 
899 
900   // Otherwise, don't merge in classLV yet, because in certain cases
901   // we need to completely ignore the visibility from it.
902 
903   // Specifically, if this decl exists and has an explicit attribute.
904   const NamedDecl *explicitSpecSuppressor = nullptr;
905 
906   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
907     // If the type of the function uses a type with unique-external
908     // linkage, it's not legally usable from outside this translation unit.
909     // But only look at the type-as-written. If this function has an
910     // auto-deduced return type, we can't compute the linkage of that type
911     // because it could require looking at the linkage of this function, and we
912     // don't need this for correctness because the type is not part of the
913     // function's signature.
914     // FIXME: This is a hack. We should be able to solve this circularity and
915     // the one in getLVForNamespaceScopeDecl for Functions some other way.
916     {
917       QualType TypeAsWritten = MD->getType();
918       if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
919         TypeAsWritten = TSI->getType();
920       if (TypeAsWritten->getLinkage() == UniqueExternalLinkage)
921         return LinkageInfo::uniqueExternal();
922     }
923     // If this is a method template specialization, use the linkage for
924     // the template parameters and arguments.
925     if (FunctionTemplateSpecializationInfo *spec
926            = MD->getTemplateSpecializationInfo()) {
927       mergeTemplateLV(LV, MD, spec, computation);
928       if (spec->isExplicitSpecialization()) {
929         explicitSpecSuppressor = MD;
930       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
931         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
932       }
933     } else if (isExplicitMemberSpecialization(MD)) {
934       explicitSpecSuppressor = MD;
935     }
936 
937   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
938     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
939       mergeTemplateLV(LV, spec, computation);
940       if (spec->isExplicitSpecialization()) {
941         explicitSpecSuppressor = spec;
942       } else {
943         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
944         if (isExplicitMemberSpecialization(temp)) {
945           explicitSpecSuppressor = temp->getTemplatedDecl();
946         }
947       }
948     } else if (isExplicitMemberSpecialization(RD)) {
949       explicitSpecSuppressor = RD;
950     }
951 
952   // Static data members.
953   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
954     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
955       mergeTemplateLV(LV, spec, computation);
956 
957     // Modify the variable's linkage by its type, but ignore the
958     // type's visibility unless it's a definition.
959     LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
960     if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
961       LV.mergeVisibility(typeLV);
962     LV.mergeExternalVisibility(typeLV);
963 
964     if (isExplicitMemberSpecialization(VD)) {
965       explicitSpecSuppressor = VD;
966     }
967 
968   // Template members.
969   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
970     bool considerVisibility =
971       (!LV.isVisibilityExplicit() &&
972        !classLV.isVisibilityExplicit() &&
973        !hasExplicitVisibilityAlready(computation));
974     LinkageInfo tempLV =
975       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
976     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
977 
978     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
979       if (isExplicitMemberSpecialization(redeclTemp)) {
980         explicitSpecSuppressor = temp->getTemplatedDecl();
981       }
982     }
983   }
984 
985   // We should never be looking for an attribute directly on a template.
986   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
987 
988   // If this member is an explicit member specialization, and it has
989   // an explicit attribute, ignore visibility from the parent.
990   bool considerClassVisibility = true;
991   if (explicitSpecSuppressor &&
992       // optimization: hasDVA() is true only with explicit visibility.
993       LV.isVisibilityExplicit() &&
994       classLV.getVisibility() != DefaultVisibility &&
995       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
996     considerClassVisibility = false;
997   }
998 
999   // Finally, merge in information from the class.
1000   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1001   return LV;
1002 }
1003 
1004 void NamedDecl::anchor() { }
1005 
1006 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1007                                     LVComputationKind computation);
1008 
1009 bool NamedDecl::isLinkageValid() const {
1010   if (!hasCachedLinkage())
1011     return true;
1012 
1013   return computeLVForDecl(this, LVForLinkageOnly).getLinkage() ==
1014          getCachedLinkage();
1015 }
1016 
1017 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1018   StringRef name = getName();
1019   if (name.empty()) return SFF_None;
1020 
1021   if (name.front() == 'C')
1022     if (name == "CFStringCreateWithFormat" ||
1023         name == "CFStringCreateWithFormatAndArguments" ||
1024         name == "CFStringAppendFormat" ||
1025         name == "CFStringAppendFormatAndArguments")
1026       return SFF_CFString;
1027   return SFF_None;
1028 }
1029 
1030 Linkage NamedDecl::getLinkageInternal() const {
1031   // We don't care about visibility here, so ask for the cheapest
1032   // possible visibility analysis.
1033   return getLVForDecl(this, LVForLinkageOnly).getLinkage();
1034 }
1035 
1036 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1037   LVComputationKind computation =
1038     (usesTypeVisibility(this) ? LVForType : LVForValue);
1039   return getLVForDecl(this, computation);
1040 }
1041 
1042 static Optional<Visibility>
1043 getExplicitVisibilityAux(const NamedDecl *ND,
1044                          NamedDecl::ExplicitVisibilityKind kind,
1045                          bool IsMostRecent) {
1046   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1047 
1048   // Check the declaration itself first.
1049   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1050     return V;
1051 
1052   // If this is a member class of a specialization of a class template
1053   // and the corresponding decl has explicit visibility, use that.
1054   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1055     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1056     if (InstantiatedFrom)
1057       return getVisibilityOf(InstantiatedFrom, kind);
1058   }
1059 
1060   // If there wasn't explicit visibility there, and this is a
1061   // specialization of a class template, check for visibility
1062   // on the pattern.
1063   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND))
1064     return getVisibilityOf(spec->getSpecializedTemplate()->getTemplatedDecl(),
1065                            kind);
1066 
1067   // Use the most recent declaration.
1068   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1069     const NamedDecl *MostRecent = ND->getMostRecentDecl();
1070     if (MostRecent != ND)
1071       return getExplicitVisibilityAux(MostRecent, kind, true);
1072   }
1073 
1074   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1075     if (Var->isStaticDataMember()) {
1076       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1077       if (InstantiatedFrom)
1078         return getVisibilityOf(InstantiatedFrom, kind);
1079     }
1080 
1081     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1082       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1083                              kind);
1084 
1085     return None;
1086   }
1087   // Also handle function template specializations.
1088   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1089     // If the function is a specialization of a template with an
1090     // explicit visibility attribute, use that.
1091     if (FunctionTemplateSpecializationInfo *templateInfo
1092           = fn->getTemplateSpecializationInfo())
1093       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1094                              kind);
1095 
1096     // If the function is a member of a specialization of a class template
1097     // and the corresponding decl has explicit visibility, use that.
1098     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1099     if (InstantiatedFrom)
1100       return getVisibilityOf(InstantiatedFrom, kind);
1101 
1102     return None;
1103   }
1104 
1105   // The visibility of a template is stored in the templated decl.
1106   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1107     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1108 
1109   return None;
1110 }
1111 
1112 Optional<Visibility>
1113 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1114   return getExplicitVisibilityAux(this, kind, false);
1115 }
1116 
1117 static LinkageInfo getLVForClosure(const DeclContext *DC, Decl *ContextDecl,
1118                                    LVComputationKind computation) {
1119   // This lambda has its linkage/visibility determined by its owner.
1120   if (ContextDecl) {
1121     if (isa<ParmVarDecl>(ContextDecl))
1122       DC = ContextDecl->getDeclContext()->getRedeclContext();
1123     else
1124       return getLVForDecl(cast<NamedDecl>(ContextDecl), computation);
1125   }
1126 
1127   if (const auto *ND = dyn_cast<NamedDecl>(DC))
1128     return getLVForDecl(ND, computation);
1129 
1130   return LinkageInfo::external();
1131 }
1132 
1133 static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
1134                                      LVComputationKind computation) {
1135   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1136     if (Function->isInAnonymousNamespace() &&
1137         !Function->isInExternCContext())
1138       return LinkageInfo::uniqueExternal();
1139 
1140     // This is a "void f();" which got merged with a file static.
1141     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1142       return LinkageInfo::internal();
1143 
1144     LinkageInfo LV;
1145     if (!hasExplicitVisibilityAlready(computation)) {
1146       if (Optional<Visibility> Vis =
1147               getExplicitVisibility(Function, computation))
1148         LV.mergeVisibility(*Vis, true);
1149     }
1150 
1151     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1152     // merging storage classes and visibility attributes, so we don't have to
1153     // look at previous decls in here.
1154 
1155     return LV;
1156   }
1157 
1158   if (const auto *Var = dyn_cast<VarDecl>(D)) {
1159     if (Var->hasExternalStorage()) {
1160       if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
1161         return LinkageInfo::uniqueExternal();
1162 
1163       LinkageInfo LV;
1164       if (Var->getStorageClass() == SC_PrivateExtern)
1165         LV.mergeVisibility(HiddenVisibility, true);
1166       else if (!hasExplicitVisibilityAlready(computation)) {
1167         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1168           LV.mergeVisibility(*Vis, true);
1169       }
1170 
1171       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1172         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1173         if (PrevLV.getLinkage())
1174           LV.setLinkage(PrevLV.getLinkage());
1175         LV.mergeVisibility(PrevLV);
1176       }
1177 
1178       return LV;
1179     }
1180 
1181     if (!Var->isStaticLocal())
1182       return LinkageInfo::none();
1183   }
1184 
1185   ASTContext &Context = D->getASTContext();
1186   if (!Context.getLangOpts().CPlusPlus)
1187     return LinkageInfo::none();
1188 
1189   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1190   if (!OuterD || OuterD->isInvalidDecl())
1191     return LinkageInfo::none();
1192 
1193   LinkageInfo LV;
1194   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1195     if (!BD->getBlockManglingNumber())
1196       return LinkageInfo::none();
1197 
1198     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1199                          BD->getBlockManglingContextDecl(), computation);
1200   } else {
1201     const auto *FD = cast<FunctionDecl>(OuterD);
1202     if (!FD->isInlined() &&
1203         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1204       return LinkageInfo::none();
1205 
1206     LV = getLVForDecl(FD, computation);
1207   }
1208   if (!isExternallyVisible(LV.getLinkage()))
1209     return LinkageInfo::none();
1210   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1211                      LV.isVisibilityExplicit());
1212 }
1213 
1214 static inline const CXXRecordDecl*
1215 getOutermostEnclosingLambda(const CXXRecordDecl *Record) {
1216   const CXXRecordDecl *Ret = Record;
1217   while (Record && Record->isLambda()) {
1218     Ret = Record;
1219     if (!Record->getParent()) break;
1220     // Get the Containing Class of this Lambda Class
1221     Record = dyn_cast_or_null<CXXRecordDecl>(
1222       Record->getParent()->getParent());
1223   }
1224   return Ret;
1225 }
1226 
1227 static LinkageInfo computeLVForDecl(const NamedDecl *D,
1228                                     LVComputationKind computation) {
1229   // Internal_linkage attribute overrides other considerations.
1230   if (D->hasAttr<InternalLinkageAttr>())
1231     return LinkageInfo::internal();
1232 
1233   // Objective-C: treat all Objective-C declarations as having external
1234   // linkage.
1235   switch (D->getKind()) {
1236     default:
1237       break;
1238 
1239     // Per C++ [basic.link]p2, only the names of objects, references,
1240     // functions, types, templates, namespaces, and values ever have linkage.
1241     //
1242     // Note that the name of a typedef, namespace alias, using declaration,
1243     // and so on are not the name of the corresponding type, namespace, or
1244     // declaration, so they do *not* have linkage.
1245     case Decl::ImplicitParam:
1246     case Decl::Label:
1247     case Decl::NamespaceAlias:
1248     case Decl::ParmVar:
1249     case Decl::Using:
1250     case Decl::UsingShadow:
1251     case Decl::UsingDirective:
1252       return LinkageInfo::none();
1253 
1254     case Decl::EnumConstant:
1255       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1256       return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1257 
1258     case Decl::Typedef:
1259     case Decl::TypeAlias:
1260       // A typedef declaration has linkage if it gives a type a name for
1261       // linkage purposes.
1262       if (!D->getASTContext().getLangOpts().CPlusPlus ||
1263           !cast<TypedefNameDecl>(D)
1264                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1265         return LinkageInfo::none();
1266       break;
1267 
1268     case Decl::TemplateTemplateParm: // count these as external
1269     case Decl::NonTypeTemplateParm:
1270     case Decl::ObjCAtDefsField:
1271     case Decl::ObjCCategory:
1272     case Decl::ObjCCategoryImpl:
1273     case Decl::ObjCCompatibleAlias:
1274     case Decl::ObjCImplementation:
1275     case Decl::ObjCMethod:
1276     case Decl::ObjCProperty:
1277     case Decl::ObjCPropertyImpl:
1278     case Decl::ObjCProtocol:
1279       return LinkageInfo::external();
1280 
1281     case Decl::CXXRecord: {
1282       const auto *Record = cast<CXXRecordDecl>(D);
1283       if (Record->isLambda()) {
1284         if (!Record->getLambdaManglingNumber()) {
1285           // This lambda has no mangling number, so it's internal.
1286           return LinkageInfo::internal();
1287         }
1288 
1289         // This lambda has its linkage/visibility determined:
1290         //  - either by the outermost lambda if that lambda has no mangling
1291         //    number.
1292         //  - or by the parent of the outer most lambda
1293         // This prevents infinite recursion in settings such as nested lambdas
1294         // used in NSDMI's, for e.g.
1295         //  struct L {
1296         //    int t{};
1297         //    int t2 = ([](int a) { return [](int b) { return b; };})(t)(t);
1298         //  };
1299         const CXXRecordDecl *OuterMostLambda =
1300             getOutermostEnclosingLambda(Record);
1301         if (!OuterMostLambda->getLambdaManglingNumber())
1302           return LinkageInfo::internal();
1303 
1304         return getLVForClosure(
1305                   OuterMostLambda->getDeclContext()->getRedeclContext(),
1306                   OuterMostLambda->getLambdaContextDecl(), computation);
1307       }
1308 
1309       break;
1310     }
1311   }
1312 
1313   // Handle linkage for namespace-scope names.
1314   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1315     return getLVForNamespaceScopeDecl(D, computation);
1316 
1317   // C++ [basic.link]p5:
1318   //   In addition, a member function, static data member, a named
1319   //   class or enumeration of class scope, or an unnamed class or
1320   //   enumeration defined in a class-scope typedef declaration such
1321   //   that the class or enumeration has the typedef name for linkage
1322   //   purposes (7.1.3), has external linkage if the name of the class
1323   //   has external linkage.
1324   if (D->getDeclContext()->isRecord())
1325     return getLVForClassMember(D, computation);
1326 
1327   // C++ [basic.link]p6:
1328   //   The name of a function declared in block scope and the name of
1329   //   an object declared by a block scope extern declaration have
1330   //   linkage. If there is a visible declaration of an entity with
1331   //   linkage having the same name and type, ignoring entities
1332   //   declared outside the innermost enclosing namespace scope, the
1333   //   block scope declaration declares that same entity and receives
1334   //   the linkage of the previous declaration. If there is more than
1335   //   one such matching entity, the program is ill-formed. Otherwise,
1336   //   if no matching entity is found, the block scope entity receives
1337   //   external linkage.
1338   if (D->getDeclContext()->isFunctionOrMethod())
1339     return getLVForLocalDecl(D, computation);
1340 
1341   // C++ [basic.link]p6:
1342   //   Names not covered by these rules have no linkage.
1343   return LinkageInfo::none();
1344 }
1345 
1346 namespace clang {
1347 class LinkageComputer {
1348 public:
1349   static LinkageInfo getLVForDecl(const NamedDecl *D,
1350                                   LVComputationKind computation) {
1351     // Internal_linkage attribute overrides other considerations.
1352     if (D->hasAttr<InternalLinkageAttr>())
1353       return LinkageInfo::internal();
1354 
1355     if (computation == LVForLinkageOnly && D->hasCachedLinkage())
1356       return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1357 
1358     LinkageInfo LV = computeLVForDecl(D, computation);
1359     if (D->hasCachedLinkage())
1360       assert(D->getCachedLinkage() == LV.getLinkage());
1361 
1362     D->setCachedLinkage(LV.getLinkage());
1363 
1364 #ifndef NDEBUG
1365     // In C (because of gnu inline) and in c++ with microsoft extensions an
1366     // static can follow an extern, so we can have two decls with different
1367     // linkages.
1368     const LangOptions &Opts = D->getASTContext().getLangOpts();
1369     if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1370       return LV;
1371 
1372     // We have just computed the linkage for this decl. By induction we know
1373     // that all other computed linkages match, check that the one we just
1374     // computed also does.
1375     NamedDecl *Old = nullptr;
1376     for (auto I : D->redecls()) {
1377       auto *T = cast<NamedDecl>(I);
1378       if (T == D)
1379         continue;
1380       if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1381         Old = T;
1382         break;
1383       }
1384     }
1385     assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1386 #endif
1387 
1388     return LV;
1389   }
1390 };
1391 }
1392 
1393 static LinkageInfo getLVForDecl(const NamedDecl *D,
1394                                 LVComputationKind computation) {
1395   return clang::LinkageComputer::getLVForDecl(D, computation);
1396 }
1397 
1398 std::string NamedDecl::getQualifiedNameAsString() const {
1399   std::string QualName;
1400   llvm::raw_string_ostream OS(QualName);
1401   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1402   return OS.str();
1403 }
1404 
1405 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1406   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1407 }
1408 
1409 void NamedDecl::printQualifiedName(raw_ostream &OS,
1410                                    const PrintingPolicy &P) const {
1411   const DeclContext *Ctx = getDeclContext();
1412 
1413   if (Ctx->isFunctionOrMethod()) {
1414     printName(OS);
1415     return;
1416   }
1417 
1418   typedef SmallVector<const DeclContext *, 8> ContextsTy;
1419   ContextsTy Contexts;
1420 
1421   // Collect contexts.
1422   while (Ctx && isa<NamedDecl>(Ctx)) {
1423     Contexts.push_back(Ctx);
1424     Ctx = Ctx->getParent();
1425   }
1426 
1427   for (const DeclContext *DC : reverse(Contexts)) {
1428     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1429       OS << Spec->getName();
1430       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1431       TemplateSpecializationType::PrintTemplateArgumentList(OS,
1432                                                             TemplateArgs.data(),
1433                                                             TemplateArgs.size(),
1434                                                             P);
1435     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1436       if (P.SuppressUnwrittenScope &&
1437           (ND->isAnonymousNamespace() || ND->isInline()))
1438         continue;
1439       if (ND->isAnonymousNamespace()) {
1440         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1441                                 : "(anonymous namespace)");
1442       }
1443       else
1444         OS << *ND;
1445     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1446       if (!RD->getIdentifier())
1447         OS << "(anonymous " << RD->getKindName() << ')';
1448       else
1449         OS << *RD;
1450     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1451       const FunctionProtoType *FT = nullptr;
1452       if (FD->hasWrittenPrototype())
1453         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1454 
1455       OS << *FD << '(';
1456       if (FT) {
1457         unsigned NumParams = FD->getNumParams();
1458         for (unsigned i = 0; i < NumParams; ++i) {
1459           if (i)
1460             OS << ", ";
1461           OS << FD->getParamDecl(i)->getType().stream(P);
1462         }
1463 
1464         if (FT->isVariadic()) {
1465           if (NumParams > 0)
1466             OS << ", ";
1467           OS << "...";
1468         }
1469       }
1470       OS << ')';
1471     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1472       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1473       // enumerator is declared in the scope that immediately contains
1474       // the enum-specifier. Each scoped enumerator is declared in the
1475       // scope of the enumeration.
1476       if (ED->isScoped() || ED->getIdentifier())
1477         OS << *ED;
1478       else
1479         continue;
1480     } else {
1481       OS << *cast<NamedDecl>(DC);
1482     }
1483     OS << "::";
1484   }
1485 
1486   if (getDeclName())
1487     OS << *this;
1488   else
1489     OS << "(anonymous)";
1490 }
1491 
1492 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1493                                      const PrintingPolicy &Policy,
1494                                      bool Qualified) const {
1495   if (Qualified)
1496     printQualifiedName(OS, Policy);
1497   else
1498     printName(OS);
1499 }
1500 
1501 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1502   return true;
1503 }
1504 static bool isRedeclarableImpl(...) { return false; }
1505 static bool isRedeclarable(Decl::Kind K) {
1506   switch (K) {
1507 #define DECL(Type, Base) \
1508   case Decl::Type: \
1509     return isRedeclarableImpl((Type##Decl *)nullptr);
1510 #define ABSTRACT_DECL(DECL)
1511 #include "clang/AST/DeclNodes.inc"
1512   }
1513   llvm_unreachable("unknown decl kind");
1514 }
1515 
1516 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1517   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1518 
1519   // Never replace one imported declaration with another; we need both results
1520   // when re-exporting.
1521   if (OldD->isFromASTFile() && isFromASTFile())
1522     return false;
1523 
1524   // A kind mismatch implies that the declaration is not replaced.
1525   if (OldD->getKind() != getKind())
1526     return false;
1527 
1528   // For method declarations, we never replace. (Why?)
1529   if (isa<ObjCMethodDecl>(this))
1530     return false;
1531 
1532   // For parameters, pick the newer one. This is either an error or (in
1533   // Objective-C) permitted as an extension.
1534   if (isa<ParmVarDecl>(this))
1535     return true;
1536 
1537   // Inline namespaces can give us two declarations with the same
1538   // name and kind in the same scope but different contexts; we should
1539   // keep both declarations in this case.
1540   if (!this->getDeclContext()->getRedeclContext()->Equals(
1541           OldD->getDeclContext()->getRedeclContext()))
1542     return false;
1543 
1544   // Using declarations can be replaced if they import the same name from the
1545   // same context.
1546   if (auto *UD = dyn_cast<UsingDecl>(this)) {
1547     ASTContext &Context = getASTContext();
1548     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1549            Context.getCanonicalNestedNameSpecifier(
1550                cast<UsingDecl>(OldD)->getQualifier());
1551   }
1552   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1553     ASTContext &Context = getASTContext();
1554     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1555            Context.getCanonicalNestedNameSpecifier(
1556                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1557   }
1558 
1559   // UsingDirectiveDecl's are not really NamedDecl's, and all have same name.
1560   // They can be replaced if they nominate the same namespace.
1561   // FIXME: Is this true even if they have different module visibility?
1562   if (auto *UD = dyn_cast<UsingDirectiveDecl>(this))
1563     return UD->getNominatedNamespace()->getOriginalNamespace() ==
1564            cast<UsingDirectiveDecl>(OldD)->getNominatedNamespace()
1565                ->getOriginalNamespace();
1566 
1567   if (isRedeclarable(getKind())) {
1568     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1569       return false;
1570 
1571     if (IsKnownNewer)
1572       return true;
1573 
1574     // Check whether this is actually newer than OldD. We want to keep the
1575     // newer declaration. This loop will usually only iterate once, because
1576     // OldD is usually the previous declaration.
1577     for (auto D : redecls()) {
1578       if (D == OldD)
1579         break;
1580 
1581       // If we reach the canonical declaration, then OldD is not actually older
1582       // than this one.
1583       //
1584       // FIXME: In this case, we should not add this decl to the lookup table.
1585       if (D->isCanonicalDecl())
1586         return false;
1587     }
1588 
1589     // It's a newer declaration of the same kind of declaration in the same
1590     // scope: we want this decl instead of the existing one.
1591     return true;
1592   }
1593 
1594   // In all other cases, we need to keep both declarations in case they have
1595   // different visibility. Any attempt to use the name will result in an
1596   // ambiguity if more than one is visible.
1597   return false;
1598 }
1599 
1600 bool NamedDecl::hasLinkage() const {
1601   return getFormalLinkage() != NoLinkage;
1602 }
1603 
1604 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1605   NamedDecl *ND = this;
1606   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1607     ND = UD->getTargetDecl();
1608 
1609   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1610     return AD->getClassInterface();
1611 
1612   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1613     return AD->getNamespace();
1614 
1615   return ND;
1616 }
1617 
1618 bool NamedDecl::isCXXInstanceMember() const {
1619   if (!isCXXClassMember())
1620     return false;
1621 
1622   const NamedDecl *D = this;
1623   if (isa<UsingShadowDecl>(D))
1624     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1625 
1626   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1627     return true;
1628   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1629     return MD->isInstance();
1630   return false;
1631 }
1632 
1633 //===----------------------------------------------------------------------===//
1634 // DeclaratorDecl Implementation
1635 //===----------------------------------------------------------------------===//
1636 
1637 template <typename DeclT>
1638 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1639   if (decl->getNumTemplateParameterLists() > 0)
1640     return decl->getTemplateParameterList(0)->getTemplateLoc();
1641   else
1642     return decl->getInnerLocStart();
1643 }
1644 
1645 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1646   TypeSourceInfo *TSI = getTypeSourceInfo();
1647   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1648   return SourceLocation();
1649 }
1650 
1651 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1652   if (QualifierLoc) {
1653     // Make sure the extended decl info is allocated.
1654     if (!hasExtInfo()) {
1655       // Save (non-extended) type source info pointer.
1656       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1657       // Allocate external info struct.
1658       DeclInfo = new (getASTContext()) ExtInfo;
1659       // Restore savedTInfo into (extended) decl info.
1660       getExtInfo()->TInfo = savedTInfo;
1661     }
1662     // Set qualifier info.
1663     getExtInfo()->QualifierLoc = QualifierLoc;
1664   } else {
1665     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1666     if (hasExtInfo()) {
1667       if (getExtInfo()->NumTemplParamLists == 0) {
1668         // Save type source info pointer.
1669         TypeSourceInfo *savedTInfo = getExtInfo()->TInfo;
1670         // Deallocate the extended decl info.
1671         getASTContext().Deallocate(getExtInfo());
1672         // Restore savedTInfo into (non-extended) decl info.
1673         DeclInfo = savedTInfo;
1674       }
1675       else
1676         getExtInfo()->QualifierLoc = QualifierLoc;
1677     }
1678   }
1679 }
1680 
1681 void DeclaratorDecl::setTemplateParameterListsInfo(
1682     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1683   assert(!TPLists.empty());
1684   // Make sure the extended decl info is allocated.
1685   if (!hasExtInfo()) {
1686     // Save (non-extended) type source info pointer.
1687     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1688     // Allocate external info struct.
1689     DeclInfo = new (getASTContext()) ExtInfo;
1690     // Restore savedTInfo into (extended) decl info.
1691     getExtInfo()->TInfo = savedTInfo;
1692   }
1693   // Set the template parameter lists info.
1694   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1695 }
1696 
1697 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1698   return getTemplateOrInnerLocStart(this);
1699 }
1700 
1701 namespace {
1702 
1703 // Helper function: returns true if QT is or contains a type
1704 // having a postfix component.
1705 bool typeIsPostfix(clang::QualType QT) {
1706   while (true) {
1707     const Type* T = QT.getTypePtr();
1708     switch (T->getTypeClass()) {
1709     default:
1710       return false;
1711     case Type::Pointer:
1712       QT = cast<PointerType>(T)->getPointeeType();
1713       break;
1714     case Type::BlockPointer:
1715       QT = cast<BlockPointerType>(T)->getPointeeType();
1716       break;
1717     case Type::MemberPointer:
1718       QT = cast<MemberPointerType>(T)->getPointeeType();
1719       break;
1720     case Type::LValueReference:
1721     case Type::RValueReference:
1722       QT = cast<ReferenceType>(T)->getPointeeType();
1723       break;
1724     case Type::PackExpansion:
1725       QT = cast<PackExpansionType>(T)->getPattern();
1726       break;
1727     case Type::Paren:
1728     case Type::ConstantArray:
1729     case Type::DependentSizedArray:
1730     case Type::IncompleteArray:
1731     case Type::VariableArray:
1732     case Type::FunctionProto:
1733     case Type::FunctionNoProto:
1734       return true;
1735     }
1736   }
1737 }
1738 
1739 } // namespace
1740 
1741 SourceRange DeclaratorDecl::getSourceRange() const {
1742   SourceLocation RangeEnd = getLocation();
1743   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1744     // If the declaration has no name or the type extends past the name take the
1745     // end location of the type.
1746     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1747       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1748   }
1749   return SourceRange(getOuterLocStart(), RangeEnd);
1750 }
1751 
1752 void QualifierInfo::setTemplateParameterListsInfo(
1753     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1754   // Free previous template parameters (if any).
1755   if (NumTemplParamLists > 0) {
1756     Context.Deallocate(TemplParamLists);
1757     TemplParamLists = nullptr;
1758     NumTemplParamLists = 0;
1759   }
1760   // Set info on matched template parameter lists (if any).
1761   if (!TPLists.empty()) {
1762     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1763     NumTemplParamLists = TPLists.size();
1764     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1765   }
1766 }
1767 
1768 //===----------------------------------------------------------------------===//
1769 // VarDecl Implementation
1770 //===----------------------------------------------------------------------===//
1771 
1772 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1773   switch (SC) {
1774   case SC_None:                 break;
1775   case SC_Auto:                 return "auto";
1776   case SC_Extern:               return "extern";
1777   case SC_PrivateExtern:        return "__private_extern__";
1778   case SC_Register:             return "register";
1779   case SC_Static:               return "static";
1780   }
1781 
1782   llvm_unreachable("Invalid storage class");
1783 }
1784 
1785 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1786                  SourceLocation StartLoc, SourceLocation IdLoc,
1787                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1788                  StorageClass SC)
1789     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1790       redeclarable_base(C), Init() {
1791   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1792                 "VarDeclBitfields too large!");
1793   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1794                 "ParmVarDeclBitfields too large!");
1795   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1796                 "NonParmVarDeclBitfields too large!");
1797   AllBits = 0;
1798   VarDeclBits.SClass = SC;
1799   // Everything else is implicitly initialized to false.
1800 }
1801 
1802 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1803                          SourceLocation StartL, SourceLocation IdL,
1804                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1805                          StorageClass S) {
1806   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1807 }
1808 
1809 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1810   return new (C, ID)
1811       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1812               QualType(), nullptr, SC_None);
1813 }
1814 
1815 void VarDecl::setStorageClass(StorageClass SC) {
1816   assert(isLegalForVariable(SC));
1817   VarDeclBits.SClass = SC;
1818 }
1819 
1820 VarDecl::TLSKind VarDecl::getTLSKind() const {
1821   switch (VarDeclBits.TSCSpec) {
1822   case TSCS_unspecified:
1823     if (!hasAttr<ThreadAttr>() &&
1824         !(getASTContext().getLangOpts().OpenMPUseTLS &&
1825           getASTContext().getTargetInfo().isTLSSupported() &&
1826           hasAttr<OMPThreadPrivateDeclAttr>()))
1827       return TLS_None;
1828     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1829                 LangOptions::MSVC2015)) ||
1830             hasAttr<OMPThreadPrivateDeclAttr>())
1831                ? TLS_Dynamic
1832                : TLS_Static;
1833   case TSCS___thread: // Fall through.
1834   case TSCS__Thread_local:
1835     return TLS_Static;
1836   case TSCS_thread_local:
1837     return TLS_Dynamic;
1838   }
1839   llvm_unreachable("Unknown thread storage class specifier!");
1840 }
1841 
1842 SourceRange VarDecl::getSourceRange() const {
1843   if (const Expr *Init = getInit()) {
1844     SourceLocation InitEnd = Init->getLocEnd();
1845     // If Init is implicit, ignore its source range and fallback on
1846     // DeclaratorDecl::getSourceRange() to handle postfix elements.
1847     if (InitEnd.isValid() && InitEnd != getLocation())
1848       return SourceRange(getOuterLocStart(), InitEnd);
1849   }
1850   return DeclaratorDecl::getSourceRange();
1851 }
1852 
1853 template<typename T>
1854 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
1855   // C++ [dcl.link]p1: All function types, function names with external linkage,
1856   // and variable names with external linkage have a language linkage.
1857   if (!D.hasExternalFormalLinkage())
1858     return NoLanguageLinkage;
1859 
1860   // Language linkage is a C++ concept, but saying that everything else in C has
1861   // C language linkage fits the implementation nicely.
1862   ASTContext &Context = D.getASTContext();
1863   if (!Context.getLangOpts().CPlusPlus)
1864     return CLanguageLinkage;
1865 
1866   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
1867   // language linkage of the names of class members and the function type of
1868   // class member functions.
1869   const DeclContext *DC = D.getDeclContext();
1870   if (DC->isRecord())
1871     return CXXLanguageLinkage;
1872 
1873   // If the first decl is in an extern "C" context, any other redeclaration
1874   // will have C language linkage. If the first one is not in an extern "C"
1875   // context, we would have reported an error for any other decl being in one.
1876   if (isFirstInExternCContext(&D))
1877     return CLanguageLinkage;
1878   return CXXLanguageLinkage;
1879 }
1880 
1881 template<typename T>
1882 static bool isDeclExternC(const T &D) {
1883   // Since the context is ignored for class members, they can only have C++
1884   // language linkage or no language linkage.
1885   const DeclContext *DC = D.getDeclContext();
1886   if (DC->isRecord()) {
1887     assert(D.getASTContext().getLangOpts().CPlusPlus);
1888     return false;
1889   }
1890 
1891   return D.getLanguageLinkage() == CLanguageLinkage;
1892 }
1893 
1894 LanguageLinkage VarDecl::getLanguageLinkage() const {
1895   return getDeclLanguageLinkage(*this);
1896 }
1897 
1898 bool VarDecl::isExternC() const {
1899   return isDeclExternC(*this);
1900 }
1901 
1902 bool VarDecl::isInExternCContext() const {
1903   return getLexicalDeclContext()->isExternCContext();
1904 }
1905 
1906 bool VarDecl::isInExternCXXContext() const {
1907   return getLexicalDeclContext()->isExternCXXContext();
1908 }
1909 
1910 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
1911 
1912 VarDecl::DefinitionKind
1913 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
1914   // C++ [basic.def]p2:
1915   //   A declaration is a definition unless [...] it contains the 'extern'
1916   //   specifier or a linkage-specification and neither an initializer [...],
1917   //   it declares a non-inline static data member in a class declaration [...],
1918   //   it declares a static data member outside a class definition and the variable
1919   //   was defined within the class with the constexpr specifier [...],
1920   // C++1y [temp.expl.spec]p15:
1921   //   An explicit specialization of a static data member or an explicit
1922   //   specialization of a static data member template is a definition if the
1923   //   declaration includes an initializer; otherwise, it is a declaration.
1924   //
1925   // FIXME: How do you declare (but not define) a partial specialization of
1926   // a static data member template outside the containing class?
1927   if (isStaticDataMember()) {
1928     if (isOutOfLine() &&
1929         !(getCanonicalDecl()->isInline() &&
1930           getCanonicalDecl()->isConstexpr()) &&
1931         (hasInit() ||
1932          // If the first declaration is out-of-line, this may be an
1933          // instantiation of an out-of-line partial specialization of a variable
1934          // template for which we have not yet instantiated the initializer.
1935          (getFirstDecl()->isOutOfLine()
1936               ? getTemplateSpecializationKind() == TSK_Undeclared
1937               : getTemplateSpecializationKind() !=
1938                     TSK_ExplicitSpecialization) ||
1939          isa<VarTemplatePartialSpecializationDecl>(this)))
1940       return Definition;
1941     else if (!isOutOfLine() && isInline())
1942       return Definition;
1943     else
1944       return DeclarationOnly;
1945   }
1946   // C99 6.7p5:
1947   //   A definition of an identifier is a declaration for that identifier that
1948   //   [...] causes storage to be reserved for that object.
1949   // Note: that applies for all non-file-scope objects.
1950   // C99 6.9.2p1:
1951   //   If the declaration of an identifier for an object has file scope and an
1952   //   initializer, the declaration is an external definition for the identifier
1953   if (hasInit())
1954     return Definition;
1955 
1956   if (hasDefiningAttr())
1957     return Definition;
1958 
1959   if (const auto *SAA = getAttr<SelectAnyAttr>())
1960     if (!SAA->isInherited())
1961       return Definition;
1962 
1963   // A variable template specialization (other than a static data member
1964   // template or an explicit specialization) is a declaration until we
1965   // instantiate its initializer.
1966   if (isa<VarTemplateSpecializationDecl>(this) &&
1967       getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
1968     return DeclarationOnly;
1969 
1970   if (hasExternalStorage())
1971     return DeclarationOnly;
1972 
1973   // [dcl.link] p7:
1974   //   A declaration directly contained in a linkage-specification is treated
1975   //   as if it contains the extern specifier for the purpose of determining
1976   //   the linkage of the declared name and whether it is a definition.
1977   if (isSingleLineLanguageLinkage(*this))
1978     return DeclarationOnly;
1979 
1980   // C99 6.9.2p2:
1981   //   A declaration of an object that has file scope without an initializer,
1982   //   and without a storage class specifier or the scs 'static', constitutes
1983   //   a tentative definition.
1984   // No such thing in C++.
1985   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
1986     return TentativeDefinition;
1987 
1988   // What's left is (in C, block-scope) declarations without initializers or
1989   // external storage. These are definitions.
1990   return Definition;
1991 }
1992 
1993 VarDecl *VarDecl::getActingDefinition() {
1994   DefinitionKind Kind = isThisDeclarationADefinition();
1995   if (Kind != TentativeDefinition)
1996     return nullptr;
1997 
1998   VarDecl *LastTentative = nullptr;
1999   VarDecl *First = getFirstDecl();
2000   for (auto I : First->redecls()) {
2001     Kind = I->isThisDeclarationADefinition();
2002     if (Kind == Definition)
2003       return nullptr;
2004     else if (Kind == TentativeDefinition)
2005       LastTentative = I;
2006   }
2007   return LastTentative;
2008 }
2009 
2010 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2011   VarDecl *First = getFirstDecl();
2012   for (auto I : First->redecls()) {
2013     if (I->isThisDeclarationADefinition(C) == Definition)
2014       return I;
2015   }
2016   return nullptr;
2017 }
2018 
2019 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2020   DefinitionKind Kind = DeclarationOnly;
2021 
2022   const VarDecl *First = getFirstDecl();
2023   for (auto I : First->redecls()) {
2024     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2025     if (Kind == Definition)
2026       break;
2027   }
2028 
2029   return Kind;
2030 }
2031 
2032 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2033   for (auto I : redecls()) {
2034     if (auto Expr = I->getInit()) {
2035       D = I;
2036       return Expr;
2037     }
2038   }
2039   return nullptr;
2040 }
2041 
2042 bool VarDecl::hasInit() const {
2043   if (auto *P = dyn_cast<ParmVarDecl>(this))
2044     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2045       return false;
2046 
2047   return !Init.isNull();
2048 }
2049 
2050 Expr *VarDecl::getInit() {
2051   if (!hasInit())
2052     return nullptr;
2053 
2054   if (auto *S = Init.dyn_cast<Stmt *>())
2055     return cast<Expr>(S);
2056 
2057   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2058 }
2059 
2060 Stmt **VarDecl::getInitAddress() {
2061   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2062     return &ES->Value;
2063 
2064   return Init.getAddrOfPtr1();
2065 }
2066 
2067 bool VarDecl::isOutOfLine() const {
2068   if (Decl::isOutOfLine())
2069     return true;
2070 
2071   if (!isStaticDataMember())
2072     return false;
2073 
2074   // If this static data member was instantiated from a static data member of
2075   // a class template, check whether that static data member was defined
2076   // out-of-line.
2077   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2078     return VD->isOutOfLine();
2079 
2080   return false;
2081 }
2082 
2083 void VarDecl::setInit(Expr *I) {
2084   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2085     Eval->~EvaluatedStmt();
2086     getASTContext().Deallocate(Eval);
2087   }
2088 
2089   Init = I;
2090 }
2091 
2092 bool VarDecl::isUsableInConstantExpressions(ASTContext &C) const {
2093   const LangOptions &Lang = C.getLangOpts();
2094 
2095   if (!Lang.CPlusPlus)
2096     return false;
2097 
2098   // In C++11, any variable of reference type can be used in a constant
2099   // expression if it is initialized by a constant expression.
2100   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2101     return true;
2102 
2103   // Only const objects can be used in constant expressions in C++. C++98 does
2104   // not require the variable to be non-volatile, but we consider this to be a
2105   // defect.
2106   if (!getType().isConstQualified() || getType().isVolatileQualified())
2107     return false;
2108 
2109   // In C++, const, non-volatile variables of integral or enumeration types
2110   // can be used in constant expressions.
2111   if (getType()->isIntegralOrEnumerationType())
2112     return true;
2113 
2114   // Additionally, in C++11, non-volatile constexpr variables can be used in
2115   // constant expressions.
2116   return Lang.CPlusPlus11 && isConstexpr();
2117 }
2118 
2119 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2120 /// form, which contains extra information on the evaluated value of the
2121 /// initializer.
2122 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2123   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2124   if (!Eval) {
2125     // Note: EvaluatedStmt contains an APValue, which usually holds
2126     // resources not allocated from the ASTContext.  We need to do some
2127     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2128     // where we can detect whether there's anything to clean up or not.
2129     Eval = new (getASTContext()) EvaluatedStmt;
2130     Eval->Value = Init.get<Stmt *>();
2131     Init = Eval;
2132   }
2133   return Eval;
2134 }
2135 
2136 APValue *VarDecl::evaluateValue() const {
2137   SmallVector<PartialDiagnosticAt, 8> Notes;
2138   return evaluateValue(Notes);
2139 }
2140 
2141 namespace {
2142 // Destroy an APValue that was allocated in an ASTContext.
2143 void DestroyAPValue(void* UntypedValue) {
2144   static_cast<APValue*>(UntypedValue)->~APValue();
2145 }
2146 } // namespace
2147 
2148 APValue *VarDecl::evaluateValue(
2149     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2150   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2151 
2152   // We only produce notes indicating why an initializer is non-constant the
2153   // first time it is evaluated. FIXME: The notes won't always be emitted the
2154   // first time we try evaluation, so might not be produced at all.
2155   if (Eval->WasEvaluated)
2156     return Eval->Evaluated.isUninit() ? nullptr : &Eval->Evaluated;
2157 
2158   const auto *Init = cast<Expr>(Eval->Value);
2159   assert(!Init->isValueDependent());
2160 
2161   if (Eval->IsEvaluating) {
2162     // FIXME: Produce a diagnostic for self-initialization.
2163     Eval->CheckedICE = true;
2164     Eval->IsICE = false;
2165     return nullptr;
2166   }
2167 
2168   Eval->IsEvaluating = true;
2169 
2170   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, getASTContext(),
2171                                             this, Notes);
2172 
2173   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2174   // or that it's empty (so that there's nothing to clean up) if evaluation
2175   // failed.
2176   if (!Result)
2177     Eval->Evaluated = APValue();
2178   else if (Eval->Evaluated.needsCleanup())
2179     getASTContext().AddDeallocation(DestroyAPValue, &Eval->Evaluated);
2180 
2181   Eval->IsEvaluating = false;
2182   Eval->WasEvaluated = true;
2183 
2184   // In C++11, we have determined whether the initializer was a constant
2185   // expression as a side-effect.
2186   if (getASTContext().getLangOpts().CPlusPlus11 && !Eval->CheckedICE) {
2187     Eval->CheckedICE = true;
2188     Eval->IsICE = Result && Notes.empty();
2189   }
2190 
2191   return Result ? &Eval->Evaluated : nullptr;
2192 }
2193 
2194 APValue *VarDecl::getEvaluatedValue() const {
2195   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2196     if (Eval->WasEvaluated)
2197       return &Eval->Evaluated;
2198 
2199   return nullptr;
2200 }
2201 
2202 bool VarDecl::isInitKnownICE() const {
2203   if (EvaluatedStmt *Eval = Init.dyn_cast<EvaluatedStmt *>())
2204     return Eval->CheckedICE;
2205 
2206   return false;
2207 }
2208 
2209 bool VarDecl::isInitICE() const {
2210   assert(isInitKnownICE() &&
2211          "Check whether we already know that the initializer is an ICE");
2212   return Init.get<EvaluatedStmt *>()->IsICE;
2213 }
2214 
2215 bool VarDecl::checkInitIsICE() const {
2216   // Initializers of weak variables are never ICEs.
2217   if (isWeak())
2218     return false;
2219 
2220   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2221   if (Eval->CheckedICE)
2222     // We have already checked whether this subexpression is an
2223     // integral constant expression.
2224     return Eval->IsICE;
2225 
2226   const auto *Init = cast<Expr>(Eval->Value);
2227   assert(!Init->isValueDependent());
2228 
2229   // In C++11, evaluate the initializer to check whether it's a constant
2230   // expression.
2231   if (getASTContext().getLangOpts().CPlusPlus11) {
2232     SmallVector<PartialDiagnosticAt, 8> Notes;
2233     evaluateValue(Notes);
2234     return Eval->IsICE;
2235   }
2236 
2237   // It's an ICE whether or not the definition we found is
2238   // out-of-line.  See DR 721 and the discussion in Clang PR
2239   // 6206 for details.
2240 
2241   if (Eval->CheckingICE)
2242     return false;
2243   Eval->CheckingICE = true;
2244 
2245   Eval->IsICE = Init->isIntegerConstantExpr(getASTContext());
2246   Eval->CheckingICE = false;
2247   Eval->CheckedICE = true;
2248   return Eval->IsICE;
2249 }
2250 
2251 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2252   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2253     return cast<VarDecl>(MSI->getInstantiatedFrom());
2254 
2255   return nullptr;
2256 }
2257 
2258 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2259   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2260     return Spec->getSpecializationKind();
2261 
2262   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2263     return MSI->getTemplateSpecializationKind();
2264 
2265   return TSK_Undeclared;
2266 }
2267 
2268 SourceLocation VarDecl::getPointOfInstantiation() const {
2269   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2270     return Spec->getPointOfInstantiation();
2271 
2272   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2273     return MSI->getPointOfInstantiation();
2274 
2275   return SourceLocation();
2276 }
2277 
2278 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2279   return getASTContext().getTemplateOrSpecializationInfo(this)
2280       .dyn_cast<VarTemplateDecl *>();
2281 }
2282 
2283 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2284   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2285 }
2286 
2287 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2288   if (isStaticDataMember())
2289     // FIXME: Remove ?
2290     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2291     return getASTContext().getTemplateOrSpecializationInfo(this)
2292         .dyn_cast<MemberSpecializationInfo *>();
2293   return nullptr;
2294 }
2295 
2296 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2297                                          SourceLocation PointOfInstantiation) {
2298   assert((isa<VarTemplateSpecializationDecl>(this) ||
2299           getMemberSpecializationInfo()) &&
2300          "not a variable or static data member template specialization");
2301 
2302   if (VarTemplateSpecializationDecl *Spec =
2303           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2304     Spec->setSpecializationKind(TSK);
2305     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2306         Spec->getPointOfInstantiation().isInvalid())
2307       Spec->setPointOfInstantiation(PointOfInstantiation);
2308   }
2309 
2310   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2311     MSI->setTemplateSpecializationKind(TSK);
2312     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2313         MSI->getPointOfInstantiation().isInvalid())
2314       MSI->setPointOfInstantiation(PointOfInstantiation);
2315   }
2316 }
2317 
2318 void
2319 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2320                                             TemplateSpecializationKind TSK) {
2321   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2322          "Previous template or instantiation?");
2323   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2324 }
2325 
2326 //===----------------------------------------------------------------------===//
2327 // ParmVarDecl Implementation
2328 //===----------------------------------------------------------------------===//
2329 
2330 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2331                                  SourceLocation StartLoc,
2332                                  SourceLocation IdLoc, IdentifierInfo *Id,
2333                                  QualType T, TypeSourceInfo *TInfo,
2334                                  StorageClass S, Expr *DefArg) {
2335   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2336                                  S, DefArg);
2337 }
2338 
2339 QualType ParmVarDecl::getOriginalType() const {
2340   TypeSourceInfo *TSI = getTypeSourceInfo();
2341   QualType T = TSI ? TSI->getType() : getType();
2342   if (const auto *DT = dyn_cast<DecayedType>(T))
2343     return DT->getOriginalType();
2344   return T;
2345 }
2346 
2347 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2348   return new (C, ID)
2349       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2350                   nullptr, QualType(), nullptr, SC_None, nullptr);
2351 }
2352 
2353 SourceRange ParmVarDecl::getSourceRange() const {
2354   if (!hasInheritedDefaultArg()) {
2355     SourceRange ArgRange = getDefaultArgRange();
2356     if (ArgRange.isValid())
2357       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2358   }
2359 
2360   // DeclaratorDecl considers the range of postfix types as overlapping with the
2361   // declaration name, but this is not the case with parameters in ObjC methods.
2362   if (isa<ObjCMethodDecl>(getDeclContext()))
2363     return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
2364 
2365   return DeclaratorDecl::getSourceRange();
2366 }
2367 
2368 Expr *ParmVarDecl::getDefaultArg() {
2369   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2370   assert(!hasUninstantiatedDefaultArg() &&
2371          "Default argument is not yet instantiated!");
2372 
2373   Expr *Arg = getInit();
2374   if (auto *E = dyn_cast_or_null<ExprWithCleanups>(Arg))
2375     return E->getSubExpr();
2376 
2377   return Arg;
2378 }
2379 
2380 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2381   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2382   Init = defarg;
2383 }
2384 
2385 SourceRange ParmVarDecl::getDefaultArgRange() const {
2386   switch (ParmVarDeclBits.DefaultArgKind) {
2387   case DAK_None:
2388   case DAK_Unparsed:
2389     // Nothing we can do here.
2390     return SourceRange();
2391 
2392   case DAK_Uninstantiated:
2393     return getUninstantiatedDefaultArg()->getSourceRange();
2394 
2395   case DAK_Normal:
2396     if (const Expr *E = getInit())
2397       return E->getSourceRange();
2398 
2399     // Missing an actual expression, may be invalid.
2400     return SourceRange();
2401   }
2402   llvm_unreachable("Invalid default argument kind.");
2403 }
2404 
2405 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2406   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2407   Init = arg;
2408 }
2409 
2410 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2411   assert(hasUninstantiatedDefaultArg() &&
2412          "Wrong kind of initialization expression!");
2413   return cast_or_null<Expr>(Init.get<Stmt *>());
2414 }
2415 
2416 bool ParmVarDecl::hasDefaultArg() const {
2417   // FIXME: We should just return false for DAK_None here once callers are
2418   // prepared for the case that we encountered an invalid default argument and
2419   // were unable to even build an invalid expression.
2420   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2421          !Init.isNull();
2422 }
2423 
2424 bool ParmVarDecl::isParameterPack() const {
2425   return isa<PackExpansionType>(getType());
2426 }
2427 
2428 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2429   getASTContext().setParameterIndex(this, parameterIndex);
2430   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2431 }
2432 
2433 unsigned ParmVarDecl::getParameterIndexLarge() const {
2434   return getASTContext().getParameterIndex(this);
2435 }
2436 
2437 //===----------------------------------------------------------------------===//
2438 // FunctionDecl Implementation
2439 //===----------------------------------------------------------------------===//
2440 
2441 void FunctionDecl::getNameForDiagnostic(
2442     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2443   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2444   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2445   if (TemplateArgs)
2446     TemplateSpecializationType::PrintTemplateArgumentList(
2447         OS, TemplateArgs->data(), TemplateArgs->size(), Policy);
2448 }
2449 
2450 bool FunctionDecl::isVariadic() const {
2451   if (const auto *FT = getType()->getAs<FunctionProtoType>())
2452     return FT->isVariadic();
2453   return false;
2454 }
2455 
2456 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2457   for (auto I : redecls()) {
2458     if (I->Body || I->IsLateTemplateParsed) {
2459       Definition = I;
2460       return true;
2461     }
2462   }
2463 
2464   return false;
2465 }
2466 
2467 bool FunctionDecl::hasTrivialBody() const
2468 {
2469   Stmt *S = getBody();
2470   if (!S) {
2471     // Since we don't have a body for this function, we don't know if it's
2472     // trivial or not.
2473     return false;
2474   }
2475 
2476   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2477     return true;
2478   return false;
2479 }
2480 
2481 bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2482   for (auto I : redecls()) {
2483     if (I->IsDeleted || I->IsDefaulted || I->Body || I->IsLateTemplateParsed ||
2484         I->hasDefiningAttr()) {
2485       Definition = I->IsDeleted ? I->getCanonicalDecl() : I;
2486       return true;
2487     }
2488   }
2489 
2490   return false;
2491 }
2492 
2493 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2494   if (!hasBody(Definition))
2495     return nullptr;
2496 
2497   if (Definition->Body)
2498     return Definition->Body.get(getASTContext().getExternalSource());
2499 
2500   return nullptr;
2501 }
2502 
2503 void FunctionDecl::setBody(Stmt *B) {
2504   Body = B;
2505   if (B)
2506     EndRangeLoc = B->getLocEnd();
2507 }
2508 
2509 void FunctionDecl::setPure(bool P) {
2510   IsPure = P;
2511   if (P)
2512     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2513       Parent->markedVirtualFunctionPure();
2514 }
2515 
2516 template<std::size_t Len>
2517 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2518   IdentifierInfo *II = ND->getIdentifier();
2519   return II && II->isStr(Str);
2520 }
2521 
2522 bool FunctionDecl::isMain() const {
2523   const TranslationUnitDecl *tunit =
2524     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2525   return tunit &&
2526          !tunit->getASTContext().getLangOpts().Freestanding &&
2527          isNamed(this, "main");
2528 }
2529 
2530 bool FunctionDecl::isMSVCRTEntryPoint() const {
2531   const TranslationUnitDecl *TUnit =
2532       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2533   if (!TUnit)
2534     return false;
2535 
2536   // Even though we aren't really targeting MSVCRT if we are freestanding,
2537   // semantic analysis for these functions remains the same.
2538 
2539   // MSVCRT entry points only exist on MSVCRT targets.
2540   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2541     return false;
2542 
2543   // Nameless functions like constructors cannot be entry points.
2544   if (!getIdentifier())
2545     return false;
2546 
2547   return llvm::StringSwitch<bool>(getName())
2548       .Cases("main",     // an ANSI console app
2549              "wmain",    // a Unicode console App
2550              "WinMain",  // an ANSI GUI app
2551              "wWinMain", // a Unicode GUI app
2552              "DllMain",  // a DLL
2553              true)
2554       .Default(false);
2555 }
2556 
2557 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2558   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
2559   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
2560          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
2561          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
2562          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
2563 
2564   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2565     return false;
2566 
2567   const auto *proto = getType()->castAs<FunctionProtoType>();
2568   if (proto->getNumParams() != 2 || proto->isVariadic())
2569     return false;
2570 
2571   ASTContext &Context =
2572     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2573       ->getASTContext();
2574 
2575   // The result type and first argument type are constant across all
2576   // these operators.  The second argument must be exactly void*.
2577   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2578 }
2579 
2580 bool FunctionDecl::isReplaceableGlobalAllocationFunction() const {
2581   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2582     return false;
2583   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2584       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2585       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2586       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2587     return false;
2588 
2589   if (isa<CXXRecordDecl>(getDeclContext()))
2590     return false;
2591 
2592   // This can only fail for an invalid 'operator new' declaration.
2593   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2594     return false;
2595 
2596   const auto *FPT = getType()->castAs<FunctionProtoType>();
2597   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 2 || FPT->isVariadic())
2598     return false;
2599 
2600   // If this is a single-parameter function, it must be a replaceable global
2601   // allocation or deallocation function.
2602   if (FPT->getNumParams() == 1)
2603     return true;
2604 
2605   // Otherwise, we're looking for a second parameter whose type is
2606   // 'const std::nothrow_t &', or, in C++1y, 'std::size_t'.
2607   QualType Ty = FPT->getParamType(1);
2608   ASTContext &Ctx = getASTContext();
2609   if (Ctx.getLangOpts().SizedDeallocation &&
2610       Ctx.hasSameType(Ty, Ctx.getSizeType()))
2611     return true;
2612   if (!Ty->isReferenceType())
2613     return false;
2614   Ty = Ty->getPointeeType();
2615   if (Ty.getCVRQualifiers() != Qualifiers::Const)
2616     return false;
2617   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
2618   return RD && isNamed(RD, "nothrow_t") && RD->isInStdNamespace();
2619 }
2620 
2621 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
2622   return getDeclLanguageLinkage(*this);
2623 }
2624 
2625 bool FunctionDecl::isExternC() const {
2626   return isDeclExternC(*this);
2627 }
2628 
2629 bool FunctionDecl::isInExternCContext() const {
2630   return getLexicalDeclContext()->isExternCContext();
2631 }
2632 
2633 bool FunctionDecl::isInExternCXXContext() const {
2634   return getLexicalDeclContext()->isExternCXXContext();
2635 }
2636 
2637 bool FunctionDecl::isGlobal() const {
2638   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
2639     return Method->isStatic();
2640 
2641   if (getCanonicalDecl()->getStorageClass() == SC_Static)
2642     return false;
2643 
2644   for (const DeclContext *DC = getDeclContext();
2645        DC->isNamespace();
2646        DC = DC->getParent()) {
2647     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
2648       if (!Namespace->getDeclName())
2649         return false;
2650       break;
2651     }
2652   }
2653 
2654   return true;
2655 }
2656 
2657 bool FunctionDecl::isNoReturn() const {
2658   return hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
2659          hasAttr<C11NoReturnAttr>() ||
2660          getType()->getAs<FunctionType>()->getNoReturnAttr();
2661 }
2662 
2663 void
2664 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
2665   redeclarable_base::setPreviousDecl(PrevDecl);
2666 
2667   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
2668     FunctionTemplateDecl *PrevFunTmpl
2669       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
2670     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
2671     FunTmpl->setPreviousDecl(PrevFunTmpl);
2672   }
2673 
2674   if (PrevDecl && PrevDecl->IsInline)
2675     IsInline = true;
2676 }
2677 
2678 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
2679 
2680 /// \brief Returns a value indicating whether this function
2681 /// corresponds to a builtin function.
2682 ///
2683 /// The function corresponds to a built-in function if it is
2684 /// declared at translation scope or within an extern "C" block and
2685 /// its name matches with the name of a builtin. The returned value
2686 /// will be 0 for functions that do not correspond to a builtin, a
2687 /// value of type \c Builtin::ID if in the target-independent range
2688 /// \c [1,Builtin::First), or a target-specific builtin value.
2689 unsigned FunctionDecl::getBuiltinID() const {
2690   if (!getIdentifier())
2691     return 0;
2692 
2693   unsigned BuiltinID = getIdentifier()->getBuiltinID();
2694   if (!BuiltinID)
2695     return 0;
2696 
2697   ASTContext &Context = getASTContext();
2698   if (Context.getLangOpts().CPlusPlus) {
2699     const auto *LinkageDecl =
2700         dyn_cast<LinkageSpecDecl>(getFirstDecl()->getDeclContext());
2701     // In C++, the first declaration of a builtin is always inside an implicit
2702     // extern "C".
2703     // FIXME: A recognised library function may not be directly in an extern "C"
2704     // declaration, for instance "extern "C" { namespace std { decl } }".
2705     if (!LinkageDecl) {
2706       if (BuiltinID == Builtin::BI__GetExceptionInfo &&
2707           Context.getTargetInfo().getCXXABI().isMicrosoft())
2708         return Builtin::BI__GetExceptionInfo;
2709       return 0;
2710     }
2711     if (LinkageDecl->getLanguage() != LinkageSpecDecl::lang_c)
2712       return 0;
2713   }
2714 
2715   // If the function is marked "overloadable", it has a different mangled name
2716   // and is not the C library function.
2717   if (hasAttr<OverloadableAttr>())
2718     return 0;
2719 
2720   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2721     return BuiltinID;
2722 
2723   // This function has the name of a known C library
2724   // function. Determine whether it actually refers to the C library
2725   // function or whether it just has the same name.
2726 
2727   // If this is a static function, it's not a builtin.
2728   if (getStorageClass() == SC_Static)
2729     return 0;
2730 
2731   // OpenCL v1.2 s6.9.f - The library functions defined in
2732   // the C99 standard headers are not available.
2733   if (Context.getLangOpts().OpenCL &&
2734       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
2735     return 0;
2736 
2737   return BuiltinID;
2738 }
2739 
2740 
2741 /// getNumParams - Return the number of parameters this function must have
2742 /// based on its FunctionType.  This is the length of the ParamInfo array
2743 /// after it has been created.
2744 unsigned FunctionDecl::getNumParams() const {
2745   const auto *FPT = getType()->getAs<FunctionProtoType>();
2746   return FPT ? FPT->getNumParams() : 0;
2747 }
2748 
2749 void FunctionDecl::setParams(ASTContext &C,
2750                              ArrayRef<ParmVarDecl *> NewParamInfo) {
2751   assert(!ParamInfo && "Already has param info!");
2752   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
2753 
2754   // Zero params -> null pointer.
2755   if (!NewParamInfo.empty()) {
2756     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
2757     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
2758   }
2759 }
2760 
2761 void FunctionDecl::setDeclsInPrototypeScope(ArrayRef<NamedDecl *> NewDecls) {
2762   assert(DeclsInPrototypeScope.empty() && "Already has prototype decls!");
2763 
2764   if (!NewDecls.empty()) {
2765     NamedDecl **A = new (getASTContext()) NamedDecl*[NewDecls.size()];
2766     std::copy(NewDecls.begin(), NewDecls.end(), A);
2767     DeclsInPrototypeScope = llvm::makeArrayRef(A, NewDecls.size());
2768     // Move declarations introduced in prototype to the function context.
2769     for (auto I : NewDecls) {
2770       DeclContext *DC = I->getDeclContext();
2771       // Forward-declared reference to an enumeration is not added to
2772       // declaration scope, so skip declaration that is absent from its
2773       // declaration contexts.
2774       if (DC->containsDecl(I)) {
2775           DC->removeDecl(I);
2776           I->setDeclContext(this);
2777           addDecl(I);
2778       }
2779     }
2780   }
2781 }
2782 
2783 /// getMinRequiredArguments - Returns the minimum number of arguments
2784 /// needed to call this function. This may be fewer than the number of
2785 /// function parameters, if some of the parameters have default
2786 /// arguments (in C++) or are parameter packs (C++11).
2787 unsigned FunctionDecl::getMinRequiredArguments() const {
2788   if (!getASTContext().getLangOpts().CPlusPlus)
2789     return getNumParams();
2790 
2791   unsigned NumRequiredArgs = 0;
2792   for (auto *Param : parameters())
2793     if (!Param->isParameterPack() && !Param->hasDefaultArg())
2794       ++NumRequiredArgs;
2795   return NumRequiredArgs;
2796 }
2797 
2798 /// \brief The combination of the extern and inline keywords under MSVC forces
2799 /// the function to be required.
2800 ///
2801 /// Note: This function assumes that we will only get called when isInlined()
2802 /// would return true for this FunctionDecl.
2803 bool FunctionDecl::isMSExternInline() const {
2804   assert(isInlined() && "expected to get called on an inlined function!");
2805 
2806   const ASTContext &Context = getASTContext();
2807   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
2808       !hasAttr<DLLExportAttr>())
2809     return false;
2810 
2811   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
2812        FD = FD->getPreviousDecl())
2813     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2814       return true;
2815 
2816   return false;
2817 }
2818 
2819 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
2820   if (Redecl->getStorageClass() != SC_Extern)
2821     return false;
2822 
2823   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
2824        FD = FD->getPreviousDecl())
2825     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
2826       return false;
2827 
2828   return true;
2829 }
2830 
2831 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
2832   // Only consider file-scope declarations in this test.
2833   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
2834     return false;
2835 
2836   // Only consider explicit declarations; the presence of a builtin for a
2837   // libcall shouldn't affect whether a definition is externally visible.
2838   if (Redecl->isImplicit())
2839     return false;
2840 
2841   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
2842     return true; // Not an inline definition
2843 
2844   return false;
2845 }
2846 
2847 /// \brief For a function declaration in C or C++, determine whether this
2848 /// declaration causes the definition to be externally visible.
2849 ///
2850 /// For instance, this determines if adding the current declaration to the set
2851 /// of redeclarations of the given functions causes
2852 /// isInlineDefinitionExternallyVisible to change from false to true.
2853 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
2854   assert(!doesThisDeclarationHaveABody() &&
2855          "Must have a declaration without a body.");
2856 
2857   ASTContext &Context = getASTContext();
2858 
2859   if (Context.getLangOpts().MSVCCompat) {
2860     const FunctionDecl *Definition;
2861     if (hasBody(Definition) && Definition->isInlined() &&
2862         redeclForcesDefMSVC(this))
2863       return true;
2864   }
2865 
2866   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2867     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
2868     // an externally visible definition.
2869     //
2870     // FIXME: What happens if gnu_inline gets added on after the first
2871     // declaration?
2872     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
2873       return false;
2874 
2875     const FunctionDecl *Prev = this;
2876     bool FoundBody = false;
2877     while ((Prev = Prev->getPreviousDecl())) {
2878       FoundBody |= Prev->Body.isValid();
2879 
2880       if (Prev->Body) {
2881         // If it's not the case that both 'inline' and 'extern' are
2882         // specified on the definition, then it is always externally visible.
2883         if (!Prev->isInlineSpecified() ||
2884             Prev->getStorageClass() != SC_Extern)
2885           return false;
2886       } else if (Prev->isInlineSpecified() &&
2887                  Prev->getStorageClass() != SC_Extern) {
2888         return false;
2889       }
2890     }
2891     return FoundBody;
2892   }
2893 
2894   if (Context.getLangOpts().CPlusPlus)
2895     return false;
2896 
2897   // C99 6.7.4p6:
2898   //   [...] If all of the file scope declarations for a function in a
2899   //   translation unit include the inline function specifier without extern,
2900   //   then the definition in that translation unit is an inline definition.
2901   if (isInlineSpecified() && getStorageClass() != SC_Extern)
2902     return false;
2903   const FunctionDecl *Prev = this;
2904   bool FoundBody = false;
2905   while ((Prev = Prev->getPreviousDecl())) {
2906     FoundBody |= Prev->Body.isValid();
2907     if (RedeclForcesDefC99(Prev))
2908       return false;
2909   }
2910   return FoundBody;
2911 }
2912 
2913 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
2914   const TypeSourceInfo *TSI = getTypeSourceInfo();
2915   if (!TSI)
2916     return SourceRange();
2917   FunctionTypeLoc FTL =
2918       TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>();
2919   if (!FTL)
2920     return SourceRange();
2921 
2922   // Skip self-referential return types.
2923   const SourceManager &SM = getASTContext().getSourceManager();
2924   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
2925   SourceLocation Boundary = getNameInfo().getLocStart();
2926   if (RTRange.isInvalid() || Boundary.isInvalid() ||
2927       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
2928     return SourceRange();
2929 
2930   return RTRange;
2931 }
2932 
2933 const Attr *FunctionDecl::getUnusedResultAttr() const {
2934   QualType RetType = getReturnType();
2935   if (RetType->isRecordType()) {
2936     const CXXRecordDecl *Ret = RetType->getAsCXXRecordDecl();
2937     const auto *MD = dyn_cast<CXXMethodDecl>(this);
2938     if (Ret && !(MD && MD->getCorrespondingMethodInClass(Ret, true))) {
2939       if (const auto *R = Ret->getAttr<WarnUnusedResultAttr>())
2940         return R;
2941     }
2942   } else if (const auto *ET = RetType->getAs<EnumType>()) {
2943     if (const EnumDecl *ED = ET->getDecl()) {
2944       if (const auto *R = ED->getAttr<WarnUnusedResultAttr>())
2945         return R;
2946     }
2947   }
2948   return getAttr<WarnUnusedResultAttr>();
2949 }
2950 
2951 /// \brief For an inline function definition in C, or for a gnu_inline function
2952 /// in C++, determine whether the definition will be externally visible.
2953 ///
2954 /// Inline function definitions are always available for inlining optimizations.
2955 /// However, depending on the language dialect, declaration specifiers, and
2956 /// attributes, the definition of an inline function may or may not be
2957 /// "externally" visible to other translation units in the program.
2958 ///
2959 /// In C99, inline definitions are not externally visible by default. However,
2960 /// if even one of the global-scope declarations is marked "extern inline", the
2961 /// inline definition becomes externally visible (C99 6.7.4p6).
2962 ///
2963 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
2964 /// definition, we use the GNU semantics for inline, which are nearly the
2965 /// opposite of C99 semantics. In particular, "inline" by itself will create
2966 /// an externally visible symbol, but "extern inline" will not create an
2967 /// externally visible symbol.
2968 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
2969   assert(doesThisDeclarationHaveABody() && "Must have the function definition");
2970   assert(isInlined() && "Function must be inline");
2971   ASTContext &Context = getASTContext();
2972 
2973   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
2974     // Note: If you change the logic here, please change
2975     // doesDeclarationForceExternallyVisibleDefinition as well.
2976     //
2977     // If it's not the case that both 'inline' and 'extern' are
2978     // specified on the definition, then this inline definition is
2979     // externally visible.
2980     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
2981       return true;
2982 
2983     // If any declaration is 'inline' but not 'extern', then this definition
2984     // is externally visible.
2985     for (auto Redecl : redecls()) {
2986       if (Redecl->isInlineSpecified() &&
2987           Redecl->getStorageClass() != SC_Extern)
2988         return true;
2989     }
2990 
2991     return false;
2992   }
2993 
2994   // The rest of this function is C-only.
2995   assert(!Context.getLangOpts().CPlusPlus &&
2996          "should not use C inline rules in C++");
2997 
2998   // C99 6.7.4p6:
2999   //   [...] If all of the file scope declarations for a function in a
3000   //   translation unit include the inline function specifier without extern,
3001   //   then the definition in that translation unit is an inline definition.
3002   for (auto Redecl : redecls()) {
3003     if (RedeclForcesDefC99(Redecl))
3004       return true;
3005   }
3006 
3007   // C99 6.7.4p6:
3008   //   An inline definition does not provide an external definition for the
3009   //   function, and does not forbid an external definition in another
3010   //   translation unit.
3011   return false;
3012 }
3013 
3014 /// getOverloadedOperator - Which C++ overloaded operator this
3015 /// function represents, if any.
3016 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3017   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3018     return getDeclName().getCXXOverloadedOperator();
3019   else
3020     return OO_None;
3021 }
3022 
3023 /// getLiteralIdentifier - The literal suffix identifier this function
3024 /// represents, if any.
3025 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3026   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3027     return getDeclName().getCXXLiteralIdentifier();
3028   else
3029     return nullptr;
3030 }
3031 
3032 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3033   if (TemplateOrSpecialization.isNull())
3034     return TK_NonTemplate;
3035   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3036     return TK_FunctionTemplate;
3037   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3038     return TK_MemberSpecialization;
3039   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3040     return TK_FunctionTemplateSpecialization;
3041   if (TemplateOrSpecialization.is
3042                                <DependentFunctionTemplateSpecializationInfo*>())
3043     return TK_DependentFunctionTemplateSpecialization;
3044 
3045   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3046 }
3047 
3048 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3049   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3050     return cast<FunctionDecl>(Info->getInstantiatedFrom());
3051 
3052   return nullptr;
3053 }
3054 
3055 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3056   return TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>();
3057 }
3058 
3059 void
3060 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3061                                                FunctionDecl *FD,
3062                                                TemplateSpecializationKind TSK) {
3063   assert(TemplateOrSpecialization.isNull() &&
3064          "Member function is already a specialization");
3065   MemberSpecializationInfo *Info
3066     = new (C) MemberSpecializationInfo(FD, TSK);
3067   TemplateOrSpecialization = Info;
3068 }
3069 
3070 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3071   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3072 }
3073 
3074 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3075   TemplateOrSpecialization = Template;
3076 }
3077 
3078 bool FunctionDecl::isImplicitlyInstantiable() const {
3079   // If the function is invalid, it can't be implicitly instantiated.
3080   if (isInvalidDecl())
3081     return false;
3082 
3083   switch (getTemplateSpecializationKind()) {
3084   case TSK_Undeclared:
3085   case TSK_ExplicitInstantiationDefinition:
3086     return false;
3087 
3088   case TSK_ImplicitInstantiation:
3089     return true;
3090 
3091   // It is possible to instantiate TSK_ExplicitSpecialization kind
3092   // if the FunctionDecl has a class scope specialization pattern.
3093   case TSK_ExplicitSpecialization:
3094     return getClassScopeSpecializationPattern() != nullptr;
3095 
3096   case TSK_ExplicitInstantiationDeclaration:
3097     // Handled below.
3098     break;
3099   }
3100 
3101   // Find the actual template from which we will instantiate.
3102   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3103   bool HasPattern = false;
3104   if (PatternDecl)
3105     HasPattern = PatternDecl->hasBody(PatternDecl);
3106 
3107   // C++0x [temp.explicit]p9:
3108   //   Except for inline functions, other explicit instantiation declarations
3109   //   have the effect of suppressing the implicit instantiation of the entity
3110   //   to which they refer.
3111   if (!HasPattern || !PatternDecl)
3112     return true;
3113 
3114   return PatternDecl->isInlined();
3115 }
3116 
3117 bool FunctionDecl::isTemplateInstantiation() const {
3118   switch (getTemplateSpecializationKind()) {
3119     case TSK_Undeclared:
3120     case TSK_ExplicitSpecialization:
3121       return false;
3122     case TSK_ImplicitInstantiation:
3123     case TSK_ExplicitInstantiationDeclaration:
3124     case TSK_ExplicitInstantiationDefinition:
3125       return true;
3126   }
3127   llvm_unreachable("All TSK values handled.");
3128 }
3129 
3130 FunctionDecl *FunctionDecl::getTemplateInstantiationPattern() const {
3131   // Handle class scope explicit specialization special case.
3132   if (getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
3133     return getClassScopeSpecializationPattern();
3134 
3135   // If this is a generic lambda call operator specialization, its
3136   // instantiation pattern is always its primary template's pattern
3137   // even if its primary template was instantiated from another
3138   // member template (which happens with nested generic lambdas).
3139   // Since a lambda's call operator's body is transformed eagerly,
3140   // we don't have to go hunting for a prototype definition template
3141   // (i.e. instantiated-from-member-template) to use as an instantiation
3142   // pattern.
3143 
3144   if (isGenericLambdaCallOperatorSpecialization(
3145           dyn_cast<CXXMethodDecl>(this))) {
3146     assert(getPrimaryTemplate() && "A generic lambda specialization must be "
3147                                    "generated from a primary call operator "
3148                                    "template");
3149     assert(getPrimaryTemplate()->getTemplatedDecl()->getBody() &&
3150            "A generic lambda call operator template must always have a body - "
3151            "even if instantiated from a prototype (i.e. as written) member "
3152            "template");
3153     return getPrimaryTemplate()->getTemplatedDecl();
3154   }
3155 
3156   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3157     while (Primary->getInstantiatedFromMemberTemplate()) {
3158       // If we have hit a point where the user provided a specialization of
3159       // this template, we're done looking.
3160       if (Primary->isMemberSpecialization())
3161         break;
3162       Primary = Primary->getInstantiatedFromMemberTemplate();
3163     }
3164 
3165     return Primary->getTemplatedDecl();
3166   }
3167 
3168   return getInstantiatedFromMemberFunction();
3169 }
3170 
3171 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3172   if (FunctionTemplateSpecializationInfo *Info
3173         = TemplateOrSpecialization
3174             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3175     return Info->Template.getPointer();
3176   }
3177   return nullptr;
3178 }
3179 
3180 FunctionDecl *FunctionDecl::getClassScopeSpecializationPattern() const {
3181     return getASTContext().getClassScopeSpecializationPattern(this);
3182 }
3183 
3184 FunctionTemplateSpecializationInfo *
3185 FunctionDecl::getTemplateSpecializationInfo() const {
3186   return TemplateOrSpecialization
3187       .dyn_cast<FunctionTemplateSpecializationInfo *>();
3188 }
3189 
3190 const TemplateArgumentList *
3191 FunctionDecl::getTemplateSpecializationArgs() const {
3192   if (FunctionTemplateSpecializationInfo *Info
3193         = TemplateOrSpecialization
3194             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3195     return Info->TemplateArguments;
3196   }
3197   return nullptr;
3198 }
3199 
3200 const ASTTemplateArgumentListInfo *
3201 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3202   if (FunctionTemplateSpecializationInfo *Info
3203         = TemplateOrSpecialization
3204             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3205     return Info->TemplateArgumentsAsWritten;
3206   }
3207   return nullptr;
3208 }
3209 
3210 void
3211 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3212                                                 FunctionTemplateDecl *Template,
3213                                      const TemplateArgumentList *TemplateArgs,
3214                                                 void *InsertPos,
3215                                                 TemplateSpecializationKind TSK,
3216                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
3217                                           SourceLocation PointOfInstantiation) {
3218   assert(TSK != TSK_Undeclared &&
3219          "Must specify the type of function template specialization");
3220   FunctionTemplateSpecializationInfo *Info
3221     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3222   if (!Info)
3223     Info = FunctionTemplateSpecializationInfo::Create(C, this, Template, TSK,
3224                                                       TemplateArgs,
3225                                                       TemplateArgsAsWritten,
3226                                                       PointOfInstantiation);
3227   TemplateOrSpecialization = Info;
3228   Template->addSpecialization(Info, InsertPos);
3229 }
3230 
3231 void
3232 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3233                                     const UnresolvedSetImpl &Templates,
3234                              const TemplateArgumentListInfo &TemplateArgs) {
3235   assert(TemplateOrSpecialization.isNull());
3236   DependentFunctionTemplateSpecializationInfo *Info =
3237       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3238                                                           TemplateArgs);
3239   TemplateOrSpecialization = Info;
3240 }
3241 
3242 DependentFunctionTemplateSpecializationInfo *
3243 FunctionDecl::getDependentSpecializationInfo() const {
3244   return TemplateOrSpecialization
3245       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3246 }
3247 
3248 DependentFunctionTemplateSpecializationInfo *
3249 DependentFunctionTemplateSpecializationInfo::Create(
3250     ASTContext &Context, const UnresolvedSetImpl &Ts,
3251     const TemplateArgumentListInfo &TArgs) {
3252   void *Buffer = Context.Allocate(
3253       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3254           TArgs.size(), Ts.size()));
3255   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3256 }
3257 
3258 DependentFunctionTemplateSpecializationInfo::
3259 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3260                                       const TemplateArgumentListInfo &TArgs)
3261   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3262 
3263   NumTemplates = Ts.size();
3264   NumArgs = TArgs.size();
3265 
3266   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3267   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3268     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3269 
3270   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3271   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3272     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3273 }
3274 
3275 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3276   // For a function template specialization, query the specialization
3277   // information object.
3278   FunctionTemplateSpecializationInfo *FTSInfo
3279     = TemplateOrSpecialization.dyn_cast<FunctionTemplateSpecializationInfo*>();
3280   if (FTSInfo)
3281     return FTSInfo->getTemplateSpecializationKind();
3282 
3283   MemberSpecializationInfo *MSInfo
3284     = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>();
3285   if (MSInfo)
3286     return MSInfo->getTemplateSpecializationKind();
3287 
3288   return TSK_Undeclared;
3289 }
3290 
3291 void
3292 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3293                                           SourceLocation PointOfInstantiation) {
3294   if (FunctionTemplateSpecializationInfo *FTSInfo
3295         = TemplateOrSpecialization.dyn_cast<
3296                                     FunctionTemplateSpecializationInfo*>()) {
3297     FTSInfo->setTemplateSpecializationKind(TSK);
3298     if (TSK != TSK_ExplicitSpecialization &&
3299         PointOfInstantiation.isValid() &&
3300         FTSInfo->getPointOfInstantiation().isInvalid())
3301       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3302   } else if (MemberSpecializationInfo *MSInfo
3303              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3304     MSInfo->setTemplateSpecializationKind(TSK);
3305     if (TSK != TSK_ExplicitSpecialization &&
3306         PointOfInstantiation.isValid() &&
3307         MSInfo->getPointOfInstantiation().isInvalid())
3308       MSInfo->setPointOfInstantiation(PointOfInstantiation);
3309   } else
3310     llvm_unreachable("Function cannot have a template specialization kind");
3311 }
3312 
3313 SourceLocation FunctionDecl::getPointOfInstantiation() const {
3314   if (FunctionTemplateSpecializationInfo *FTSInfo
3315         = TemplateOrSpecialization.dyn_cast<
3316                                         FunctionTemplateSpecializationInfo*>())
3317     return FTSInfo->getPointOfInstantiation();
3318   else if (MemberSpecializationInfo *MSInfo
3319              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3320     return MSInfo->getPointOfInstantiation();
3321 
3322   return SourceLocation();
3323 }
3324 
3325 bool FunctionDecl::isOutOfLine() const {
3326   if (Decl::isOutOfLine())
3327     return true;
3328 
3329   // If this function was instantiated from a member function of a
3330   // class template, check whether that member function was defined out-of-line.
3331   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3332     const FunctionDecl *Definition;
3333     if (FD->hasBody(Definition))
3334       return Definition->isOutOfLine();
3335   }
3336 
3337   // If this function was instantiated from a function template,
3338   // check whether that function template was defined out-of-line.
3339   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3340     const FunctionDecl *Definition;
3341     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3342       return Definition->isOutOfLine();
3343   }
3344 
3345   return false;
3346 }
3347 
3348 SourceRange FunctionDecl::getSourceRange() const {
3349   return SourceRange(getOuterLocStart(), EndRangeLoc);
3350 }
3351 
3352 unsigned FunctionDecl::getMemoryFunctionKind() const {
3353   IdentifierInfo *FnInfo = getIdentifier();
3354 
3355   if (!FnInfo)
3356     return 0;
3357 
3358   // Builtin handling.
3359   switch (getBuiltinID()) {
3360   case Builtin::BI__builtin_memset:
3361   case Builtin::BI__builtin___memset_chk:
3362   case Builtin::BImemset:
3363     return Builtin::BImemset;
3364 
3365   case Builtin::BI__builtin_memcpy:
3366   case Builtin::BI__builtin___memcpy_chk:
3367   case Builtin::BImemcpy:
3368     return Builtin::BImemcpy;
3369 
3370   case Builtin::BI__builtin_memmove:
3371   case Builtin::BI__builtin___memmove_chk:
3372   case Builtin::BImemmove:
3373     return Builtin::BImemmove;
3374 
3375   case Builtin::BIstrlcpy:
3376   case Builtin::BI__builtin___strlcpy_chk:
3377     return Builtin::BIstrlcpy;
3378 
3379   case Builtin::BIstrlcat:
3380   case Builtin::BI__builtin___strlcat_chk:
3381     return Builtin::BIstrlcat;
3382 
3383   case Builtin::BI__builtin_memcmp:
3384   case Builtin::BImemcmp:
3385     return Builtin::BImemcmp;
3386 
3387   case Builtin::BI__builtin_strncpy:
3388   case Builtin::BI__builtin___strncpy_chk:
3389   case Builtin::BIstrncpy:
3390     return Builtin::BIstrncpy;
3391 
3392   case Builtin::BI__builtin_strncmp:
3393   case Builtin::BIstrncmp:
3394     return Builtin::BIstrncmp;
3395 
3396   case Builtin::BI__builtin_strncasecmp:
3397   case Builtin::BIstrncasecmp:
3398     return Builtin::BIstrncasecmp;
3399 
3400   case Builtin::BI__builtin_strncat:
3401   case Builtin::BI__builtin___strncat_chk:
3402   case Builtin::BIstrncat:
3403     return Builtin::BIstrncat;
3404 
3405   case Builtin::BI__builtin_strndup:
3406   case Builtin::BIstrndup:
3407     return Builtin::BIstrndup;
3408 
3409   case Builtin::BI__builtin_strlen:
3410   case Builtin::BIstrlen:
3411     return Builtin::BIstrlen;
3412 
3413   default:
3414     if (isExternC()) {
3415       if (FnInfo->isStr("memset"))
3416         return Builtin::BImemset;
3417       else if (FnInfo->isStr("memcpy"))
3418         return Builtin::BImemcpy;
3419       else if (FnInfo->isStr("memmove"))
3420         return Builtin::BImemmove;
3421       else if (FnInfo->isStr("memcmp"))
3422         return Builtin::BImemcmp;
3423       else if (FnInfo->isStr("strncpy"))
3424         return Builtin::BIstrncpy;
3425       else if (FnInfo->isStr("strncmp"))
3426         return Builtin::BIstrncmp;
3427       else if (FnInfo->isStr("strncasecmp"))
3428         return Builtin::BIstrncasecmp;
3429       else if (FnInfo->isStr("strncat"))
3430         return Builtin::BIstrncat;
3431       else if (FnInfo->isStr("strndup"))
3432         return Builtin::BIstrndup;
3433       else if (FnInfo->isStr("strlen"))
3434         return Builtin::BIstrlen;
3435     }
3436     break;
3437   }
3438   return 0;
3439 }
3440 
3441 //===----------------------------------------------------------------------===//
3442 // FieldDecl Implementation
3443 //===----------------------------------------------------------------------===//
3444 
3445 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
3446                              SourceLocation StartLoc, SourceLocation IdLoc,
3447                              IdentifierInfo *Id, QualType T,
3448                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
3449                              InClassInitStyle InitStyle) {
3450   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
3451                                BW, Mutable, InitStyle);
3452 }
3453 
3454 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3455   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
3456                                SourceLocation(), nullptr, QualType(), nullptr,
3457                                nullptr, false, ICIS_NoInit);
3458 }
3459 
3460 bool FieldDecl::isAnonymousStructOrUnion() const {
3461   if (!isImplicit() || getDeclName())
3462     return false;
3463 
3464   if (const auto *Record = getType()->getAs<RecordType>())
3465     return Record->getDecl()->isAnonymousStructOrUnion();
3466 
3467   return false;
3468 }
3469 
3470 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
3471   assert(isBitField() && "not a bitfield");
3472   auto *BitWidth = static_cast<Expr *>(InitStorage.getPointer());
3473   return BitWidth->EvaluateKnownConstInt(Ctx).getZExtValue();
3474 }
3475 
3476 unsigned FieldDecl::getFieldIndex() const {
3477   const FieldDecl *Canonical = getCanonicalDecl();
3478   if (Canonical != this)
3479     return Canonical->getFieldIndex();
3480 
3481   if (CachedFieldIndex) return CachedFieldIndex - 1;
3482 
3483   unsigned Index = 0;
3484   const RecordDecl *RD = getParent();
3485 
3486   for (auto *Field : RD->fields()) {
3487     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
3488     ++Index;
3489   }
3490 
3491   assert(CachedFieldIndex && "failed to find field in parent");
3492   return CachedFieldIndex - 1;
3493 }
3494 
3495 SourceRange FieldDecl::getSourceRange() const {
3496   switch (InitStorage.getInt()) {
3497   // All three of these cases store an optional Expr*.
3498   case ISK_BitWidthOrNothing:
3499   case ISK_InClassCopyInit:
3500   case ISK_InClassListInit:
3501     if (const auto *E = static_cast<const Expr *>(InitStorage.getPointer()))
3502       return SourceRange(getInnerLocStart(), E->getLocEnd());
3503     // FALLTHROUGH
3504 
3505   case ISK_CapturedVLAType:
3506     return DeclaratorDecl::getSourceRange();
3507   }
3508   llvm_unreachable("bad init storage kind");
3509 }
3510 
3511 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
3512   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
3513          "capturing type in non-lambda or captured record.");
3514   assert(InitStorage.getInt() == ISK_BitWidthOrNothing &&
3515          InitStorage.getPointer() == nullptr &&
3516          "bit width, initializer or captured type already set");
3517   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
3518                                ISK_CapturedVLAType);
3519 }
3520 
3521 //===----------------------------------------------------------------------===//
3522 // TagDecl Implementation
3523 //===----------------------------------------------------------------------===//
3524 
3525 SourceLocation TagDecl::getOuterLocStart() const {
3526   return getTemplateOrInnerLocStart(this);
3527 }
3528 
3529 SourceRange TagDecl::getSourceRange() const {
3530   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
3531   return SourceRange(getOuterLocStart(), E);
3532 }
3533 
3534 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
3535 
3536 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
3537   TypedefNameDeclOrQualifier = TDD;
3538   if (const Type *T = getTypeForDecl()) {
3539     (void)T;
3540     assert(T->isLinkageValid());
3541   }
3542   assert(isLinkageValid());
3543 }
3544 
3545 void TagDecl::startDefinition() {
3546   IsBeingDefined = true;
3547 
3548   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
3549     struct CXXRecordDecl::DefinitionData *Data =
3550       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
3551     for (auto I : redecls())
3552       cast<CXXRecordDecl>(I)->DefinitionData = Data;
3553   }
3554 }
3555 
3556 void TagDecl::completeDefinition() {
3557   assert((!isa<CXXRecordDecl>(this) ||
3558           cast<CXXRecordDecl>(this)->hasDefinition()) &&
3559          "definition completed but not started");
3560 
3561   IsCompleteDefinition = true;
3562   IsBeingDefined = false;
3563 
3564   if (ASTMutationListener *L = getASTMutationListener())
3565     L->CompletedTagDefinition(this);
3566 }
3567 
3568 TagDecl *TagDecl::getDefinition() const {
3569   if (isCompleteDefinition())
3570     return const_cast<TagDecl *>(this);
3571 
3572   // If it's possible for us to have an out-of-date definition, check now.
3573   if (MayHaveOutOfDateDef) {
3574     if (IdentifierInfo *II = getIdentifier()) {
3575       if (II->isOutOfDate()) {
3576         updateOutOfDate(*II);
3577       }
3578     }
3579   }
3580 
3581   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
3582     return CXXRD->getDefinition();
3583 
3584   for (auto R : redecls())
3585     if (R->isCompleteDefinition())
3586       return R;
3587 
3588   return nullptr;
3589 }
3590 
3591 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
3592   if (QualifierLoc) {
3593     // Make sure the extended qualifier info is allocated.
3594     if (!hasExtInfo())
3595       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3596     // Set qualifier info.
3597     getExtInfo()->QualifierLoc = QualifierLoc;
3598   } else {
3599     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
3600     if (hasExtInfo()) {
3601       if (getExtInfo()->NumTemplParamLists == 0) {
3602         getASTContext().Deallocate(getExtInfo());
3603         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
3604       }
3605       else
3606         getExtInfo()->QualifierLoc = QualifierLoc;
3607     }
3608   }
3609 }
3610 
3611 void TagDecl::setTemplateParameterListsInfo(
3612     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
3613   assert(!TPLists.empty());
3614   // Make sure the extended decl info is allocated.
3615   if (!hasExtInfo())
3616     // Allocate external info struct.
3617     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
3618   // Set the template parameter lists info.
3619   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
3620 }
3621 
3622 //===----------------------------------------------------------------------===//
3623 // EnumDecl Implementation
3624 //===----------------------------------------------------------------------===//
3625 
3626 void EnumDecl::anchor() { }
3627 
3628 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
3629                            SourceLocation StartLoc, SourceLocation IdLoc,
3630                            IdentifierInfo *Id,
3631                            EnumDecl *PrevDecl, bool IsScoped,
3632                            bool IsScopedUsingClassTag, bool IsFixed) {
3633   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
3634                                     IsScoped, IsScopedUsingClassTag, IsFixed);
3635   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3636   C.getTypeDeclType(Enum, PrevDecl);
3637   return Enum;
3638 }
3639 
3640 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3641   EnumDecl *Enum =
3642       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
3643                            nullptr, nullptr, false, false, false);
3644   Enum->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3645   return Enum;
3646 }
3647 
3648 SourceRange EnumDecl::getIntegerTypeRange() const {
3649   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
3650     return TI->getTypeLoc().getSourceRange();
3651   return SourceRange();
3652 }
3653 
3654 void EnumDecl::completeDefinition(QualType NewType,
3655                                   QualType NewPromotionType,
3656                                   unsigned NumPositiveBits,
3657                                   unsigned NumNegativeBits) {
3658   assert(!isCompleteDefinition() && "Cannot redefine enums!");
3659   if (!IntegerType)
3660     IntegerType = NewType.getTypePtr();
3661   PromotionType = NewPromotionType;
3662   setNumPositiveBits(NumPositiveBits);
3663   setNumNegativeBits(NumNegativeBits);
3664   TagDecl::completeDefinition();
3665 }
3666 
3667 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
3668   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
3669     return MSI->getTemplateSpecializationKind();
3670 
3671   return TSK_Undeclared;
3672 }
3673 
3674 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3675                                          SourceLocation PointOfInstantiation) {
3676   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
3677   assert(MSI && "Not an instantiated member enumeration?");
3678   MSI->setTemplateSpecializationKind(TSK);
3679   if (TSK != TSK_ExplicitSpecialization &&
3680       PointOfInstantiation.isValid() &&
3681       MSI->getPointOfInstantiation().isInvalid())
3682     MSI->setPointOfInstantiation(PointOfInstantiation);
3683 }
3684 
3685 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
3686   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
3687     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
3688       EnumDecl *ED = getInstantiatedFromMemberEnum();
3689       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
3690         ED = NewED;
3691       return ED;
3692     }
3693   }
3694 
3695   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
3696          "couldn't find pattern for enum instantiation");
3697   return nullptr;
3698 }
3699 
3700 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
3701   if (SpecializationInfo)
3702     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
3703 
3704   return nullptr;
3705 }
3706 
3707 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
3708                                             TemplateSpecializationKind TSK) {
3709   assert(!SpecializationInfo && "Member enum is already a specialization");
3710   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
3711 }
3712 
3713 //===----------------------------------------------------------------------===//
3714 // RecordDecl Implementation
3715 //===----------------------------------------------------------------------===//
3716 
3717 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
3718                        DeclContext *DC, SourceLocation StartLoc,
3719                        SourceLocation IdLoc, IdentifierInfo *Id,
3720                        RecordDecl *PrevDecl)
3721     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
3722   HasFlexibleArrayMember = false;
3723   AnonymousStructOrUnion = false;
3724   HasObjectMember = false;
3725   HasVolatileMember = false;
3726   LoadedFieldsFromExternalStorage = false;
3727   assert(classof(static_cast<Decl*>(this)) && "Invalid Kind!");
3728 }
3729 
3730 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
3731                                SourceLocation StartLoc, SourceLocation IdLoc,
3732                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
3733   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
3734                                          StartLoc, IdLoc, Id, PrevDecl);
3735   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3736 
3737   C.getTypeDeclType(R, PrevDecl);
3738   return R;
3739 }
3740 
3741 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
3742   RecordDecl *R =
3743       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
3744                              SourceLocation(), nullptr, nullptr);
3745   R->MayHaveOutOfDateDef = C.getLangOpts().Modules;
3746   return R;
3747 }
3748 
3749 bool RecordDecl::isInjectedClassName() const {
3750   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
3751     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
3752 }
3753 
3754 bool RecordDecl::isLambda() const {
3755   if (auto RD = dyn_cast<CXXRecordDecl>(this))
3756     return RD->isLambda();
3757   return false;
3758 }
3759 
3760 bool RecordDecl::isCapturedRecord() const {
3761   return hasAttr<CapturedRecordAttr>();
3762 }
3763 
3764 void RecordDecl::setCapturedRecord() {
3765   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
3766 }
3767 
3768 RecordDecl::field_iterator RecordDecl::field_begin() const {
3769   if (hasExternalLexicalStorage() && !LoadedFieldsFromExternalStorage)
3770     LoadFieldsFromExternalStorage();
3771 
3772   return field_iterator(decl_iterator(FirstDecl));
3773 }
3774 
3775 /// completeDefinition - Notes that the definition of this type is now
3776 /// complete.
3777 void RecordDecl::completeDefinition() {
3778   assert(!isCompleteDefinition() && "Cannot redefine record!");
3779   TagDecl::completeDefinition();
3780 }
3781 
3782 /// isMsStruct - Get whether or not this record uses ms_struct layout.
3783 /// This which can be turned on with an attribute, pragma, or the
3784 /// -mms-bitfields command-line option.
3785 bool RecordDecl::isMsStruct(const ASTContext &C) const {
3786   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
3787 }
3788 
3789 void RecordDecl::LoadFieldsFromExternalStorage() const {
3790   ExternalASTSource *Source = getASTContext().getExternalSource();
3791   assert(hasExternalLexicalStorage() && Source && "No external storage?");
3792 
3793   // Notify that we have a RecordDecl doing some initialization.
3794   ExternalASTSource::Deserializing TheFields(Source);
3795 
3796   SmallVector<Decl*, 64> Decls;
3797   LoadedFieldsFromExternalStorage = true;
3798   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
3799     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
3800   }, Decls);
3801 
3802 #ifndef NDEBUG
3803   // Check that all decls we got were FieldDecls.
3804   for (unsigned i=0, e=Decls.size(); i != e; ++i)
3805     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
3806 #endif
3807 
3808   if (Decls.empty())
3809     return;
3810 
3811   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
3812                                                  /*FieldsAlreadyLoaded=*/false);
3813 }
3814 
3815 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
3816   ASTContext &Context = getASTContext();
3817   if (!Context.getLangOpts().Sanitize.hasOneOf(
3818           SanitizerKind::Address | SanitizerKind::KernelAddress) ||
3819       !Context.getLangOpts().SanitizeAddressFieldPadding)
3820     return false;
3821   const auto &Blacklist = Context.getSanitizerBlacklist();
3822   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
3823   // We may be able to relax some of these requirements.
3824   int ReasonToReject = -1;
3825   if (!CXXRD || CXXRD->isExternCContext())
3826     ReasonToReject = 0;  // is not C++.
3827   else if (CXXRD->hasAttr<PackedAttr>())
3828     ReasonToReject = 1;  // is packed.
3829   else if (CXXRD->isUnion())
3830     ReasonToReject = 2;  // is a union.
3831   else if (CXXRD->isTriviallyCopyable())
3832     ReasonToReject = 3;  // is trivially copyable.
3833   else if (CXXRD->hasTrivialDestructor())
3834     ReasonToReject = 4;  // has trivial destructor.
3835   else if (CXXRD->isStandardLayout())
3836     ReasonToReject = 5;  // is standard layout.
3837   else if (Blacklist.isBlacklistedLocation(getLocation(), "field-padding"))
3838     ReasonToReject = 6;  // is in a blacklisted file.
3839   else if (Blacklist.isBlacklistedType(getQualifiedNameAsString(),
3840                                        "field-padding"))
3841     ReasonToReject = 7;  // is blacklisted.
3842 
3843   if (EmitRemark) {
3844     if (ReasonToReject >= 0)
3845       Context.getDiagnostics().Report(
3846           getLocation(),
3847           diag::remark_sanitize_address_insert_extra_padding_rejected)
3848           << getQualifiedNameAsString() << ReasonToReject;
3849     else
3850       Context.getDiagnostics().Report(
3851           getLocation(),
3852           diag::remark_sanitize_address_insert_extra_padding_accepted)
3853           << getQualifiedNameAsString();
3854   }
3855   return ReasonToReject < 0;
3856 }
3857 
3858 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
3859   for (const auto *I : fields()) {
3860     if (I->getIdentifier())
3861       return I;
3862 
3863     if (const auto *RT = I->getType()->getAs<RecordType>())
3864       if (const FieldDecl *NamedDataMember =
3865               RT->getDecl()->findFirstNamedDataMember())
3866         return NamedDataMember;
3867   }
3868 
3869   // We didn't find a named data member.
3870   return nullptr;
3871 }
3872 
3873 
3874 //===----------------------------------------------------------------------===//
3875 // BlockDecl Implementation
3876 //===----------------------------------------------------------------------===//
3877 
3878 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
3879   assert(!ParamInfo && "Already has param info!");
3880 
3881   // Zero params -> null pointer.
3882   if (!NewParamInfo.empty()) {
3883     NumParams = NewParamInfo.size();
3884     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
3885     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3886   }
3887 }
3888 
3889 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
3890                             bool CapturesCXXThis) {
3891   this->CapturesCXXThis = CapturesCXXThis;
3892   this->NumCaptures = Captures.size();
3893 
3894   if (Captures.empty()) {
3895     this->Captures = nullptr;
3896     return;
3897   }
3898 
3899   this->Captures = Captures.copy(Context).data();
3900 }
3901 
3902 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
3903   for (const auto &I : captures())
3904     // Only auto vars can be captured, so no redeclaration worries.
3905     if (I.getVariable() == variable)
3906       return true;
3907 
3908   return false;
3909 }
3910 
3911 SourceRange BlockDecl::getSourceRange() const {
3912   return SourceRange(getLocation(), Body? Body->getLocEnd() : getLocation());
3913 }
3914 
3915 //===----------------------------------------------------------------------===//
3916 // Other Decl Allocation/Deallocation Method Implementations
3917 //===----------------------------------------------------------------------===//
3918 
3919 void TranslationUnitDecl::anchor() { }
3920 
3921 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
3922   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
3923 }
3924 
3925 void PragmaCommentDecl::anchor() { }
3926 
3927 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
3928                                              TranslationUnitDecl *DC,
3929                                              SourceLocation CommentLoc,
3930                                              PragmaMSCommentKind CommentKind,
3931                                              StringRef Arg) {
3932   PragmaCommentDecl *PCD =
3933       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
3934           PragmaCommentDecl(DC, CommentLoc, CommentKind);
3935   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
3936   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
3937   return PCD;
3938 }
3939 
3940 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
3941                                                          unsigned ID,
3942                                                          unsigned ArgSize) {
3943   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
3944       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
3945 }
3946 
3947 void PragmaDetectMismatchDecl::anchor() { }
3948 
3949 PragmaDetectMismatchDecl *
3950 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
3951                                  SourceLocation Loc, StringRef Name,
3952                                  StringRef Value) {
3953   size_t ValueStart = Name.size() + 1;
3954   PragmaDetectMismatchDecl *PDMD =
3955       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
3956           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
3957   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
3958   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
3959   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
3960          Value.size());
3961   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
3962   return PDMD;
3963 }
3964 
3965 PragmaDetectMismatchDecl *
3966 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
3967                                              unsigned NameValueSize) {
3968   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
3969       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
3970 }
3971 
3972 void ExternCContextDecl::anchor() { }
3973 
3974 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
3975                                                TranslationUnitDecl *DC) {
3976   return new (C, DC) ExternCContextDecl(DC);
3977 }
3978 
3979 void LabelDecl::anchor() { }
3980 
3981 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3982                              SourceLocation IdentL, IdentifierInfo *II) {
3983   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
3984 }
3985 
3986 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
3987                              SourceLocation IdentL, IdentifierInfo *II,
3988                              SourceLocation GnuLabelL) {
3989   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
3990   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
3991 }
3992 
3993 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
3994   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
3995                                SourceLocation());
3996 }
3997 
3998 void LabelDecl::setMSAsmLabel(StringRef Name) {
3999   char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4000   memcpy(Buffer, Name.data(), Name.size());
4001   Buffer[Name.size()] = '\0';
4002   MSAsmName = Buffer;
4003 }
4004 
4005 void ValueDecl::anchor() { }
4006 
4007 bool ValueDecl::isWeak() const {
4008   for (const auto *I : attrs())
4009     if (isa<WeakAttr>(I) || isa<WeakRefAttr>(I))
4010       return true;
4011 
4012   return isWeakImported();
4013 }
4014 
4015 void ImplicitParamDecl::anchor() { }
4016 
4017 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4018                                              SourceLocation IdLoc,
4019                                              IdentifierInfo *Id,
4020                                              QualType Type) {
4021   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type);
4022 }
4023 
4024 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4025                                                          unsigned ID) {
4026   return new (C, ID) ImplicitParamDecl(C, nullptr, SourceLocation(), nullptr,
4027                                        QualType());
4028 }
4029 
4030 FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4031                                    SourceLocation StartLoc,
4032                                    const DeclarationNameInfo &NameInfo,
4033                                    QualType T, TypeSourceInfo *TInfo,
4034                                    StorageClass SC,
4035                                    bool isInlineSpecified,
4036                                    bool hasWrittenPrototype,
4037                                    bool isConstexprSpecified) {
4038   FunctionDecl *New =
4039       new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4040                                SC, isInlineSpecified, isConstexprSpecified);
4041   New->HasWrittenPrototype = hasWrittenPrototype;
4042   return New;
4043 }
4044 
4045 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4046   return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
4047                                   DeclarationNameInfo(), QualType(), nullptr,
4048                                   SC_None, false, false);
4049 }
4050 
4051 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4052   return new (C, DC) BlockDecl(DC, L);
4053 }
4054 
4055 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4056   return new (C, ID) BlockDecl(nullptr, SourceLocation());
4057 }
4058 
4059 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4060     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4061       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4062 
4063 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4064                                    unsigned NumParams) {
4065   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4066       CapturedDecl(DC, NumParams);
4067 }
4068 
4069 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4070                                                unsigned NumParams) {
4071   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4072       CapturedDecl(nullptr, NumParams);
4073 }
4074 
4075 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4076 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4077 
4078 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4079 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4080 
4081 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4082                                            SourceLocation L,
4083                                            IdentifierInfo *Id, QualType T,
4084                                            Expr *E, const llvm::APSInt &V) {
4085   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4086 }
4087 
4088 EnumConstantDecl *
4089 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4090   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4091                                       QualType(), nullptr, llvm::APSInt());
4092 }
4093 
4094 void IndirectFieldDecl::anchor() { }
4095 
4096 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4097                                      SourceLocation L, DeclarationName N,
4098                                      QualType T,
4099                                      MutableArrayRef<NamedDecl *> CH)
4100     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4101       ChainingSize(CH.size()) {
4102   // In C++, indirect field declarations conflict with tag declarations in the
4103   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4104   if (C.getLangOpts().CPlusPlus)
4105     IdentifierNamespace |= IDNS_Tag;
4106 }
4107 
4108 IndirectFieldDecl *
4109 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4110                           IdentifierInfo *Id, QualType T,
4111                           llvm::MutableArrayRef<NamedDecl *> CH) {
4112   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4113 }
4114 
4115 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4116                                                          unsigned ID) {
4117   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4118                                        DeclarationName(), QualType(), None);
4119 }
4120 
4121 SourceRange EnumConstantDecl::getSourceRange() const {
4122   SourceLocation End = getLocation();
4123   if (Init)
4124     End = Init->getLocEnd();
4125   return SourceRange(getLocation(), End);
4126 }
4127 
4128 void TypeDecl::anchor() { }
4129 
4130 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4131                                  SourceLocation StartLoc, SourceLocation IdLoc,
4132                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4133   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4134 }
4135 
4136 void TypedefNameDecl::anchor() { }
4137 
4138 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4139   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4140     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4141     auto *ThisTypedef = this;
4142     if (AnyRedecl && OwningTypedef) {
4143       OwningTypedef = OwningTypedef->getCanonicalDecl();
4144       ThisTypedef = ThisTypedef->getCanonicalDecl();
4145     }
4146     if (OwningTypedef == ThisTypedef)
4147       return TT->getDecl();
4148   }
4149 
4150   return nullptr;
4151 }
4152 
4153 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4154   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4155                                  nullptr, nullptr);
4156 }
4157 
4158 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4159                                      SourceLocation StartLoc,
4160                                      SourceLocation IdLoc, IdentifierInfo *Id,
4161                                      TypeSourceInfo *TInfo) {
4162   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4163 }
4164 
4165 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4166   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4167                                    SourceLocation(), nullptr, nullptr);
4168 }
4169 
4170 SourceRange TypedefDecl::getSourceRange() const {
4171   SourceLocation RangeEnd = getLocation();
4172   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4173     if (typeIsPostfix(TInfo->getType()))
4174       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4175   }
4176   return SourceRange(getLocStart(), RangeEnd);
4177 }
4178 
4179 SourceRange TypeAliasDecl::getSourceRange() const {
4180   SourceLocation RangeEnd = getLocStart();
4181   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4182     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4183   return SourceRange(getLocStart(), RangeEnd);
4184 }
4185 
4186 void FileScopeAsmDecl::anchor() { }
4187 
4188 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4189                                            StringLiteral *Str,
4190                                            SourceLocation AsmLoc,
4191                                            SourceLocation RParenLoc) {
4192   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4193 }
4194 
4195 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4196                                                        unsigned ID) {
4197   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4198                                       SourceLocation());
4199 }
4200 
4201 void EmptyDecl::anchor() {}
4202 
4203 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4204   return new (C, DC) EmptyDecl(DC, L);
4205 }
4206 
4207 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4208   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4209 }
4210 
4211 //===----------------------------------------------------------------------===//
4212 // ImportDecl Implementation
4213 //===----------------------------------------------------------------------===//
4214 
4215 /// \brief Retrieve the number of module identifiers needed to name the given
4216 /// module.
4217 static unsigned getNumModuleIdentifiers(Module *Mod) {
4218   unsigned Result = 1;
4219   while (Mod->Parent) {
4220     Mod = Mod->Parent;
4221     ++Result;
4222   }
4223   return Result;
4224 }
4225 
4226 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4227                        Module *Imported,
4228                        ArrayRef<SourceLocation> IdentifierLocs)
4229   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, true),
4230     NextLocalImport()
4231 {
4232   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
4233   auto *StoredLocs = getTrailingObjects<SourceLocation>();
4234   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4235                           StoredLocs);
4236 }
4237 
4238 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4239                        Module *Imported, SourceLocation EndLoc)
4240   : Decl(Import, DC, StartLoc), ImportedAndComplete(Imported, false),
4241     NextLocalImport()
4242 {
4243   *getTrailingObjects<SourceLocation>() = EndLoc;
4244 }
4245 
4246 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4247                                SourceLocation StartLoc, Module *Imported,
4248                                ArrayRef<SourceLocation> IdentifierLocs) {
4249   return new (C, DC,
4250               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4251       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4252 }
4253 
4254 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4255                                        SourceLocation StartLoc,
4256                                        Module *Imported,
4257                                        SourceLocation EndLoc) {
4258   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4259       ImportDecl(DC, StartLoc, Imported, EndLoc);
4260   Import->setImplicit();
4261   return Import;
4262 }
4263 
4264 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4265                                            unsigned NumLocations) {
4266   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4267       ImportDecl(EmptyShell());
4268 }
4269 
4270 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4271   if (!ImportedAndComplete.getInt())
4272     return None;
4273 
4274   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4275   return llvm::makeArrayRef(StoredLocs,
4276                             getNumModuleIdentifiers(getImportedModule()));
4277 }
4278 
4279 SourceRange ImportDecl::getSourceRange() const {
4280   if (!ImportedAndComplete.getInt())
4281     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
4282 
4283   return SourceRange(getLocation(), getIdentifierLocs().back());
4284 }
4285