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