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