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