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