xref: /llvm-project-15.0.7/clang/lib/AST/Decl.cpp (revision 4e00a192)
1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Decl.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CanonicalType.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclarationName.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/ODRHash.h"
31 #include "clang/AST/PrettyDeclStackTrace.h"
32 #include "clang/AST/PrettyPrinter.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/Basic/Builtins.h"
39 #include "clang/Basic/IdentifierTable.h"
40 #include "clang/Basic/LLVM.h"
41 #include "clang/Basic/LangOptions.h"
42 #include "clang/Basic/Linkage.h"
43 #include "clang/Basic/Module.h"
44 #include "clang/Basic/NoSanitizeList.h"
45 #include "clang/Basic/PartialDiagnostic.h"
46 #include "clang/Basic/Sanitizers.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/SourceManager.h"
49 #include "clang/Basic/Specifiers.h"
50 #include "clang/Basic/TargetCXXABI.h"
51 #include "clang/Basic/TargetInfo.h"
52 #include "clang/Basic/Visibility.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/StringRef.h"
60 #include "llvm/ADT/StringSwitch.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), redeclarable_base(ctx), 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 /// Determine whether D is declared in the purview of a named module.
572 static bool isInModulePurview(const NamedDecl *D) {
573   if (auto *M = D->getOwningModule())
574     return M->isModulePurview();
575   return false;
576 }
577 
578 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
579   // FIXME: Handle isModulePrivate.
580   switch (D->getModuleOwnershipKind()) {
581   case Decl::ModuleOwnershipKind::Unowned:
582   case Decl::ModuleOwnershipKind::ModulePrivate:
583     return false;
584   case Decl::ModuleOwnershipKind::Visible:
585   case Decl::ModuleOwnershipKind::VisibleWhenImported:
586     return isInModulePurview(D);
587   }
588   llvm_unreachable("unexpected module ownership kind");
589 }
590 
591 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
592   // Internal linkage declarations within a module interface unit are modeled
593   // as "module-internal linkage", which means that they have internal linkage
594   // formally but can be indirectly accessed from outside the module via inline
595   // functions and templates defined within the module.
596   if (isInModulePurview(D))
597     return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
598 
599   return LinkageInfo::internal();
600 }
601 
602 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
603   // C++ Modules TS [basic.link]/6.8:
604   //   - A name declared at namespace scope that does not have internal linkage
605   //     by the previous rules and that is introduced by a non-exported
606   //     declaration has module linkage.
607   //
608   // [basic.namespace.general]/p2
609   //   A namespace is never attached to a named module and never has a name with
610   //   module linkage.
611   if (isInModulePurview(D) &&
612       !isExportedFromModuleInterfaceUnit(
613           cast<NamedDecl>(D->getCanonicalDecl())) &&
614       !isa<NamespaceDecl>(D))
615     return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
616 
617   return LinkageInfo::external();
618 }
619 
620 static StorageClass getStorageClass(const Decl *D) {
621   if (auto *TD = dyn_cast<TemplateDecl>(D))
622     D = TD->getTemplatedDecl();
623   if (D) {
624     if (auto *VD = dyn_cast<VarDecl>(D))
625       return VD->getStorageClass();
626     if (auto *FD = dyn_cast<FunctionDecl>(D))
627       return FD->getStorageClass();
628   }
629   return SC_None;
630 }
631 
632 LinkageInfo
633 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
634                                             LVComputationKind computation,
635                                             bool IgnoreVarTypeLinkage) {
636   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
637          "Not a name having namespace scope");
638   ASTContext &Context = D->getASTContext();
639 
640   // C++ [basic.link]p3:
641   //   A name having namespace scope (3.3.6) has internal linkage if it
642   //   is the name of
643 
644   if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
645     // - a variable, variable template, function, or function template
646     //   that is explicitly declared static; or
647     // (This bullet corresponds to C99 6.2.2p3.)
648     return getInternalLinkageFor(D);
649   }
650 
651   if (const auto *Var = dyn_cast<VarDecl>(D)) {
652     // - a non-template variable of non-volatile const-qualified type, unless
653     //   - it is explicitly declared extern, or
654     //   - it is inline or exported, or
655     //   - it was previously declared and the prior declaration did not have
656     //     internal linkage
657     // (There is no equivalent in C99.)
658     if (Context.getLangOpts().CPlusPlus &&
659         Var->getType().isConstQualified() &&
660         !Var->getType().isVolatileQualified() &&
661         !Var->isInline() &&
662         !isExportedFromModuleInterfaceUnit(Var) &&
663         !isa<VarTemplateSpecializationDecl>(Var) &&
664         !Var->getDescribedVarTemplate()) {
665       const VarDecl *PrevVar = Var->getPreviousDecl();
666       if (PrevVar)
667         return getLVForDecl(PrevVar, computation);
668 
669       if (Var->getStorageClass() != SC_Extern &&
670           Var->getStorageClass() != SC_PrivateExtern &&
671           !isSingleLineLanguageLinkage(*Var))
672         return getInternalLinkageFor(Var);
673     }
674 
675     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
676          PrevVar = PrevVar->getPreviousDecl()) {
677       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
678           Var->getStorageClass() == SC_None)
679         return getDeclLinkageAndVisibility(PrevVar);
680       // Explicitly declared static.
681       if (PrevVar->getStorageClass() == SC_Static)
682         return getInternalLinkageFor(Var);
683     }
684   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
685     //   - a data member of an anonymous union.
686     const VarDecl *VD = IFD->getVarDecl();
687     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
688     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
689   }
690   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
691 
692   // FIXME: This gives internal linkage to names that should have no linkage
693   // (those not covered by [basic.link]p6).
694   if (D->isInAnonymousNamespace()) {
695     const auto *Var = dyn_cast<VarDecl>(D);
696     const auto *Func = dyn_cast<FunctionDecl>(D);
697     // FIXME: The check for extern "C" here is not justified by the standard
698     // wording, but we retain it from the pre-DR1113 model to avoid breaking
699     // code.
700     //
701     // C++11 [basic.link]p4:
702     //   An unnamed namespace or a namespace declared directly or indirectly
703     //   within an unnamed namespace has internal linkage.
704     if ((!Var || !isFirstInExternCContext(Var)) &&
705         (!Func || !isFirstInExternCContext(Func)))
706       return getInternalLinkageFor(D);
707   }
708 
709   // Set up the defaults.
710 
711   // C99 6.2.2p5:
712   //   If the declaration of an identifier for an object has file
713   //   scope and no storage-class specifier, its linkage is
714   //   external.
715   LinkageInfo LV = getExternalLinkageFor(D);
716 
717   if (!hasExplicitVisibilityAlready(computation)) {
718     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
719       LV.mergeVisibility(*Vis, true);
720     } else {
721       // If we're declared in a namespace with a visibility attribute,
722       // use that namespace's visibility, and it still counts as explicit.
723       for (const DeclContext *DC = D->getDeclContext();
724            !isa<TranslationUnitDecl>(DC);
725            DC = DC->getParent()) {
726         const auto *ND = dyn_cast<NamespaceDecl>(DC);
727         if (!ND) continue;
728         if (Optional<Visibility> Vis = getExplicitVisibility(ND, computation)) {
729           LV.mergeVisibility(*Vis, true);
730           break;
731         }
732       }
733     }
734 
735     // Add in global settings if the above didn't give us direct visibility.
736     if (!LV.isVisibilityExplicit()) {
737       // Use global type/value visibility as appropriate.
738       Visibility globalVisibility =
739           computation.isValueVisibility()
740               ? Context.getLangOpts().getValueVisibilityMode()
741               : Context.getLangOpts().getTypeVisibilityMode();
742       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
743 
744       // If we're paying attention to global visibility, apply
745       // -finline-visibility-hidden if this is an inline method.
746       if (useInlineVisibilityHidden(D))
747         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
748     }
749   }
750 
751   // C++ [basic.link]p4:
752 
753   //   A name having namespace scope that has not been given internal linkage
754   //   above and that is the name of
755   //   [...bullets...]
756   //   has its linkage determined as follows:
757   //     - if the enclosing namespace has internal linkage, the name has
758   //       internal linkage; [handled above]
759   //     - otherwise, if the declaration of the name is attached to a named
760   //       module and is not exported, the name has module linkage;
761   //     - otherwise, the name has external linkage.
762   // LV is currently set up to handle the last two bullets.
763   //
764   //   The bullets are:
765 
766   //     - a variable; or
767   if (const auto *Var = dyn_cast<VarDecl>(D)) {
768     // GCC applies the following optimization to variables and static
769     // data members, but not to functions:
770     //
771     // Modify the variable's LV by the LV of its type unless this is
772     // C or extern "C".  This follows from [basic.link]p9:
773     //   A type without linkage shall not be used as the type of a
774     //   variable or function with external linkage unless
775     //    - the entity has C language linkage, or
776     //    - the entity is declared within an unnamed namespace, or
777     //    - the entity is not used or is defined in the same
778     //      translation unit.
779     // and [basic.link]p10:
780     //   ...the types specified by all declarations referring to a
781     //   given variable or function shall be identical...
782     // C does not have an equivalent rule.
783     //
784     // Ignore this if we've got an explicit attribute;  the user
785     // probably knows what they're doing.
786     //
787     // Note that we don't want to make the variable non-external
788     // because of this, but unique-external linkage suits us.
789 
790     // We need variables inside OpenMP declare target directives to be visible.
791     if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var))
792       return LinkageInfo::external();
793 
794     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
795         !IgnoreVarTypeLinkage) {
796       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
797       if (!isExternallyVisible(TypeLV.getLinkage()))
798         return LinkageInfo::uniqueExternal();
799       if (!LV.isVisibilityExplicit())
800         LV.mergeVisibility(TypeLV);
801     }
802 
803     if (Var->getStorageClass() == SC_PrivateExtern)
804       LV.mergeVisibility(HiddenVisibility, true);
805 
806     // Note that Sema::MergeVarDecl already takes care of implementing
807     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
808     // to do it here.
809 
810     // As per function and class template specializations (below),
811     // consider LV for the template and template arguments.  We're at file
812     // scope, so we do not need to worry about nested specializations.
813     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
814       mergeTemplateLV(LV, spec, computation);
815     }
816 
817   //     - a function; or
818   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
819     // In theory, we can modify the function's LV by the LV of its
820     // type unless it has C linkage (see comment above about variables
821     // for justification).  In practice, GCC doesn't do this, so it's
822     // just too painful to make work.
823 
824     if (Function->getStorageClass() == SC_PrivateExtern)
825       LV.mergeVisibility(HiddenVisibility, true);
826 
827     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
828     // merging storage classes and visibility attributes, so we don't have to
829     // look at previous decls in here.
830 
831     // In C++, then if the type of the function uses a type with
832     // unique-external linkage, it's not legally usable from outside
833     // this translation unit.  However, we should use the C linkage
834     // rules instead for extern "C" declarations.
835     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
836       // Only look at the type-as-written. Otherwise, deducing the return type
837       // of a function could change its linkage.
838       QualType TypeAsWritten = Function->getType();
839       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
840         TypeAsWritten = TSI->getType();
841       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
842         return LinkageInfo::uniqueExternal();
843     }
844 
845     // Consider LV from the template and the template arguments.
846     // We're at file scope, so we do not need to worry about nested
847     // specializations.
848     if (FunctionTemplateSpecializationInfo *specInfo
849                                = Function->getTemplateSpecializationInfo()) {
850       mergeTemplateLV(LV, Function, specInfo, computation);
851     }
852 
853   //     - a named class (Clause 9), or an unnamed class defined in a
854   //       typedef declaration in which the class has the typedef name
855   //       for linkage purposes (7.1.3); or
856   //     - a named enumeration (7.2), or an unnamed enumeration
857   //       defined in a typedef declaration in which the enumeration
858   //       has the typedef name for linkage purposes (7.1.3); or
859   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
860     // Unnamed tags have no linkage.
861     if (!Tag->hasNameForLinkage())
862       return LinkageInfo::none();
863 
864     // If this is a class template specialization, consider the
865     // linkage of the template and template arguments.  We're at file
866     // scope, so we do not need to worry about nested specializations.
867     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
868       mergeTemplateLV(LV, spec, computation);
869     }
870 
871   // FIXME: This is not part of the C++ standard any more.
872   //     - an enumerator belonging to an enumeration with external linkage; or
873   } else if (isa<EnumConstantDecl>(D)) {
874     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
875                                       computation);
876     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
877       return LinkageInfo::none();
878     LV.merge(EnumLV);
879 
880   //     - a template
881   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
882     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
883     LinkageInfo tempLV =
884       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
885     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
886 
887   //     An unnamed namespace or a namespace declared directly or indirectly
888   //     within an unnamed namespace has internal linkage. All other namespaces
889   //     have external linkage.
890   //
891   // We handled names in anonymous namespaces above.
892   } else if (isa<NamespaceDecl>(D)) {
893     return LV;
894 
895   // By extension, we assign external linkage to Objective-C
896   // interfaces.
897   } else if (isa<ObjCInterfaceDecl>(D)) {
898     // fallout
899 
900   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
901     // A typedef declaration has linkage if it gives a type a name for
902     // linkage purposes.
903     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
904       return LinkageInfo::none();
905 
906   } else if (isa<MSGuidDecl>(D)) {
907     // A GUID behaves like an inline variable with external linkage. Fall
908     // through.
909 
910   // Everything not covered here has no linkage.
911   } else {
912     return LinkageInfo::none();
913   }
914 
915   // If we ended up with non-externally-visible linkage, visibility should
916   // always be default.
917   if (!isExternallyVisible(LV.getLinkage()))
918     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
919 
920   // Mark the symbols as hidden when compiling for the device.
921   if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice)
922     LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
923 
924   return LV;
925 }
926 
927 LinkageInfo
928 LinkageComputer::getLVForClassMember(const NamedDecl *D,
929                                      LVComputationKind computation,
930                                      bool IgnoreVarTypeLinkage) {
931   // Only certain class members have linkage.  Note that fields don't
932   // really have linkage, but it's convenient to say they do for the
933   // purposes of calculating linkage of pointer-to-data-member
934   // template arguments.
935   //
936   // Templates also don't officially have linkage, but since we ignore
937   // the C++ standard and look at template arguments when determining
938   // linkage and visibility of a template specialization, we might hit
939   // a template template argument that way. If we do, we need to
940   // consider its linkage.
941   if (!(isa<CXXMethodDecl>(D) ||
942         isa<VarDecl>(D) ||
943         isa<FieldDecl>(D) ||
944         isa<IndirectFieldDecl>(D) ||
945         isa<TagDecl>(D) ||
946         isa<TemplateDecl>(D)))
947     return LinkageInfo::none();
948 
949   LinkageInfo LV;
950 
951   // If we have an explicit visibility attribute, merge that in.
952   if (!hasExplicitVisibilityAlready(computation)) {
953     if (Optional<Visibility> Vis = getExplicitVisibility(D, computation))
954       LV.mergeVisibility(*Vis, true);
955     // If we're paying attention to global visibility, apply
956     // -finline-visibility-hidden if this is an inline method.
957     //
958     // Note that we do this before merging information about
959     // the class visibility.
960     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
961       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
962   }
963 
964   // If this class member has an explicit visibility attribute, the only
965   // thing that can change its visibility is the template arguments, so
966   // only look for them when processing the class.
967   LVComputationKind classComputation = computation;
968   if (LV.isVisibilityExplicit())
969     classComputation = withExplicitVisibilityAlready(computation);
970 
971   LinkageInfo classLV =
972     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
973   // The member has the same linkage as the class. If that's not externally
974   // visible, we don't need to compute anything about the linkage.
975   // FIXME: If we're only computing linkage, can we bail out here?
976   if (!isExternallyVisible(classLV.getLinkage()))
977     return classLV;
978 
979 
980   // Otherwise, don't merge in classLV yet, because in certain cases
981   // we need to completely ignore the visibility from it.
982 
983   // Specifically, if this decl exists and has an explicit attribute.
984   const NamedDecl *explicitSpecSuppressor = nullptr;
985 
986   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
987     // Only look at the type-as-written. Otherwise, deducing the return type
988     // of a function could change its linkage.
989     QualType TypeAsWritten = MD->getType();
990     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
991       TypeAsWritten = TSI->getType();
992     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
993       return LinkageInfo::uniqueExternal();
994 
995     // If this is a method template specialization, use the linkage for
996     // the template parameters and arguments.
997     if (FunctionTemplateSpecializationInfo *spec
998            = MD->getTemplateSpecializationInfo()) {
999       mergeTemplateLV(LV, MD, spec, computation);
1000       if (spec->isExplicitSpecialization()) {
1001         explicitSpecSuppressor = MD;
1002       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
1003         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
1004       }
1005     } else if (isExplicitMemberSpecialization(MD)) {
1006       explicitSpecSuppressor = MD;
1007     }
1008 
1009   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1010     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1011       mergeTemplateLV(LV, spec, computation);
1012       if (spec->isExplicitSpecialization()) {
1013         explicitSpecSuppressor = spec;
1014       } else {
1015         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1016         if (isExplicitMemberSpecialization(temp)) {
1017           explicitSpecSuppressor = temp->getTemplatedDecl();
1018         }
1019       }
1020     } else if (isExplicitMemberSpecialization(RD)) {
1021       explicitSpecSuppressor = RD;
1022     }
1023 
1024   // Static data members.
1025   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1026     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1027       mergeTemplateLV(LV, spec, computation);
1028 
1029     // Modify the variable's linkage by its type, but ignore the
1030     // type's visibility unless it's a definition.
1031     if (!IgnoreVarTypeLinkage) {
1032       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1033       // FIXME: If the type's linkage is not externally visible, we can
1034       // give this static data member UniqueExternalLinkage.
1035       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1036         LV.mergeVisibility(typeLV);
1037       LV.mergeExternalVisibility(typeLV);
1038     }
1039 
1040     if (isExplicitMemberSpecialization(VD)) {
1041       explicitSpecSuppressor = VD;
1042     }
1043 
1044   // Template members.
1045   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1046     bool considerVisibility =
1047       (!LV.isVisibilityExplicit() &&
1048        !classLV.isVisibilityExplicit() &&
1049        !hasExplicitVisibilityAlready(computation));
1050     LinkageInfo tempLV =
1051       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1052     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1053 
1054     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1055       if (isExplicitMemberSpecialization(redeclTemp)) {
1056         explicitSpecSuppressor = temp->getTemplatedDecl();
1057       }
1058     }
1059   }
1060 
1061   // We should never be looking for an attribute directly on a template.
1062   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1063 
1064   // If this member is an explicit member specialization, and it has
1065   // an explicit attribute, ignore visibility from the parent.
1066   bool considerClassVisibility = true;
1067   if (explicitSpecSuppressor &&
1068       // optimization: hasDVA() is true only with explicit visibility.
1069       LV.isVisibilityExplicit() &&
1070       classLV.getVisibility() != DefaultVisibility &&
1071       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1072     considerClassVisibility = false;
1073   }
1074 
1075   // Finally, merge in information from the class.
1076   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1077 
1078   // We need variables inside OpenMP declare target directives to be visible.
1079   if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1080     if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
1081       return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
1082 
1083   return LV;
1084 }
1085 
1086 void NamedDecl::anchor() {}
1087 
1088 bool NamedDecl::isLinkageValid() const {
1089   if (!hasCachedLinkage())
1090     return true;
1091 
1092   Linkage L = LinkageComputer{}
1093                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1094                   .getLinkage();
1095   return L == getCachedLinkage();
1096 }
1097 
1098 ReservedIdentifierStatus
1099 NamedDecl::isReserved(const LangOptions &LangOpts) const {
1100   const IdentifierInfo *II = getIdentifier();
1101 
1102   // This triggers at least for CXXLiteralIdentifiers, which we already checked
1103   // at lexing time.
1104   if (!II)
1105     return ReservedIdentifierStatus::NotReserved;
1106 
1107   ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1108   if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1109     // This name is only reserved at global scope. Check if this declaration
1110     // conflicts with a global scope declaration.
1111     if (isa<ParmVarDecl>(this) || isTemplateParameter())
1112       return ReservedIdentifierStatus::NotReserved;
1113 
1114     // C++ [dcl.link]/7:
1115     //   Two declarations [conflict] if [...] one declares a function or
1116     //   variable with C language linkage, and the other declares [...] a
1117     //   variable that belongs to the global scope.
1118     //
1119     // Therefore names that are reserved at global scope are also reserved as
1120     // names of variables and functions with C language linkage.
1121     const DeclContext *DC = getDeclContext()->getRedeclContext();
1122     if (DC->isTranslationUnit())
1123       return Status;
1124     if (auto *VD = dyn_cast<VarDecl>(this))
1125       if (VD->isExternC())
1126         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1127     if (auto *FD = dyn_cast<FunctionDecl>(this))
1128       if (FD->isExternC())
1129         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1130     return ReservedIdentifierStatus::NotReserved;
1131   }
1132 
1133   return Status;
1134 }
1135 
1136 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1137   StringRef name = getName();
1138   if (name.empty()) return SFF_None;
1139 
1140   if (name.front() == 'C')
1141     if (name == "CFStringCreateWithFormat" ||
1142         name == "CFStringCreateWithFormatAndArguments" ||
1143         name == "CFStringAppendFormat" ||
1144         name == "CFStringAppendFormatAndArguments")
1145       return SFF_CFString;
1146   return SFF_None;
1147 }
1148 
1149 Linkage NamedDecl::getLinkageInternal() const {
1150   // We don't care about visibility here, so ask for the cheapest
1151   // possible visibility analysis.
1152   return LinkageComputer{}
1153       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1154       .getLinkage();
1155 }
1156 
1157 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1158   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1159 }
1160 
1161 static Optional<Visibility>
1162 getExplicitVisibilityAux(const NamedDecl *ND,
1163                          NamedDecl::ExplicitVisibilityKind kind,
1164                          bool IsMostRecent) {
1165   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1166 
1167   // Check the declaration itself first.
1168   if (Optional<Visibility> V = getVisibilityOf(ND, kind))
1169     return V;
1170 
1171   // If this is a member class of a specialization of a class template
1172   // and the corresponding decl has explicit visibility, use that.
1173   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1174     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1175     if (InstantiatedFrom)
1176       return getVisibilityOf(InstantiatedFrom, kind);
1177   }
1178 
1179   // If there wasn't explicit visibility there, and this is a
1180   // specialization of a class template, check for visibility
1181   // on the pattern.
1182   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1183     // Walk all the template decl till this point to see if there are
1184     // explicit visibility attributes.
1185     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1186     while (TD != nullptr) {
1187       auto Vis = getVisibilityOf(TD, kind);
1188       if (Vis != None)
1189         return Vis;
1190       TD = TD->getPreviousDecl();
1191     }
1192     return None;
1193   }
1194 
1195   // Use the most recent declaration.
1196   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1197     const NamedDecl *MostRecent = ND->getMostRecentDecl();
1198     if (MostRecent != ND)
1199       return getExplicitVisibilityAux(MostRecent, kind, true);
1200   }
1201 
1202   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1203     if (Var->isStaticDataMember()) {
1204       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1205       if (InstantiatedFrom)
1206         return getVisibilityOf(InstantiatedFrom, kind);
1207     }
1208 
1209     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1210       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1211                              kind);
1212 
1213     return None;
1214   }
1215   // Also handle function template specializations.
1216   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1217     // If the function is a specialization of a template with an
1218     // explicit visibility attribute, use that.
1219     if (FunctionTemplateSpecializationInfo *templateInfo
1220           = fn->getTemplateSpecializationInfo())
1221       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1222                              kind);
1223 
1224     // If the function is a member of a specialization of a class template
1225     // and the corresponding decl has explicit visibility, use that.
1226     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1227     if (InstantiatedFrom)
1228       return getVisibilityOf(InstantiatedFrom, kind);
1229 
1230     return None;
1231   }
1232 
1233   // The visibility of a template is stored in the templated decl.
1234   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1235     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1236 
1237   return None;
1238 }
1239 
1240 Optional<Visibility>
1241 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1242   return getExplicitVisibilityAux(this, kind, false);
1243 }
1244 
1245 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1246                                              Decl *ContextDecl,
1247                                              LVComputationKind computation) {
1248   // This lambda has its linkage/visibility determined by its owner.
1249   const NamedDecl *Owner;
1250   if (!ContextDecl)
1251     Owner = dyn_cast<NamedDecl>(DC);
1252   else if (isa<ParmVarDecl>(ContextDecl))
1253     Owner =
1254         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1255   else
1256     Owner = cast<NamedDecl>(ContextDecl);
1257 
1258   if (!Owner)
1259     return LinkageInfo::none();
1260 
1261   // If the owner has a deduced type, we need to skip querying the linkage and
1262   // visibility of that type, because it might involve this closure type.  The
1263   // only effect of this is that we might give a lambda VisibleNoLinkage rather
1264   // than NoLinkage when we don't strictly need to, which is benign.
1265   auto *VD = dyn_cast<VarDecl>(Owner);
1266   LinkageInfo OwnerLV =
1267       VD && VD->getType()->getContainedDeducedType()
1268           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1269           : getLVForDecl(Owner, computation);
1270 
1271   // A lambda never formally has linkage. But if the owner is externally
1272   // visible, then the lambda is too. We apply the same rules to blocks.
1273   if (!isExternallyVisible(OwnerLV.getLinkage()))
1274     return LinkageInfo::none();
1275   return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1276                      OwnerLV.isVisibilityExplicit());
1277 }
1278 
1279 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1280                                                LVComputationKind computation) {
1281   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1282     if (Function->isInAnonymousNamespace() &&
1283         !isFirstInExternCContext(Function))
1284       return getInternalLinkageFor(Function);
1285 
1286     // This is a "void f();" which got merged with a file static.
1287     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1288       return getInternalLinkageFor(Function);
1289 
1290     LinkageInfo LV;
1291     if (!hasExplicitVisibilityAlready(computation)) {
1292       if (Optional<Visibility> Vis =
1293               getExplicitVisibility(Function, computation))
1294         LV.mergeVisibility(*Vis, true);
1295     }
1296 
1297     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1298     // merging storage classes and visibility attributes, so we don't have to
1299     // look at previous decls in here.
1300 
1301     return LV;
1302   }
1303 
1304   if (const auto *Var = dyn_cast<VarDecl>(D)) {
1305     if (Var->hasExternalStorage()) {
1306       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1307         return getInternalLinkageFor(Var);
1308 
1309       LinkageInfo LV;
1310       if (Var->getStorageClass() == SC_PrivateExtern)
1311         LV.mergeVisibility(HiddenVisibility, true);
1312       else if (!hasExplicitVisibilityAlready(computation)) {
1313         if (Optional<Visibility> Vis = getExplicitVisibility(Var, computation))
1314           LV.mergeVisibility(*Vis, true);
1315       }
1316 
1317       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1318         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1319         if (PrevLV.getLinkage())
1320           LV.setLinkage(PrevLV.getLinkage());
1321         LV.mergeVisibility(PrevLV);
1322       }
1323 
1324       return LV;
1325     }
1326 
1327     if (!Var->isStaticLocal())
1328       return LinkageInfo::none();
1329   }
1330 
1331   ASTContext &Context = D->getASTContext();
1332   if (!Context.getLangOpts().CPlusPlus)
1333     return LinkageInfo::none();
1334 
1335   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1336   if (!OuterD || OuterD->isInvalidDecl())
1337     return LinkageInfo::none();
1338 
1339   LinkageInfo LV;
1340   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1341     if (!BD->getBlockManglingNumber())
1342       return LinkageInfo::none();
1343 
1344     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1345                          BD->getBlockManglingContextDecl(), computation);
1346   } else {
1347     const auto *FD = cast<FunctionDecl>(OuterD);
1348     if (!FD->isInlined() &&
1349         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1350       return LinkageInfo::none();
1351 
1352     // If a function is hidden by -fvisibility-inlines-hidden option and
1353     // is not explicitly attributed as a hidden function,
1354     // we should not make static local variables in the function hidden.
1355     LV = getLVForDecl(FD, computation);
1356     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1357         !LV.isVisibilityExplicit() &&
1358         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1359       assert(cast<VarDecl>(D)->isStaticLocal());
1360       // If this was an implicitly hidden inline method, check again for
1361       // explicit visibility on the parent class, and use that for static locals
1362       // if present.
1363       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1364         LV = getLVForDecl(MD->getParent(), computation);
1365       if (!LV.isVisibilityExplicit()) {
1366         Visibility globalVisibility =
1367             computation.isValueVisibility()
1368                 ? Context.getLangOpts().getValueVisibilityMode()
1369                 : Context.getLangOpts().getTypeVisibilityMode();
1370         return LinkageInfo(VisibleNoLinkage, globalVisibility,
1371                            /*visibilityExplicit=*/false);
1372       }
1373     }
1374   }
1375   if (!isExternallyVisible(LV.getLinkage()))
1376     return LinkageInfo::none();
1377   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1378                      LV.isVisibilityExplicit());
1379 }
1380 
1381 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1382                                               LVComputationKind computation,
1383                                               bool IgnoreVarTypeLinkage) {
1384   // Internal_linkage attribute overrides other considerations.
1385   if (D->hasAttr<InternalLinkageAttr>())
1386     return getInternalLinkageFor(D);
1387 
1388   // Objective-C: treat all Objective-C declarations as having external
1389   // linkage.
1390   switch (D->getKind()) {
1391     default:
1392       break;
1393 
1394     // Per C++ [basic.link]p2, only the names of objects, references,
1395     // functions, types, templates, namespaces, and values ever have linkage.
1396     //
1397     // Note that the name of a typedef, namespace alias, using declaration,
1398     // and so on are not the name of the corresponding type, namespace, or
1399     // declaration, so they do *not* have linkage.
1400     case Decl::ImplicitParam:
1401     case Decl::Label:
1402     case Decl::NamespaceAlias:
1403     case Decl::ParmVar:
1404     case Decl::Using:
1405     case Decl::UsingEnum:
1406     case Decl::UsingShadow:
1407     case Decl::UsingDirective:
1408       return LinkageInfo::none();
1409 
1410     case Decl::EnumConstant:
1411       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1412       if (D->getASTContext().getLangOpts().CPlusPlus)
1413         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1414       return LinkageInfo::visible_none();
1415 
1416     case Decl::Typedef:
1417     case Decl::TypeAlias:
1418       // A typedef declaration has linkage if it gives a type a name for
1419       // linkage purposes.
1420       if (!cast<TypedefNameDecl>(D)
1421                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1422         return LinkageInfo::none();
1423       break;
1424 
1425     case Decl::TemplateTemplateParm: // count these as external
1426     case Decl::NonTypeTemplateParm:
1427     case Decl::ObjCAtDefsField:
1428     case Decl::ObjCCategory:
1429     case Decl::ObjCCategoryImpl:
1430     case Decl::ObjCCompatibleAlias:
1431     case Decl::ObjCImplementation:
1432     case Decl::ObjCMethod:
1433     case Decl::ObjCProperty:
1434     case Decl::ObjCPropertyImpl:
1435     case Decl::ObjCProtocol:
1436       return getExternalLinkageFor(D);
1437 
1438     case Decl::CXXRecord: {
1439       const auto *Record = cast<CXXRecordDecl>(D);
1440       if (Record->isLambda()) {
1441         if (Record->hasKnownLambdaInternalLinkage() ||
1442             !Record->getLambdaManglingNumber()) {
1443           // This lambda has no mangling number, so it's internal.
1444           return getInternalLinkageFor(D);
1445         }
1446 
1447         return getLVForClosure(
1448                   Record->getDeclContext()->getRedeclContext(),
1449                   Record->getLambdaContextDecl(), computation);
1450       }
1451 
1452       break;
1453     }
1454 
1455     case Decl::TemplateParamObject: {
1456       // The template parameter object can be referenced from anywhere its type
1457       // and value can be referenced.
1458       auto *TPO = cast<TemplateParamObjectDecl>(D);
1459       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1460       LV.merge(getLVForValue(TPO->getValue(), computation));
1461       return LV;
1462     }
1463   }
1464 
1465   // Handle linkage for namespace-scope names.
1466   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1467     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1468 
1469   // C++ [basic.link]p5:
1470   //   In addition, a member function, static data member, a named
1471   //   class or enumeration of class scope, or an unnamed class or
1472   //   enumeration defined in a class-scope typedef declaration such
1473   //   that the class or enumeration has the typedef name for linkage
1474   //   purposes (7.1.3), has external linkage if the name of the class
1475   //   has external linkage.
1476   if (D->getDeclContext()->isRecord())
1477     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1478 
1479   // C++ [basic.link]p6:
1480   //   The name of a function declared in block scope and the name of
1481   //   an object declared by a block scope extern declaration have
1482   //   linkage. If there is a visible declaration of an entity with
1483   //   linkage having the same name and type, ignoring entities
1484   //   declared outside the innermost enclosing namespace scope, the
1485   //   block scope declaration declares that same entity and receives
1486   //   the linkage of the previous declaration. If there is more than
1487   //   one such matching entity, the program is ill-formed. Otherwise,
1488   //   if no matching entity is found, the block scope entity receives
1489   //   external linkage.
1490   if (D->getDeclContext()->isFunctionOrMethod())
1491     return getLVForLocalDecl(D, computation);
1492 
1493   // C++ [basic.link]p6:
1494   //   Names not covered by these rules have no linkage.
1495   return LinkageInfo::none();
1496 }
1497 
1498 /// getLVForDecl - Get the linkage and visibility for the given declaration.
1499 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1500                                           LVComputationKind computation) {
1501   // Internal_linkage attribute overrides other considerations.
1502   if (D->hasAttr<InternalLinkageAttr>())
1503     return getInternalLinkageFor(D);
1504 
1505   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1506     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1507 
1508   if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1509     return *LI;
1510 
1511   LinkageInfo LV = computeLVForDecl(D, computation);
1512   if (D->hasCachedLinkage())
1513     assert(D->getCachedLinkage() == LV.getLinkage());
1514 
1515   D->setCachedLinkage(LV.getLinkage());
1516   cache(D, computation, LV);
1517 
1518 #ifndef NDEBUG
1519   // In C (because of gnu inline) and in c++ with microsoft extensions an
1520   // static can follow an extern, so we can have two decls with different
1521   // linkages.
1522   const LangOptions &Opts = D->getASTContext().getLangOpts();
1523   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1524     return LV;
1525 
1526   // We have just computed the linkage for this decl. By induction we know
1527   // that all other computed linkages match, check that the one we just
1528   // computed also does.
1529   NamedDecl *Old = nullptr;
1530   for (auto I : D->redecls()) {
1531     auto *T = cast<NamedDecl>(I);
1532     if (T == D)
1533       continue;
1534     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1535       Old = T;
1536       break;
1537     }
1538   }
1539   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1540 #endif
1541 
1542   return LV;
1543 }
1544 
1545 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1546   NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1547                                              ? NamedDecl::VisibilityForType
1548                                              : NamedDecl::VisibilityForValue;
1549   LVComputationKind CK(EK);
1550   return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1551                              ? CK.forLinkageOnly()
1552                              : CK);
1553 }
1554 
1555 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1556   Module *M = getOwningModule();
1557   if (!M)
1558     return nullptr;
1559 
1560   switch (M->Kind) {
1561   case Module::ModuleMapModule:
1562     // Module map modules have no special linkage semantics.
1563     return nullptr;
1564 
1565   case Module::ModuleInterfaceUnit:
1566     return M;
1567 
1568   case Module::GlobalModuleFragment: {
1569     // External linkage declarations in the global module have no owning module
1570     // for linkage purposes. But internal linkage declarations in the global
1571     // module fragment of a particular module are owned by that module for
1572     // linkage purposes.
1573     if (IgnoreLinkage)
1574       return nullptr;
1575     bool InternalLinkage;
1576     if (auto *ND = dyn_cast<NamedDecl>(this))
1577       InternalLinkage = !ND->hasExternalFormalLinkage();
1578     else {
1579       auto *NSD = dyn_cast<NamespaceDecl>(this);
1580       InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1581                         isInAnonymousNamespace();
1582     }
1583     return InternalLinkage ? M->Parent : nullptr;
1584   }
1585 
1586   case Module::PrivateModuleFragment:
1587     // The private module fragment is part of its containing module for linkage
1588     // purposes.
1589     return M->Parent;
1590   }
1591 
1592   llvm_unreachable("unknown module kind");
1593 }
1594 
1595 void NamedDecl::printName(raw_ostream &os) const {
1596   os << Name;
1597 }
1598 
1599 std::string NamedDecl::getQualifiedNameAsString() const {
1600   std::string QualName;
1601   llvm::raw_string_ostream OS(QualName);
1602   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1603   return QualName;
1604 }
1605 
1606 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1607   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1608 }
1609 
1610 void NamedDecl::printQualifiedName(raw_ostream &OS,
1611                                    const PrintingPolicy &P) const {
1612   if (getDeclContext()->isFunctionOrMethod()) {
1613     // We do not print '(anonymous)' for function parameters without name.
1614     printName(OS);
1615     return;
1616   }
1617   printNestedNameSpecifier(OS, P);
1618   if (getDeclName())
1619     OS << *this;
1620   else {
1621     // Give the printName override a chance to pick a different name before we
1622     // fall back to "(anonymous)".
1623     SmallString<64> NameBuffer;
1624     llvm::raw_svector_ostream NameOS(NameBuffer);
1625     printName(NameOS);
1626     if (NameBuffer.empty())
1627       OS << "(anonymous)";
1628     else
1629       OS << NameBuffer;
1630   }
1631 }
1632 
1633 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1634   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1635 }
1636 
1637 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1638                                          const PrintingPolicy &P) const {
1639   const DeclContext *Ctx = getDeclContext();
1640 
1641   // For ObjC methods and properties, look through categories and use the
1642   // interface as context.
1643   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1644     if (auto *ID = MD->getClassInterface())
1645       Ctx = ID;
1646   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1647     if (auto *MD = PD->getGetterMethodDecl())
1648       if (auto *ID = MD->getClassInterface())
1649         Ctx = ID;
1650   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1651     if (auto *CI = ID->getContainingInterface())
1652       Ctx = CI;
1653   }
1654 
1655   if (Ctx->isFunctionOrMethod())
1656     return;
1657 
1658   using ContextsTy = SmallVector<const DeclContext *, 8>;
1659   ContextsTy Contexts;
1660 
1661   // Collect named contexts.
1662   DeclarationName NameInScope = getDeclName();
1663   for (; Ctx; Ctx = Ctx->getParent()) {
1664     // Suppress anonymous namespace if requested.
1665     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1666         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1667       continue;
1668 
1669     // Suppress inline namespace if it doesn't make the result ambiguous.
1670     if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1671         cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1672       continue;
1673 
1674     // Skip non-named contexts such as linkage specifications and ExportDecls.
1675     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1676     if (!ND)
1677       continue;
1678 
1679     Contexts.push_back(Ctx);
1680     NameInScope = ND->getDeclName();
1681   }
1682 
1683   for (const DeclContext *DC : llvm::reverse(Contexts)) {
1684     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1685       OS << Spec->getName();
1686       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1687       printTemplateArgumentList(
1688           OS, TemplateArgs.asArray(), P,
1689           Spec->getSpecializedTemplate()->getTemplateParameters());
1690     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1691       if (ND->isAnonymousNamespace()) {
1692         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1693                                 : "(anonymous namespace)");
1694       }
1695       else
1696         OS << *ND;
1697     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1698       if (!RD->getIdentifier())
1699         OS << "(anonymous " << RD->getKindName() << ')';
1700       else
1701         OS << *RD;
1702     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1703       const FunctionProtoType *FT = nullptr;
1704       if (FD->hasWrittenPrototype())
1705         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1706 
1707       OS << *FD << '(';
1708       if (FT) {
1709         unsigned NumParams = FD->getNumParams();
1710         for (unsigned i = 0; i < NumParams; ++i) {
1711           if (i)
1712             OS << ", ";
1713           OS << FD->getParamDecl(i)->getType().stream(P);
1714         }
1715 
1716         if (FT->isVariadic()) {
1717           if (NumParams > 0)
1718             OS << ", ";
1719           OS << "...";
1720         }
1721       }
1722       OS << ')';
1723     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1724       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1725       // enumerator is declared in the scope that immediately contains
1726       // the enum-specifier. Each scoped enumerator is declared in the
1727       // scope of the enumeration.
1728       // For the case of unscoped enumerator, do not include in the qualified
1729       // name any information about its enum enclosing scope, as its visibility
1730       // is global.
1731       if (ED->isScoped())
1732         OS << *ED;
1733       else
1734         continue;
1735     } else {
1736       OS << *cast<NamedDecl>(DC);
1737     }
1738     OS << "::";
1739   }
1740 }
1741 
1742 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1743                                      const PrintingPolicy &Policy,
1744                                      bool Qualified) const {
1745   if (Qualified)
1746     printQualifiedName(OS, Policy);
1747   else
1748     printName(OS);
1749 }
1750 
1751 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1752   return true;
1753 }
1754 static bool isRedeclarableImpl(...) { return false; }
1755 static bool isRedeclarable(Decl::Kind K) {
1756   switch (K) {
1757 #define DECL(Type, Base) \
1758   case Decl::Type: \
1759     return isRedeclarableImpl((Type##Decl *)nullptr);
1760 #define ABSTRACT_DECL(DECL)
1761 #include "clang/AST/DeclNodes.inc"
1762   }
1763   llvm_unreachable("unknown decl kind");
1764 }
1765 
1766 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1767   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1768 
1769   // Never replace one imported declaration with another; we need both results
1770   // when re-exporting.
1771   if (OldD->isFromASTFile() && isFromASTFile())
1772     return false;
1773 
1774   // A kind mismatch implies that the declaration is not replaced.
1775   if (OldD->getKind() != getKind())
1776     return false;
1777 
1778   // For method declarations, we never replace. (Why?)
1779   if (isa<ObjCMethodDecl>(this))
1780     return false;
1781 
1782   // For parameters, pick the newer one. This is either an error or (in
1783   // Objective-C) permitted as an extension.
1784   if (isa<ParmVarDecl>(this))
1785     return true;
1786 
1787   // Inline namespaces can give us two declarations with the same
1788   // name and kind in the same scope but different contexts; we should
1789   // keep both declarations in this case.
1790   if (!this->getDeclContext()->getRedeclContext()->Equals(
1791           OldD->getDeclContext()->getRedeclContext()))
1792     return false;
1793 
1794   // Using declarations can be replaced if they import the same name from the
1795   // same context.
1796   if (auto *UD = dyn_cast<UsingDecl>(this)) {
1797     ASTContext &Context = getASTContext();
1798     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1799            Context.getCanonicalNestedNameSpecifier(
1800                cast<UsingDecl>(OldD)->getQualifier());
1801   }
1802   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1803     ASTContext &Context = getASTContext();
1804     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1805            Context.getCanonicalNestedNameSpecifier(
1806                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1807   }
1808 
1809   if (isRedeclarable(getKind())) {
1810     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1811       return false;
1812 
1813     if (IsKnownNewer)
1814       return true;
1815 
1816     // Check whether this is actually newer than OldD. We want to keep the
1817     // newer declaration. This loop will usually only iterate once, because
1818     // OldD is usually the previous declaration.
1819     for (auto D : redecls()) {
1820       if (D == OldD)
1821         break;
1822 
1823       // If we reach the canonical declaration, then OldD is not actually older
1824       // than this one.
1825       //
1826       // FIXME: In this case, we should not add this decl to the lookup table.
1827       if (D->isCanonicalDecl())
1828         return false;
1829     }
1830 
1831     // It's a newer declaration of the same kind of declaration in the same
1832     // scope: we want this decl instead of the existing one.
1833     return true;
1834   }
1835 
1836   // In all other cases, we need to keep both declarations in case they have
1837   // different visibility. Any attempt to use the name will result in an
1838   // ambiguity if more than one is visible.
1839   return false;
1840 }
1841 
1842 bool NamedDecl::hasLinkage() const {
1843   return getFormalLinkage() != NoLinkage;
1844 }
1845 
1846 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1847   NamedDecl *ND = this;
1848   while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1849     ND = UD->getTargetDecl();
1850 
1851   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1852     return AD->getClassInterface();
1853 
1854   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1855     return AD->getNamespace();
1856 
1857   return ND;
1858 }
1859 
1860 bool NamedDecl::isCXXInstanceMember() const {
1861   if (!isCXXClassMember())
1862     return false;
1863 
1864   const NamedDecl *D = this;
1865   if (isa<UsingShadowDecl>(D))
1866     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1867 
1868   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1869     return true;
1870   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1871     return MD->isInstance();
1872   return false;
1873 }
1874 
1875 //===----------------------------------------------------------------------===//
1876 // DeclaratorDecl Implementation
1877 //===----------------------------------------------------------------------===//
1878 
1879 template <typename DeclT>
1880 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1881   if (decl->getNumTemplateParameterLists() > 0)
1882     return decl->getTemplateParameterList(0)->getTemplateLoc();
1883   return decl->getInnerLocStart();
1884 }
1885 
1886 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1887   TypeSourceInfo *TSI = getTypeSourceInfo();
1888   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1889   return SourceLocation();
1890 }
1891 
1892 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1893   TypeSourceInfo *TSI = getTypeSourceInfo();
1894   if (TSI) return TSI->getTypeLoc().getEndLoc();
1895   return SourceLocation();
1896 }
1897 
1898 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1899   if (QualifierLoc) {
1900     // Make sure the extended decl info is allocated.
1901     if (!hasExtInfo()) {
1902       // Save (non-extended) type source info pointer.
1903       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1904       // Allocate external info struct.
1905       DeclInfo = new (getASTContext()) ExtInfo;
1906       // Restore savedTInfo into (extended) decl info.
1907       getExtInfo()->TInfo = savedTInfo;
1908     }
1909     // Set qualifier info.
1910     getExtInfo()->QualifierLoc = QualifierLoc;
1911   } else if (hasExtInfo()) {
1912     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1913     getExtInfo()->QualifierLoc = QualifierLoc;
1914   }
1915 }
1916 
1917 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1918   assert(TrailingRequiresClause);
1919   // Make sure the extended decl info is allocated.
1920   if (!hasExtInfo()) {
1921     // Save (non-extended) type source info pointer.
1922     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1923     // Allocate external info struct.
1924     DeclInfo = new (getASTContext()) ExtInfo;
1925     // Restore savedTInfo into (extended) decl info.
1926     getExtInfo()->TInfo = savedTInfo;
1927   }
1928   // Set requires clause info.
1929   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1930 }
1931 
1932 void DeclaratorDecl::setTemplateParameterListsInfo(
1933     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1934   assert(!TPLists.empty());
1935   // Make sure the extended decl info is allocated.
1936   if (!hasExtInfo()) {
1937     // Save (non-extended) type source info pointer.
1938     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1939     // Allocate external info struct.
1940     DeclInfo = new (getASTContext()) ExtInfo;
1941     // Restore savedTInfo into (extended) decl info.
1942     getExtInfo()->TInfo = savedTInfo;
1943   }
1944   // Set the template parameter lists info.
1945   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1946 }
1947 
1948 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1949   return getTemplateOrInnerLocStart(this);
1950 }
1951 
1952 // Helper function: returns true if QT is or contains a type
1953 // having a postfix component.
1954 static bool typeIsPostfix(QualType QT) {
1955   while (true) {
1956     const Type* T = QT.getTypePtr();
1957     switch (T->getTypeClass()) {
1958     default:
1959       return false;
1960     case Type::Pointer:
1961       QT = cast<PointerType>(T)->getPointeeType();
1962       break;
1963     case Type::BlockPointer:
1964       QT = cast<BlockPointerType>(T)->getPointeeType();
1965       break;
1966     case Type::MemberPointer:
1967       QT = cast<MemberPointerType>(T)->getPointeeType();
1968       break;
1969     case Type::LValueReference:
1970     case Type::RValueReference:
1971       QT = cast<ReferenceType>(T)->getPointeeType();
1972       break;
1973     case Type::PackExpansion:
1974       QT = cast<PackExpansionType>(T)->getPattern();
1975       break;
1976     case Type::Paren:
1977     case Type::ConstantArray:
1978     case Type::DependentSizedArray:
1979     case Type::IncompleteArray:
1980     case Type::VariableArray:
1981     case Type::FunctionProto:
1982     case Type::FunctionNoProto:
1983       return true;
1984     }
1985   }
1986 }
1987 
1988 SourceRange DeclaratorDecl::getSourceRange() const {
1989   SourceLocation RangeEnd = getLocation();
1990   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1991     // If the declaration has no name or the type extends past the name take the
1992     // end location of the type.
1993     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1994       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1995   }
1996   return SourceRange(getOuterLocStart(), RangeEnd);
1997 }
1998 
1999 void QualifierInfo::setTemplateParameterListsInfo(
2000     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2001   // Free previous template parameters (if any).
2002   if (NumTemplParamLists > 0) {
2003     Context.Deallocate(TemplParamLists);
2004     TemplParamLists = nullptr;
2005     NumTemplParamLists = 0;
2006   }
2007   // Set info on matched template parameter lists (if any).
2008   if (!TPLists.empty()) {
2009     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2010     NumTemplParamLists = TPLists.size();
2011     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2012   }
2013 }
2014 
2015 //===----------------------------------------------------------------------===//
2016 // VarDecl Implementation
2017 //===----------------------------------------------------------------------===//
2018 
2019 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
2020   switch (SC) {
2021   case SC_None:                 break;
2022   case SC_Auto:                 return "auto";
2023   case SC_Extern:               return "extern";
2024   case SC_PrivateExtern:        return "__private_extern__";
2025   case SC_Register:             return "register";
2026   case SC_Static:               return "static";
2027   }
2028 
2029   llvm_unreachable("Invalid storage class");
2030 }
2031 
2032 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2033                  SourceLocation StartLoc, SourceLocation IdLoc,
2034                  IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2035                  StorageClass SC)
2036     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2037       redeclarable_base(C) {
2038   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2039                 "VarDeclBitfields too large!");
2040   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2041                 "ParmVarDeclBitfields too large!");
2042   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2043                 "NonParmVarDeclBitfields too large!");
2044   AllBits = 0;
2045   VarDeclBits.SClass = SC;
2046   // Everything else is implicitly initialized to false.
2047 }
2048 
2049 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
2050                          SourceLocation StartL, SourceLocation IdL,
2051                          IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2052                          StorageClass S) {
2053   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2054 }
2055 
2056 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2057   return new (C, ID)
2058       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2059               QualType(), nullptr, SC_None);
2060 }
2061 
2062 void VarDecl::setStorageClass(StorageClass SC) {
2063   assert(isLegalForVariable(SC));
2064   VarDeclBits.SClass = SC;
2065 }
2066 
2067 VarDecl::TLSKind VarDecl::getTLSKind() const {
2068   switch (VarDeclBits.TSCSpec) {
2069   case TSCS_unspecified:
2070     if (!hasAttr<ThreadAttr>() &&
2071         !(getASTContext().getLangOpts().OpenMPUseTLS &&
2072           getASTContext().getTargetInfo().isTLSSupported() &&
2073           hasAttr<OMPThreadPrivateDeclAttr>()))
2074       return TLS_None;
2075     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2076                 LangOptions::MSVC2015)) ||
2077             hasAttr<OMPThreadPrivateDeclAttr>())
2078                ? TLS_Dynamic
2079                : TLS_Static;
2080   case TSCS___thread: // Fall through.
2081   case TSCS__Thread_local:
2082     return TLS_Static;
2083   case TSCS_thread_local:
2084     return TLS_Dynamic;
2085   }
2086   llvm_unreachable("Unknown thread storage class specifier!");
2087 }
2088 
2089 SourceRange VarDecl::getSourceRange() const {
2090   if (const Expr *Init = getInit()) {
2091     SourceLocation InitEnd = Init->getEndLoc();
2092     // If Init is implicit, ignore its source range and fallback on
2093     // DeclaratorDecl::getSourceRange() to handle postfix elements.
2094     if (InitEnd.isValid() && InitEnd != getLocation())
2095       return SourceRange(getOuterLocStart(), InitEnd);
2096   }
2097   return DeclaratorDecl::getSourceRange();
2098 }
2099 
2100 template<typename T>
2101 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2102   // C++ [dcl.link]p1: All function types, function names with external linkage,
2103   // and variable names with external linkage have a language linkage.
2104   if (!D.hasExternalFormalLinkage())
2105     return NoLanguageLinkage;
2106 
2107   // Language linkage is a C++ concept, but saying that everything else in C has
2108   // C language linkage fits the implementation nicely.
2109   ASTContext &Context = D.getASTContext();
2110   if (!Context.getLangOpts().CPlusPlus)
2111     return CLanguageLinkage;
2112 
2113   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2114   // language linkage of the names of class members and the function type of
2115   // class member functions.
2116   const DeclContext *DC = D.getDeclContext();
2117   if (DC->isRecord())
2118     return CXXLanguageLinkage;
2119 
2120   // If the first decl is in an extern "C" context, any other redeclaration
2121   // will have C language linkage. If the first one is not in an extern "C"
2122   // context, we would have reported an error for any other decl being in one.
2123   if (isFirstInExternCContext(&D))
2124     return CLanguageLinkage;
2125   return CXXLanguageLinkage;
2126 }
2127 
2128 template<typename T>
2129 static bool isDeclExternC(const T &D) {
2130   // Since the context is ignored for class members, they can only have C++
2131   // language linkage or no language linkage.
2132   const DeclContext *DC = D.getDeclContext();
2133   if (DC->isRecord()) {
2134     assert(D.getASTContext().getLangOpts().CPlusPlus);
2135     return false;
2136   }
2137 
2138   return D.getLanguageLinkage() == CLanguageLinkage;
2139 }
2140 
2141 LanguageLinkage VarDecl::getLanguageLinkage() const {
2142   return getDeclLanguageLinkage(*this);
2143 }
2144 
2145 bool VarDecl::isExternC() const {
2146   return isDeclExternC(*this);
2147 }
2148 
2149 bool VarDecl::isInExternCContext() const {
2150   return getLexicalDeclContext()->isExternCContext();
2151 }
2152 
2153 bool VarDecl::isInExternCXXContext() const {
2154   return getLexicalDeclContext()->isExternCXXContext();
2155 }
2156 
2157 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2158 
2159 VarDecl::DefinitionKind
2160 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2161   if (isThisDeclarationADemotedDefinition())
2162     return DeclarationOnly;
2163 
2164   // C++ [basic.def]p2:
2165   //   A declaration is a definition unless [...] it contains the 'extern'
2166   //   specifier or a linkage-specification and neither an initializer [...],
2167   //   it declares a non-inline static data member in a class declaration [...],
2168   //   it declares a static data member outside a class definition and the variable
2169   //   was defined within the class with the constexpr specifier [...],
2170   // C++1y [temp.expl.spec]p15:
2171   //   An explicit specialization of a static data member or an explicit
2172   //   specialization of a static data member template is a definition if the
2173   //   declaration includes an initializer; otherwise, it is a declaration.
2174   //
2175   // FIXME: How do you declare (but not define) a partial specialization of
2176   // a static data member template outside the containing class?
2177   if (isStaticDataMember()) {
2178     if (isOutOfLine() &&
2179         !(getCanonicalDecl()->isInline() &&
2180           getCanonicalDecl()->isConstexpr()) &&
2181         (hasInit() ||
2182          // If the first declaration is out-of-line, this may be an
2183          // instantiation of an out-of-line partial specialization of a variable
2184          // template for which we have not yet instantiated the initializer.
2185          (getFirstDecl()->isOutOfLine()
2186               ? getTemplateSpecializationKind() == TSK_Undeclared
2187               : getTemplateSpecializationKind() !=
2188                     TSK_ExplicitSpecialization) ||
2189          isa<VarTemplatePartialSpecializationDecl>(this)))
2190       return Definition;
2191     if (!isOutOfLine() && isInline())
2192       return Definition;
2193     return DeclarationOnly;
2194   }
2195   // C99 6.7p5:
2196   //   A definition of an identifier is a declaration for that identifier that
2197   //   [...] causes storage to be reserved for that object.
2198   // Note: that applies for all non-file-scope objects.
2199   // C99 6.9.2p1:
2200   //   If the declaration of an identifier for an object has file scope and an
2201   //   initializer, the declaration is an external definition for the identifier
2202   if (hasInit())
2203     return Definition;
2204 
2205   if (hasDefiningAttr())
2206     return Definition;
2207 
2208   if (const auto *SAA = getAttr<SelectAnyAttr>())
2209     if (!SAA->isInherited())
2210       return Definition;
2211 
2212   // A variable template specialization (other than a static data member
2213   // template or an explicit specialization) is a declaration until we
2214   // instantiate its initializer.
2215   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2216     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2217         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2218         !VTSD->IsCompleteDefinition)
2219       return DeclarationOnly;
2220   }
2221 
2222   if (hasExternalStorage())
2223     return DeclarationOnly;
2224 
2225   // [dcl.link] p7:
2226   //   A declaration directly contained in a linkage-specification is treated
2227   //   as if it contains the extern specifier for the purpose of determining
2228   //   the linkage of the declared name and whether it is a definition.
2229   if (isSingleLineLanguageLinkage(*this))
2230     return DeclarationOnly;
2231 
2232   // C99 6.9.2p2:
2233   //   A declaration of an object that has file scope without an initializer,
2234   //   and without a storage class specifier or the scs 'static', constitutes
2235   //   a tentative definition.
2236   // No such thing in C++.
2237   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2238     return TentativeDefinition;
2239 
2240   // What's left is (in C, block-scope) declarations without initializers or
2241   // external storage. These are definitions.
2242   return Definition;
2243 }
2244 
2245 VarDecl *VarDecl::getActingDefinition() {
2246   DefinitionKind Kind = isThisDeclarationADefinition();
2247   if (Kind != TentativeDefinition)
2248     return nullptr;
2249 
2250   VarDecl *LastTentative = nullptr;
2251 
2252   // Loop through the declaration chain, starting with the most recent.
2253   for (VarDecl *Decl = getMostRecentDecl(); Decl;
2254        Decl = Decl->getPreviousDecl()) {
2255     Kind = Decl->isThisDeclarationADefinition();
2256     if (Kind == Definition)
2257       return nullptr;
2258     // Record the first (most recent) TentativeDefinition that is encountered.
2259     if (Kind == TentativeDefinition && !LastTentative)
2260       LastTentative = Decl;
2261   }
2262 
2263   return LastTentative;
2264 }
2265 
2266 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2267   VarDecl *First = getFirstDecl();
2268   for (auto I : First->redecls()) {
2269     if (I->isThisDeclarationADefinition(C) == Definition)
2270       return I;
2271   }
2272   return nullptr;
2273 }
2274 
2275 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2276   DefinitionKind Kind = DeclarationOnly;
2277 
2278   const VarDecl *First = getFirstDecl();
2279   for (auto I : First->redecls()) {
2280     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2281     if (Kind == Definition)
2282       break;
2283   }
2284 
2285   return Kind;
2286 }
2287 
2288 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2289   for (auto I : redecls()) {
2290     if (auto Expr = I->getInit()) {
2291       D = I;
2292       return Expr;
2293     }
2294   }
2295   return nullptr;
2296 }
2297 
2298 bool VarDecl::hasInit() const {
2299   if (auto *P = dyn_cast<ParmVarDecl>(this))
2300     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2301       return false;
2302 
2303   return !Init.isNull();
2304 }
2305 
2306 Expr *VarDecl::getInit() {
2307   if (!hasInit())
2308     return nullptr;
2309 
2310   if (auto *S = Init.dyn_cast<Stmt *>())
2311     return cast<Expr>(S);
2312 
2313   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2314 }
2315 
2316 Stmt **VarDecl::getInitAddress() {
2317   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2318     return &ES->Value;
2319 
2320   return Init.getAddrOfPtr1();
2321 }
2322 
2323 VarDecl *VarDecl::getInitializingDeclaration() {
2324   VarDecl *Def = nullptr;
2325   for (auto I : redecls()) {
2326     if (I->hasInit())
2327       return I;
2328 
2329     if (I->isThisDeclarationADefinition()) {
2330       if (isStaticDataMember())
2331         return I;
2332       Def = I;
2333     }
2334   }
2335   return Def;
2336 }
2337 
2338 bool VarDecl::isOutOfLine() const {
2339   if (Decl::isOutOfLine())
2340     return true;
2341 
2342   if (!isStaticDataMember())
2343     return false;
2344 
2345   // If this static data member was instantiated from a static data member of
2346   // a class template, check whether that static data member was defined
2347   // out-of-line.
2348   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2349     return VD->isOutOfLine();
2350 
2351   return false;
2352 }
2353 
2354 void VarDecl::setInit(Expr *I) {
2355   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2356     Eval->~EvaluatedStmt();
2357     getASTContext().Deallocate(Eval);
2358   }
2359 
2360   Init = I;
2361 }
2362 
2363 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2364   const LangOptions &Lang = C.getLangOpts();
2365 
2366   // OpenCL permits const integral variables to be used in constant
2367   // expressions, like in C++98.
2368   if (!Lang.CPlusPlus && !Lang.OpenCL)
2369     return false;
2370 
2371   // Function parameters are never usable in constant expressions.
2372   if (isa<ParmVarDecl>(this))
2373     return false;
2374 
2375   // The values of weak variables are never usable in constant expressions.
2376   if (isWeak())
2377     return false;
2378 
2379   // In C++11, any variable of reference type can be used in a constant
2380   // expression if it is initialized by a constant expression.
2381   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2382     return true;
2383 
2384   // Only const objects can be used in constant expressions in C++. C++98 does
2385   // not require the variable to be non-volatile, but we consider this to be a
2386   // defect.
2387   if (!getType().isConstant(C) || getType().isVolatileQualified())
2388     return false;
2389 
2390   // In C++, const, non-volatile variables of integral or enumeration types
2391   // can be used in constant expressions.
2392   if (getType()->isIntegralOrEnumerationType())
2393     return true;
2394 
2395   // Additionally, in C++11, non-volatile constexpr variables can be used in
2396   // constant expressions.
2397   return Lang.CPlusPlus11 && isConstexpr();
2398 }
2399 
2400 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2401   // C++2a [expr.const]p3:
2402   //   A variable is usable in constant expressions after its initializing
2403   //   declaration is encountered...
2404   const VarDecl *DefVD = nullptr;
2405   const Expr *Init = getAnyInitializer(DefVD);
2406   if (!Init || Init->isValueDependent() || getType()->isDependentType())
2407     return false;
2408   //   ... if it is a constexpr variable, or it is of reference type or of
2409   //   const-qualified integral or enumeration type, ...
2410   if (!DefVD->mightBeUsableInConstantExpressions(Context))
2411     return false;
2412   //   ... and its initializer is a constant initializer.
2413   if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2414     return false;
2415   // C++98 [expr.const]p1:
2416   //   An integral constant-expression can involve only [...] const variables
2417   //   or static data members of integral or enumeration types initialized with
2418   //   [integer] constant expressions (dcl.init)
2419   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2420       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2421     return false;
2422   return true;
2423 }
2424 
2425 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2426 /// form, which contains extra information on the evaluated value of the
2427 /// initializer.
2428 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2429   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2430   if (!Eval) {
2431     // Note: EvaluatedStmt contains an APValue, which usually holds
2432     // resources not allocated from the ASTContext.  We need to do some
2433     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2434     // where we can detect whether there's anything to clean up or not.
2435     Eval = new (getASTContext()) EvaluatedStmt;
2436     Eval->Value = Init.get<Stmt *>();
2437     Init = Eval;
2438   }
2439   return Eval;
2440 }
2441 
2442 EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2443   return Init.dyn_cast<EvaluatedStmt *>();
2444 }
2445 
2446 APValue *VarDecl::evaluateValue() const {
2447   SmallVector<PartialDiagnosticAt, 8> Notes;
2448   return evaluateValueImpl(Notes, hasConstantInitialization());
2449 }
2450 
2451 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2452                                     bool IsConstantInitialization) const {
2453   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2454 
2455   const auto *Init = cast<Expr>(Eval->Value);
2456   assert(!Init->isValueDependent());
2457 
2458   // We only produce notes indicating why an initializer is non-constant the
2459   // first time it is evaluated. FIXME: The notes won't always be emitted the
2460   // first time we try evaluation, so might not be produced at all.
2461   if (Eval->WasEvaluated)
2462     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2463 
2464   if (Eval->IsEvaluating) {
2465     // FIXME: Produce a diagnostic for self-initialization.
2466     return nullptr;
2467   }
2468 
2469   Eval->IsEvaluating = true;
2470 
2471   ASTContext &Ctx = getASTContext();
2472   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2473                                             IsConstantInitialization);
2474 
2475   // In C++11, this isn't a constant initializer if we produced notes. In that
2476   // case, we can't keep the result, because it may only be correct under the
2477   // assumption that the initializer is a constant context.
2478   if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2479       !Notes.empty())
2480     Result = false;
2481 
2482   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2483   // or that it's empty (so that there's nothing to clean up) if evaluation
2484   // failed.
2485   if (!Result)
2486     Eval->Evaluated = APValue();
2487   else if (Eval->Evaluated.needsCleanup())
2488     Ctx.addDestruction(&Eval->Evaluated);
2489 
2490   Eval->IsEvaluating = false;
2491   Eval->WasEvaluated = true;
2492 
2493   return Result ? &Eval->Evaluated : nullptr;
2494 }
2495 
2496 APValue *VarDecl::getEvaluatedValue() const {
2497   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2498     if (Eval->WasEvaluated)
2499       return &Eval->Evaluated;
2500 
2501   return nullptr;
2502 }
2503 
2504 bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2505   const Expr *Init = getInit();
2506   assert(Init && "no initializer");
2507 
2508   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2509   if (!Eval->CheckedForICEInit) {
2510     Eval->CheckedForICEInit = true;
2511     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2512   }
2513   return Eval->HasICEInit;
2514 }
2515 
2516 bool VarDecl::hasConstantInitialization() const {
2517   // In C, all globals (and only globals) have constant initialization.
2518   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2519     return true;
2520 
2521   // In C++, it depends on whether the evaluation at the point of definition
2522   // was evaluatable as a constant initializer.
2523   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2524     return Eval->HasConstantInitialization;
2525 
2526   return false;
2527 }
2528 
2529 bool VarDecl::checkForConstantInitialization(
2530     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2531   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2532   // If we ask for the value before we know whether we have a constant
2533   // initializer, we can compute the wrong value (for example, due to
2534   // std::is_constant_evaluated()).
2535   assert(!Eval->WasEvaluated &&
2536          "already evaluated var value before checking for constant init");
2537   assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2538 
2539   assert(!cast<Expr>(Eval->Value)->isValueDependent());
2540 
2541   // Evaluate the initializer to check whether it's a constant expression.
2542   Eval->HasConstantInitialization =
2543       evaluateValueImpl(Notes, true) && Notes.empty();
2544 
2545   // If evaluation as a constant initializer failed, allow re-evaluation as a
2546   // non-constant initializer if we later find we want the value.
2547   if (!Eval->HasConstantInitialization)
2548     Eval->WasEvaluated = false;
2549 
2550   return Eval->HasConstantInitialization;
2551 }
2552 
2553 bool VarDecl::isParameterPack() const {
2554   return isa<PackExpansionType>(getType());
2555 }
2556 
2557 template<typename DeclT>
2558 static DeclT *getDefinitionOrSelf(DeclT *D) {
2559   assert(D);
2560   if (auto *Def = D->getDefinition())
2561     return Def;
2562   return D;
2563 }
2564 
2565 bool VarDecl::isEscapingByref() const {
2566   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2567 }
2568 
2569 bool VarDecl::isNonEscapingByref() const {
2570   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2571 }
2572 
2573 bool VarDecl::hasDependentAlignment() const {
2574   QualType T = getType();
2575   return T->isDependentType() || T->isUndeducedAutoType() ||
2576          llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2577            return AA->isAlignmentDependent();
2578          });
2579 }
2580 
2581 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2582   const VarDecl *VD = this;
2583 
2584   // If this is an instantiated member, walk back to the template from which
2585   // it was instantiated.
2586   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2587     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2588       VD = VD->getInstantiatedFromStaticDataMember();
2589       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2590         VD = NewVD;
2591     }
2592   }
2593 
2594   // If it's an instantiated variable template specialization, find the
2595   // template or partial specialization from which it was instantiated.
2596   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2597     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2598       auto From = VDTemplSpec->getInstantiatedFrom();
2599       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2600         while (!VTD->isMemberSpecialization()) {
2601           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2602           if (!NewVTD)
2603             break;
2604           VTD = NewVTD;
2605         }
2606         return getDefinitionOrSelf(VTD->getTemplatedDecl());
2607       }
2608       if (auto *VTPSD =
2609               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2610         while (!VTPSD->isMemberSpecialization()) {
2611           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2612           if (!NewVTPSD)
2613             break;
2614           VTPSD = NewVTPSD;
2615         }
2616         return getDefinitionOrSelf<VarDecl>(VTPSD);
2617       }
2618     }
2619   }
2620 
2621   // If this is the pattern of a variable template, find where it was
2622   // instantiated from. FIXME: Is this necessary?
2623   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2624     while (!VarTemplate->isMemberSpecialization()) {
2625       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2626       if (!NewVT)
2627         break;
2628       VarTemplate = NewVT;
2629     }
2630 
2631     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2632   }
2633 
2634   if (VD == this)
2635     return nullptr;
2636   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2637 }
2638 
2639 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2640   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2641     return cast<VarDecl>(MSI->getInstantiatedFrom());
2642 
2643   return nullptr;
2644 }
2645 
2646 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2647   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2648     return Spec->getSpecializationKind();
2649 
2650   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2651     return MSI->getTemplateSpecializationKind();
2652 
2653   return TSK_Undeclared;
2654 }
2655 
2656 TemplateSpecializationKind
2657 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2658   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2659     return MSI->getTemplateSpecializationKind();
2660 
2661   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2662     return Spec->getSpecializationKind();
2663 
2664   return TSK_Undeclared;
2665 }
2666 
2667 SourceLocation VarDecl::getPointOfInstantiation() const {
2668   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2669     return Spec->getPointOfInstantiation();
2670 
2671   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2672     return MSI->getPointOfInstantiation();
2673 
2674   return SourceLocation();
2675 }
2676 
2677 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2678   return getASTContext().getTemplateOrSpecializationInfo(this)
2679       .dyn_cast<VarTemplateDecl *>();
2680 }
2681 
2682 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2683   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2684 }
2685 
2686 bool VarDecl::isKnownToBeDefined() const {
2687   const auto &LangOpts = getASTContext().getLangOpts();
2688   // In CUDA mode without relocatable device code, variables of form 'extern
2689   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2690   // memory pool.  These are never undefined variables, even if they appear
2691   // inside of an anon namespace or static function.
2692   //
2693   // With CUDA relocatable device code enabled, these variables don't get
2694   // special handling; they're treated like regular extern variables.
2695   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2696       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2697       isa<IncompleteArrayType>(getType()))
2698     return true;
2699 
2700   return hasDefinition();
2701 }
2702 
2703 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2704   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2705                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2706                                  !hasAttr<AlwaysDestroyAttr>()));
2707 }
2708 
2709 QualType::DestructionKind
2710 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2711   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2712     if (Eval->HasConstantDestruction)
2713       return QualType::DK_none;
2714 
2715   if (isNoDestroy(Ctx))
2716     return QualType::DK_none;
2717 
2718   return getType().isDestructedType();
2719 }
2720 
2721 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2722   if (isStaticDataMember())
2723     // FIXME: Remove ?
2724     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2725     return getASTContext().getTemplateOrSpecializationInfo(this)
2726         .dyn_cast<MemberSpecializationInfo *>();
2727   return nullptr;
2728 }
2729 
2730 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2731                                          SourceLocation PointOfInstantiation) {
2732   assert((isa<VarTemplateSpecializationDecl>(this) ||
2733           getMemberSpecializationInfo()) &&
2734          "not a variable or static data member template specialization");
2735 
2736   if (VarTemplateSpecializationDecl *Spec =
2737           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2738     Spec->setSpecializationKind(TSK);
2739     if (TSK != TSK_ExplicitSpecialization &&
2740         PointOfInstantiation.isValid() &&
2741         Spec->getPointOfInstantiation().isInvalid()) {
2742       Spec->setPointOfInstantiation(PointOfInstantiation);
2743       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2744         L->InstantiationRequested(this);
2745     }
2746   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2747     MSI->setTemplateSpecializationKind(TSK);
2748     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2749         MSI->getPointOfInstantiation().isInvalid()) {
2750       MSI->setPointOfInstantiation(PointOfInstantiation);
2751       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2752         L->InstantiationRequested(this);
2753     }
2754   }
2755 }
2756 
2757 void
2758 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2759                                             TemplateSpecializationKind TSK) {
2760   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2761          "Previous template or instantiation?");
2762   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2763 }
2764 
2765 //===----------------------------------------------------------------------===//
2766 // ParmVarDecl Implementation
2767 //===----------------------------------------------------------------------===//
2768 
2769 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2770                                  SourceLocation StartLoc,
2771                                  SourceLocation IdLoc, IdentifierInfo *Id,
2772                                  QualType T, TypeSourceInfo *TInfo,
2773                                  StorageClass S, Expr *DefArg) {
2774   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2775                                  S, DefArg);
2776 }
2777 
2778 QualType ParmVarDecl::getOriginalType() const {
2779   TypeSourceInfo *TSI = getTypeSourceInfo();
2780   QualType T = TSI ? TSI->getType() : getType();
2781   if (const auto *DT = dyn_cast<DecayedType>(T))
2782     return DT->getOriginalType();
2783   return T;
2784 }
2785 
2786 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2787   return new (C, ID)
2788       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2789                   nullptr, QualType(), nullptr, SC_None, nullptr);
2790 }
2791 
2792 SourceRange ParmVarDecl::getSourceRange() const {
2793   if (!hasInheritedDefaultArg()) {
2794     SourceRange ArgRange = getDefaultArgRange();
2795     if (ArgRange.isValid())
2796       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2797   }
2798 
2799   // DeclaratorDecl considers the range of postfix types as overlapping with the
2800   // declaration name, but this is not the case with parameters in ObjC methods.
2801   if (isa<ObjCMethodDecl>(getDeclContext()))
2802     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2803 
2804   return DeclaratorDecl::getSourceRange();
2805 }
2806 
2807 bool ParmVarDecl::isDestroyedInCallee() const {
2808   // ns_consumed only affects code generation in ARC
2809   if (hasAttr<NSConsumedAttr>())
2810     return getASTContext().getLangOpts().ObjCAutoRefCount;
2811 
2812   // FIXME: isParamDestroyedInCallee() should probably imply
2813   // isDestructedType()
2814   auto *RT = getType()->getAs<RecordType>();
2815   if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2816       getType().isDestructedType())
2817     return true;
2818 
2819   return false;
2820 }
2821 
2822 Expr *ParmVarDecl::getDefaultArg() {
2823   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2824   assert(!hasUninstantiatedDefaultArg() &&
2825          "Default argument is not yet instantiated!");
2826 
2827   Expr *Arg = getInit();
2828   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2829     return E->getSubExpr();
2830 
2831   return Arg;
2832 }
2833 
2834 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2835   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2836   Init = defarg;
2837 }
2838 
2839 SourceRange ParmVarDecl::getDefaultArgRange() const {
2840   switch (ParmVarDeclBits.DefaultArgKind) {
2841   case DAK_None:
2842   case DAK_Unparsed:
2843     // Nothing we can do here.
2844     return SourceRange();
2845 
2846   case DAK_Uninstantiated:
2847     return getUninstantiatedDefaultArg()->getSourceRange();
2848 
2849   case DAK_Normal:
2850     if (const Expr *E = getInit())
2851       return E->getSourceRange();
2852 
2853     // Missing an actual expression, may be invalid.
2854     return SourceRange();
2855   }
2856   llvm_unreachable("Invalid default argument kind.");
2857 }
2858 
2859 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2860   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2861   Init = arg;
2862 }
2863 
2864 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2865   assert(hasUninstantiatedDefaultArg() &&
2866          "Wrong kind of initialization expression!");
2867   return cast_or_null<Expr>(Init.get<Stmt *>());
2868 }
2869 
2870 bool ParmVarDecl::hasDefaultArg() const {
2871   // FIXME: We should just return false for DAK_None here once callers are
2872   // prepared for the case that we encountered an invalid default argument and
2873   // were unable to even build an invalid expression.
2874   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2875          !Init.isNull();
2876 }
2877 
2878 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2879   getASTContext().setParameterIndex(this, parameterIndex);
2880   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2881 }
2882 
2883 unsigned ParmVarDecl::getParameterIndexLarge() const {
2884   return getASTContext().getParameterIndex(this);
2885 }
2886 
2887 //===----------------------------------------------------------------------===//
2888 // FunctionDecl Implementation
2889 //===----------------------------------------------------------------------===//
2890 
2891 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2892                            SourceLocation StartLoc,
2893                            const DeclarationNameInfo &NameInfo, QualType T,
2894                            TypeSourceInfo *TInfo, StorageClass S,
2895                            bool UsesFPIntrin, bool isInlineSpecified,
2896                            ConstexprSpecKind ConstexprKind,
2897                            Expr *TrailingRequiresClause)
2898     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2899                      StartLoc),
2900       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2901       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2902   assert(T.isNull() || T->isFunctionType());
2903   FunctionDeclBits.SClass = S;
2904   FunctionDeclBits.IsInline = isInlineSpecified;
2905   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2906   FunctionDeclBits.IsVirtualAsWritten = false;
2907   FunctionDeclBits.IsPure = false;
2908   FunctionDeclBits.HasInheritedPrototype = false;
2909   FunctionDeclBits.HasWrittenPrototype = true;
2910   FunctionDeclBits.IsDeleted = false;
2911   FunctionDeclBits.IsTrivial = false;
2912   FunctionDeclBits.IsTrivialForCall = false;
2913   FunctionDeclBits.IsDefaulted = false;
2914   FunctionDeclBits.IsExplicitlyDefaulted = false;
2915   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2916   FunctionDeclBits.HasImplicitReturnZero = false;
2917   FunctionDeclBits.IsLateTemplateParsed = false;
2918   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
2919   FunctionDeclBits.InstantiationIsPending = false;
2920   FunctionDeclBits.UsesSEHTry = false;
2921   FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
2922   FunctionDeclBits.HasSkippedBody = false;
2923   FunctionDeclBits.WillHaveBody = false;
2924   FunctionDeclBits.IsMultiVersion = false;
2925   FunctionDeclBits.IsCopyDeductionCandidate = false;
2926   FunctionDeclBits.HasODRHash = false;
2927   if (TrailingRequiresClause)
2928     setTrailingRequiresClause(TrailingRequiresClause);
2929 }
2930 
2931 void FunctionDecl::getNameForDiagnostic(
2932     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2933   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2934   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2935   if (TemplateArgs)
2936     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2937 }
2938 
2939 bool FunctionDecl::isVariadic() const {
2940   if (const auto *FT = getType()->getAs<FunctionProtoType>())
2941     return FT->isVariadic();
2942   return false;
2943 }
2944 
2945 FunctionDecl::DefaultedFunctionInfo *
2946 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2947                                             ArrayRef<DeclAccessPair> Lookups) {
2948   DefaultedFunctionInfo *Info = new (Context.Allocate(
2949       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2950       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2951       DefaultedFunctionInfo;
2952   Info->NumLookups = Lookups.size();
2953   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2954                           Info->getTrailingObjects<DeclAccessPair>());
2955   return Info;
2956 }
2957 
2958 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2959   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
2960   assert(!Body && "can't replace function body with defaulted function info");
2961 
2962   FunctionDeclBits.HasDefaultedFunctionInfo = true;
2963   DefaultedInfo = Info;
2964 }
2965 
2966 FunctionDecl::DefaultedFunctionInfo *
2967 FunctionDecl::getDefaultedFunctionInfo() const {
2968   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2969 }
2970 
2971 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2972   for (auto I : redecls()) {
2973     if (I->doesThisDeclarationHaveABody()) {
2974       Definition = I;
2975       return true;
2976     }
2977   }
2978 
2979   return false;
2980 }
2981 
2982 bool FunctionDecl::hasTrivialBody() const {
2983   Stmt *S = getBody();
2984   if (!S) {
2985     // Since we don't have a body for this function, we don't know if it's
2986     // trivial or not.
2987     return false;
2988   }
2989 
2990   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2991     return true;
2992   return false;
2993 }
2994 
2995 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
2996   if (!getFriendObjectKind())
2997     return false;
2998 
2999   // Check for a friend function instantiated from a friend function
3000   // definition in a templated class.
3001   if (const FunctionDecl *InstantiatedFrom =
3002           getInstantiatedFromMemberFunction())
3003     return InstantiatedFrom->getFriendObjectKind() &&
3004            InstantiatedFrom->isThisDeclarationADefinition();
3005 
3006   // Check for a friend function template instantiated from a friend
3007   // function template definition in a templated class.
3008   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3009     if (const FunctionTemplateDecl *InstantiatedFrom =
3010             Template->getInstantiatedFromMemberTemplate())
3011       return InstantiatedFrom->getFriendObjectKind() &&
3012              InstantiatedFrom->isThisDeclarationADefinition();
3013   }
3014 
3015   return false;
3016 }
3017 
3018 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3019                              bool CheckForPendingFriendDefinition) const {
3020   for (const FunctionDecl *FD : redecls()) {
3021     if (FD->isThisDeclarationADefinition()) {
3022       Definition = FD;
3023       return true;
3024     }
3025 
3026     // If this is a friend function defined in a class template, it does not
3027     // have a body until it is used, nevertheless it is a definition, see
3028     // [temp.inst]p2:
3029     //
3030     // ... for the purpose of determining whether an instantiated redeclaration
3031     // is valid according to [basic.def.odr] and [class.mem], a declaration that
3032     // corresponds to a definition in the template is considered to be a
3033     // definition.
3034     //
3035     // The following code must produce redefinition error:
3036     //
3037     //     template<typename T> struct C20 { friend void func_20() {} };
3038     //     C20<int> c20i;
3039     //     void func_20() {}
3040     //
3041     if (CheckForPendingFriendDefinition &&
3042         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3043       Definition = FD;
3044       return true;
3045     }
3046   }
3047 
3048   return false;
3049 }
3050 
3051 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3052   if (!hasBody(Definition))
3053     return nullptr;
3054 
3055   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3056          "definition should not have a body");
3057   if (Definition->Body)
3058     return Definition->Body.get(getASTContext().getExternalSource());
3059 
3060   return nullptr;
3061 }
3062 
3063 void FunctionDecl::setBody(Stmt *B) {
3064   FunctionDeclBits.HasDefaultedFunctionInfo = false;
3065   Body = LazyDeclStmtPtr(B);
3066   if (B)
3067     EndRangeLoc = B->getEndLoc();
3068 }
3069 
3070 void FunctionDecl::setPure(bool P) {
3071   FunctionDeclBits.IsPure = P;
3072   if (P)
3073     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3074       Parent->markedVirtualFunctionPure();
3075 }
3076 
3077 template<std::size_t Len>
3078 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3079   IdentifierInfo *II = ND->getIdentifier();
3080   return II && II->isStr(Str);
3081 }
3082 
3083 bool FunctionDecl::isMain() const {
3084   const TranslationUnitDecl *tunit =
3085     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3086   return tunit &&
3087          !tunit->getASTContext().getLangOpts().Freestanding &&
3088          isNamed(this, "main");
3089 }
3090 
3091 bool FunctionDecl::isMSVCRTEntryPoint() const {
3092   const TranslationUnitDecl *TUnit =
3093       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3094   if (!TUnit)
3095     return false;
3096 
3097   // Even though we aren't really targeting MSVCRT if we are freestanding,
3098   // semantic analysis for these functions remains the same.
3099 
3100   // MSVCRT entry points only exist on MSVCRT targets.
3101   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3102     return false;
3103 
3104   // Nameless functions like constructors cannot be entry points.
3105   if (!getIdentifier())
3106     return false;
3107 
3108   return llvm::StringSwitch<bool>(getName())
3109       .Cases("main",     // an ANSI console app
3110              "wmain",    // a Unicode console App
3111              "WinMain",  // an ANSI GUI app
3112              "wWinMain", // a Unicode GUI app
3113              "DllMain",  // a DLL
3114              true)
3115       .Default(false);
3116 }
3117 
3118 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3119   assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName);
3120   assert(getDeclName().getCXXOverloadedOperator() == OO_New ||
3121          getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3122          getDeclName().getCXXOverloadedOperator() == OO_Array_New ||
3123          getDeclName().getCXXOverloadedOperator() == OO_Array_Delete);
3124 
3125   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3126     return false;
3127 
3128   const auto *proto = getType()->castAs<FunctionProtoType>();
3129   if (proto->getNumParams() != 2 || proto->isVariadic())
3130     return false;
3131 
3132   ASTContext &Context =
3133     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3134       ->getASTContext();
3135 
3136   // The result type and first argument type are constant across all
3137   // these operators.  The second argument must be exactly void*.
3138   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3139 }
3140 
3141 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3142     Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3143   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3144     return false;
3145   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3146       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3147       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3148       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3149     return false;
3150 
3151   if (isa<CXXRecordDecl>(getDeclContext()))
3152     return false;
3153 
3154   // This can only fail for an invalid 'operator new' declaration.
3155   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3156     return false;
3157 
3158   const auto *FPT = getType()->castAs<FunctionProtoType>();
3159   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
3160     return false;
3161 
3162   // If this is a single-parameter function, it must be a replaceable global
3163   // allocation or deallocation function.
3164   if (FPT->getNumParams() == 1)
3165     return true;
3166 
3167   unsigned Params = 1;
3168   QualType Ty = FPT->getParamType(Params);
3169   ASTContext &Ctx = getASTContext();
3170 
3171   auto Consume = [&] {
3172     ++Params;
3173     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3174   };
3175 
3176   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3177   bool IsSizedDelete = false;
3178   if (Ctx.getLangOpts().SizedDeallocation &&
3179       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3180        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3181       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3182     IsSizedDelete = true;
3183     Consume();
3184   }
3185 
3186   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3187   // new/delete.
3188   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3189     Consume();
3190     if (AlignmentParam)
3191       *AlignmentParam = Params;
3192   }
3193 
3194   // Finally, if this is not a sized delete, the final parameter can
3195   // be a 'const std::nothrow_t&'.
3196   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3197     Ty = Ty->getPointeeType();
3198     if (Ty.getCVRQualifiers() != Qualifiers::Const)
3199       return false;
3200     if (Ty->isNothrowT()) {
3201       if (IsNothrow)
3202         *IsNothrow = true;
3203       Consume();
3204     }
3205   }
3206 
3207   return Params == FPT->getNumParams();
3208 }
3209 
3210 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3211   if (!getBuiltinID())
3212     return false;
3213 
3214   const FunctionDecl *Definition;
3215   return hasBody(Definition) && Definition->isInlineSpecified() &&
3216          Definition->hasAttr<AlwaysInlineAttr>() &&
3217          Definition->hasAttr<GNUInlineAttr>();
3218 }
3219 
3220 bool FunctionDecl::isDestroyingOperatorDelete() const {
3221   // C++ P0722:
3222   //   Within a class C, a single object deallocation function with signature
3223   //     (T, std::destroying_delete_t, <more params>)
3224   //   is a destroying operator delete.
3225   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3226       getNumParams() < 2)
3227     return false;
3228 
3229   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3230   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3231          RD->getIdentifier()->isStr("destroying_delete_t");
3232 }
3233 
3234 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3235   return getDeclLanguageLinkage(*this);
3236 }
3237 
3238 bool FunctionDecl::isExternC() const {
3239   return isDeclExternC(*this);
3240 }
3241 
3242 bool FunctionDecl::isInExternCContext() const {
3243   if (hasAttr<OpenCLKernelAttr>())
3244     return true;
3245   return getLexicalDeclContext()->isExternCContext();
3246 }
3247 
3248 bool FunctionDecl::isInExternCXXContext() const {
3249   return getLexicalDeclContext()->isExternCXXContext();
3250 }
3251 
3252 bool FunctionDecl::isGlobal() const {
3253   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3254     return Method->isStatic();
3255 
3256   if (getCanonicalDecl()->getStorageClass() == SC_Static)
3257     return false;
3258 
3259   for (const DeclContext *DC = getDeclContext();
3260        DC->isNamespace();
3261        DC = DC->getParent()) {
3262     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3263       if (!Namespace->getDeclName())
3264         return false;
3265     }
3266   }
3267 
3268   return true;
3269 }
3270 
3271 bool FunctionDecl::isNoReturn() const {
3272   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3273       hasAttr<C11NoReturnAttr>())
3274     return true;
3275 
3276   if (auto *FnTy = getType()->getAs<FunctionType>())
3277     return FnTy->getNoReturnAttr();
3278 
3279   return false;
3280 }
3281 
3282 
3283 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3284   if (hasAttr<TargetAttr>())
3285     return MultiVersionKind::Target;
3286   if (hasAttr<CPUDispatchAttr>())
3287     return MultiVersionKind::CPUDispatch;
3288   if (hasAttr<CPUSpecificAttr>())
3289     return MultiVersionKind::CPUSpecific;
3290   if (hasAttr<TargetClonesAttr>())
3291     return MultiVersionKind::TargetClones;
3292   return MultiVersionKind::None;
3293 }
3294 
3295 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3296   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3297 }
3298 
3299 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3300   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3301 }
3302 
3303 bool FunctionDecl::isTargetMultiVersion() const {
3304   return isMultiVersion() && hasAttr<TargetAttr>();
3305 }
3306 
3307 bool FunctionDecl::isTargetClonesMultiVersion() const {
3308   return isMultiVersion() && hasAttr<TargetClonesAttr>();
3309 }
3310 
3311 void
3312 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3313   redeclarable_base::setPreviousDecl(PrevDecl);
3314 
3315   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3316     FunctionTemplateDecl *PrevFunTmpl
3317       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3318     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3319     FunTmpl->setPreviousDecl(PrevFunTmpl);
3320   }
3321 
3322   if (PrevDecl && PrevDecl->isInlined())
3323     setImplicitlyInline(true);
3324 }
3325 
3326 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3327 
3328 /// Returns a value indicating whether this function corresponds to a builtin
3329 /// function.
3330 ///
3331 /// The function corresponds to a built-in function if it is declared at
3332 /// translation scope or within an extern "C" block and its name matches with
3333 /// the name of a builtin. The returned value will be 0 for functions that do
3334 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3335 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3336 /// value.
3337 ///
3338 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3339 /// functions as their wrapped builtins. This shouldn't be done in general, but
3340 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3341 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3342   unsigned BuiltinID = 0;
3343 
3344   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3345     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3346   } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3347     BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3348   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3349     BuiltinID = A->getID();
3350   }
3351 
3352   if (!BuiltinID)
3353     return 0;
3354 
3355   // If the function is marked "overloadable", it has a different mangled name
3356   // and is not the C library function.
3357   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3358       (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3359     return 0;
3360 
3361   ASTContext &Context = getASTContext();
3362   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3363     return BuiltinID;
3364 
3365   // This function has the name of a known C library
3366   // function. Determine whether it actually refers to the C library
3367   // function or whether it just has the same name.
3368 
3369   // If this is a static function, it's not a builtin.
3370   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3371     return 0;
3372 
3373   // OpenCL v1.2 s6.9.f - The library functions defined in
3374   // the C99 standard headers are not available.
3375   if (Context.getLangOpts().OpenCL &&
3376       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3377     return 0;
3378 
3379   // CUDA does not have device-side standard library. printf and malloc are the
3380   // only special cases that are supported by device-side runtime.
3381   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3382       !hasAttr<CUDAHostAttr>() &&
3383       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3384     return 0;
3385 
3386   // As AMDGCN implementation of OpenMP does not have a device-side standard
3387   // library, none of the predefined library functions except printf and malloc
3388   // should be treated as a builtin i.e. 0 should be returned for them.
3389   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3390       Context.getLangOpts().OpenMPIsDevice &&
3391       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3392       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3393     return 0;
3394 
3395   return BuiltinID;
3396 }
3397 
3398 /// getNumParams - Return the number of parameters this function must have
3399 /// based on its FunctionType.  This is the length of the ParamInfo array
3400 /// after it has been created.
3401 unsigned FunctionDecl::getNumParams() const {
3402   const auto *FPT = getType()->getAs<FunctionProtoType>();
3403   return FPT ? FPT->getNumParams() : 0;
3404 }
3405 
3406 void FunctionDecl::setParams(ASTContext &C,
3407                              ArrayRef<ParmVarDecl *> NewParamInfo) {
3408   assert(!ParamInfo && "Already has param info!");
3409   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3410 
3411   // Zero params -> null pointer.
3412   if (!NewParamInfo.empty()) {
3413     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3414     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3415   }
3416 }
3417 
3418 /// getMinRequiredArguments - Returns the minimum number of arguments
3419 /// needed to call this function. This may be fewer than the number of
3420 /// function parameters, if some of the parameters have default
3421 /// arguments (in C++) or are parameter packs (C++11).
3422 unsigned FunctionDecl::getMinRequiredArguments() const {
3423   if (!getASTContext().getLangOpts().CPlusPlus)
3424     return getNumParams();
3425 
3426   // Note that it is possible for a parameter with no default argument to
3427   // follow a parameter with a default argument.
3428   unsigned NumRequiredArgs = 0;
3429   unsigned MinParamsSoFar = 0;
3430   for (auto *Param : parameters()) {
3431     if (!Param->isParameterPack()) {
3432       ++MinParamsSoFar;
3433       if (!Param->hasDefaultArg())
3434         NumRequiredArgs = MinParamsSoFar;
3435     }
3436   }
3437   return NumRequiredArgs;
3438 }
3439 
3440 bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3441   return getNumParams() == 1 ||
3442          (getNumParams() > 1 &&
3443           std::all_of(param_begin() + 1, param_end(),
3444                       [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3445 }
3446 
3447 /// The combination of the extern and inline keywords under MSVC forces
3448 /// the function to be required.
3449 ///
3450 /// Note: This function assumes that we will only get called when isInlined()
3451 /// would return true for this FunctionDecl.
3452 bool FunctionDecl::isMSExternInline() const {
3453   assert(isInlined() && "expected to get called on an inlined function!");
3454 
3455   const ASTContext &Context = getASTContext();
3456   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3457       !hasAttr<DLLExportAttr>())
3458     return false;
3459 
3460   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3461        FD = FD->getPreviousDecl())
3462     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3463       return true;
3464 
3465   return false;
3466 }
3467 
3468 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3469   if (Redecl->getStorageClass() != SC_Extern)
3470     return false;
3471 
3472   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3473        FD = FD->getPreviousDecl())
3474     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3475       return false;
3476 
3477   return true;
3478 }
3479 
3480 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3481   // Only consider file-scope declarations in this test.
3482   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3483     return false;
3484 
3485   // Only consider explicit declarations; the presence of a builtin for a
3486   // libcall shouldn't affect whether a definition is externally visible.
3487   if (Redecl->isImplicit())
3488     return false;
3489 
3490   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3491     return true; // Not an inline definition
3492 
3493   return false;
3494 }
3495 
3496 /// For a function declaration in C or C++, determine whether this
3497 /// declaration causes the definition to be externally visible.
3498 ///
3499 /// For instance, this determines if adding the current declaration to the set
3500 /// of redeclarations of the given functions causes
3501 /// isInlineDefinitionExternallyVisible to change from false to true.
3502 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3503   assert(!doesThisDeclarationHaveABody() &&
3504          "Must have a declaration without a body.");
3505 
3506   ASTContext &Context = getASTContext();
3507 
3508   if (Context.getLangOpts().MSVCCompat) {
3509     const FunctionDecl *Definition;
3510     if (hasBody(Definition) && Definition->isInlined() &&
3511         redeclForcesDefMSVC(this))
3512       return true;
3513   }
3514 
3515   if (Context.getLangOpts().CPlusPlus)
3516     return false;
3517 
3518   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3519     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3520     // an externally visible definition.
3521     //
3522     // FIXME: What happens if gnu_inline gets added on after the first
3523     // declaration?
3524     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3525       return false;
3526 
3527     const FunctionDecl *Prev = this;
3528     bool FoundBody = false;
3529     while ((Prev = Prev->getPreviousDecl())) {
3530       FoundBody |= Prev->doesThisDeclarationHaveABody();
3531 
3532       if (Prev->doesThisDeclarationHaveABody()) {
3533         // If it's not the case that both 'inline' and 'extern' are
3534         // specified on the definition, then it is always externally visible.
3535         if (!Prev->isInlineSpecified() ||
3536             Prev->getStorageClass() != SC_Extern)
3537           return false;
3538       } else if (Prev->isInlineSpecified() &&
3539                  Prev->getStorageClass() != SC_Extern) {
3540         return false;
3541       }
3542     }
3543     return FoundBody;
3544   }
3545 
3546   // C99 6.7.4p6:
3547   //   [...] If all of the file scope declarations for a function in a
3548   //   translation unit include the inline function specifier without extern,
3549   //   then the definition in that translation unit is an inline definition.
3550   if (isInlineSpecified() && getStorageClass() != SC_Extern)
3551     return false;
3552   const FunctionDecl *Prev = this;
3553   bool FoundBody = false;
3554   while ((Prev = Prev->getPreviousDecl())) {
3555     FoundBody |= Prev->doesThisDeclarationHaveABody();
3556     if (RedeclForcesDefC99(Prev))
3557       return false;
3558   }
3559   return FoundBody;
3560 }
3561 
3562 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3563   const TypeSourceInfo *TSI = getTypeSourceInfo();
3564   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3565              : FunctionTypeLoc();
3566 }
3567 
3568 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3569   FunctionTypeLoc FTL = getFunctionTypeLoc();
3570   if (!FTL)
3571     return SourceRange();
3572 
3573   // Skip self-referential return types.
3574   const SourceManager &SM = getASTContext().getSourceManager();
3575   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3576   SourceLocation Boundary = getNameInfo().getBeginLoc();
3577   if (RTRange.isInvalid() || Boundary.isInvalid() ||
3578       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3579     return SourceRange();
3580 
3581   return RTRange;
3582 }
3583 
3584 SourceRange FunctionDecl::getParametersSourceRange() const {
3585   unsigned NP = getNumParams();
3586   SourceLocation EllipsisLoc = getEllipsisLoc();
3587 
3588   if (NP == 0 && EllipsisLoc.isInvalid())
3589     return SourceRange();
3590 
3591   SourceLocation Begin =
3592       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3593   SourceLocation End = EllipsisLoc.isValid()
3594                            ? EllipsisLoc
3595                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3596 
3597   return SourceRange(Begin, End);
3598 }
3599 
3600 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3601   FunctionTypeLoc FTL = getFunctionTypeLoc();
3602   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3603 }
3604 
3605 /// For an inline function definition in C, or for a gnu_inline function
3606 /// in C++, determine whether the definition will be externally visible.
3607 ///
3608 /// Inline function definitions are always available for inlining optimizations.
3609 /// However, depending on the language dialect, declaration specifiers, and
3610 /// attributes, the definition of an inline function may or may not be
3611 /// "externally" visible to other translation units in the program.
3612 ///
3613 /// In C99, inline definitions are not externally visible by default. However,
3614 /// if even one of the global-scope declarations is marked "extern inline", the
3615 /// inline definition becomes externally visible (C99 6.7.4p6).
3616 ///
3617 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3618 /// definition, we use the GNU semantics for inline, which are nearly the
3619 /// opposite of C99 semantics. In particular, "inline" by itself will create
3620 /// an externally visible symbol, but "extern inline" will not create an
3621 /// externally visible symbol.
3622 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3623   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3624           hasAttr<AliasAttr>()) &&
3625          "Must be a function definition");
3626   assert(isInlined() && "Function must be inline");
3627   ASTContext &Context = getASTContext();
3628 
3629   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3630     // Note: If you change the logic here, please change
3631     // doesDeclarationForceExternallyVisibleDefinition as well.
3632     //
3633     // If it's not the case that both 'inline' and 'extern' are
3634     // specified on the definition, then this inline definition is
3635     // externally visible.
3636     if (Context.getLangOpts().CPlusPlus)
3637       return false;
3638     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3639       return true;
3640 
3641     // If any declaration is 'inline' but not 'extern', then this definition
3642     // is externally visible.
3643     for (auto Redecl : redecls()) {
3644       if (Redecl->isInlineSpecified() &&
3645           Redecl->getStorageClass() != SC_Extern)
3646         return true;
3647     }
3648 
3649     return false;
3650   }
3651 
3652   // The rest of this function is C-only.
3653   assert(!Context.getLangOpts().CPlusPlus &&
3654          "should not use C inline rules in C++");
3655 
3656   // C99 6.7.4p6:
3657   //   [...] If all of the file scope declarations for a function in a
3658   //   translation unit include the inline function specifier without extern,
3659   //   then the definition in that translation unit is an inline definition.
3660   for (auto Redecl : redecls()) {
3661     if (RedeclForcesDefC99(Redecl))
3662       return true;
3663   }
3664 
3665   // C99 6.7.4p6:
3666   //   An inline definition does not provide an external definition for the
3667   //   function, and does not forbid an external definition in another
3668   //   translation unit.
3669   return false;
3670 }
3671 
3672 /// getOverloadedOperator - Which C++ overloaded operator this
3673 /// function represents, if any.
3674 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3675   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3676     return getDeclName().getCXXOverloadedOperator();
3677   return OO_None;
3678 }
3679 
3680 /// getLiteralIdentifier - The literal suffix identifier this function
3681 /// represents, if any.
3682 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3683   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3684     return getDeclName().getCXXLiteralIdentifier();
3685   return nullptr;
3686 }
3687 
3688 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3689   if (TemplateOrSpecialization.isNull())
3690     return TK_NonTemplate;
3691   if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3692     return TK_FunctionTemplate;
3693   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3694     return TK_MemberSpecialization;
3695   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3696     return TK_FunctionTemplateSpecialization;
3697   if (TemplateOrSpecialization.is
3698                                <DependentFunctionTemplateSpecializationInfo*>())
3699     return TK_DependentFunctionTemplateSpecialization;
3700 
3701   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3702 }
3703 
3704 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3705   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3706     return cast<FunctionDecl>(Info->getInstantiatedFrom());
3707 
3708   return nullptr;
3709 }
3710 
3711 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3712   if (auto *MSI =
3713           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3714     return MSI;
3715   if (auto *FTSI = TemplateOrSpecialization
3716                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
3717     return FTSI->getMemberSpecializationInfo();
3718   return nullptr;
3719 }
3720 
3721 void
3722 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3723                                                FunctionDecl *FD,
3724                                                TemplateSpecializationKind TSK) {
3725   assert(TemplateOrSpecialization.isNull() &&
3726          "Member function is already a specialization");
3727   MemberSpecializationInfo *Info
3728     = new (C) MemberSpecializationInfo(FD, TSK);
3729   TemplateOrSpecialization = Info;
3730 }
3731 
3732 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3733   return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3734 }
3735 
3736 void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3737   assert(TemplateOrSpecialization.isNull() &&
3738          "Member function is already a specialization");
3739   TemplateOrSpecialization = Template;
3740 }
3741 
3742 bool FunctionDecl::isImplicitlyInstantiable() const {
3743   // If the function is invalid, it can't be implicitly instantiated.
3744   if (isInvalidDecl())
3745     return false;
3746 
3747   switch (getTemplateSpecializationKindForInstantiation()) {
3748   case TSK_Undeclared:
3749   case TSK_ExplicitInstantiationDefinition:
3750   case TSK_ExplicitSpecialization:
3751     return false;
3752 
3753   case TSK_ImplicitInstantiation:
3754     return true;
3755 
3756   case TSK_ExplicitInstantiationDeclaration:
3757     // Handled below.
3758     break;
3759   }
3760 
3761   // Find the actual template from which we will instantiate.
3762   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3763   bool HasPattern = false;
3764   if (PatternDecl)
3765     HasPattern = PatternDecl->hasBody(PatternDecl);
3766 
3767   // C++0x [temp.explicit]p9:
3768   //   Except for inline functions, other explicit instantiation declarations
3769   //   have the effect of suppressing the implicit instantiation of the entity
3770   //   to which they refer.
3771   if (!HasPattern || !PatternDecl)
3772     return true;
3773 
3774   return PatternDecl->isInlined();
3775 }
3776 
3777 bool FunctionDecl::isTemplateInstantiation() const {
3778   // FIXME: Remove this, it's not clear what it means. (Which template
3779   // specialization kind?)
3780   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3781 }
3782 
3783 FunctionDecl *
3784 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3785   // If this is a generic lambda call operator specialization, its
3786   // instantiation pattern is always its primary template's pattern
3787   // even if its primary template was instantiated from another
3788   // member template (which happens with nested generic lambdas).
3789   // Since a lambda's call operator's body is transformed eagerly,
3790   // we don't have to go hunting for a prototype definition template
3791   // (i.e. instantiated-from-member-template) to use as an instantiation
3792   // pattern.
3793 
3794   if (isGenericLambdaCallOperatorSpecialization(
3795           dyn_cast<CXXMethodDecl>(this))) {
3796     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3797     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3798   }
3799 
3800   // Check for a declaration of this function that was instantiated from a
3801   // friend definition.
3802   const FunctionDecl *FD = nullptr;
3803   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3804     FD = this;
3805 
3806   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3807     if (ForDefinition &&
3808         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3809       return nullptr;
3810     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3811   }
3812 
3813   if (ForDefinition &&
3814       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3815     return nullptr;
3816 
3817   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3818     // If we hit a point where the user provided a specialization of this
3819     // template, we're done looking.
3820     while (!ForDefinition || !Primary->isMemberSpecialization()) {
3821       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3822       if (!NewPrimary)
3823         break;
3824       Primary = NewPrimary;
3825     }
3826 
3827     return getDefinitionOrSelf(Primary->getTemplatedDecl());
3828   }
3829 
3830   return nullptr;
3831 }
3832 
3833 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3834   if (FunctionTemplateSpecializationInfo *Info
3835         = TemplateOrSpecialization
3836             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3837     return Info->getTemplate();
3838   }
3839   return nullptr;
3840 }
3841 
3842 FunctionTemplateSpecializationInfo *
3843 FunctionDecl::getTemplateSpecializationInfo() const {
3844   return TemplateOrSpecialization
3845       .dyn_cast<FunctionTemplateSpecializationInfo *>();
3846 }
3847 
3848 const TemplateArgumentList *
3849 FunctionDecl::getTemplateSpecializationArgs() const {
3850   if (FunctionTemplateSpecializationInfo *Info
3851         = TemplateOrSpecialization
3852             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3853     return Info->TemplateArguments;
3854   }
3855   return nullptr;
3856 }
3857 
3858 const ASTTemplateArgumentListInfo *
3859 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3860   if (FunctionTemplateSpecializationInfo *Info
3861         = TemplateOrSpecialization
3862             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3863     return Info->TemplateArgumentsAsWritten;
3864   }
3865   return nullptr;
3866 }
3867 
3868 void
3869 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3870                                                 FunctionTemplateDecl *Template,
3871                                      const TemplateArgumentList *TemplateArgs,
3872                                                 void *InsertPos,
3873                                                 TemplateSpecializationKind TSK,
3874                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
3875                                           SourceLocation PointOfInstantiation) {
3876   assert((TemplateOrSpecialization.isNull() ||
3877           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3878          "Member function is already a specialization");
3879   assert(TSK != TSK_Undeclared &&
3880          "Must specify the type of function template specialization");
3881   assert((TemplateOrSpecialization.isNull() ||
3882           TSK == TSK_ExplicitSpecialization) &&
3883          "Member specialization must be an explicit specialization");
3884   FunctionTemplateSpecializationInfo *Info =
3885       FunctionTemplateSpecializationInfo::Create(
3886           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3887           PointOfInstantiation,
3888           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3889   TemplateOrSpecialization = Info;
3890   Template->addSpecialization(Info, InsertPos);
3891 }
3892 
3893 void
3894 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3895                                     const UnresolvedSetImpl &Templates,
3896                              const TemplateArgumentListInfo &TemplateArgs) {
3897   assert(TemplateOrSpecialization.isNull());
3898   DependentFunctionTemplateSpecializationInfo *Info =
3899       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3900                                                           TemplateArgs);
3901   TemplateOrSpecialization = Info;
3902 }
3903 
3904 DependentFunctionTemplateSpecializationInfo *
3905 FunctionDecl::getDependentSpecializationInfo() const {
3906   return TemplateOrSpecialization
3907       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3908 }
3909 
3910 DependentFunctionTemplateSpecializationInfo *
3911 DependentFunctionTemplateSpecializationInfo::Create(
3912     ASTContext &Context, const UnresolvedSetImpl &Ts,
3913     const TemplateArgumentListInfo &TArgs) {
3914   void *Buffer = Context.Allocate(
3915       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3916           TArgs.size(), Ts.size()));
3917   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3918 }
3919 
3920 DependentFunctionTemplateSpecializationInfo::
3921 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3922                                       const TemplateArgumentListInfo &TArgs)
3923   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3924   NumTemplates = Ts.size();
3925   NumArgs = TArgs.size();
3926 
3927   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3928   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
3929     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3930 
3931   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
3932   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
3933     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
3934 }
3935 
3936 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3937   // For a function template specialization, query the specialization
3938   // information object.
3939   if (FunctionTemplateSpecializationInfo *FTSInfo =
3940           TemplateOrSpecialization
3941               .dyn_cast<FunctionTemplateSpecializationInfo *>())
3942     return FTSInfo->getTemplateSpecializationKind();
3943 
3944   if (MemberSpecializationInfo *MSInfo =
3945           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3946     return MSInfo->getTemplateSpecializationKind();
3947 
3948   return TSK_Undeclared;
3949 }
3950 
3951 TemplateSpecializationKind
3952 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3953   // This is the same as getTemplateSpecializationKind(), except that for a
3954   // function that is both a function template specialization and a member
3955   // specialization, we prefer the member specialization information. Eg:
3956   //
3957   // template<typename T> struct A {
3958   //   template<typename U> void f() {}
3959   //   template<> void f<int>() {}
3960   // };
3961   //
3962   // For A<int>::f<int>():
3963   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3964   // * getTemplateSpecializationKindForInstantiation() will return
3965   //       TSK_ImplicitInstantiation
3966   //
3967   // This reflects the facts that A<int>::f<int> is an explicit specialization
3968   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3969   // from A::f<int> if a definition is needed.
3970   if (FunctionTemplateSpecializationInfo *FTSInfo =
3971           TemplateOrSpecialization
3972               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3973     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3974       return MSInfo->getTemplateSpecializationKind();
3975     return FTSInfo->getTemplateSpecializationKind();
3976   }
3977 
3978   if (MemberSpecializationInfo *MSInfo =
3979           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3980     return MSInfo->getTemplateSpecializationKind();
3981 
3982   return TSK_Undeclared;
3983 }
3984 
3985 void
3986 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3987                                           SourceLocation PointOfInstantiation) {
3988   if (FunctionTemplateSpecializationInfo *FTSInfo
3989         = TemplateOrSpecialization.dyn_cast<
3990                                     FunctionTemplateSpecializationInfo*>()) {
3991     FTSInfo->setTemplateSpecializationKind(TSK);
3992     if (TSK != TSK_ExplicitSpecialization &&
3993         PointOfInstantiation.isValid() &&
3994         FTSInfo->getPointOfInstantiation().isInvalid()) {
3995       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3996       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3997         L->InstantiationRequested(this);
3998     }
3999   } else if (MemberSpecializationInfo *MSInfo
4000              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4001     MSInfo->setTemplateSpecializationKind(TSK);
4002     if (TSK != TSK_ExplicitSpecialization &&
4003         PointOfInstantiation.isValid() &&
4004         MSInfo->getPointOfInstantiation().isInvalid()) {
4005       MSInfo->setPointOfInstantiation(PointOfInstantiation);
4006       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4007         L->InstantiationRequested(this);
4008     }
4009   } else
4010     llvm_unreachable("Function cannot have a template specialization kind");
4011 }
4012 
4013 SourceLocation FunctionDecl::getPointOfInstantiation() const {
4014   if (FunctionTemplateSpecializationInfo *FTSInfo
4015         = TemplateOrSpecialization.dyn_cast<
4016                                         FunctionTemplateSpecializationInfo*>())
4017     return FTSInfo->getPointOfInstantiation();
4018   if (MemberSpecializationInfo *MSInfo =
4019           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4020     return MSInfo->getPointOfInstantiation();
4021 
4022   return SourceLocation();
4023 }
4024 
4025 bool FunctionDecl::isOutOfLine() const {
4026   if (Decl::isOutOfLine())
4027     return true;
4028 
4029   // If this function was instantiated from a member function of a
4030   // class template, check whether that member function was defined out-of-line.
4031   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4032     const FunctionDecl *Definition;
4033     if (FD->hasBody(Definition))
4034       return Definition->isOutOfLine();
4035   }
4036 
4037   // If this function was instantiated from a function template,
4038   // check whether that function template was defined out-of-line.
4039   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4040     const FunctionDecl *Definition;
4041     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4042       return Definition->isOutOfLine();
4043   }
4044 
4045   return false;
4046 }
4047 
4048 SourceRange FunctionDecl::getSourceRange() const {
4049   return SourceRange(getOuterLocStart(), EndRangeLoc);
4050 }
4051 
4052 unsigned FunctionDecl::getMemoryFunctionKind() const {
4053   IdentifierInfo *FnInfo = getIdentifier();
4054 
4055   if (!FnInfo)
4056     return 0;
4057 
4058   // Builtin handling.
4059   switch (getBuiltinID()) {
4060   case Builtin::BI__builtin_memset:
4061   case Builtin::BI__builtin___memset_chk:
4062   case Builtin::BImemset:
4063     return Builtin::BImemset;
4064 
4065   case Builtin::BI__builtin_memcpy:
4066   case Builtin::BI__builtin___memcpy_chk:
4067   case Builtin::BImemcpy:
4068     return Builtin::BImemcpy;
4069 
4070   case Builtin::BI__builtin_mempcpy:
4071   case Builtin::BI__builtin___mempcpy_chk:
4072   case Builtin::BImempcpy:
4073     return Builtin::BImempcpy;
4074 
4075   case Builtin::BI__builtin_memmove:
4076   case Builtin::BI__builtin___memmove_chk:
4077   case Builtin::BImemmove:
4078     return Builtin::BImemmove;
4079 
4080   case Builtin::BIstrlcpy:
4081   case Builtin::BI__builtin___strlcpy_chk:
4082     return Builtin::BIstrlcpy;
4083 
4084   case Builtin::BIstrlcat:
4085   case Builtin::BI__builtin___strlcat_chk:
4086     return Builtin::BIstrlcat;
4087 
4088   case Builtin::BI__builtin_memcmp:
4089   case Builtin::BImemcmp:
4090     return Builtin::BImemcmp;
4091 
4092   case Builtin::BI__builtin_bcmp:
4093   case Builtin::BIbcmp:
4094     return Builtin::BIbcmp;
4095 
4096   case Builtin::BI__builtin_strncpy:
4097   case Builtin::BI__builtin___strncpy_chk:
4098   case Builtin::BIstrncpy:
4099     return Builtin::BIstrncpy;
4100 
4101   case Builtin::BI__builtin_strncmp:
4102   case Builtin::BIstrncmp:
4103     return Builtin::BIstrncmp;
4104 
4105   case Builtin::BI__builtin_strncasecmp:
4106   case Builtin::BIstrncasecmp:
4107     return Builtin::BIstrncasecmp;
4108 
4109   case Builtin::BI__builtin_strncat:
4110   case Builtin::BI__builtin___strncat_chk:
4111   case Builtin::BIstrncat:
4112     return Builtin::BIstrncat;
4113 
4114   case Builtin::BI__builtin_strndup:
4115   case Builtin::BIstrndup:
4116     return Builtin::BIstrndup;
4117 
4118   case Builtin::BI__builtin_strlen:
4119   case Builtin::BIstrlen:
4120     return Builtin::BIstrlen;
4121 
4122   case Builtin::BI__builtin_bzero:
4123   case Builtin::BIbzero:
4124     return Builtin::BIbzero;
4125 
4126   case Builtin::BIfree:
4127     return Builtin::BIfree;
4128 
4129   default:
4130     if (isExternC()) {
4131       if (FnInfo->isStr("memset"))
4132         return Builtin::BImemset;
4133       if (FnInfo->isStr("memcpy"))
4134         return Builtin::BImemcpy;
4135       if (FnInfo->isStr("mempcpy"))
4136         return Builtin::BImempcpy;
4137       if (FnInfo->isStr("memmove"))
4138         return Builtin::BImemmove;
4139       if (FnInfo->isStr("memcmp"))
4140         return Builtin::BImemcmp;
4141       if (FnInfo->isStr("bcmp"))
4142         return Builtin::BIbcmp;
4143       if (FnInfo->isStr("strncpy"))
4144         return Builtin::BIstrncpy;
4145       if (FnInfo->isStr("strncmp"))
4146         return Builtin::BIstrncmp;
4147       if (FnInfo->isStr("strncasecmp"))
4148         return Builtin::BIstrncasecmp;
4149       if (FnInfo->isStr("strncat"))
4150         return Builtin::BIstrncat;
4151       if (FnInfo->isStr("strndup"))
4152         return Builtin::BIstrndup;
4153       if (FnInfo->isStr("strlen"))
4154         return Builtin::BIstrlen;
4155       if (FnInfo->isStr("bzero"))
4156         return Builtin::BIbzero;
4157     } else if (isInStdNamespace()) {
4158       if (FnInfo->isStr("free"))
4159         return Builtin::BIfree;
4160     }
4161     break;
4162   }
4163   return 0;
4164 }
4165 
4166 unsigned FunctionDecl::getODRHash() const {
4167   assert(hasODRHash());
4168   return ODRHash;
4169 }
4170 
4171 unsigned FunctionDecl::getODRHash() {
4172   if (hasODRHash())
4173     return ODRHash;
4174 
4175   if (auto *FT = getInstantiatedFromMemberFunction()) {
4176     setHasODRHash(true);
4177     ODRHash = FT->getODRHash();
4178     return ODRHash;
4179   }
4180 
4181   class ODRHash Hash;
4182   Hash.AddFunctionDecl(this);
4183   setHasODRHash(true);
4184   ODRHash = Hash.CalculateHash();
4185   return ODRHash;
4186 }
4187 
4188 //===----------------------------------------------------------------------===//
4189 // FieldDecl Implementation
4190 //===----------------------------------------------------------------------===//
4191 
4192 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4193                              SourceLocation StartLoc, SourceLocation IdLoc,
4194                              IdentifierInfo *Id, QualType T,
4195                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4196                              InClassInitStyle InitStyle) {
4197   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4198                                BW, Mutable, InitStyle);
4199 }
4200 
4201 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4202   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4203                                SourceLocation(), nullptr, QualType(), nullptr,
4204                                nullptr, false, ICIS_NoInit);
4205 }
4206 
4207 bool FieldDecl::isAnonymousStructOrUnion() const {
4208   if (!isImplicit() || getDeclName())
4209     return false;
4210 
4211   if (const auto *Record = getType()->getAs<RecordType>())
4212     return Record->getDecl()->isAnonymousStructOrUnion();
4213 
4214   return false;
4215 }
4216 
4217 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4218   assert(isBitField() && "not a bitfield");
4219   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4220 }
4221 
4222 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4223   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4224          getBitWidthValue(Ctx) == 0;
4225 }
4226 
4227 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4228   if (isZeroLengthBitField(Ctx))
4229     return true;
4230 
4231   // C++2a [intro.object]p7:
4232   //   An object has nonzero size if it
4233   //     -- is not a potentially-overlapping subobject, or
4234   if (!hasAttr<NoUniqueAddressAttr>())
4235     return false;
4236 
4237   //     -- is not of class type, or
4238   const auto *RT = getType()->getAs<RecordType>();
4239   if (!RT)
4240     return false;
4241   const RecordDecl *RD = RT->getDecl()->getDefinition();
4242   if (!RD) {
4243     assert(isInvalidDecl() && "valid field has incomplete type");
4244     return false;
4245   }
4246 
4247   //     -- [has] virtual member functions or virtual base classes, or
4248   //     -- has subobjects of nonzero size or bit-fields of nonzero length
4249   const auto *CXXRD = cast<CXXRecordDecl>(RD);
4250   if (!CXXRD->isEmpty())
4251     return false;
4252 
4253   // Otherwise, [...] the circumstances under which the object has zero size
4254   // are implementation-defined.
4255   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4256   // ABI will do.
4257   return true;
4258 }
4259 
4260 unsigned FieldDecl::getFieldIndex() const {
4261   const FieldDecl *Canonical = getCanonicalDecl();
4262   if (Canonical != this)
4263     return Canonical->getFieldIndex();
4264 
4265   if (CachedFieldIndex) return CachedFieldIndex - 1;
4266 
4267   unsigned Index = 0;
4268   const RecordDecl *RD = getParent()->getDefinition();
4269   assert(RD && "requested index for field of struct with no definition");
4270 
4271   for (auto *Field : RD->fields()) {
4272     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4273     ++Index;
4274   }
4275 
4276   assert(CachedFieldIndex && "failed to find field in parent");
4277   return CachedFieldIndex - 1;
4278 }
4279 
4280 SourceRange FieldDecl::getSourceRange() const {
4281   const Expr *FinalExpr = getInClassInitializer();
4282   if (!FinalExpr)
4283     FinalExpr = getBitWidth();
4284   if (FinalExpr)
4285     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4286   return DeclaratorDecl::getSourceRange();
4287 }
4288 
4289 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4290   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4291          "capturing type in non-lambda or captured record.");
4292   assert(InitStorage.getInt() == ISK_NoInit &&
4293          InitStorage.getPointer() == nullptr &&
4294          "bit width, initializer or captured type already set");
4295   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4296                                ISK_CapturedVLAType);
4297 }
4298 
4299 //===----------------------------------------------------------------------===//
4300 // TagDecl Implementation
4301 //===----------------------------------------------------------------------===//
4302 
4303 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4304                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4305                  SourceLocation StartL)
4306     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4307       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4308   assert((DK != Enum || TK == TTK_Enum) &&
4309          "EnumDecl not matched with TTK_Enum");
4310   setPreviousDecl(PrevDecl);
4311   setTagKind(TK);
4312   setCompleteDefinition(false);
4313   setBeingDefined(false);
4314   setEmbeddedInDeclarator(false);
4315   setFreeStanding(false);
4316   setCompleteDefinitionRequired(false);
4317 }
4318 
4319 SourceLocation TagDecl::getOuterLocStart() const {
4320   return getTemplateOrInnerLocStart(this);
4321 }
4322 
4323 SourceRange TagDecl::getSourceRange() const {
4324   SourceLocation RBraceLoc = BraceRange.getEnd();
4325   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4326   return SourceRange(getOuterLocStart(), E);
4327 }
4328 
4329 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4330 
4331 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4332   TypedefNameDeclOrQualifier = TDD;
4333   if (const Type *T = getTypeForDecl()) {
4334     (void)T;
4335     assert(T->isLinkageValid());
4336   }
4337   assert(isLinkageValid());
4338 }
4339 
4340 void TagDecl::startDefinition() {
4341   setBeingDefined(true);
4342 
4343   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4344     struct CXXRecordDecl::DefinitionData *Data =
4345       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4346     for (auto I : redecls())
4347       cast<CXXRecordDecl>(I)->DefinitionData = Data;
4348   }
4349 }
4350 
4351 void TagDecl::completeDefinition() {
4352   assert((!isa<CXXRecordDecl>(this) ||
4353           cast<CXXRecordDecl>(this)->hasDefinition()) &&
4354          "definition completed but not started");
4355 
4356   setCompleteDefinition(true);
4357   setBeingDefined(false);
4358 
4359   if (ASTMutationListener *L = getASTMutationListener())
4360     L->CompletedTagDefinition(this);
4361 }
4362 
4363 TagDecl *TagDecl::getDefinition() const {
4364   if (isCompleteDefinition())
4365     return const_cast<TagDecl *>(this);
4366 
4367   // If it's possible for us to have an out-of-date definition, check now.
4368   if (mayHaveOutOfDateDef()) {
4369     if (IdentifierInfo *II = getIdentifier()) {
4370       if (II->isOutOfDate()) {
4371         updateOutOfDate(*II);
4372       }
4373     }
4374   }
4375 
4376   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4377     return CXXRD->getDefinition();
4378 
4379   for (auto R : redecls())
4380     if (R->isCompleteDefinition())
4381       return R;
4382 
4383   return nullptr;
4384 }
4385 
4386 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4387   if (QualifierLoc) {
4388     // Make sure the extended qualifier info is allocated.
4389     if (!hasExtInfo())
4390       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4391     // Set qualifier info.
4392     getExtInfo()->QualifierLoc = QualifierLoc;
4393   } else {
4394     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4395     if (hasExtInfo()) {
4396       if (getExtInfo()->NumTemplParamLists == 0) {
4397         getASTContext().Deallocate(getExtInfo());
4398         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4399       }
4400       else
4401         getExtInfo()->QualifierLoc = QualifierLoc;
4402     }
4403   }
4404 }
4405 
4406 void TagDecl::setTemplateParameterListsInfo(
4407     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4408   assert(!TPLists.empty());
4409   // Make sure the extended decl info is allocated.
4410   if (!hasExtInfo())
4411     // Allocate external info struct.
4412     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4413   // Set the template parameter lists info.
4414   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4415 }
4416 
4417 //===----------------------------------------------------------------------===//
4418 // EnumDecl Implementation
4419 //===----------------------------------------------------------------------===//
4420 
4421 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4422                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4423                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4424     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4425   assert(Scoped || !ScopedUsingClassTag);
4426   IntegerType = nullptr;
4427   setNumPositiveBits(0);
4428   setNumNegativeBits(0);
4429   setScoped(Scoped);
4430   setScopedUsingClassTag(ScopedUsingClassTag);
4431   setFixed(Fixed);
4432   setHasODRHash(false);
4433   ODRHash = 0;
4434 }
4435 
4436 void EnumDecl::anchor() {}
4437 
4438 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4439                            SourceLocation StartLoc, SourceLocation IdLoc,
4440                            IdentifierInfo *Id,
4441                            EnumDecl *PrevDecl, bool IsScoped,
4442                            bool IsScopedUsingClassTag, bool IsFixed) {
4443   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4444                                     IsScoped, IsScopedUsingClassTag, IsFixed);
4445   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4446   C.getTypeDeclType(Enum, PrevDecl);
4447   return Enum;
4448 }
4449 
4450 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4451   EnumDecl *Enum =
4452       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4453                            nullptr, nullptr, false, false, false);
4454   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4455   return Enum;
4456 }
4457 
4458 SourceRange EnumDecl::getIntegerTypeRange() const {
4459   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4460     return TI->getTypeLoc().getSourceRange();
4461   return SourceRange();
4462 }
4463 
4464 void EnumDecl::completeDefinition(QualType NewType,
4465                                   QualType NewPromotionType,
4466                                   unsigned NumPositiveBits,
4467                                   unsigned NumNegativeBits) {
4468   assert(!isCompleteDefinition() && "Cannot redefine enums!");
4469   if (!IntegerType)
4470     IntegerType = NewType.getTypePtr();
4471   PromotionType = NewPromotionType;
4472   setNumPositiveBits(NumPositiveBits);
4473   setNumNegativeBits(NumNegativeBits);
4474   TagDecl::completeDefinition();
4475 }
4476 
4477 bool EnumDecl::isClosed() const {
4478   if (const auto *A = getAttr<EnumExtensibilityAttr>())
4479     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4480   return true;
4481 }
4482 
4483 bool EnumDecl::isClosedFlag() const {
4484   return isClosed() && hasAttr<FlagEnumAttr>();
4485 }
4486 
4487 bool EnumDecl::isClosedNonFlag() const {
4488   return isClosed() && !hasAttr<FlagEnumAttr>();
4489 }
4490 
4491 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4492   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4493     return MSI->getTemplateSpecializationKind();
4494 
4495   return TSK_Undeclared;
4496 }
4497 
4498 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4499                                          SourceLocation PointOfInstantiation) {
4500   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4501   assert(MSI && "Not an instantiated member enumeration?");
4502   MSI->setTemplateSpecializationKind(TSK);
4503   if (TSK != TSK_ExplicitSpecialization &&
4504       PointOfInstantiation.isValid() &&
4505       MSI->getPointOfInstantiation().isInvalid())
4506     MSI->setPointOfInstantiation(PointOfInstantiation);
4507 }
4508 
4509 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4510   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4511     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4512       EnumDecl *ED = getInstantiatedFromMemberEnum();
4513       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4514         ED = NewED;
4515       return getDefinitionOrSelf(ED);
4516     }
4517   }
4518 
4519   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4520          "couldn't find pattern for enum instantiation");
4521   return nullptr;
4522 }
4523 
4524 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4525   if (SpecializationInfo)
4526     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4527 
4528   return nullptr;
4529 }
4530 
4531 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4532                                             TemplateSpecializationKind TSK) {
4533   assert(!SpecializationInfo && "Member enum is already a specialization");
4534   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4535 }
4536 
4537 unsigned EnumDecl::getODRHash() {
4538   if (hasODRHash())
4539     return ODRHash;
4540 
4541   class ODRHash Hash;
4542   Hash.AddEnumDecl(this);
4543   setHasODRHash(true);
4544   ODRHash = Hash.CalculateHash();
4545   return ODRHash;
4546 }
4547 
4548 SourceRange EnumDecl::getSourceRange() const {
4549   auto Res = TagDecl::getSourceRange();
4550   // Set end-point to enum-base, e.g. enum foo : ^bar
4551   if (auto *TSI = getIntegerTypeSourceInfo()) {
4552     // TagDecl doesn't know about the enum base.
4553     if (!getBraceRange().getEnd().isValid())
4554       Res.setEnd(TSI->getTypeLoc().getEndLoc());
4555   }
4556   return Res;
4557 }
4558 
4559 //===----------------------------------------------------------------------===//
4560 // RecordDecl Implementation
4561 //===----------------------------------------------------------------------===//
4562 
4563 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4564                        DeclContext *DC, SourceLocation StartLoc,
4565                        SourceLocation IdLoc, IdentifierInfo *Id,
4566                        RecordDecl *PrevDecl)
4567     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4568   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4569   setHasFlexibleArrayMember(false);
4570   setAnonymousStructOrUnion(false);
4571   setHasObjectMember(false);
4572   setHasVolatileMember(false);
4573   setHasLoadedFieldsFromExternalStorage(false);
4574   setNonTrivialToPrimitiveDefaultInitialize(false);
4575   setNonTrivialToPrimitiveCopy(false);
4576   setNonTrivialToPrimitiveDestroy(false);
4577   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4578   setHasNonTrivialToPrimitiveDestructCUnion(false);
4579   setHasNonTrivialToPrimitiveCopyCUnion(false);
4580   setParamDestroyedInCallee(false);
4581   setArgPassingRestrictions(APK_CanPassInRegs);
4582 }
4583 
4584 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4585                                SourceLocation StartLoc, SourceLocation IdLoc,
4586                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
4587   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4588                                          StartLoc, IdLoc, Id, PrevDecl);
4589   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4590 
4591   C.getTypeDeclType(R, PrevDecl);
4592   return R;
4593 }
4594 
4595 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4596   RecordDecl *R =
4597       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4598                              SourceLocation(), nullptr, nullptr);
4599   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4600   return R;
4601 }
4602 
4603 bool RecordDecl::isInjectedClassName() const {
4604   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4605     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4606 }
4607 
4608 bool RecordDecl::isLambda() const {
4609   if (auto RD = dyn_cast<CXXRecordDecl>(this))
4610     return RD->isLambda();
4611   return false;
4612 }
4613 
4614 bool RecordDecl::isCapturedRecord() const {
4615   return hasAttr<CapturedRecordAttr>();
4616 }
4617 
4618 void RecordDecl::setCapturedRecord() {
4619   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4620 }
4621 
4622 bool RecordDecl::isOrContainsUnion() const {
4623   if (isUnion())
4624     return true;
4625 
4626   if (const RecordDecl *Def = getDefinition()) {
4627     for (const FieldDecl *FD : Def->fields()) {
4628       const RecordType *RT = FD->getType()->getAs<RecordType>();
4629       if (RT && RT->getDecl()->isOrContainsUnion())
4630         return true;
4631     }
4632   }
4633 
4634   return false;
4635 }
4636 
4637 RecordDecl::field_iterator RecordDecl::field_begin() const {
4638   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4639     LoadFieldsFromExternalStorage();
4640 
4641   return field_iterator(decl_iterator(FirstDecl));
4642 }
4643 
4644 /// completeDefinition - Notes that the definition of this type is now
4645 /// complete.
4646 void RecordDecl::completeDefinition() {
4647   assert(!isCompleteDefinition() && "Cannot redefine record!");
4648   TagDecl::completeDefinition();
4649 
4650   ASTContext &Ctx = getASTContext();
4651 
4652   // Layouts are dumped when computed, so if we are dumping for all complete
4653   // types, we need to force usage to get types that wouldn't be used elsewhere.
4654   if (Ctx.getLangOpts().DumpRecordLayoutsComplete)
4655     (void)Ctx.getASTRecordLayout(this);
4656 }
4657 
4658 /// isMsStruct - Get whether or not this record uses ms_struct layout.
4659 /// This which can be turned on with an attribute, pragma, or the
4660 /// -mms-bitfields command-line option.
4661 bool RecordDecl::isMsStruct(const ASTContext &C) const {
4662   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4663 }
4664 
4665 void RecordDecl::LoadFieldsFromExternalStorage() const {
4666   ExternalASTSource *Source = getASTContext().getExternalSource();
4667   assert(hasExternalLexicalStorage() && Source && "No external storage?");
4668 
4669   // Notify that we have a RecordDecl doing some initialization.
4670   ExternalASTSource::Deserializing TheFields(Source);
4671 
4672   SmallVector<Decl*, 64> Decls;
4673   setHasLoadedFieldsFromExternalStorage(true);
4674   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4675     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4676   }, Decls);
4677 
4678 #ifndef NDEBUG
4679   // Check that all decls we got were FieldDecls.
4680   for (unsigned i=0, e=Decls.size(); i != e; ++i)
4681     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4682 #endif
4683 
4684   if (Decls.empty())
4685     return;
4686 
4687   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4688                                                  /*FieldsAlreadyLoaded=*/false);
4689 }
4690 
4691 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4692   ASTContext &Context = getASTContext();
4693   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4694       (SanitizerKind::Address | SanitizerKind::KernelAddress);
4695   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4696     return false;
4697   const auto &NoSanitizeList = Context.getNoSanitizeList();
4698   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4699   // We may be able to relax some of these requirements.
4700   int ReasonToReject = -1;
4701   if (!CXXRD || CXXRD->isExternCContext())
4702     ReasonToReject = 0;  // is not C++.
4703   else if (CXXRD->hasAttr<PackedAttr>())
4704     ReasonToReject = 1;  // is packed.
4705   else if (CXXRD->isUnion())
4706     ReasonToReject = 2;  // is a union.
4707   else if (CXXRD->isTriviallyCopyable())
4708     ReasonToReject = 3;  // is trivially copyable.
4709   else if (CXXRD->hasTrivialDestructor())
4710     ReasonToReject = 4;  // has trivial destructor.
4711   else if (CXXRD->isStandardLayout())
4712     ReasonToReject = 5;  // is standard layout.
4713   else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
4714                                            "field-padding"))
4715     ReasonToReject = 6;  // is in an excluded file.
4716   else if (NoSanitizeList.containsType(
4717                EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4718     ReasonToReject = 7;  // The type is excluded.
4719 
4720   if (EmitRemark) {
4721     if (ReasonToReject >= 0)
4722       Context.getDiagnostics().Report(
4723           getLocation(),
4724           diag::remark_sanitize_address_insert_extra_padding_rejected)
4725           << getQualifiedNameAsString() << ReasonToReject;
4726     else
4727       Context.getDiagnostics().Report(
4728           getLocation(),
4729           diag::remark_sanitize_address_insert_extra_padding_accepted)
4730           << getQualifiedNameAsString();
4731   }
4732   return ReasonToReject < 0;
4733 }
4734 
4735 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4736   for (const auto *I : fields()) {
4737     if (I->getIdentifier())
4738       return I;
4739 
4740     if (const auto *RT = I->getType()->getAs<RecordType>())
4741       if (const FieldDecl *NamedDataMember =
4742               RT->getDecl()->findFirstNamedDataMember())
4743         return NamedDataMember;
4744   }
4745 
4746   // We didn't find a named data member.
4747   return nullptr;
4748 }
4749 
4750 //===----------------------------------------------------------------------===//
4751 // BlockDecl Implementation
4752 //===----------------------------------------------------------------------===//
4753 
4754 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4755     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4756   setIsVariadic(false);
4757   setCapturesCXXThis(false);
4758   setBlockMissingReturnType(true);
4759   setIsConversionFromLambda(false);
4760   setDoesNotEscape(false);
4761   setCanAvoidCopyToHeap(false);
4762 }
4763 
4764 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4765   assert(!ParamInfo && "Already has param info!");
4766 
4767   // Zero params -> null pointer.
4768   if (!NewParamInfo.empty()) {
4769     NumParams = NewParamInfo.size();
4770     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4771     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4772   }
4773 }
4774 
4775 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4776                             bool CapturesCXXThis) {
4777   this->setCapturesCXXThis(CapturesCXXThis);
4778   this->NumCaptures = Captures.size();
4779 
4780   if (Captures.empty()) {
4781     this->Captures = nullptr;
4782     return;
4783   }
4784 
4785   this->Captures = Captures.copy(Context).data();
4786 }
4787 
4788 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4789   for (const auto &I : captures())
4790     // Only auto vars can be captured, so no redeclaration worries.
4791     if (I.getVariable() == variable)
4792       return true;
4793 
4794   return false;
4795 }
4796 
4797 SourceRange BlockDecl::getSourceRange() const {
4798   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4799 }
4800 
4801 //===----------------------------------------------------------------------===//
4802 // Other Decl Allocation/Deallocation Method Implementations
4803 //===----------------------------------------------------------------------===//
4804 
4805 void TranslationUnitDecl::anchor() {}
4806 
4807 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4808   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4809 }
4810 
4811 void PragmaCommentDecl::anchor() {}
4812 
4813 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4814                                              TranslationUnitDecl *DC,
4815                                              SourceLocation CommentLoc,
4816                                              PragmaMSCommentKind CommentKind,
4817                                              StringRef Arg) {
4818   PragmaCommentDecl *PCD =
4819       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4820           PragmaCommentDecl(DC, CommentLoc, CommentKind);
4821   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4822   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4823   return PCD;
4824 }
4825 
4826 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4827                                                          unsigned ID,
4828                                                          unsigned ArgSize) {
4829   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4830       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4831 }
4832 
4833 void PragmaDetectMismatchDecl::anchor() {}
4834 
4835 PragmaDetectMismatchDecl *
4836 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4837                                  SourceLocation Loc, StringRef Name,
4838                                  StringRef Value) {
4839   size_t ValueStart = Name.size() + 1;
4840   PragmaDetectMismatchDecl *PDMD =
4841       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4842           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4843   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4844   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4845   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4846          Value.size());
4847   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4848   return PDMD;
4849 }
4850 
4851 PragmaDetectMismatchDecl *
4852 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4853                                              unsigned NameValueSize) {
4854   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4855       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4856 }
4857 
4858 void ExternCContextDecl::anchor() {}
4859 
4860 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4861                                                TranslationUnitDecl *DC) {
4862   return new (C, DC) ExternCContextDecl(DC);
4863 }
4864 
4865 void LabelDecl::anchor() {}
4866 
4867 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4868                              SourceLocation IdentL, IdentifierInfo *II) {
4869   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4870 }
4871 
4872 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4873                              SourceLocation IdentL, IdentifierInfo *II,
4874                              SourceLocation GnuLabelL) {
4875   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
4876   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4877 }
4878 
4879 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4880   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4881                                SourceLocation());
4882 }
4883 
4884 void LabelDecl::setMSAsmLabel(StringRef Name) {
4885 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4886   memcpy(Buffer, Name.data(), Name.size());
4887   Buffer[Name.size()] = '\0';
4888   MSAsmName = Buffer;
4889 }
4890 
4891 void ValueDecl::anchor() {}
4892 
4893 bool ValueDecl::isWeak() const {
4894   auto *MostRecent = getMostRecentDecl();
4895   return MostRecent->hasAttr<WeakAttr>() ||
4896          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
4897 }
4898 
4899 void ImplicitParamDecl::anchor() {}
4900 
4901 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4902                                              SourceLocation IdLoc,
4903                                              IdentifierInfo *Id, QualType Type,
4904                                              ImplicitParamKind ParamKind) {
4905   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4906 }
4907 
4908 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4909                                              ImplicitParamKind ParamKind) {
4910   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4911 }
4912 
4913 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4914                                                          unsigned ID) {
4915   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4916 }
4917 
4918 FunctionDecl *
4919 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4920                      const DeclarationNameInfo &NameInfo, QualType T,
4921                      TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
4922                      bool isInlineSpecified, bool hasWrittenPrototype,
4923                      ConstexprSpecKind ConstexprKind,
4924                      Expr *TrailingRequiresClause) {
4925   FunctionDecl *New = new (C, DC) FunctionDecl(
4926       Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
4927       isInlineSpecified, ConstexprKind, TrailingRequiresClause);
4928   New->setHasWrittenPrototype(hasWrittenPrototype);
4929   return New;
4930 }
4931 
4932 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4933   return new (C, ID) FunctionDecl(
4934       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
4935       nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
4936 }
4937 
4938 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4939   return new (C, DC) BlockDecl(DC, L);
4940 }
4941 
4942 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4943   return new (C, ID) BlockDecl(nullptr, SourceLocation());
4944 }
4945 
4946 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4947     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4948       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4949 
4950 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4951                                    unsigned NumParams) {
4952   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4953       CapturedDecl(DC, NumParams);
4954 }
4955 
4956 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4957                                                unsigned NumParams) {
4958   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4959       CapturedDecl(nullptr, NumParams);
4960 }
4961 
4962 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4963 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4964 
4965 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4966 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4967 
4968 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4969                                            SourceLocation L,
4970                                            IdentifierInfo *Id, QualType T,
4971                                            Expr *E, const llvm::APSInt &V) {
4972   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4973 }
4974 
4975 EnumConstantDecl *
4976 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4977   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4978                                       QualType(), nullptr, llvm::APSInt());
4979 }
4980 
4981 void IndirectFieldDecl::anchor() {}
4982 
4983 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4984                                      SourceLocation L, DeclarationName N,
4985                                      QualType T,
4986                                      MutableArrayRef<NamedDecl *> CH)
4987     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4988       ChainingSize(CH.size()) {
4989   // In C++, indirect field declarations conflict with tag declarations in the
4990   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4991   if (C.getLangOpts().CPlusPlus)
4992     IdentifierNamespace |= IDNS_Tag;
4993 }
4994 
4995 IndirectFieldDecl *
4996 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4997                           IdentifierInfo *Id, QualType T,
4998                           llvm::MutableArrayRef<NamedDecl *> CH) {
4999   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5000 }
5001 
5002 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
5003                                                          unsigned ID) {
5004   return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
5005                                        DeclarationName(), QualType(), None);
5006 }
5007 
5008 SourceRange EnumConstantDecl::getSourceRange() const {
5009   SourceLocation End = getLocation();
5010   if (Init)
5011     End = Init->getEndLoc();
5012   return SourceRange(getLocation(), End);
5013 }
5014 
5015 void TypeDecl::anchor() {}
5016 
5017 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
5018                                  SourceLocation StartLoc, SourceLocation IdLoc,
5019                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
5020   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5021 }
5022 
5023 void TypedefNameDecl::anchor() {}
5024 
5025 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
5026   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5027     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5028     auto *ThisTypedef = this;
5029     if (AnyRedecl && OwningTypedef) {
5030       OwningTypedef = OwningTypedef->getCanonicalDecl();
5031       ThisTypedef = ThisTypedef->getCanonicalDecl();
5032     }
5033     if (OwningTypedef == ThisTypedef)
5034       return TT->getDecl();
5035   }
5036 
5037   return nullptr;
5038 }
5039 
5040 bool TypedefNameDecl::isTransparentTagSlow() const {
5041   auto determineIsTransparent = [&]() {
5042     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5043       if (auto *TD = TT->getDecl()) {
5044         if (TD->getName() != getName())
5045           return false;
5046         SourceLocation TTLoc = getLocation();
5047         SourceLocation TDLoc = TD->getLocation();
5048         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5049           return false;
5050         SourceManager &SM = getASTContext().getSourceManager();
5051         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5052       }
5053     }
5054     return false;
5055   };
5056 
5057   bool isTransparent = determineIsTransparent();
5058   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5059   return isTransparent;
5060 }
5061 
5062 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5063   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5064                                  nullptr, nullptr);
5065 }
5066 
5067 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
5068                                      SourceLocation StartLoc,
5069                                      SourceLocation IdLoc, IdentifierInfo *Id,
5070                                      TypeSourceInfo *TInfo) {
5071   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5072 }
5073 
5074 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5075   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5076                                    SourceLocation(), nullptr, nullptr);
5077 }
5078 
5079 SourceRange TypedefDecl::getSourceRange() const {
5080   SourceLocation RangeEnd = getLocation();
5081   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5082     if (typeIsPostfix(TInfo->getType()))
5083       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5084   }
5085   return SourceRange(getBeginLoc(), RangeEnd);
5086 }
5087 
5088 SourceRange TypeAliasDecl::getSourceRange() const {
5089   SourceLocation RangeEnd = getBeginLoc();
5090   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5091     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5092   return SourceRange(getBeginLoc(), RangeEnd);
5093 }
5094 
5095 void FileScopeAsmDecl::anchor() {}
5096 
5097 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5098                                            StringLiteral *Str,
5099                                            SourceLocation AsmLoc,
5100                                            SourceLocation RParenLoc) {
5101   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5102 }
5103 
5104 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5105                                                        unsigned ID) {
5106   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5107                                       SourceLocation());
5108 }
5109 
5110 void EmptyDecl::anchor() {}
5111 
5112 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5113   return new (C, DC) EmptyDecl(DC, L);
5114 }
5115 
5116 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5117   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5118 }
5119 
5120 //===----------------------------------------------------------------------===//
5121 // ImportDecl Implementation
5122 //===----------------------------------------------------------------------===//
5123 
5124 /// Retrieve the number of module identifiers needed to name the given
5125 /// module.
5126 static unsigned getNumModuleIdentifiers(Module *Mod) {
5127   unsigned Result = 1;
5128   while (Mod->Parent) {
5129     Mod = Mod->Parent;
5130     ++Result;
5131   }
5132   return Result;
5133 }
5134 
5135 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5136                        Module *Imported,
5137                        ArrayRef<SourceLocation> IdentifierLocs)
5138     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5139       NextLocalImportAndComplete(nullptr, true) {
5140   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5141   auto *StoredLocs = getTrailingObjects<SourceLocation>();
5142   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5143                           StoredLocs);
5144 }
5145 
5146 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5147                        Module *Imported, SourceLocation EndLoc)
5148     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5149       NextLocalImportAndComplete(nullptr, false) {
5150   *getTrailingObjects<SourceLocation>() = EndLoc;
5151 }
5152 
5153 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5154                                SourceLocation StartLoc, Module *Imported,
5155                                ArrayRef<SourceLocation> IdentifierLocs) {
5156   return new (C, DC,
5157               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5158       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5159 }
5160 
5161 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5162                                        SourceLocation StartLoc,
5163                                        Module *Imported,
5164                                        SourceLocation EndLoc) {
5165   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5166       ImportDecl(DC, StartLoc, Imported, EndLoc);
5167   Import->setImplicit();
5168   return Import;
5169 }
5170 
5171 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5172                                            unsigned NumLocations) {
5173   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5174       ImportDecl(EmptyShell());
5175 }
5176 
5177 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5178   if (!isImportComplete())
5179     return None;
5180 
5181   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5182   return llvm::makeArrayRef(StoredLocs,
5183                             getNumModuleIdentifiers(getImportedModule()));
5184 }
5185 
5186 SourceRange ImportDecl::getSourceRange() const {
5187   if (!isImportComplete())
5188     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5189 
5190   return SourceRange(getLocation(), getIdentifierLocs().back());
5191 }
5192 
5193 //===----------------------------------------------------------------------===//
5194 // ExportDecl Implementation
5195 //===----------------------------------------------------------------------===//
5196 
5197 void ExportDecl::anchor() {}
5198 
5199 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5200                                SourceLocation ExportLoc) {
5201   return new (C, DC) ExportDecl(DC, ExportLoc);
5202 }
5203 
5204 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5205   return new (C, ID) ExportDecl(nullptr, SourceLocation());
5206 }
5207