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