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