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