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