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