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