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