xref: /openbsd/gnu/llvm/clang/lib/AST/Decl.cpp (revision 12c85518)
1 //===- Decl.cpp - Declaration AST Node Implementation ---------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the Decl subclasses.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/AST/Decl.h"
14 #include "Linkage.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTDiagnostic.h"
17 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/ASTMutationListener.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/CanonicalType.h"
21 #include "clang/AST/DeclBase.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclarationName.h"
27 #include "clang/AST/Expr.h"
28 #include "clang/AST/ExprCXX.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/ODRHash.h"
31 #include "clang/AST/PrettyDeclStackTrace.h"
32 #include "clang/AST/PrettyPrinter.h"
33 #include "clang/AST/Randstruct.h"
34 #include "clang/AST/RecordLayout.h"
35 #include "clang/AST/Redeclarable.h"
36 #include "clang/AST/Stmt.h"
37 #include "clang/AST/TemplateBase.h"
38 #include "clang/AST/Type.h"
39 #include "clang/AST/TypeLoc.h"
40 #include "clang/Basic/Builtins.h"
41 #include "clang/Basic/IdentifierTable.h"
42 #include "clang/Basic/LLVM.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/Linkage.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/NoSanitizeList.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/Sanitizers.h"
49 #include "clang/Basic/SourceLocation.h"
50 #include "clang/Basic/SourceManager.h"
51 #include "clang/Basic/Specifiers.h"
52 #include "clang/Basic/TargetCXXABI.h"
53 #include "clang/Basic/TargetInfo.h"
54 #include "clang/Basic/Visibility.h"
55 #include "llvm/ADT/APSInt.h"
56 #include "llvm/ADT/ArrayRef.h"
57 #include "llvm/ADT/STLExtras.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/StringRef.h"
60 #include "llvm/ADT/StringSwitch.h"
61 #include "llvm/ADT/Triple.h"
62 #include "llvm/Support/Casting.h"
63 #include "llvm/Support/ErrorHandling.h"
64 #include "llvm/Support/raw_ostream.h"
65 #include <algorithm>
66 #include <cassert>
67 #include <cstddef>
68 #include <cstring>
69 #include <memory>
70 #include <optional>
71 #include <string>
72 #include <tuple>
73 #include <type_traits>
74 
75 using namespace clang;
76 
getPrimaryMergedDecl(Decl * D)77 Decl *clang::getPrimaryMergedDecl(Decl *D) {
78   return D->getASTContext().getPrimaryMergedDecl(D);
79 }
80 
print(raw_ostream & OS) const81 void PrettyDeclStackTraceEntry::print(raw_ostream &OS) const {
82   SourceLocation Loc = this->Loc;
83   if (!Loc.isValid() && TheDecl) Loc = TheDecl->getLocation();
84   if (Loc.isValid()) {
85     Loc.print(OS, Context.getSourceManager());
86     OS << ": ";
87   }
88   OS << Message;
89 
90   if (auto *ND = dyn_cast_or_null<NamedDecl>(TheDecl)) {
91     OS << " '";
92     ND->getNameForDiagnostic(OS, Context.getPrintingPolicy(), true);
93     OS << "'";
94   }
95 
96   OS << '\n';
97 }
98 
99 // Defined here so that it can be inlined into its direct callers.
isOutOfLine() const100 bool Decl::isOutOfLine() const {
101   return !getLexicalDeclContext()->Equals(getDeclContext());
102 }
103 
TranslationUnitDecl(ASTContext & ctx)104 TranslationUnitDecl::TranslationUnitDecl(ASTContext &ctx)
105     : Decl(TranslationUnit, nullptr, SourceLocation()),
106       DeclContext(TranslationUnit), redeclarable_base(ctx), Ctx(ctx) {}
107 
108 //===----------------------------------------------------------------------===//
109 // NamedDecl Implementation
110 //===----------------------------------------------------------------------===//
111 
112 // Visibility rules aren't rigorously externally specified, but here
113 // are the basic principles behind what we implement:
114 //
115 // 1. An explicit visibility attribute is generally a direct expression
116 // of the user's intent and should be honored.  Only the innermost
117 // visibility attribute applies.  If no visibility attribute applies,
118 // global visibility settings are considered.
119 //
120 // 2. There is one caveat to the above: on or in a template pattern,
121 // an explicit visibility attribute is just a default rule, and
122 // visibility can be decreased by the visibility of template
123 // arguments.  But this, too, has an exception: an attribute on an
124 // explicit specialization or instantiation causes all the visibility
125 // restrictions of the template arguments to be ignored.
126 //
127 // 3. A variable that does not otherwise have explicit visibility can
128 // be restricted by the visibility of its type.
129 //
130 // 4. A visibility restriction is explicit if it comes from an
131 // attribute (or something like it), not a global visibility setting.
132 // When emitting a reference to an external symbol, visibility
133 // restrictions are ignored unless they are explicit.
134 //
135 // 5. When computing the visibility of a non-type, including a
136 // non-type member of a class, only non-type visibility restrictions
137 // are considered: the 'visibility' attribute, global value-visibility
138 // settings, and a few special cases like __private_extern.
139 //
140 // 6. When computing the visibility of a type, including a type member
141 // of a class, only type visibility restrictions are considered:
142 // the 'type_visibility' attribute and global type-visibility settings.
143 // However, a 'visibility' attribute counts as a 'type_visibility'
144 // attribute on any declaration that only has the former.
145 //
146 // The visibility of a "secondary" entity, like a template argument,
147 // is computed using the kind of that entity, not the kind of the
148 // primary entity for which we are computing visibility.  For example,
149 // the visibility of a specialization of either of these templates:
150 //   template <class T, bool (&compare)(T, X)> bool has_match(list<T>, X);
151 //   template <class T, bool (&compare)(T, X)> class matcher;
152 // is restricted according to the type visibility of the argument 'T',
153 // the type visibility of 'bool(&)(T,X)', and the value visibility of
154 // the argument function 'compare'.  That 'has_match' is a value
155 // and 'matcher' is a type only matters when looking for attributes
156 // and settings from the immediate context.
157 
158 /// Does this computation kind permit us to consider additional
159 /// visibility settings from attributes and the like?
hasExplicitVisibilityAlready(LVComputationKind computation)160 static bool hasExplicitVisibilityAlready(LVComputationKind computation) {
161   return computation.IgnoreExplicitVisibility;
162 }
163 
164 /// Given an LVComputationKind, return one of the same type/value sort
165 /// that records that it already has explicit visibility.
166 static LVComputationKind
withExplicitVisibilityAlready(LVComputationKind Kind)167 withExplicitVisibilityAlready(LVComputationKind Kind) {
168   Kind.IgnoreExplicitVisibility = true;
169   return Kind;
170 }
171 
getExplicitVisibility(const NamedDecl * D,LVComputationKind kind)172 static std::optional<Visibility> getExplicitVisibility(const NamedDecl *D,
173                                                        LVComputationKind kind) {
174   assert(!kind.IgnoreExplicitVisibility &&
175          "asking for explicit visibility when we shouldn't be");
176   return D->getExplicitVisibility(kind.getExplicitVisibilityKind());
177 }
178 
179 /// Is the given declaration a "type" or a "value" for the purposes of
180 /// visibility computation?
usesTypeVisibility(const NamedDecl * D)181 static bool usesTypeVisibility(const NamedDecl *D) {
182   return isa<TypeDecl>(D) ||
183          isa<ClassTemplateDecl>(D) ||
184          isa<ObjCInterfaceDecl>(D);
185 }
186 
187 /// Does the given declaration have member specialization information,
188 /// and if so, is it an explicit specialization?
189 template <class T>
190 static std::enable_if_t<!std::is_base_of_v<RedeclarableTemplateDecl, T>, bool>
isExplicitMemberSpecialization(const T * D)191 isExplicitMemberSpecialization(const T *D) {
192   if (const MemberSpecializationInfo *member =
193         D->getMemberSpecializationInfo()) {
194     return member->isExplicitSpecialization();
195   }
196   return false;
197 }
198 
199 /// For templates, this question is easier: a member template can't be
200 /// explicitly instantiated, so there's a single bit indicating whether
201 /// or not this is an explicit member specialization.
isExplicitMemberSpecialization(const RedeclarableTemplateDecl * D)202 static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
203   return D->isMemberSpecialization();
204 }
205 
206 /// Given a visibility attribute, return the explicit visibility
207 /// associated with it.
208 template <class T>
getVisibilityFromAttr(const T * attr)209 static Visibility getVisibilityFromAttr(const T *attr) {
210   switch (attr->getVisibility()) {
211   case T::Default:
212     return DefaultVisibility;
213   case T::Hidden:
214     return HiddenVisibility;
215   case T::Protected:
216     return ProtectedVisibility;
217   }
218   llvm_unreachable("bad visibility kind");
219 }
220 
221 /// Return the explicit visibility of the given declaration.
222 static std::optional<Visibility>
getVisibilityOf(const NamedDecl * D,NamedDecl::ExplicitVisibilityKind kind)223 getVisibilityOf(const NamedDecl *D, NamedDecl::ExplicitVisibilityKind kind) {
224   // If we're ultimately computing the visibility of a type, look for
225   // a 'type_visibility' attribute before looking for 'visibility'.
226   if (kind == NamedDecl::VisibilityForType) {
227     if (const auto *A = D->getAttr<TypeVisibilityAttr>()) {
228       return getVisibilityFromAttr(A);
229     }
230   }
231 
232   // If this declaration has an explicit visibility attribute, use it.
233   if (const auto *A = D->getAttr<VisibilityAttr>()) {
234     return getVisibilityFromAttr(A);
235   }
236 
237   return std::nullopt;
238 }
239 
getLVForType(const Type & T,LVComputationKind computation)240 LinkageInfo LinkageComputer::getLVForType(const Type &T,
241                                           LVComputationKind computation) {
242   if (computation.IgnoreAllVisibility)
243     return LinkageInfo(T.getLinkage(), DefaultVisibility, true);
244   return getTypeLinkageAndVisibility(&T);
245 }
246 
247 /// Get the most restrictive linkage for the types in the given
248 /// template parameter list.  For visibility purposes, template
249 /// parameters are part of the signature of a template.
getLVForTemplateParameterList(const TemplateParameterList * Params,LVComputationKind computation)250 LinkageInfo LinkageComputer::getLVForTemplateParameterList(
251     const TemplateParameterList *Params, LVComputationKind computation) {
252   LinkageInfo LV;
253   for (const NamedDecl *P : *Params) {
254     // Template type parameters are the most common and never
255     // contribute to visibility, pack or not.
256     if (isa<TemplateTypeParmDecl>(P))
257       continue;
258 
259     // Non-type template parameters can be restricted by the value type, e.g.
260     //   template <enum X> class A { ... };
261     // We have to be careful here, though, because we can be dealing with
262     // dependent types.
263     if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P)) {
264       // Handle the non-pack case first.
265       if (!NTTP->isExpandedParameterPack()) {
266         if (!NTTP->getType()->isDependentType()) {
267           LV.merge(getLVForType(*NTTP->getType(), computation));
268         }
269         continue;
270       }
271 
272       // Look at all the types in an expanded pack.
273       for (unsigned i = 0, n = NTTP->getNumExpansionTypes(); i != n; ++i) {
274         QualType type = NTTP->getExpansionType(i);
275         if (!type->isDependentType())
276           LV.merge(getTypeLinkageAndVisibility(type));
277       }
278       continue;
279     }
280 
281     // Template template parameters can be restricted by their
282     // template parameters, recursively.
283     const auto *TTP = cast<TemplateTemplateParmDecl>(P);
284 
285     // Handle the non-pack case first.
286     if (!TTP->isExpandedParameterPack()) {
287       LV.merge(getLVForTemplateParameterList(TTP->getTemplateParameters(),
288                                              computation));
289       continue;
290     }
291 
292     // Look at all expansions in an expanded pack.
293     for (unsigned i = 0, n = TTP->getNumExpansionTemplateParameters();
294            i != n; ++i) {
295       LV.merge(getLVForTemplateParameterList(
296           TTP->getExpansionTemplateParameters(i), computation));
297     }
298   }
299 
300   return LV;
301 }
302 
getOutermostFuncOrBlockContext(const Decl * D)303 static const Decl *getOutermostFuncOrBlockContext(const Decl *D) {
304   const Decl *Ret = nullptr;
305   const DeclContext *DC = D->getDeclContext();
306   while (DC->getDeclKind() != Decl::TranslationUnit) {
307     if (isa<FunctionDecl>(DC) || isa<BlockDecl>(DC))
308       Ret = cast<Decl>(DC);
309     DC = DC->getParent();
310   }
311   return Ret;
312 }
313 
314 /// Get the most restrictive linkage for the types and
315 /// declarations in the given template argument list.
316 ///
317 /// Note that we don't take an LVComputationKind because we always
318 /// want to honor the visibility of template arguments in the same way.
319 LinkageInfo
getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,LVComputationKind computation)320 LinkageComputer::getLVForTemplateArgumentList(ArrayRef<TemplateArgument> Args,
321                                               LVComputationKind computation) {
322   LinkageInfo LV;
323 
324   for (const TemplateArgument &Arg : Args) {
325     switch (Arg.getKind()) {
326     case TemplateArgument::Null:
327     case TemplateArgument::Integral:
328     case TemplateArgument::Expression:
329       continue;
330 
331     case TemplateArgument::Type:
332       LV.merge(getLVForType(*Arg.getAsType(), computation));
333       continue;
334 
335     case TemplateArgument::Declaration: {
336       const NamedDecl *ND = Arg.getAsDecl();
337       assert(!usesTypeVisibility(ND));
338       LV.merge(getLVForDecl(ND, computation));
339       continue;
340     }
341 
342     case TemplateArgument::NullPtr:
343       LV.merge(getTypeLinkageAndVisibility(Arg.getNullPtrType()));
344       continue;
345 
346     case TemplateArgument::Template:
347     case TemplateArgument::TemplateExpansion:
348       if (TemplateDecl *Template =
349               Arg.getAsTemplateOrTemplatePattern().getAsTemplateDecl())
350         LV.merge(getLVForDecl(Template, computation));
351       continue;
352 
353     case TemplateArgument::Pack:
354       LV.merge(getLVForTemplateArgumentList(Arg.getPackAsArray(), computation));
355       continue;
356     }
357     llvm_unreachable("bad template argument kind");
358   }
359 
360   return LV;
361 }
362 
363 LinkageInfo
getLVForTemplateArgumentList(const TemplateArgumentList & TArgs,LVComputationKind computation)364 LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
365                                               LVComputationKind computation) {
366   return getLVForTemplateArgumentList(TArgs.asArray(), computation);
367 }
368 
shouldConsiderTemplateVisibility(const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo)369 static bool shouldConsiderTemplateVisibility(const FunctionDecl *fn,
370                         const FunctionTemplateSpecializationInfo *specInfo) {
371   // Include visibility from the template parameters and arguments
372   // only if this is not an explicit instantiation or specialization
373   // with direct explicit visibility.  (Implicit instantiations won't
374   // have a direct attribute.)
375   if (!specInfo->isExplicitInstantiationOrSpecialization())
376     return true;
377 
378   return !fn->hasAttr<VisibilityAttr>();
379 }
380 
381 /// Merge in template-related linkage and visibility for the given
382 /// function template specialization.
383 ///
384 /// We don't need a computation kind here because we can assume
385 /// LVForValue.
386 ///
387 /// \param[out] LV the computation to use for the parent
mergeTemplateLV(LinkageInfo & LV,const FunctionDecl * fn,const FunctionTemplateSpecializationInfo * specInfo,LVComputationKind computation)388 void LinkageComputer::mergeTemplateLV(
389     LinkageInfo &LV, const FunctionDecl *fn,
390     const FunctionTemplateSpecializationInfo *specInfo,
391     LVComputationKind computation) {
392   bool considerVisibility =
393     shouldConsiderTemplateVisibility(fn, specInfo);
394 
395   FunctionTemplateDecl *temp = specInfo->getTemplate();
396   // Merge information from the template declaration.
397   LinkageInfo tempLV = getLVForDecl(temp, computation);
398   // The linkage of the specialization should be consistent with the
399   // template declaration.
400   LV.setLinkage(tempLV.getLinkage());
401 
402   // Merge information from the template parameters.
403   LinkageInfo paramsLV =
404       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
405   LV.mergeMaybeWithVisibility(paramsLV, considerVisibility);
406 
407   // Merge information from the template arguments.
408   const TemplateArgumentList &templateArgs = *specInfo->TemplateArguments;
409   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
410   LV.mergeMaybeWithVisibility(argsLV, considerVisibility);
411 }
412 
413 /// Does the given declaration have a direct visibility attribute
414 /// that would match the given rules?
hasDirectVisibilityAttribute(const NamedDecl * D,LVComputationKind computation)415 static bool hasDirectVisibilityAttribute(const NamedDecl *D,
416                                          LVComputationKind computation) {
417   if (computation.IgnoreAllVisibility)
418     return false;
419 
420   return (computation.isTypeVisibility() && D->hasAttr<TypeVisibilityAttr>()) ||
421          D->hasAttr<VisibilityAttr>();
422 }
423 
424 /// Should we consider visibility associated with the template
425 /// arguments and parameters of the given class template specialization?
shouldConsiderTemplateVisibility(const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)426 static bool shouldConsiderTemplateVisibility(
427                                  const ClassTemplateSpecializationDecl *spec,
428                                  LVComputationKind computation) {
429   // Include visibility from the template parameters and arguments
430   // only if this is not an explicit instantiation or specialization
431   // with direct explicit visibility (and note that implicit
432   // instantiations won't have a direct attribute).
433   //
434   // Furthermore, we want to ignore template parameters and arguments
435   // for an explicit specialization when computing the visibility of a
436   // member thereof with explicit visibility.
437   //
438   // This is a bit complex; let's unpack it.
439   //
440   // An explicit class specialization is an independent, top-level
441   // declaration.  As such, if it or any of its members has an
442   // explicit visibility attribute, that must directly express the
443   // user's intent, and we should honor it.  The same logic applies to
444   // an explicit instantiation of a member of such a thing.
445 
446   // Fast path: if this is not an explicit instantiation or
447   // specialization, we always want to consider template-related
448   // visibility restrictions.
449   if (!spec->isExplicitInstantiationOrSpecialization())
450     return true;
451 
452   // This is the 'member thereof' check.
453   if (spec->isExplicitSpecialization() &&
454       hasExplicitVisibilityAlready(computation))
455     return false;
456 
457   return !hasDirectVisibilityAttribute(spec, computation);
458 }
459 
460 /// Merge in template-related linkage and visibility for the given
461 /// class template specialization.
mergeTemplateLV(LinkageInfo & LV,const ClassTemplateSpecializationDecl * spec,LVComputationKind computation)462 void LinkageComputer::mergeTemplateLV(
463     LinkageInfo &LV, const ClassTemplateSpecializationDecl *spec,
464     LVComputationKind computation) {
465   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
466 
467   // Merge information from the template parameters, but ignore
468   // visibility if we're only considering template arguments.
469   ClassTemplateDecl *temp = spec->getSpecializedTemplate();
470   // Merge information from the template declaration.
471   LinkageInfo tempLV = getLVForDecl(temp, computation);
472   // The linkage of the specialization should be consistent with the
473   // template declaration.
474   LV.setLinkage(tempLV.getLinkage());
475 
476   LinkageInfo paramsLV =
477     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
478   LV.mergeMaybeWithVisibility(paramsLV,
479            considerVisibility && !hasExplicitVisibilityAlready(computation));
480 
481   // Merge information from the template arguments.  We ignore
482   // template-argument visibility if we've got an explicit
483   // instantiation with a visibility attribute.
484   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
485   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
486   if (considerVisibility)
487     LV.mergeVisibility(argsLV);
488   LV.mergeExternalVisibility(argsLV);
489 }
490 
491 /// Should we consider visibility associated with the template
492 /// arguments and parameters of the given variable template
493 /// specialization? As usual, follow class template specialization
494 /// logic up to initialization.
shouldConsiderTemplateVisibility(const VarTemplateSpecializationDecl * spec,LVComputationKind computation)495 static bool shouldConsiderTemplateVisibility(
496                                  const VarTemplateSpecializationDecl *spec,
497                                  LVComputationKind computation) {
498   // Include visibility from the template parameters and arguments
499   // only if this is not an explicit instantiation or specialization
500   // with direct explicit visibility (and note that implicit
501   // instantiations won't have a direct attribute).
502   if (!spec->isExplicitInstantiationOrSpecialization())
503     return true;
504 
505   // An explicit variable specialization is an independent, top-level
506   // declaration.  As such, if it has an explicit visibility attribute,
507   // that must directly express the user's intent, and we should honor
508   // it.
509   if (spec->isExplicitSpecialization() &&
510       hasExplicitVisibilityAlready(computation))
511     return false;
512 
513   return !hasDirectVisibilityAttribute(spec, computation);
514 }
515 
516 /// Merge in template-related linkage and visibility for the given
517 /// variable template specialization. As usual, follow class template
518 /// specialization logic up to initialization.
mergeTemplateLV(LinkageInfo & LV,const VarTemplateSpecializationDecl * spec,LVComputationKind computation)519 void LinkageComputer::mergeTemplateLV(LinkageInfo &LV,
520                                       const VarTemplateSpecializationDecl *spec,
521                                       LVComputationKind computation) {
522   bool considerVisibility = shouldConsiderTemplateVisibility(spec, computation);
523 
524   // Merge information from the template parameters, but ignore
525   // visibility if we're only considering template arguments.
526   VarTemplateDecl *temp = spec->getSpecializedTemplate();
527   LinkageInfo tempLV =
528     getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
529   LV.mergeMaybeWithVisibility(tempLV,
530            considerVisibility && !hasExplicitVisibilityAlready(computation));
531 
532   // Merge information from the template arguments.  We ignore
533   // template-argument visibility if we've got an explicit
534   // instantiation with a visibility attribute.
535   const TemplateArgumentList &templateArgs = spec->getTemplateArgs();
536   LinkageInfo argsLV = getLVForTemplateArgumentList(templateArgs, computation);
537   if (considerVisibility)
538     LV.mergeVisibility(argsLV);
539   LV.mergeExternalVisibility(argsLV);
540 }
541 
useInlineVisibilityHidden(const NamedDecl * D)542 static bool useInlineVisibilityHidden(const NamedDecl *D) {
543   // FIXME: we should warn if -fvisibility-inlines-hidden is used with c.
544   const LangOptions &Opts = D->getASTContext().getLangOpts();
545   if (!Opts.CPlusPlus || !Opts.InlineVisibilityHidden)
546     return false;
547 
548   const auto *FD = dyn_cast<FunctionDecl>(D);
549   if (!FD)
550     return false;
551 
552   TemplateSpecializationKind TSK = TSK_Undeclared;
553   if (FunctionTemplateSpecializationInfo *spec
554       = FD->getTemplateSpecializationInfo()) {
555     TSK = spec->getTemplateSpecializationKind();
556   } else if (MemberSpecializationInfo *MSI =
557              FD->getMemberSpecializationInfo()) {
558     TSK = MSI->getTemplateSpecializationKind();
559   }
560 
561   const FunctionDecl *Def = nullptr;
562   // InlineVisibilityHidden only applies to definitions, and
563   // isInlined() only gives meaningful answers on definitions
564   // anyway.
565   return TSK != TSK_ExplicitInstantiationDeclaration &&
566     TSK != TSK_ExplicitInstantiationDefinition &&
567     FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
568 }
569 
isFirstInExternCContext(T * D)570 template <typename T> static bool isFirstInExternCContext(T *D) {
571   const T *First = D->getFirstDecl();
572   return First->isInExternCContext();
573 }
574 
isSingleLineLanguageLinkage(const Decl & D)575 static bool isSingleLineLanguageLinkage(const Decl &D) {
576   if (const auto *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
577     if (!SD->hasBraces())
578       return true;
579   return false;
580 }
581 
582 /// Determine whether D is declared in the purview of a named module.
isInModulePurview(const NamedDecl * D)583 static bool isInModulePurview(const NamedDecl *D) {
584   if (auto *M = D->getOwningModule())
585     return M->isModulePurview();
586   return false;
587 }
588 
isExportedFromModuleInterfaceUnit(const NamedDecl * D)589 static bool isExportedFromModuleInterfaceUnit(const NamedDecl *D) {
590   // FIXME: Handle isModulePrivate.
591   switch (D->getModuleOwnershipKind()) {
592   case Decl::ModuleOwnershipKind::Unowned:
593   case Decl::ModuleOwnershipKind::ReachableWhenImported:
594   case Decl::ModuleOwnershipKind::ModulePrivate:
595     return false;
596   case Decl::ModuleOwnershipKind::Visible:
597   case Decl::ModuleOwnershipKind::VisibleWhenImported:
598     return isInModulePurview(D);
599   }
600   llvm_unreachable("unexpected module ownership kind");
601 }
602 
getInternalLinkageFor(const NamedDecl * D)603 static LinkageInfo getInternalLinkageFor(const NamedDecl *D) {
604   // (for the modules ts) Internal linkage declarations within a module
605   // interface unit are modeled as "module-internal linkage", which means that
606   // they have internal linkage formally but can be indirectly accessed from
607   // outside the module via inline functions and templates defined within the
608   // module.
609   if (isInModulePurview(D) && D->getASTContext().getLangOpts().ModulesTS)
610     return LinkageInfo(ModuleInternalLinkage, DefaultVisibility, false);
611 
612   return LinkageInfo::internal();
613 }
614 
getExternalLinkageFor(const NamedDecl * D)615 static LinkageInfo getExternalLinkageFor(const NamedDecl *D) {
616   // C++ Modules TS [basic.link]/6.8:
617   //   - A name declared at namespace scope that does not have internal linkage
618   //     by the previous rules and that is introduced by a non-exported
619   //     declaration has module linkage.
620   //
621   // [basic.namespace.general]/p2
622   //   A namespace is never attached to a named module and never has a name with
623   //   module linkage.
624   if (isInModulePurview(D) &&
625       !isExportedFromModuleInterfaceUnit(
626           cast<NamedDecl>(D->getCanonicalDecl())) &&
627       !isa<NamespaceDecl>(D))
628     return LinkageInfo(ModuleLinkage, DefaultVisibility, false);
629 
630   return LinkageInfo::external();
631 }
632 
getStorageClass(const Decl * D)633 static StorageClass getStorageClass(const Decl *D) {
634   if (auto *TD = dyn_cast<TemplateDecl>(D))
635     D = TD->getTemplatedDecl();
636   if (D) {
637     if (auto *VD = dyn_cast<VarDecl>(D))
638       return VD->getStorageClass();
639     if (auto *FD = dyn_cast<FunctionDecl>(D))
640       return FD->getStorageClass();
641   }
642   return SC_None;
643 }
644 
645 LinkageInfo
getLVForNamespaceScopeDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)646 LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
647                                             LVComputationKind computation,
648                                             bool IgnoreVarTypeLinkage) {
649   assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&
650          "Not a name having namespace scope");
651   ASTContext &Context = D->getASTContext();
652 
653   // C++ [basic.link]p3:
654   //   A name having namespace scope (3.3.6) has internal linkage if it
655   //   is the name of
656 
657   if (getStorageClass(D->getCanonicalDecl()) == SC_Static) {
658     // - a variable, variable template, function, or function template
659     //   that is explicitly declared static; or
660     // (This bullet corresponds to C99 6.2.2p3.)
661     return getInternalLinkageFor(D);
662   }
663 
664   if (const auto *Var = dyn_cast<VarDecl>(D)) {
665     // - a non-template variable of non-volatile const-qualified type, unless
666     //   - it is explicitly declared extern, or
667     //   - it is inline or exported, or
668     //   - it was previously declared and the prior declaration did not have
669     //     internal linkage
670     // (There is no equivalent in C99.)
671     if (Context.getLangOpts().CPlusPlus &&
672         Var->getType().isConstQualified() &&
673         !Var->getType().isVolatileQualified() &&
674         !Var->isInline() &&
675         !isExportedFromModuleInterfaceUnit(Var) &&
676         !isa<VarTemplateSpecializationDecl>(Var) &&
677         !Var->getDescribedVarTemplate()) {
678       const VarDecl *PrevVar = Var->getPreviousDecl();
679       if (PrevVar)
680         return getLVForDecl(PrevVar, computation);
681 
682       if (Var->getStorageClass() != SC_Extern &&
683           Var->getStorageClass() != SC_PrivateExtern &&
684           !isSingleLineLanguageLinkage(*Var))
685         return getInternalLinkageFor(Var);
686     }
687 
688     for (const VarDecl *PrevVar = Var->getPreviousDecl(); PrevVar;
689          PrevVar = PrevVar->getPreviousDecl()) {
690       if (PrevVar->getStorageClass() == SC_PrivateExtern &&
691           Var->getStorageClass() == SC_None)
692         return getDeclLinkageAndVisibility(PrevVar);
693       // Explicitly declared static.
694       if (PrevVar->getStorageClass() == SC_Static)
695         return getInternalLinkageFor(Var);
696     }
697   } else if (const auto *IFD = dyn_cast<IndirectFieldDecl>(D)) {
698     //   - a data member of an anonymous union.
699     const VarDecl *VD = IFD->getVarDecl();
700     assert(VD && "Expected a VarDecl in this IndirectFieldDecl!");
701     return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
702   }
703   assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!");
704 
705   // FIXME: This gives internal linkage to names that should have no linkage
706   // (those not covered by [basic.link]p6).
707   if (D->isInAnonymousNamespace()) {
708     const auto *Var = dyn_cast<VarDecl>(D);
709     const auto *Func = dyn_cast<FunctionDecl>(D);
710     // FIXME: The check for extern "C" here is not justified by the standard
711     // wording, but we retain it from the pre-DR1113 model to avoid breaking
712     // code.
713     //
714     // C++11 [basic.link]p4:
715     //   An unnamed namespace or a namespace declared directly or indirectly
716     //   within an unnamed namespace has internal linkage.
717     if ((!Var || !isFirstInExternCContext(Var)) &&
718         (!Func || !isFirstInExternCContext(Func)))
719       return getInternalLinkageFor(D);
720   }
721 
722   // Set up the defaults.
723 
724   // C99 6.2.2p5:
725   //   If the declaration of an identifier for an object has file
726   //   scope and no storage-class specifier, its linkage is
727   //   external.
728   LinkageInfo LV = getExternalLinkageFor(D);
729 
730   if (!hasExplicitVisibilityAlready(computation)) {
731     if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation)) {
732       LV.mergeVisibility(*Vis, true);
733     } else {
734       // If we're declared in a namespace with a visibility attribute,
735       // use that namespace's visibility, and it still counts as explicit.
736       for (const DeclContext *DC = D->getDeclContext();
737            !isa<TranslationUnitDecl>(DC);
738            DC = DC->getParent()) {
739         const auto *ND = dyn_cast<NamespaceDecl>(DC);
740         if (!ND) continue;
741         if (std::optional<Visibility> Vis =
742                 getExplicitVisibility(ND, computation)) {
743           LV.mergeVisibility(*Vis, true);
744           break;
745         }
746       }
747     }
748 
749     // Add in global settings if the above didn't give us direct visibility.
750     if (!LV.isVisibilityExplicit()) {
751       // Use global type/value visibility as appropriate.
752       Visibility globalVisibility =
753           computation.isValueVisibility()
754               ? Context.getLangOpts().getValueVisibilityMode()
755               : Context.getLangOpts().getTypeVisibilityMode();
756       LV.mergeVisibility(globalVisibility, /*explicit*/ false);
757 
758       // If we're paying attention to global visibility, apply
759       // -finline-visibility-hidden if this is an inline method.
760       if (useInlineVisibilityHidden(D))
761         LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
762     }
763   }
764 
765   // C++ [basic.link]p4:
766 
767   //   A name having namespace scope that has not been given internal linkage
768   //   above and that is the name of
769   //   [...bullets...]
770   //   has its linkage determined as follows:
771   //     - if the enclosing namespace has internal linkage, the name has
772   //       internal linkage; [handled above]
773   //     - otherwise, if the declaration of the name is attached to a named
774   //       module and is not exported, the name has module linkage;
775   //     - otherwise, the name has external linkage.
776   // LV is currently set up to handle the last two bullets.
777   //
778   //   The bullets are:
779 
780   //     - a variable; or
781   if (const auto *Var = dyn_cast<VarDecl>(D)) {
782     // GCC applies the following optimization to variables and static
783     // data members, but not to functions:
784     //
785     // Modify the variable's LV by the LV of its type unless this is
786     // C or extern "C".  This follows from [basic.link]p9:
787     //   A type without linkage shall not be used as the type of a
788     //   variable or function with external linkage unless
789     //    - the entity has C language linkage, or
790     //    - the entity is declared within an unnamed namespace, or
791     //    - the entity is not used or is defined in the same
792     //      translation unit.
793     // and [basic.link]p10:
794     //   ...the types specified by all declarations referring to a
795     //   given variable or function shall be identical...
796     // C does not have an equivalent rule.
797     //
798     // Ignore this if we've got an explicit attribute;  the user
799     // probably knows what they're doing.
800     //
801     // Note that we don't want to make the variable non-external
802     // because of this, but unique-external linkage suits us.
803 
804     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var) &&
805         !IgnoreVarTypeLinkage) {
806       LinkageInfo TypeLV = getLVForType(*Var->getType(), computation);
807       if (!isExternallyVisible(TypeLV.getLinkage()))
808         return LinkageInfo::uniqueExternal();
809       if (!LV.isVisibilityExplicit())
810         LV.mergeVisibility(TypeLV);
811     }
812 
813     if (Var->getStorageClass() == SC_PrivateExtern)
814       LV.mergeVisibility(HiddenVisibility, true);
815 
816     // Note that Sema::MergeVarDecl already takes care of implementing
817     // C99 6.2.2p4 and propagating the visibility attribute, so we don't have
818     // to do it here.
819 
820     // As per function and class template specializations (below),
821     // consider LV for the template and template arguments.  We're at file
822     // scope, so we do not need to worry about nested specializations.
823     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
824       mergeTemplateLV(LV, spec, computation);
825     }
826 
827   //     - a function; or
828   } else if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
829     // In theory, we can modify the function's LV by the LV of its
830     // type unless it has C linkage (see comment above about variables
831     // for justification).  In practice, GCC doesn't do this, so it's
832     // just too painful to make work.
833 
834     if (Function->getStorageClass() == SC_PrivateExtern)
835       LV.mergeVisibility(HiddenVisibility, true);
836 
837     // OpenMP target declare device functions are not callable from the host so
838     // they should not be exported from the device image. This applies to all
839     // functions as the host-callable kernel functions are emitted at codegen.
840     if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice &&
841         ((Context.getTargetInfo().getTriple().isAMDGPU() ||
842           Context.getTargetInfo().getTriple().isNVPTX()) ||
843          OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Function)))
844       LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
845 
846     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
847     // merging storage classes and visibility attributes, so we don't have to
848     // look at previous decls in here.
849 
850     // In C++, then if the type of the function uses a type with
851     // unique-external linkage, it's not legally usable from outside
852     // this translation unit.  However, we should use the C linkage
853     // rules instead for extern "C" declarations.
854     if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Function)) {
855       // Only look at the type-as-written. Otherwise, deducing the return type
856       // of a function could change its linkage.
857       QualType TypeAsWritten = Function->getType();
858       if (TypeSourceInfo *TSI = Function->getTypeSourceInfo())
859         TypeAsWritten = TSI->getType();
860       if (!isExternallyVisible(TypeAsWritten->getLinkage()))
861         return LinkageInfo::uniqueExternal();
862     }
863 
864     // Consider LV from the template and the template arguments.
865     // We're at file scope, so we do not need to worry about nested
866     // specializations.
867     if (FunctionTemplateSpecializationInfo *specInfo
868                                = Function->getTemplateSpecializationInfo()) {
869       mergeTemplateLV(LV, Function, specInfo, computation);
870     }
871 
872   //     - a named class (Clause 9), or an unnamed class defined in a
873   //       typedef declaration in which the class has the typedef name
874   //       for linkage purposes (7.1.3); or
875   //     - a named enumeration (7.2), or an unnamed enumeration
876   //       defined in a typedef declaration in which the enumeration
877   //       has the typedef name for linkage purposes (7.1.3); or
878   } else if (const auto *Tag = dyn_cast<TagDecl>(D)) {
879     // Unnamed tags have no linkage.
880     if (!Tag->hasNameForLinkage())
881       return LinkageInfo::none();
882 
883     // If this is a class template specialization, consider the
884     // linkage of the template and template arguments.  We're at file
885     // scope, so we do not need to worry about nested specializations.
886     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(Tag)) {
887       mergeTemplateLV(LV, spec, computation);
888     }
889 
890   // FIXME: This is not part of the C++ standard any more.
891   //     - an enumerator belonging to an enumeration with external linkage; or
892   } else if (isa<EnumConstantDecl>(D)) {
893     LinkageInfo EnumLV = getLVForDecl(cast<NamedDecl>(D->getDeclContext()),
894                                       computation);
895     if (!isExternalFormalLinkage(EnumLV.getLinkage()))
896       return LinkageInfo::none();
897     LV.merge(EnumLV);
898 
899   //     - a template
900   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
901     bool considerVisibility = !hasExplicitVisibilityAlready(computation);
902     LinkageInfo tempLV =
903       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
904     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
905 
906   //     An unnamed namespace or a namespace declared directly or indirectly
907   //     within an unnamed namespace has internal linkage. All other namespaces
908   //     have external linkage.
909   //
910   // We handled names in anonymous namespaces above.
911   } else if (isa<NamespaceDecl>(D)) {
912     return LV;
913 
914   // By extension, we assign external linkage to Objective-C
915   // interfaces.
916   } else if (isa<ObjCInterfaceDecl>(D)) {
917     // fallout
918 
919   } else if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
920     // A typedef declaration has linkage if it gives a type a name for
921     // linkage purposes.
922     if (!TD->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
923       return LinkageInfo::none();
924 
925   } else if (isa<MSGuidDecl>(D)) {
926     // A GUID behaves like an inline variable with external linkage. Fall
927     // through.
928 
929   // Everything not covered here has no linkage.
930   } else {
931     return LinkageInfo::none();
932   }
933 
934   // If we ended up with non-externally-visible linkage, visibility should
935   // always be default.
936   if (!isExternallyVisible(LV.getLinkage()))
937     return LinkageInfo(LV.getLinkage(), DefaultVisibility, false);
938 
939   return LV;
940 }
941 
942 LinkageInfo
getLVForClassMember(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)943 LinkageComputer::getLVForClassMember(const NamedDecl *D,
944                                      LVComputationKind computation,
945                                      bool IgnoreVarTypeLinkage) {
946   // Only certain class members have linkage.  Note that fields don't
947   // really have linkage, but it's convenient to say they do for the
948   // purposes of calculating linkage of pointer-to-data-member
949   // template arguments.
950   //
951   // Templates also don't officially have linkage, but since we ignore
952   // the C++ standard and look at template arguments when determining
953   // linkage and visibility of a template specialization, we might hit
954   // a template template argument that way. If we do, we need to
955   // consider its linkage.
956   if (!(isa<CXXMethodDecl>(D) ||
957         isa<VarDecl>(D) ||
958         isa<FieldDecl>(D) ||
959         isa<IndirectFieldDecl>(D) ||
960         isa<TagDecl>(D) ||
961         isa<TemplateDecl>(D)))
962     return LinkageInfo::none();
963 
964   LinkageInfo LV;
965 
966   // If we have an explicit visibility attribute, merge that in.
967   if (!hasExplicitVisibilityAlready(computation)) {
968     if (std::optional<Visibility> Vis = getExplicitVisibility(D, computation))
969       LV.mergeVisibility(*Vis, true);
970     // If we're paying attention to global visibility, apply
971     // -finline-visibility-hidden if this is an inline method.
972     //
973     // Note that we do this before merging information about
974     // the class visibility.
975     if (!LV.isVisibilityExplicit() && useInlineVisibilityHidden(D))
976       LV.mergeVisibility(HiddenVisibility, /*visibilityExplicit=*/false);
977   }
978 
979   // If this class member has an explicit visibility attribute, the only
980   // thing that can change its visibility is the template arguments, so
981   // only look for them when processing the class.
982   LVComputationKind classComputation = computation;
983   if (LV.isVisibilityExplicit())
984     classComputation = withExplicitVisibilityAlready(computation);
985 
986   LinkageInfo classLV =
987     getLVForDecl(cast<RecordDecl>(D->getDeclContext()), classComputation);
988   // The member has the same linkage as the class. If that's not externally
989   // visible, we don't need to compute anything about the linkage.
990   // FIXME: If we're only computing linkage, can we bail out here?
991   if (!isExternallyVisible(classLV.getLinkage()))
992     return classLV;
993 
994 
995   // Otherwise, don't merge in classLV yet, because in certain cases
996   // we need to completely ignore the visibility from it.
997 
998   // Specifically, if this decl exists and has an explicit attribute.
999   const NamedDecl *explicitSpecSuppressor = nullptr;
1000 
1001   if (const auto *MD = dyn_cast<CXXMethodDecl>(D)) {
1002     // Only look at the type-as-written. Otherwise, deducing the return type
1003     // of a function could change its linkage.
1004     QualType TypeAsWritten = MD->getType();
1005     if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
1006       TypeAsWritten = TSI->getType();
1007     if (!isExternallyVisible(TypeAsWritten->getLinkage()))
1008       return LinkageInfo::uniqueExternal();
1009 
1010     // If this is a method template specialization, use the linkage for
1011     // the template parameters and arguments.
1012     if (FunctionTemplateSpecializationInfo *spec
1013            = MD->getTemplateSpecializationInfo()) {
1014       mergeTemplateLV(LV, MD, spec, computation);
1015       if (spec->isExplicitSpecialization()) {
1016         explicitSpecSuppressor = MD;
1017       } else if (isExplicitMemberSpecialization(spec->getTemplate())) {
1018         explicitSpecSuppressor = spec->getTemplate()->getTemplatedDecl();
1019       }
1020     } else if (isExplicitMemberSpecialization(MD)) {
1021       explicitSpecSuppressor = MD;
1022     }
1023 
1024     // OpenMP target declare device functions are not callable from the host so
1025     // they should not be exported from the device image. This applies to all
1026     // functions as the host-callable kernel functions are emitted at codegen.
1027     ASTContext &Context = D->getASTContext();
1028     if (Context.getLangOpts().OpenMP && Context.getLangOpts().OpenMPIsDevice &&
1029         ((Context.getTargetInfo().getTriple().isAMDGPU() ||
1030           Context.getTargetInfo().getTriple().isNVPTX()) ||
1031          OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(MD)))
1032       LV.mergeVisibility(HiddenVisibility, /*newExplicit=*/false);
1033 
1034   } else if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
1035     if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(RD)) {
1036       mergeTemplateLV(LV, spec, computation);
1037       if (spec->isExplicitSpecialization()) {
1038         explicitSpecSuppressor = spec;
1039       } else {
1040         const ClassTemplateDecl *temp = spec->getSpecializedTemplate();
1041         if (isExplicitMemberSpecialization(temp)) {
1042           explicitSpecSuppressor = temp->getTemplatedDecl();
1043         }
1044       }
1045     } else if (isExplicitMemberSpecialization(RD)) {
1046       explicitSpecSuppressor = RD;
1047     }
1048 
1049   // Static data members.
1050   } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
1051     if (const auto *spec = dyn_cast<VarTemplateSpecializationDecl>(VD))
1052       mergeTemplateLV(LV, spec, computation);
1053 
1054     // Modify the variable's linkage by its type, but ignore the
1055     // type's visibility unless it's a definition.
1056     if (!IgnoreVarTypeLinkage) {
1057       LinkageInfo typeLV = getLVForType(*VD->getType(), computation);
1058       // FIXME: If the type's linkage is not externally visible, we can
1059       // give this static data member UniqueExternalLinkage.
1060       if (!LV.isVisibilityExplicit() && !classLV.isVisibilityExplicit())
1061         LV.mergeVisibility(typeLV);
1062       LV.mergeExternalVisibility(typeLV);
1063     }
1064 
1065     if (isExplicitMemberSpecialization(VD)) {
1066       explicitSpecSuppressor = VD;
1067     }
1068 
1069   // Template members.
1070   } else if (const auto *temp = dyn_cast<TemplateDecl>(D)) {
1071     bool considerVisibility =
1072       (!LV.isVisibilityExplicit() &&
1073        !classLV.isVisibilityExplicit() &&
1074        !hasExplicitVisibilityAlready(computation));
1075     LinkageInfo tempLV =
1076       getLVForTemplateParameterList(temp->getTemplateParameters(), computation);
1077     LV.mergeMaybeWithVisibility(tempLV, considerVisibility);
1078 
1079     if (const auto *redeclTemp = dyn_cast<RedeclarableTemplateDecl>(temp)) {
1080       if (isExplicitMemberSpecialization(redeclTemp)) {
1081         explicitSpecSuppressor = temp->getTemplatedDecl();
1082       }
1083     }
1084   }
1085 
1086   // We should never be looking for an attribute directly on a template.
1087   assert(!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor));
1088 
1089   // If this member is an explicit member specialization, and it has
1090   // an explicit attribute, ignore visibility from the parent.
1091   bool considerClassVisibility = true;
1092   if (explicitSpecSuppressor &&
1093       // optimization: hasDVA() is true only with explicit visibility.
1094       LV.isVisibilityExplicit() &&
1095       classLV.getVisibility() != DefaultVisibility &&
1096       hasDirectVisibilityAttribute(explicitSpecSuppressor, computation)) {
1097     considerClassVisibility = false;
1098   }
1099 
1100   // Finally, merge in information from the class.
1101   LV.mergeMaybeWithVisibility(classLV, considerClassVisibility);
1102   return LV;
1103 }
1104 
anchor()1105 void NamedDecl::anchor() {}
1106 
isLinkageValid() const1107 bool NamedDecl::isLinkageValid() const {
1108   if (!hasCachedLinkage())
1109     return true;
1110 
1111   Linkage L = LinkageComputer{}
1112                   .computeLVForDecl(this, LVComputationKind::forLinkageOnly())
1113                   .getLinkage();
1114   return L == getCachedLinkage();
1115 }
1116 
1117 ReservedIdentifierStatus
isReserved(const LangOptions & LangOpts) const1118 NamedDecl::isReserved(const LangOptions &LangOpts) const {
1119   const IdentifierInfo *II = getIdentifier();
1120 
1121   // This triggers at least for CXXLiteralIdentifiers, which we already checked
1122   // at lexing time.
1123   if (!II)
1124     return ReservedIdentifierStatus::NotReserved;
1125 
1126   ReservedIdentifierStatus Status = II->isReserved(LangOpts);
1127   if (isReservedAtGlobalScope(Status) && !isReservedInAllContexts(Status)) {
1128     // This name is only reserved at global scope. Check if this declaration
1129     // conflicts with a global scope declaration.
1130     if (isa<ParmVarDecl>(this) || isTemplateParameter())
1131       return ReservedIdentifierStatus::NotReserved;
1132 
1133     // C++ [dcl.link]/7:
1134     //   Two declarations [conflict] if [...] one declares a function or
1135     //   variable with C language linkage, and the other declares [...] a
1136     //   variable that belongs to the global scope.
1137     //
1138     // Therefore names that are reserved at global scope are also reserved as
1139     // names of variables and functions with C language linkage.
1140     const DeclContext *DC = getDeclContext()->getRedeclContext();
1141     if (DC->isTranslationUnit())
1142       return Status;
1143     if (auto *VD = dyn_cast<VarDecl>(this))
1144       if (VD->isExternC())
1145         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1146     if (auto *FD = dyn_cast<FunctionDecl>(this))
1147       if (FD->isExternC())
1148         return ReservedIdentifierStatus::StartsWithUnderscoreAndIsExternC;
1149     return ReservedIdentifierStatus::NotReserved;
1150   }
1151 
1152   return Status;
1153 }
1154 
getObjCFStringFormattingFamily() const1155 ObjCStringFormatFamily NamedDecl::getObjCFStringFormattingFamily() const {
1156   StringRef name = getName();
1157   if (name.empty()) return SFF_None;
1158 
1159   if (name.front() == 'C')
1160     if (name == "CFStringCreateWithFormat" ||
1161         name == "CFStringCreateWithFormatAndArguments" ||
1162         name == "CFStringAppendFormat" ||
1163         name == "CFStringAppendFormatAndArguments")
1164       return SFF_CFString;
1165   return SFF_None;
1166 }
1167 
getLinkageInternal() const1168 Linkage NamedDecl::getLinkageInternal() const {
1169   // We don't care about visibility here, so ask for the cheapest
1170   // possible visibility analysis.
1171   return LinkageComputer{}
1172       .getLVForDecl(this, LVComputationKind::forLinkageOnly())
1173       .getLinkage();
1174 }
1175 
getLinkageAndVisibility() const1176 LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1177   return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1178 }
1179 
1180 static std::optional<Visibility>
getExplicitVisibilityAux(const NamedDecl * ND,NamedDecl::ExplicitVisibilityKind kind,bool IsMostRecent)1181 getExplicitVisibilityAux(const NamedDecl *ND,
1182                          NamedDecl::ExplicitVisibilityKind kind,
1183                          bool IsMostRecent) {
1184   assert(!IsMostRecent || ND == ND->getMostRecentDecl());
1185 
1186   // Check the declaration itself first.
1187   if (std::optional<Visibility> V = getVisibilityOf(ND, kind))
1188     return V;
1189 
1190   // If this is a member class of a specialization of a class template
1191   // and the corresponding decl has explicit visibility, use that.
1192   if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
1193     CXXRecordDecl *InstantiatedFrom = RD->getInstantiatedFromMemberClass();
1194     if (InstantiatedFrom)
1195       return getVisibilityOf(InstantiatedFrom, kind);
1196   }
1197 
1198   // If there wasn't explicit visibility there, and this is a
1199   // specialization of a class template, check for visibility
1200   // on the pattern.
1201   if (const auto *spec = dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
1202     // Walk all the template decl till this point to see if there are
1203     // explicit visibility attributes.
1204     const auto *TD = spec->getSpecializedTemplate()->getTemplatedDecl();
1205     while (TD != nullptr) {
1206       auto Vis = getVisibilityOf(TD, kind);
1207       if (Vis != std::nullopt)
1208         return Vis;
1209       TD = TD->getPreviousDecl();
1210     }
1211     return std::nullopt;
1212   }
1213 
1214   // Use the most recent declaration.
1215   if (!IsMostRecent && !isa<NamespaceDecl>(ND)) {
1216     const NamedDecl *MostRecent = ND->getMostRecentDecl();
1217     if (MostRecent != ND)
1218       return getExplicitVisibilityAux(MostRecent, kind, true);
1219   }
1220 
1221   if (const auto *Var = dyn_cast<VarDecl>(ND)) {
1222     if (Var->isStaticDataMember()) {
1223       VarDecl *InstantiatedFrom = Var->getInstantiatedFromStaticDataMember();
1224       if (InstantiatedFrom)
1225         return getVisibilityOf(InstantiatedFrom, kind);
1226     }
1227 
1228     if (const auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(Var))
1229       return getVisibilityOf(VTSD->getSpecializedTemplate()->getTemplatedDecl(),
1230                              kind);
1231 
1232     return std::nullopt;
1233   }
1234   // Also handle function template specializations.
1235   if (const auto *fn = dyn_cast<FunctionDecl>(ND)) {
1236     // If the function is a specialization of a template with an
1237     // explicit visibility attribute, use that.
1238     if (FunctionTemplateSpecializationInfo *templateInfo
1239           = fn->getTemplateSpecializationInfo())
1240       return getVisibilityOf(templateInfo->getTemplate()->getTemplatedDecl(),
1241                              kind);
1242 
1243     // If the function is a member of a specialization of a class template
1244     // and the corresponding decl has explicit visibility, use that.
1245     FunctionDecl *InstantiatedFrom = fn->getInstantiatedFromMemberFunction();
1246     if (InstantiatedFrom)
1247       return getVisibilityOf(InstantiatedFrom, kind);
1248 
1249     return std::nullopt;
1250   }
1251 
1252   // The visibility of a template is stored in the templated decl.
1253   if (const auto *TD = dyn_cast<TemplateDecl>(ND))
1254     return getVisibilityOf(TD->getTemplatedDecl(), kind);
1255 
1256   return std::nullopt;
1257 }
1258 
1259 std::optional<Visibility>
getExplicitVisibility(ExplicitVisibilityKind kind) const1260 NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1261   return getExplicitVisibilityAux(this, kind, false);
1262 }
1263 
getLVForClosure(const DeclContext * DC,Decl * ContextDecl,LVComputationKind computation)1264 LinkageInfo LinkageComputer::getLVForClosure(const DeclContext *DC,
1265                                              Decl *ContextDecl,
1266                                              LVComputationKind computation) {
1267   // This lambda has its linkage/visibility determined by its owner.
1268   const NamedDecl *Owner;
1269   if (!ContextDecl)
1270     Owner = dyn_cast<NamedDecl>(DC);
1271   else if (isa<ParmVarDecl>(ContextDecl))
1272     Owner =
1273         dyn_cast<NamedDecl>(ContextDecl->getDeclContext()->getRedeclContext());
1274   else if (isa<ImplicitConceptSpecializationDecl>(ContextDecl)) {
1275     // Replace with the concept's owning decl, which is either a namespace or a
1276     // TU, so this needs a dyn_cast.
1277     Owner = dyn_cast<NamedDecl>(ContextDecl->getDeclContext());
1278   } else {
1279     Owner = cast<NamedDecl>(ContextDecl);
1280   }
1281 
1282   if (!Owner)
1283     return LinkageInfo::none();
1284 
1285   // If the owner has a deduced type, we need to skip querying the linkage and
1286   // visibility of that type, because it might involve this closure type.  The
1287   // only effect of this is that we might give a lambda VisibleNoLinkage rather
1288   // than NoLinkage when we don't strictly need to, which is benign.
1289   auto *VD = dyn_cast<VarDecl>(Owner);
1290   LinkageInfo OwnerLV =
1291       VD && VD->getType()->getContainedDeducedType()
1292           ? computeLVForDecl(Owner, computation, /*IgnoreVarTypeLinkage*/true)
1293           : getLVForDecl(Owner, computation);
1294 
1295   // A lambda never formally has linkage. But if the owner is externally
1296   // visible, then the lambda is too. We apply the same rules to blocks.
1297   if (!isExternallyVisible(OwnerLV.getLinkage()))
1298     return LinkageInfo::none();
1299   return LinkageInfo(VisibleNoLinkage, OwnerLV.getVisibility(),
1300                      OwnerLV.isVisibilityExplicit());
1301 }
1302 
getLVForLocalDecl(const NamedDecl * D,LVComputationKind computation)1303 LinkageInfo LinkageComputer::getLVForLocalDecl(const NamedDecl *D,
1304                                                LVComputationKind computation) {
1305   if (const auto *Function = dyn_cast<FunctionDecl>(D)) {
1306     if (Function->isInAnonymousNamespace() &&
1307         !isFirstInExternCContext(Function))
1308       return getInternalLinkageFor(Function);
1309 
1310     // This is a "void f();" which got merged with a file static.
1311     if (Function->getCanonicalDecl()->getStorageClass() == SC_Static)
1312       return getInternalLinkageFor(Function);
1313 
1314     LinkageInfo LV;
1315     if (!hasExplicitVisibilityAlready(computation)) {
1316       if (std::optional<Visibility> Vis =
1317               getExplicitVisibility(Function, computation))
1318         LV.mergeVisibility(*Vis, true);
1319     }
1320 
1321     // Note that Sema::MergeCompatibleFunctionDecls already takes care of
1322     // merging storage classes and visibility attributes, so we don't have to
1323     // look at previous decls in here.
1324 
1325     return LV;
1326   }
1327 
1328   if (const auto *Var = dyn_cast<VarDecl>(D)) {
1329     if (Var->hasExternalStorage()) {
1330       if (Var->isInAnonymousNamespace() && !isFirstInExternCContext(Var))
1331         return getInternalLinkageFor(Var);
1332 
1333       LinkageInfo LV;
1334       if (Var->getStorageClass() == SC_PrivateExtern)
1335         LV.mergeVisibility(HiddenVisibility, true);
1336       else if (!hasExplicitVisibilityAlready(computation)) {
1337         if (std::optional<Visibility> Vis =
1338                 getExplicitVisibility(Var, computation))
1339           LV.mergeVisibility(*Vis, true);
1340       }
1341 
1342       if (const VarDecl *Prev = Var->getPreviousDecl()) {
1343         LinkageInfo PrevLV = getLVForDecl(Prev, computation);
1344         if (PrevLV.getLinkage())
1345           LV.setLinkage(PrevLV.getLinkage());
1346         LV.mergeVisibility(PrevLV);
1347       }
1348 
1349       return LV;
1350     }
1351 
1352     if (!Var->isStaticLocal())
1353       return LinkageInfo::none();
1354   }
1355 
1356   ASTContext &Context = D->getASTContext();
1357   if (!Context.getLangOpts().CPlusPlus)
1358     return LinkageInfo::none();
1359 
1360   const Decl *OuterD = getOutermostFuncOrBlockContext(D);
1361   if (!OuterD || OuterD->isInvalidDecl())
1362     return LinkageInfo::none();
1363 
1364   LinkageInfo LV;
1365   if (const auto *BD = dyn_cast<BlockDecl>(OuterD)) {
1366     if (!BD->getBlockManglingNumber())
1367       return LinkageInfo::none();
1368 
1369     LV = getLVForClosure(BD->getDeclContext()->getRedeclContext(),
1370                          BD->getBlockManglingContextDecl(), computation);
1371   } else {
1372     const auto *FD = cast<FunctionDecl>(OuterD);
1373     if (!FD->isInlined() &&
1374         !isTemplateInstantiation(FD->getTemplateSpecializationKind()))
1375       return LinkageInfo::none();
1376 
1377     // If a function is hidden by -fvisibility-inlines-hidden option and
1378     // is not explicitly attributed as a hidden function,
1379     // we should not make static local variables in the function hidden.
1380     LV = getLVForDecl(FD, computation);
1381     if (isa<VarDecl>(D) && useInlineVisibilityHidden(FD) &&
1382         !LV.isVisibilityExplicit() &&
1383         !Context.getLangOpts().VisibilityInlinesHiddenStaticLocalVar) {
1384       assert(cast<VarDecl>(D)->isStaticLocal());
1385       // If this was an implicitly hidden inline method, check again for
1386       // explicit visibility on the parent class, and use that for static locals
1387       // if present.
1388       if (const auto *MD = dyn_cast<CXXMethodDecl>(FD))
1389         LV = getLVForDecl(MD->getParent(), computation);
1390       if (!LV.isVisibilityExplicit()) {
1391         Visibility globalVisibility =
1392             computation.isValueVisibility()
1393                 ? Context.getLangOpts().getValueVisibilityMode()
1394                 : Context.getLangOpts().getTypeVisibilityMode();
1395         return LinkageInfo(VisibleNoLinkage, globalVisibility,
1396                            /*visibilityExplicit=*/false);
1397       }
1398     }
1399   }
1400   if (!isExternallyVisible(LV.getLinkage()))
1401     return LinkageInfo::none();
1402   return LinkageInfo(VisibleNoLinkage, LV.getVisibility(),
1403                      LV.isVisibilityExplicit());
1404 }
1405 
computeLVForDecl(const NamedDecl * D,LVComputationKind computation,bool IgnoreVarTypeLinkage)1406 LinkageInfo LinkageComputer::computeLVForDecl(const NamedDecl *D,
1407                                               LVComputationKind computation,
1408                                               bool IgnoreVarTypeLinkage) {
1409   // Internal_linkage attribute overrides other considerations.
1410   if (D->hasAttr<InternalLinkageAttr>())
1411     return getInternalLinkageFor(D);
1412 
1413   // Objective-C: treat all Objective-C declarations as having external
1414   // linkage.
1415   switch (D->getKind()) {
1416     default:
1417       break;
1418 
1419     // Per C++ [basic.link]p2, only the names of objects, references,
1420     // functions, types, templates, namespaces, and values ever have linkage.
1421     //
1422     // Note that the name of a typedef, namespace alias, using declaration,
1423     // and so on are not the name of the corresponding type, namespace, or
1424     // declaration, so they do *not* have linkage.
1425     case Decl::ImplicitParam:
1426     case Decl::Label:
1427     case Decl::NamespaceAlias:
1428     case Decl::ParmVar:
1429     case Decl::Using:
1430     case Decl::UsingEnum:
1431     case Decl::UsingShadow:
1432     case Decl::UsingDirective:
1433       return LinkageInfo::none();
1434 
1435     case Decl::EnumConstant:
1436       // C++ [basic.link]p4: an enumerator has the linkage of its enumeration.
1437       if (D->getASTContext().getLangOpts().CPlusPlus)
1438         return getLVForDecl(cast<EnumDecl>(D->getDeclContext()), computation);
1439       return LinkageInfo::visible_none();
1440 
1441     case Decl::Typedef:
1442     case Decl::TypeAlias:
1443       // A typedef declaration has linkage if it gives a type a name for
1444       // linkage purposes.
1445       if (!cast<TypedefNameDecl>(D)
1446                ->getAnonDeclWithTypedefName(/*AnyRedecl*/true))
1447         return LinkageInfo::none();
1448       break;
1449 
1450     case Decl::TemplateTemplateParm: // count these as external
1451     case Decl::NonTypeTemplateParm:
1452     case Decl::ObjCAtDefsField:
1453     case Decl::ObjCCategory:
1454     case Decl::ObjCCategoryImpl:
1455     case Decl::ObjCCompatibleAlias:
1456     case Decl::ObjCImplementation:
1457     case Decl::ObjCMethod:
1458     case Decl::ObjCProperty:
1459     case Decl::ObjCPropertyImpl:
1460     case Decl::ObjCProtocol:
1461       return getExternalLinkageFor(D);
1462 
1463     case Decl::CXXRecord: {
1464       const auto *Record = cast<CXXRecordDecl>(D);
1465       if (Record->isLambda()) {
1466         if (Record->hasKnownLambdaInternalLinkage() ||
1467             !Record->getLambdaManglingNumber()) {
1468           // This lambda has no mangling number, so it's internal.
1469           return getInternalLinkageFor(D);
1470         }
1471 
1472         return getLVForClosure(
1473                   Record->getDeclContext()->getRedeclContext(),
1474                   Record->getLambdaContextDecl(), computation);
1475       }
1476 
1477       break;
1478     }
1479 
1480     case Decl::TemplateParamObject: {
1481       // The template parameter object can be referenced from anywhere its type
1482       // and value can be referenced.
1483       auto *TPO = cast<TemplateParamObjectDecl>(D);
1484       LinkageInfo LV = getLVForType(*TPO->getType(), computation);
1485       LV.merge(getLVForValue(TPO->getValue(), computation));
1486       return LV;
1487     }
1488   }
1489 
1490   // Handle linkage for namespace-scope names.
1491   if (D->getDeclContext()->getRedeclContext()->isFileContext())
1492     return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1493 
1494   // C++ [basic.link]p5:
1495   //   In addition, a member function, static data member, a named
1496   //   class or enumeration of class scope, or an unnamed class or
1497   //   enumeration defined in a class-scope typedef declaration such
1498   //   that the class or enumeration has the typedef name for linkage
1499   //   purposes (7.1.3), has external linkage if the name of the class
1500   //   has external linkage.
1501   if (D->getDeclContext()->isRecord())
1502     return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1503 
1504   // C++ [basic.link]p6:
1505   //   The name of a function declared in block scope and the name of
1506   //   an object declared by a block scope extern declaration have
1507   //   linkage. If there is a visible declaration of an entity with
1508   //   linkage having the same name and type, ignoring entities
1509   //   declared outside the innermost enclosing namespace scope, the
1510   //   block scope declaration declares that same entity and receives
1511   //   the linkage of the previous declaration. If there is more than
1512   //   one such matching entity, the program is ill-formed. Otherwise,
1513   //   if no matching entity is found, the block scope entity receives
1514   //   external linkage.
1515   if (D->getDeclContext()->isFunctionOrMethod())
1516     return getLVForLocalDecl(D, computation);
1517 
1518   // C++ [basic.link]p6:
1519   //   Names not covered by these rules have no linkage.
1520   return LinkageInfo::none();
1521 }
1522 
1523 /// getLVForDecl - Get the linkage and visibility for the given declaration.
getLVForDecl(const NamedDecl * D,LVComputationKind computation)1524 LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1525                                           LVComputationKind computation) {
1526   // Internal_linkage attribute overrides other considerations.
1527   if (D->hasAttr<InternalLinkageAttr>())
1528     return getInternalLinkageFor(D);
1529 
1530   if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1531     return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1532 
1533   if (std::optional<LinkageInfo> LI = lookup(D, computation))
1534     return *LI;
1535 
1536   LinkageInfo LV = computeLVForDecl(D, computation);
1537   if (D->hasCachedLinkage())
1538     assert(D->getCachedLinkage() == LV.getLinkage());
1539 
1540   D->setCachedLinkage(LV.getLinkage());
1541   cache(D, computation, LV);
1542 
1543 #ifndef NDEBUG
1544   // In C (because of gnu inline) and in c++ with microsoft extensions an
1545   // static can follow an extern, so we can have two decls with different
1546   // linkages.
1547   const LangOptions &Opts = D->getASTContext().getLangOpts();
1548   if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1549     return LV;
1550 
1551   // We have just computed the linkage for this decl. By induction we know
1552   // that all other computed linkages match, check that the one we just
1553   // computed also does.
1554   NamedDecl *Old = nullptr;
1555   for (auto *I : D->redecls()) {
1556     auto *T = cast<NamedDecl>(I);
1557     if (T == D)
1558       continue;
1559     if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1560       Old = T;
1561       break;
1562     }
1563   }
1564   assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage());
1565 #endif
1566 
1567   return LV;
1568 }
1569 
getDeclLinkageAndVisibility(const NamedDecl * D)1570 LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1571   NamedDecl::ExplicitVisibilityKind EK = usesTypeVisibility(D)
1572                                              ? NamedDecl::VisibilityForType
1573                                              : NamedDecl::VisibilityForValue;
1574   LVComputationKind CK(EK);
1575   return getLVForDecl(D, D->getASTContext().getLangOpts().IgnoreXCOFFVisibility
1576                              ? CK.forLinkageOnly()
1577                              : CK);
1578 }
1579 
getOwningModuleForLinkage(bool IgnoreLinkage) const1580 Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1581   if (isa<NamespaceDecl>(this))
1582     // Namespaces never have module linkage.  It is the entities within them
1583     // that [may] do.
1584     return nullptr;
1585 
1586   Module *M = getOwningModule();
1587   if (!M)
1588     return nullptr;
1589 
1590   switch (M->Kind) {
1591   case Module::ModuleMapModule:
1592     // Module map modules have no special linkage semantics.
1593     return nullptr;
1594 
1595   case Module::ModuleInterfaceUnit:
1596   case Module::ModulePartitionInterface:
1597   case Module::ModulePartitionImplementation:
1598     return M;
1599 
1600   case Module::ModuleHeaderUnit:
1601   case Module::GlobalModuleFragment: {
1602     // External linkage declarations in the global module have no owning module
1603     // for linkage purposes. But internal linkage declarations in the global
1604     // module fragment of a particular module are owned by that module for
1605     // linkage purposes.
1606     // FIXME: p1815 removes the need for this distinction -- there are no
1607     // internal linkage declarations that need to be referred to from outside
1608     // this TU.
1609     if (IgnoreLinkage)
1610       return nullptr;
1611     bool InternalLinkage;
1612     if (auto *ND = dyn_cast<NamedDecl>(this))
1613       InternalLinkage = !ND->hasExternalFormalLinkage();
1614     else
1615       InternalLinkage = isInAnonymousNamespace();
1616     return InternalLinkage ? M->Kind == Module::ModuleHeaderUnit ? M : M->Parent
1617                            : nullptr;
1618   }
1619 
1620   case Module::PrivateModuleFragment:
1621     // The private module fragment is part of its containing module for linkage
1622     // purposes.
1623     return M->Parent;
1624   }
1625 
1626   llvm_unreachable("unknown module kind");
1627 }
1628 
printName(raw_ostream & OS,const PrintingPolicy &) const1629 void NamedDecl::printName(raw_ostream &OS, const PrintingPolicy&) const {
1630   OS << Name;
1631 }
1632 
printName(raw_ostream & OS) const1633 void NamedDecl::printName(raw_ostream &OS) const {
1634   printName(OS, getASTContext().getPrintingPolicy());
1635 }
1636 
getQualifiedNameAsString() const1637 std::string NamedDecl::getQualifiedNameAsString() const {
1638   std::string QualName;
1639   llvm::raw_string_ostream OS(QualName);
1640   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1641   return QualName;
1642 }
1643 
printQualifiedName(raw_ostream & OS) const1644 void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1645   printQualifiedName(OS, getASTContext().getPrintingPolicy());
1646 }
1647 
printQualifiedName(raw_ostream & OS,const PrintingPolicy & P) const1648 void NamedDecl::printQualifiedName(raw_ostream &OS,
1649                                    const PrintingPolicy &P) const {
1650   if (getDeclContext()->isFunctionOrMethod()) {
1651     // We do not print '(anonymous)' for function parameters without name.
1652     printName(OS, P);
1653     return;
1654   }
1655   printNestedNameSpecifier(OS, P);
1656   if (getDeclName())
1657     OS << *this;
1658   else {
1659     // Give the printName override a chance to pick a different name before we
1660     // fall back to "(anonymous)".
1661     SmallString<64> NameBuffer;
1662     llvm::raw_svector_ostream NameOS(NameBuffer);
1663     printName(NameOS, P);
1664     if (NameBuffer.empty())
1665       OS << "(anonymous)";
1666     else
1667       OS << NameBuffer;
1668   }
1669 }
1670 
printNestedNameSpecifier(raw_ostream & OS) const1671 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1672   printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1673 }
1674 
printNestedNameSpecifier(raw_ostream & OS,const PrintingPolicy & P) const1675 void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1676                                          const PrintingPolicy &P) const {
1677   const DeclContext *Ctx = getDeclContext();
1678 
1679   // For ObjC methods and properties, look through categories and use the
1680   // interface as context.
1681   if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1682     if (auto *ID = MD->getClassInterface())
1683       Ctx = ID;
1684   } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1685     if (auto *MD = PD->getGetterMethodDecl())
1686       if (auto *ID = MD->getClassInterface())
1687         Ctx = ID;
1688   } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1689     if (auto *CI = ID->getContainingInterface())
1690       Ctx = CI;
1691   }
1692 
1693   if (Ctx->isFunctionOrMethod())
1694     return;
1695 
1696   using ContextsTy = SmallVector<const DeclContext *, 8>;
1697   ContextsTy Contexts;
1698 
1699   // Collect named contexts.
1700   DeclarationName NameInScope = getDeclName();
1701   for (; Ctx; Ctx = Ctx->getParent()) {
1702     // Suppress anonymous namespace if requested.
1703     if (P.SuppressUnwrittenScope && isa<NamespaceDecl>(Ctx) &&
1704         cast<NamespaceDecl>(Ctx)->isAnonymousNamespace())
1705       continue;
1706 
1707     // Suppress inline namespace if it doesn't make the result ambiguous.
1708     if (P.SuppressInlineNamespace && Ctx->isInlineNamespace() && NameInScope &&
1709         cast<NamespaceDecl>(Ctx)->isRedundantInlineQualifierFor(NameInScope))
1710       continue;
1711 
1712     // Skip non-named contexts such as linkage specifications and ExportDecls.
1713     const NamedDecl *ND = dyn_cast<NamedDecl>(Ctx);
1714     if (!ND)
1715       continue;
1716 
1717     Contexts.push_back(Ctx);
1718     NameInScope = ND->getDeclName();
1719   }
1720 
1721   for (const DeclContext *DC : llvm::reverse(Contexts)) {
1722     if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1723       OS << Spec->getName();
1724       const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1725       printTemplateArgumentList(
1726           OS, TemplateArgs.asArray(), P,
1727           Spec->getSpecializedTemplate()->getTemplateParameters());
1728     } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1729       if (ND->isAnonymousNamespace()) {
1730         OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1731                                 : "(anonymous namespace)");
1732       }
1733       else
1734         OS << *ND;
1735     } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1736       if (!RD->getIdentifier())
1737         OS << "(anonymous " << RD->getKindName() << ')';
1738       else
1739         OS << *RD;
1740     } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1741       const FunctionProtoType *FT = nullptr;
1742       if (FD->hasWrittenPrototype())
1743         FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1744 
1745       OS << *FD << '(';
1746       if (FT) {
1747         unsigned NumParams = FD->getNumParams();
1748         for (unsigned i = 0; i < NumParams; ++i) {
1749           if (i)
1750             OS << ", ";
1751           OS << FD->getParamDecl(i)->getType().stream(P);
1752         }
1753 
1754         if (FT->isVariadic()) {
1755           if (NumParams > 0)
1756             OS << ", ";
1757           OS << "...";
1758         }
1759       }
1760       OS << ')';
1761     } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1762       // C++ [dcl.enum]p10: Each enum-name and each unscoped
1763       // enumerator is declared in the scope that immediately contains
1764       // the enum-specifier. Each scoped enumerator is declared in the
1765       // scope of the enumeration.
1766       // For the case of unscoped enumerator, do not include in the qualified
1767       // name any information about its enum enclosing scope, as its visibility
1768       // is global.
1769       if (ED->isScoped())
1770         OS << *ED;
1771       else
1772         continue;
1773     } else {
1774       OS << *cast<NamedDecl>(DC);
1775     }
1776     OS << "::";
1777   }
1778 }
1779 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const1780 void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1781                                      const PrintingPolicy &Policy,
1782                                      bool Qualified) const {
1783   if (Qualified)
1784     printQualifiedName(OS, Policy);
1785   else
1786     printName(OS, Policy);
1787 }
1788 
isRedeclarableImpl(Redeclarable<T> *)1789 template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1790   return true;
1791 }
isRedeclarableImpl(...)1792 static bool isRedeclarableImpl(...) { return false; }
isRedeclarable(Decl::Kind K)1793 static bool isRedeclarable(Decl::Kind K) {
1794   switch (K) {
1795 #define DECL(Type, Base) \
1796   case Decl::Type: \
1797     return isRedeclarableImpl((Type##Decl *)nullptr);
1798 #define ABSTRACT_DECL(DECL)
1799 #include "clang/AST/DeclNodes.inc"
1800   }
1801   llvm_unreachable("unknown decl kind");
1802 }
1803 
declarationReplaces(NamedDecl * OldD,bool IsKnownNewer) const1804 bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1805   assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch");
1806 
1807   // Never replace one imported declaration with another; we need both results
1808   // when re-exporting.
1809   if (OldD->isFromASTFile() && isFromASTFile())
1810     return false;
1811 
1812   // A kind mismatch implies that the declaration is not replaced.
1813   if (OldD->getKind() != getKind())
1814     return false;
1815 
1816   // For method declarations, we never replace. (Why?)
1817   if (isa<ObjCMethodDecl>(this))
1818     return false;
1819 
1820   // For parameters, pick the newer one. This is either an error or (in
1821   // Objective-C) permitted as an extension.
1822   if (isa<ParmVarDecl>(this))
1823     return true;
1824 
1825   // Inline namespaces can give us two declarations with the same
1826   // name and kind in the same scope but different contexts; we should
1827   // keep both declarations in this case.
1828   if (!this->getDeclContext()->getRedeclContext()->Equals(
1829           OldD->getDeclContext()->getRedeclContext()))
1830     return false;
1831 
1832   // Using declarations can be replaced if they import the same name from the
1833   // same context.
1834   if (auto *UD = dyn_cast<UsingDecl>(this)) {
1835     ASTContext &Context = getASTContext();
1836     return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1837            Context.getCanonicalNestedNameSpecifier(
1838                cast<UsingDecl>(OldD)->getQualifier());
1839   }
1840   if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1841     ASTContext &Context = getASTContext();
1842     return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1843            Context.getCanonicalNestedNameSpecifier(
1844                         cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1845   }
1846 
1847   if (isRedeclarable(getKind())) {
1848     if (getCanonicalDecl() != OldD->getCanonicalDecl())
1849       return false;
1850 
1851     if (IsKnownNewer)
1852       return true;
1853 
1854     // Check whether this is actually newer than OldD. We want to keep the
1855     // newer declaration. This loop will usually only iterate once, because
1856     // OldD is usually the previous declaration.
1857     for (auto *D : redecls()) {
1858       if (D == OldD)
1859         break;
1860 
1861       // If we reach the canonical declaration, then OldD is not actually older
1862       // than this one.
1863       //
1864       // FIXME: In this case, we should not add this decl to the lookup table.
1865       if (D->isCanonicalDecl())
1866         return false;
1867     }
1868 
1869     // It's a newer declaration of the same kind of declaration in the same
1870     // scope: we want this decl instead of the existing one.
1871     return true;
1872   }
1873 
1874   // In all other cases, we need to keep both declarations in case they have
1875   // different visibility. Any attempt to use the name will result in an
1876   // ambiguity if more than one is visible.
1877   return false;
1878 }
1879 
hasLinkage() const1880 bool NamedDecl::hasLinkage() const {
1881   return getFormalLinkage() != NoLinkage;
1882 }
1883 
getUnderlyingDeclImpl()1884 NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1885   NamedDecl *ND = this;
1886   if (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1887     ND = UD->getTargetDecl();
1888 
1889   if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1890     return AD->getClassInterface();
1891 
1892   if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1893     return AD->getNamespace();
1894 
1895   return ND;
1896 }
1897 
isCXXInstanceMember() const1898 bool NamedDecl::isCXXInstanceMember() const {
1899   if (!isCXXClassMember())
1900     return false;
1901 
1902   const NamedDecl *D = this;
1903   if (isa<UsingShadowDecl>(D))
1904     D = cast<UsingShadowDecl>(D)->getTargetDecl();
1905 
1906   if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1907     return true;
1908   if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1909     return MD->isInstance();
1910   return false;
1911 }
1912 
1913 //===----------------------------------------------------------------------===//
1914 // DeclaratorDecl Implementation
1915 //===----------------------------------------------------------------------===//
1916 
1917 template <typename DeclT>
getTemplateOrInnerLocStart(const DeclT * decl)1918 static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1919   if (decl->getNumTemplateParameterLists() > 0)
1920     return decl->getTemplateParameterList(0)->getTemplateLoc();
1921   return decl->getInnerLocStart();
1922 }
1923 
getTypeSpecStartLoc() const1924 SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1925   TypeSourceInfo *TSI = getTypeSourceInfo();
1926   if (TSI) return TSI->getTypeLoc().getBeginLoc();
1927   return SourceLocation();
1928 }
1929 
getTypeSpecEndLoc() const1930 SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1931   TypeSourceInfo *TSI = getTypeSourceInfo();
1932   if (TSI) return TSI->getTypeLoc().getEndLoc();
1933   return SourceLocation();
1934 }
1935 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)1936 void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1937   if (QualifierLoc) {
1938     // Make sure the extended decl info is allocated.
1939     if (!hasExtInfo()) {
1940       // Save (non-extended) type source info pointer.
1941       auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1942       // Allocate external info struct.
1943       DeclInfo = new (getASTContext()) ExtInfo;
1944       // Restore savedTInfo into (extended) decl info.
1945       getExtInfo()->TInfo = savedTInfo;
1946     }
1947     // Set qualifier info.
1948     getExtInfo()->QualifierLoc = QualifierLoc;
1949   } else if (hasExtInfo()) {
1950     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1951     getExtInfo()->QualifierLoc = QualifierLoc;
1952   }
1953 }
1954 
setTrailingRequiresClause(Expr * TrailingRequiresClause)1955 void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1956   assert(TrailingRequiresClause);
1957   // Make sure the extended decl info is allocated.
1958   if (!hasExtInfo()) {
1959     // Save (non-extended) type source info pointer.
1960     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1961     // Allocate external info struct.
1962     DeclInfo = new (getASTContext()) ExtInfo;
1963     // Restore savedTInfo into (extended) decl info.
1964     getExtInfo()->TInfo = savedTInfo;
1965   }
1966   // Set requires clause info.
1967   getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1968 }
1969 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)1970 void DeclaratorDecl::setTemplateParameterListsInfo(
1971     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1972   assert(!TPLists.empty());
1973   // Make sure the extended decl info is allocated.
1974   if (!hasExtInfo()) {
1975     // Save (non-extended) type source info pointer.
1976     auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1977     // Allocate external info struct.
1978     DeclInfo = new (getASTContext()) ExtInfo;
1979     // Restore savedTInfo into (extended) decl info.
1980     getExtInfo()->TInfo = savedTInfo;
1981   }
1982   // Set the template parameter lists info.
1983   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1984 }
1985 
getOuterLocStart() const1986 SourceLocation DeclaratorDecl::getOuterLocStart() const {
1987   return getTemplateOrInnerLocStart(this);
1988 }
1989 
1990 // Helper function: returns true if QT is or contains a type
1991 // having a postfix component.
typeIsPostfix(QualType QT)1992 static bool typeIsPostfix(QualType QT) {
1993   while (true) {
1994     const Type* T = QT.getTypePtr();
1995     switch (T->getTypeClass()) {
1996     default:
1997       return false;
1998     case Type::Pointer:
1999       QT = cast<PointerType>(T)->getPointeeType();
2000       break;
2001     case Type::BlockPointer:
2002       QT = cast<BlockPointerType>(T)->getPointeeType();
2003       break;
2004     case Type::MemberPointer:
2005       QT = cast<MemberPointerType>(T)->getPointeeType();
2006       break;
2007     case Type::LValueReference:
2008     case Type::RValueReference:
2009       QT = cast<ReferenceType>(T)->getPointeeType();
2010       break;
2011     case Type::PackExpansion:
2012       QT = cast<PackExpansionType>(T)->getPattern();
2013       break;
2014     case Type::Paren:
2015     case Type::ConstantArray:
2016     case Type::DependentSizedArray:
2017     case Type::IncompleteArray:
2018     case Type::VariableArray:
2019     case Type::FunctionProto:
2020     case Type::FunctionNoProto:
2021       return true;
2022     }
2023   }
2024 }
2025 
getSourceRange() const2026 SourceRange DeclaratorDecl::getSourceRange() const {
2027   SourceLocation RangeEnd = getLocation();
2028   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
2029     // If the declaration has no name or the type extends past the name take the
2030     // end location of the type.
2031     if (!getDeclName() || typeIsPostfix(TInfo->getType()))
2032       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
2033   }
2034   return SourceRange(getOuterLocStart(), RangeEnd);
2035 }
2036 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)2037 void QualifierInfo::setTemplateParameterListsInfo(
2038     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
2039   // Free previous template parameters (if any).
2040   if (NumTemplParamLists > 0) {
2041     Context.Deallocate(TemplParamLists);
2042     TemplParamLists = nullptr;
2043     NumTemplParamLists = 0;
2044   }
2045   // Set info on matched template parameter lists (if any).
2046   if (!TPLists.empty()) {
2047     TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
2048     NumTemplParamLists = TPLists.size();
2049     std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
2050   }
2051 }
2052 
2053 //===----------------------------------------------------------------------===//
2054 // VarDecl Implementation
2055 //===----------------------------------------------------------------------===//
2056 
getStorageClassSpecifierString(StorageClass SC)2057 const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
2058   switch (SC) {
2059   case SC_None:                 break;
2060   case SC_Auto:                 return "auto";
2061   case SC_Extern:               return "extern";
2062   case SC_PrivateExtern:        return "__private_extern__";
2063   case SC_Register:             return "register";
2064   case SC_Static:               return "static";
2065   }
2066 
2067   llvm_unreachable("Invalid storage class");
2068 }
2069 
VarDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,const IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass SC)2070 VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
2071                  SourceLocation StartLoc, SourceLocation IdLoc,
2072                  const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
2073                  StorageClass SC)
2074     : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
2075       redeclarable_base(C) {
2076   static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
2077                 "VarDeclBitfields too large!");
2078   static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
2079                 "ParmVarDeclBitfields too large!");
2080   static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
2081                 "NonParmVarDeclBitfields too large!");
2082   AllBits = 0;
2083   VarDeclBits.SClass = SC;
2084   // Everything else is implicitly initialized to false.
2085 }
2086 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartL,SourceLocation IdL,const IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S)2087 VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartL,
2088                          SourceLocation IdL, const IdentifierInfo *Id,
2089                          QualType T, TypeSourceInfo *TInfo, StorageClass S) {
2090   return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
2091 }
2092 
CreateDeserialized(ASTContext & C,unsigned ID)2093 VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2094   return new (C, ID)
2095       VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
2096               QualType(), nullptr, SC_None);
2097 }
2098 
setStorageClass(StorageClass SC)2099 void VarDecl::setStorageClass(StorageClass SC) {
2100   assert(isLegalForVariable(SC));
2101   VarDeclBits.SClass = SC;
2102 }
2103 
getTLSKind() const2104 VarDecl::TLSKind VarDecl::getTLSKind() const {
2105   switch (VarDeclBits.TSCSpec) {
2106   case TSCS_unspecified:
2107     if (!hasAttr<ThreadAttr>() &&
2108         !(getASTContext().getLangOpts().OpenMPUseTLS &&
2109           getASTContext().getTargetInfo().isTLSSupported() &&
2110           hasAttr<OMPThreadPrivateDeclAttr>()))
2111       return TLS_None;
2112     return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
2113                 LangOptions::MSVC2015)) ||
2114             hasAttr<OMPThreadPrivateDeclAttr>())
2115                ? TLS_Dynamic
2116                : TLS_Static;
2117   case TSCS___thread: // Fall through.
2118   case TSCS__Thread_local:
2119     return TLS_Static;
2120   case TSCS_thread_local:
2121     return TLS_Dynamic;
2122   }
2123   llvm_unreachable("Unknown thread storage class specifier!");
2124 }
2125 
getSourceRange() const2126 SourceRange VarDecl::getSourceRange() const {
2127   if (const Expr *Init = getInit()) {
2128     SourceLocation InitEnd = Init->getEndLoc();
2129     // If Init is implicit, ignore its source range and fallback on
2130     // DeclaratorDecl::getSourceRange() to handle postfix elements.
2131     if (InitEnd.isValid() && InitEnd != getLocation())
2132       return SourceRange(getOuterLocStart(), InitEnd);
2133   }
2134   return DeclaratorDecl::getSourceRange();
2135 }
2136 
2137 template<typename T>
getDeclLanguageLinkage(const T & D)2138 static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2139   // C++ [dcl.link]p1: All function types, function names with external linkage,
2140   // and variable names with external linkage have a language linkage.
2141   if (!D.hasExternalFormalLinkage())
2142     return NoLanguageLinkage;
2143 
2144   // Language linkage is a C++ concept, but saying that everything else in C has
2145   // C language linkage fits the implementation nicely.
2146   ASTContext &Context = D.getASTContext();
2147   if (!Context.getLangOpts().CPlusPlus)
2148     return CLanguageLinkage;
2149 
2150   // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2151   // language linkage of the names of class members and the function type of
2152   // class member functions.
2153   const DeclContext *DC = D.getDeclContext();
2154   if (DC->isRecord())
2155     return CXXLanguageLinkage;
2156 
2157   // If the first decl is in an extern "C" context, any other redeclaration
2158   // will have C language linkage. If the first one is not in an extern "C"
2159   // context, we would have reported an error for any other decl being in one.
2160   if (isFirstInExternCContext(&D))
2161     return CLanguageLinkage;
2162   return CXXLanguageLinkage;
2163 }
2164 
2165 template<typename T>
isDeclExternC(const T & D)2166 static bool isDeclExternC(const T &D) {
2167   // Since the context is ignored for class members, they can only have C++
2168   // language linkage or no language linkage.
2169   const DeclContext *DC = D.getDeclContext();
2170   if (DC->isRecord()) {
2171     assert(D.getASTContext().getLangOpts().CPlusPlus);
2172     return false;
2173   }
2174 
2175   return D.getLanguageLinkage() == CLanguageLinkage;
2176 }
2177 
getLanguageLinkage() const2178 LanguageLinkage VarDecl::getLanguageLinkage() const {
2179   return getDeclLanguageLinkage(*this);
2180 }
2181 
isExternC() const2182 bool VarDecl::isExternC() const {
2183   return isDeclExternC(*this);
2184 }
2185 
isInExternCContext() const2186 bool VarDecl::isInExternCContext() const {
2187   return getLexicalDeclContext()->isExternCContext();
2188 }
2189 
isInExternCXXContext() const2190 bool VarDecl::isInExternCXXContext() const {
2191   return getLexicalDeclContext()->isExternCXXContext();
2192 }
2193 
getCanonicalDecl()2194 VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2195 
2196 VarDecl::DefinitionKind
isThisDeclarationADefinition(ASTContext & C) const2197 VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2198   if (isThisDeclarationADemotedDefinition())
2199     return DeclarationOnly;
2200 
2201   // C++ [basic.def]p2:
2202   //   A declaration is a definition unless [...] it contains the 'extern'
2203   //   specifier or a linkage-specification and neither an initializer [...],
2204   //   it declares a non-inline static data member in a class declaration [...],
2205   //   it declares a static data member outside a class definition and the variable
2206   //   was defined within the class with the constexpr specifier [...],
2207   // C++1y [temp.expl.spec]p15:
2208   //   An explicit specialization of a static data member or an explicit
2209   //   specialization of a static data member template is a definition if the
2210   //   declaration includes an initializer; otherwise, it is a declaration.
2211   //
2212   // FIXME: How do you declare (but not define) a partial specialization of
2213   // a static data member template outside the containing class?
2214   if (isStaticDataMember()) {
2215     if (isOutOfLine() &&
2216         !(getCanonicalDecl()->isInline() &&
2217           getCanonicalDecl()->isConstexpr()) &&
2218         (hasInit() ||
2219          // If the first declaration is out-of-line, this may be an
2220          // instantiation of an out-of-line partial specialization of a variable
2221          // template for which we have not yet instantiated the initializer.
2222          (getFirstDecl()->isOutOfLine()
2223               ? getTemplateSpecializationKind() == TSK_Undeclared
2224               : getTemplateSpecializationKind() !=
2225                     TSK_ExplicitSpecialization) ||
2226          isa<VarTemplatePartialSpecializationDecl>(this)))
2227       return Definition;
2228     if (!isOutOfLine() && isInline())
2229       return Definition;
2230     return DeclarationOnly;
2231   }
2232   // C99 6.7p5:
2233   //   A definition of an identifier is a declaration for that identifier that
2234   //   [...] causes storage to be reserved for that object.
2235   // Note: that applies for all non-file-scope objects.
2236   // C99 6.9.2p1:
2237   //   If the declaration of an identifier for an object has file scope and an
2238   //   initializer, the declaration is an external definition for the identifier
2239   if (hasInit())
2240     return Definition;
2241 
2242   if (hasDefiningAttr())
2243     return Definition;
2244 
2245   if (const auto *SAA = getAttr<SelectAnyAttr>())
2246     if (!SAA->isInherited())
2247       return Definition;
2248 
2249   // A variable template specialization (other than a static data member
2250   // template or an explicit specialization) is a declaration until we
2251   // instantiate its initializer.
2252   if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2253     if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2254         !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2255         !VTSD->IsCompleteDefinition)
2256       return DeclarationOnly;
2257   }
2258 
2259   if (hasExternalStorage())
2260     return DeclarationOnly;
2261 
2262   // [dcl.link] p7:
2263   //   A declaration directly contained in a linkage-specification is treated
2264   //   as if it contains the extern specifier for the purpose of determining
2265   //   the linkage of the declared name and whether it is a definition.
2266   if (isSingleLineLanguageLinkage(*this))
2267     return DeclarationOnly;
2268 
2269   // C99 6.9.2p2:
2270   //   A declaration of an object that has file scope without an initializer,
2271   //   and without a storage class specifier or the scs 'static', constitutes
2272   //   a tentative definition.
2273   // No such thing in C++.
2274   if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2275     return TentativeDefinition;
2276 
2277   // What's left is (in C, block-scope) declarations without initializers or
2278   // external storage. These are definitions.
2279   return Definition;
2280 }
2281 
getActingDefinition()2282 VarDecl *VarDecl::getActingDefinition() {
2283   DefinitionKind Kind = isThisDeclarationADefinition();
2284   if (Kind != TentativeDefinition)
2285     return nullptr;
2286 
2287   VarDecl *LastTentative = nullptr;
2288 
2289   // Loop through the declaration chain, starting with the most recent.
2290   for (VarDecl *Decl = getMostRecentDecl(); Decl;
2291        Decl = Decl->getPreviousDecl()) {
2292     Kind = Decl->isThisDeclarationADefinition();
2293     if (Kind == Definition)
2294       return nullptr;
2295     // Record the first (most recent) TentativeDefinition that is encountered.
2296     if (Kind == TentativeDefinition && !LastTentative)
2297       LastTentative = Decl;
2298   }
2299 
2300   return LastTentative;
2301 }
2302 
getDefinition(ASTContext & C)2303 VarDecl *VarDecl::getDefinition(ASTContext &C) {
2304   VarDecl *First = getFirstDecl();
2305   for (auto *I : First->redecls()) {
2306     if (I->isThisDeclarationADefinition(C) == Definition)
2307       return I;
2308   }
2309   return nullptr;
2310 }
2311 
hasDefinition(ASTContext & C) const2312 VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2313   DefinitionKind Kind = DeclarationOnly;
2314 
2315   const VarDecl *First = getFirstDecl();
2316   for (auto *I : First->redecls()) {
2317     Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2318     if (Kind == Definition)
2319       break;
2320   }
2321 
2322   return Kind;
2323 }
2324 
getAnyInitializer(const VarDecl * & D) const2325 const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2326   for (auto *I : redecls()) {
2327     if (auto Expr = I->getInit()) {
2328       D = I;
2329       return Expr;
2330     }
2331   }
2332   return nullptr;
2333 }
2334 
hasInit() const2335 bool VarDecl::hasInit() const {
2336   if (auto *P = dyn_cast<ParmVarDecl>(this))
2337     if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2338       return false;
2339 
2340   return !Init.isNull();
2341 }
2342 
getInit()2343 Expr *VarDecl::getInit() {
2344   if (!hasInit())
2345     return nullptr;
2346 
2347   if (auto *S = Init.dyn_cast<Stmt *>())
2348     return cast<Expr>(S);
2349 
2350   return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2351 }
2352 
getInitAddress()2353 Stmt **VarDecl::getInitAddress() {
2354   if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2355     return &ES->Value;
2356 
2357   return Init.getAddrOfPtr1();
2358 }
2359 
getInitializingDeclaration()2360 VarDecl *VarDecl::getInitializingDeclaration() {
2361   VarDecl *Def = nullptr;
2362   for (auto *I : redecls()) {
2363     if (I->hasInit())
2364       return I;
2365 
2366     if (I->isThisDeclarationADefinition()) {
2367       if (isStaticDataMember())
2368         return I;
2369       Def = I;
2370     }
2371   }
2372   return Def;
2373 }
2374 
isOutOfLine() const2375 bool VarDecl::isOutOfLine() const {
2376   if (Decl::isOutOfLine())
2377     return true;
2378 
2379   if (!isStaticDataMember())
2380     return false;
2381 
2382   // If this static data member was instantiated from a static data member of
2383   // a class template, check whether that static data member was defined
2384   // out-of-line.
2385   if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2386     return VD->isOutOfLine();
2387 
2388   return false;
2389 }
2390 
setInit(Expr * I)2391 void VarDecl::setInit(Expr *I) {
2392   if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2393     Eval->~EvaluatedStmt();
2394     getASTContext().Deallocate(Eval);
2395   }
2396 
2397   Init = I;
2398 }
2399 
mightBeUsableInConstantExpressions(const ASTContext & C) const2400 bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2401   const LangOptions &Lang = C.getLangOpts();
2402 
2403   // OpenCL permits const integral variables to be used in constant
2404   // expressions, like in C++98.
2405   if (!Lang.CPlusPlus && !Lang.OpenCL)
2406     return false;
2407 
2408   // Function parameters are never usable in constant expressions.
2409   if (isa<ParmVarDecl>(this))
2410     return false;
2411 
2412   // The values of weak variables are never usable in constant expressions.
2413   if (isWeak())
2414     return false;
2415 
2416   // In C++11, any variable of reference type can be used in a constant
2417   // expression if it is initialized by a constant expression.
2418   if (Lang.CPlusPlus11 && getType()->isReferenceType())
2419     return true;
2420 
2421   // Only const objects can be used in constant expressions in C++. C++98 does
2422   // not require the variable to be non-volatile, but we consider this to be a
2423   // defect.
2424   if (!getType().isConstant(C) || getType().isVolatileQualified())
2425     return false;
2426 
2427   // In C++, const, non-volatile variables of integral or enumeration types
2428   // can be used in constant expressions.
2429   if (getType()->isIntegralOrEnumerationType())
2430     return true;
2431 
2432   // Additionally, in C++11, non-volatile constexpr variables can be used in
2433   // constant expressions.
2434   return Lang.CPlusPlus11 && isConstexpr();
2435 }
2436 
isUsableInConstantExpressions(const ASTContext & Context) const2437 bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2438   // C++2a [expr.const]p3:
2439   //   A variable is usable in constant expressions after its initializing
2440   //   declaration is encountered...
2441   const VarDecl *DefVD = nullptr;
2442   const Expr *Init = getAnyInitializer(DefVD);
2443   if (!Init || Init->isValueDependent() || getType()->isDependentType())
2444     return false;
2445   //   ... if it is a constexpr variable, or it is of reference type or of
2446   //   const-qualified integral or enumeration type, ...
2447   if (!DefVD->mightBeUsableInConstantExpressions(Context))
2448     return false;
2449   //   ... and its initializer is a constant initializer.
2450   if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2451     return false;
2452   // C++98 [expr.const]p1:
2453   //   An integral constant-expression can involve only [...] const variables
2454   //   or static data members of integral or enumeration types initialized with
2455   //   [integer] constant expressions (dcl.init)
2456   if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2457       !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2458     return false;
2459   return true;
2460 }
2461 
2462 /// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2463 /// form, which contains extra information on the evaluated value of the
2464 /// initializer.
ensureEvaluatedStmt() const2465 EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2466   auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2467   if (!Eval) {
2468     // Note: EvaluatedStmt contains an APValue, which usually holds
2469     // resources not allocated from the ASTContext.  We need to do some
2470     // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2471     // where we can detect whether there's anything to clean up or not.
2472     Eval = new (getASTContext()) EvaluatedStmt;
2473     Eval->Value = Init.get<Stmt *>();
2474     Init = Eval;
2475   }
2476   return Eval;
2477 }
2478 
getEvaluatedStmt() const2479 EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2480   return Init.dyn_cast<EvaluatedStmt *>();
2481 }
2482 
evaluateValue() const2483 APValue *VarDecl::evaluateValue() const {
2484   SmallVector<PartialDiagnosticAt, 8> Notes;
2485   return evaluateValueImpl(Notes, hasConstantInitialization());
2486 }
2487 
evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> & Notes,bool IsConstantInitialization) const2488 APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2489                                     bool IsConstantInitialization) const {
2490   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2491 
2492   const auto *Init = cast<Expr>(Eval->Value);
2493   assert(!Init->isValueDependent());
2494 
2495   // We only produce notes indicating why an initializer is non-constant the
2496   // first time it is evaluated. FIXME: The notes won't always be emitted the
2497   // first time we try evaluation, so might not be produced at all.
2498   if (Eval->WasEvaluated)
2499     return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2500 
2501   if (Eval->IsEvaluating) {
2502     // FIXME: Produce a diagnostic for self-initialization.
2503     return nullptr;
2504   }
2505 
2506   Eval->IsEvaluating = true;
2507 
2508   ASTContext &Ctx = getASTContext();
2509   bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2510                                             IsConstantInitialization);
2511 
2512   // In C++11, this isn't a constant initializer if we produced notes. In that
2513   // case, we can't keep the result, because it may only be correct under the
2514   // assumption that the initializer is a constant context.
2515   if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2516       !Notes.empty())
2517     Result = false;
2518 
2519   // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2520   // or that it's empty (so that there's nothing to clean up) if evaluation
2521   // failed.
2522   if (!Result)
2523     Eval->Evaluated = APValue();
2524   else if (Eval->Evaluated.needsCleanup())
2525     Ctx.addDestruction(&Eval->Evaluated);
2526 
2527   Eval->IsEvaluating = false;
2528   Eval->WasEvaluated = true;
2529 
2530   return Result ? &Eval->Evaluated : nullptr;
2531 }
2532 
getEvaluatedValue() const2533 APValue *VarDecl::getEvaluatedValue() const {
2534   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2535     if (Eval->WasEvaluated)
2536       return &Eval->Evaluated;
2537 
2538   return nullptr;
2539 }
2540 
hasICEInitializer(const ASTContext & Context) const2541 bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2542   const Expr *Init = getInit();
2543   assert(Init && "no initializer");
2544 
2545   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2546   if (!Eval->CheckedForICEInit) {
2547     Eval->CheckedForICEInit = true;
2548     Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2549   }
2550   return Eval->HasICEInit;
2551 }
2552 
hasConstantInitialization() const2553 bool VarDecl::hasConstantInitialization() const {
2554   // In C, all globals (and only globals) have constant initialization.
2555   if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2556     return true;
2557 
2558   // In C++, it depends on whether the evaluation at the point of definition
2559   // was evaluatable as a constant initializer.
2560   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2561     return Eval->HasConstantInitialization;
2562 
2563   return false;
2564 }
2565 
checkForConstantInitialization(SmallVectorImpl<PartialDiagnosticAt> & Notes) const2566 bool VarDecl::checkForConstantInitialization(
2567     SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2568   EvaluatedStmt *Eval = ensureEvaluatedStmt();
2569   // If we ask for the value before we know whether we have a constant
2570   // initializer, we can compute the wrong value (for example, due to
2571   // std::is_constant_evaluated()).
2572   assert(!Eval->WasEvaluated &&
2573          "already evaluated var value before checking for constant init");
2574   assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++");
2575 
2576   assert(!cast<Expr>(Eval->Value)->isValueDependent());
2577 
2578   // Evaluate the initializer to check whether it's a constant expression.
2579   Eval->HasConstantInitialization =
2580       evaluateValueImpl(Notes, true) && Notes.empty();
2581 
2582   // If evaluation as a constant initializer failed, allow re-evaluation as a
2583   // non-constant initializer if we later find we want the value.
2584   if (!Eval->HasConstantInitialization)
2585     Eval->WasEvaluated = false;
2586 
2587   return Eval->HasConstantInitialization;
2588 }
2589 
isParameterPack() const2590 bool VarDecl::isParameterPack() const {
2591   return isa<PackExpansionType>(getType());
2592 }
2593 
2594 template<typename DeclT>
getDefinitionOrSelf(DeclT * D)2595 static DeclT *getDefinitionOrSelf(DeclT *D) {
2596   assert(D);
2597   if (auto *Def = D->getDefinition())
2598     return Def;
2599   return D;
2600 }
2601 
isEscapingByref() const2602 bool VarDecl::isEscapingByref() const {
2603   return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2604 }
2605 
isNonEscapingByref() const2606 bool VarDecl::isNonEscapingByref() const {
2607   return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2608 }
2609 
hasDependentAlignment() const2610 bool VarDecl::hasDependentAlignment() const {
2611   QualType T = getType();
2612   return T->isDependentType() || T->isUndeducedType() ||
2613          llvm::any_of(specific_attrs<AlignedAttr>(), [](const AlignedAttr *AA) {
2614            return AA->isAlignmentDependent();
2615          });
2616 }
2617 
getTemplateInstantiationPattern() const2618 VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2619   const VarDecl *VD = this;
2620 
2621   // If this is an instantiated member, walk back to the template from which
2622   // it was instantiated.
2623   if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2624     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2625       VD = VD->getInstantiatedFromStaticDataMember();
2626       while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2627         VD = NewVD;
2628     }
2629   }
2630 
2631   // If it's an instantiated variable template specialization, find the
2632   // template or partial specialization from which it was instantiated.
2633   if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2634     if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2635       auto From = VDTemplSpec->getInstantiatedFrom();
2636       if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2637         while (!VTD->isMemberSpecialization()) {
2638           auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2639           if (!NewVTD)
2640             break;
2641           VTD = NewVTD;
2642         }
2643         return getDefinitionOrSelf(VTD->getTemplatedDecl());
2644       }
2645       if (auto *VTPSD =
2646               From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2647         while (!VTPSD->isMemberSpecialization()) {
2648           auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2649           if (!NewVTPSD)
2650             break;
2651           VTPSD = NewVTPSD;
2652         }
2653         return getDefinitionOrSelf<VarDecl>(VTPSD);
2654       }
2655     }
2656   }
2657 
2658   // If this is the pattern of a variable template, find where it was
2659   // instantiated from. FIXME: Is this necessary?
2660   if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2661     while (!VarTemplate->isMemberSpecialization()) {
2662       auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2663       if (!NewVT)
2664         break;
2665       VarTemplate = NewVT;
2666     }
2667 
2668     return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2669   }
2670 
2671   if (VD == this)
2672     return nullptr;
2673   return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2674 }
2675 
getInstantiatedFromStaticDataMember() const2676 VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2677   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2678     return cast<VarDecl>(MSI->getInstantiatedFrom());
2679 
2680   return nullptr;
2681 }
2682 
getTemplateSpecializationKind() const2683 TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2684   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2685     return Spec->getSpecializationKind();
2686 
2687   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2688     return MSI->getTemplateSpecializationKind();
2689 
2690   return TSK_Undeclared;
2691 }
2692 
2693 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const2694 VarDecl::getTemplateSpecializationKindForInstantiation() const {
2695   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2696     return MSI->getTemplateSpecializationKind();
2697 
2698   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2699     return Spec->getSpecializationKind();
2700 
2701   return TSK_Undeclared;
2702 }
2703 
getPointOfInstantiation() const2704 SourceLocation VarDecl::getPointOfInstantiation() const {
2705   if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2706     return Spec->getPointOfInstantiation();
2707 
2708   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2709     return MSI->getPointOfInstantiation();
2710 
2711   return SourceLocation();
2712 }
2713 
getDescribedVarTemplate() const2714 VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2715   return getASTContext().getTemplateOrSpecializationInfo(this)
2716       .dyn_cast<VarTemplateDecl *>();
2717 }
2718 
setDescribedVarTemplate(VarTemplateDecl * Template)2719 void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2720   getASTContext().setTemplateOrSpecializationInfo(this, Template);
2721 }
2722 
isKnownToBeDefined() const2723 bool VarDecl::isKnownToBeDefined() const {
2724   const auto &LangOpts = getASTContext().getLangOpts();
2725   // In CUDA mode without relocatable device code, variables of form 'extern
2726   // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2727   // memory pool.  These are never undefined variables, even if they appear
2728   // inside of an anon namespace or static function.
2729   //
2730   // With CUDA relocatable device code enabled, these variables don't get
2731   // special handling; they're treated like regular extern variables.
2732   if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2733       hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2734       isa<IncompleteArrayType>(getType()))
2735     return true;
2736 
2737   return hasDefinition();
2738 }
2739 
isNoDestroy(const ASTContext & Ctx) const2740 bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2741   return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2742                                 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2743                                  !hasAttr<AlwaysDestroyAttr>()));
2744 }
2745 
2746 QualType::DestructionKind
needsDestruction(const ASTContext & Ctx) const2747 VarDecl::needsDestruction(const ASTContext &Ctx) const {
2748   if (EvaluatedStmt *Eval = getEvaluatedStmt())
2749     if (Eval->HasConstantDestruction)
2750       return QualType::DK_none;
2751 
2752   if (isNoDestroy(Ctx))
2753     return QualType::DK_none;
2754 
2755   return getType().isDestructedType();
2756 }
2757 
hasFlexibleArrayInit(const ASTContext & Ctx) const2758 bool VarDecl::hasFlexibleArrayInit(const ASTContext &Ctx) const {
2759   assert(hasInit() && "Expect initializer to check for flexible array init");
2760   auto *Ty = getType()->getAs<RecordType>();
2761   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2762     return false;
2763   auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2764   if (!List)
2765     return false;
2766   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2767   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2768   if (!InitTy)
2769     return false;
2770   return InitTy->getSize() != 0;
2771 }
2772 
getFlexibleArrayInitChars(const ASTContext & Ctx) const2773 CharUnits VarDecl::getFlexibleArrayInitChars(const ASTContext &Ctx) const {
2774   assert(hasInit() && "Expect initializer to check for flexible array init");
2775   auto *Ty = getType()->getAs<RecordType>();
2776   if (!Ty || !Ty->getDecl()->hasFlexibleArrayMember())
2777     return CharUnits::Zero();
2778   auto *List = dyn_cast<InitListExpr>(getInit()->IgnoreParens());
2779   if (!List)
2780     return CharUnits::Zero();
2781   const Expr *FlexibleInit = List->getInit(List->getNumInits() - 1);
2782   auto InitTy = Ctx.getAsConstantArrayType(FlexibleInit->getType());
2783   if (!InitTy)
2784     return CharUnits::Zero();
2785   CharUnits FlexibleArraySize = Ctx.getTypeSizeInChars(InitTy);
2786   const ASTRecordLayout &RL = Ctx.getASTRecordLayout(Ty->getDecl());
2787   CharUnits FlexibleArrayOffset =
2788       Ctx.toCharUnitsFromBits(RL.getFieldOffset(RL.getFieldCount() - 1));
2789   if (FlexibleArrayOffset + FlexibleArraySize < RL.getSize())
2790     return CharUnits::Zero();
2791   return FlexibleArrayOffset + FlexibleArraySize - RL.getSize();
2792 }
2793 
getMemberSpecializationInfo() const2794 MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2795   if (isStaticDataMember())
2796     // FIXME: Remove ?
2797     // return getASTContext().getInstantiatedFromStaticDataMember(this);
2798     return getASTContext().getTemplateOrSpecializationInfo(this)
2799         .dyn_cast<MemberSpecializationInfo *>();
2800   return nullptr;
2801 }
2802 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)2803 void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2804                                          SourceLocation PointOfInstantiation) {
2805   assert((isa<VarTemplateSpecializationDecl>(this) ||
2806           getMemberSpecializationInfo()) &&
2807          "not a variable or static data member template specialization");
2808 
2809   if (VarTemplateSpecializationDecl *Spec =
2810           dyn_cast<VarTemplateSpecializationDecl>(this)) {
2811     Spec->setSpecializationKind(TSK);
2812     if (TSK != TSK_ExplicitSpecialization &&
2813         PointOfInstantiation.isValid() &&
2814         Spec->getPointOfInstantiation().isInvalid()) {
2815       Spec->setPointOfInstantiation(PointOfInstantiation);
2816       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2817         L->InstantiationRequested(this);
2818     }
2819   } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2820     MSI->setTemplateSpecializationKind(TSK);
2821     if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2822         MSI->getPointOfInstantiation().isInvalid()) {
2823       MSI->setPointOfInstantiation(PointOfInstantiation);
2824       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2825         L->InstantiationRequested(this);
2826     }
2827   }
2828 }
2829 
2830 void
setInstantiationOfStaticDataMember(VarDecl * VD,TemplateSpecializationKind TSK)2831 VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2832                                             TemplateSpecializationKind TSK) {
2833   assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&
2834          "Previous template or instantiation?");
2835   getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2836 }
2837 
2838 //===----------------------------------------------------------------------===//
2839 // ParmVarDecl Implementation
2840 //===----------------------------------------------------------------------===//
2841 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,StorageClass S,Expr * DefArg)2842 ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2843                                  SourceLocation StartLoc,
2844                                  SourceLocation IdLoc, IdentifierInfo *Id,
2845                                  QualType T, TypeSourceInfo *TInfo,
2846                                  StorageClass S, Expr *DefArg) {
2847   return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2848                                  S, DefArg);
2849 }
2850 
getOriginalType() const2851 QualType ParmVarDecl::getOriginalType() const {
2852   TypeSourceInfo *TSI = getTypeSourceInfo();
2853   QualType T = TSI ? TSI->getType() : getType();
2854   if (const auto *DT = dyn_cast<DecayedType>(T))
2855     return DT->getOriginalType();
2856   return T;
2857 }
2858 
CreateDeserialized(ASTContext & C,unsigned ID)2859 ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2860   return new (C, ID)
2861       ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2862                   nullptr, QualType(), nullptr, SC_None, nullptr);
2863 }
2864 
getSourceRange() const2865 SourceRange ParmVarDecl::getSourceRange() const {
2866   if (!hasInheritedDefaultArg()) {
2867     SourceRange ArgRange = getDefaultArgRange();
2868     if (ArgRange.isValid())
2869       return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2870   }
2871 
2872   // DeclaratorDecl considers the range of postfix types as overlapping with the
2873   // declaration name, but this is not the case with parameters in ObjC methods.
2874   if (isa<ObjCMethodDecl>(getDeclContext()))
2875     return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2876 
2877   return DeclaratorDecl::getSourceRange();
2878 }
2879 
isDestroyedInCallee() const2880 bool ParmVarDecl::isDestroyedInCallee() const {
2881   // ns_consumed only affects code generation in ARC
2882   if (hasAttr<NSConsumedAttr>())
2883     return getASTContext().getLangOpts().ObjCAutoRefCount;
2884 
2885   // FIXME: isParamDestroyedInCallee() should probably imply
2886   // isDestructedType()
2887   auto *RT = getType()->getAs<RecordType>();
2888   if (RT && RT->getDecl()->isParamDestroyedInCallee() &&
2889       getType().isDestructedType())
2890     return true;
2891 
2892   return false;
2893 }
2894 
getDefaultArg()2895 Expr *ParmVarDecl::getDefaultArg() {
2896   assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!");
2897   assert(!hasUninstantiatedDefaultArg() &&
2898          "Default argument is not yet instantiated!");
2899 
2900   Expr *Arg = getInit();
2901   if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2902     return E->getSubExpr();
2903 
2904   return Arg;
2905 }
2906 
setDefaultArg(Expr * defarg)2907 void ParmVarDecl::setDefaultArg(Expr *defarg) {
2908   ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2909   Init = defarg;
2910 }
2911 
getDefaultArgRange() const2912 SourceRange ParmVarDecl::getDefaultArgRange() const {
2913   switch (ParmVarDeclBits.DefaultArgKind) {
2914   case DAK_None:
2915   case DAK_Unparsed:
2916     // Nothing we can do here.
2917     return SourceRange();
2918 
2919   case DAK_Uninstantiated:
2920     return getUninstantiatedDefaultArg()->getSourceRange();
2921 
2922   case DAK_Normal:
2923     if (const Expr *E = getInit())
2924       return E->getSourceRange();
2925 
2926     // Missing an actual expression, may be invalid.
2927     return SourceRange();
2928   }
2929   llvm_unreachable("Invalid default argument kind.");
2930 }
2931 
setUninstantiatedDefaultArg(Expr * arg)2932 void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2933   ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2934   Init = arg;
2935 }
2936 
getUninstantiatedDefaultArg()2937 Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2938   assert(hasUninstantiatedDefaultArg() &&
2939          "Wrong kind of initialization expression!");
2940   return cast_or_null<Expr>(Init.get<Stmt *>());
2941 }
2942 
hasDefaultArg() const2943 bool ParmVarDecl::hasDefaultArg() const {
2944   // FIXME: We should just return false for DAK_None here once callers are
2945   // prepared for the case that we encountered an invalid default argument and
2946   // were unable to even build an invalid expression.
2947   return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2948          !Init.isNull();
2949 }
2950 
setParameterIndexLarge(unsigned parameterIndex)2951 void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2952   getASTContext().setParameterIndex(this, parameterIndex);
2953   ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2954 }
2955 
getParameterIndexLarge() const2956 unsigned ParmVarDecl::getParameterIndexLarge() const {
2957   return getASTContext().getParameterIndex(this);
2958 }
2959 
2960 //===----------------------------------------------------------------------===//
2961 // FunctionDecl Implementation
2962 //===----------------------------------------------------------------------===//
2963 
FunctionDecl(Kind DK,ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass S,bool UsesFPIntrin,bool isInlineSpecified,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)2964 FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2965                            SourceLocation StartLoc,
2966                            const DeclarationNameInfo &NameInfo, QualType T,
2967                            TypeSourceInfo *TInfo, StorageClass S,
2968                            bool UsesFPIntrin, bool isInlineSpecified,
2969                            ConstexprSpecKind ConstexprKind,
2970                            Expr *TrailingRequiresClause)
2971     : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2972                      StartLoc),
2973       DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2974       EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2975   assert(T.isNull() || T->isFunctionType());
2976   FunctionDeclBits.SClass = S;
2977   FunctionDeclBits.IsInline = isInlineSpecified;
2978   FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2979   FunctionDeclBits.IsVirtualAsWritten = false;
2980   FunctionDeclBits.IsPure = false;
2981   FunctionDeclBits.HasInheritedPrototype = false;
2982   FunctionDeclBits.HasWrittenPrototype = true;
2983   FunctionDeclBits.IsDeleted = false;
2984   FunctionDeclBits.IsTrivial = false;
2985   FunctionDeclBits.IsTrivialForCall = false;
2986   FunctionDeclBits.IsDefaulted = false;
2987   FunctionDeclBits.IsExplicitlyDefaulted = false;
2988   FunctionDeclBits.HasDefaultedFunctionInfo = false;
2989   FunctionDeclBits.IsIneligibleOrNotSelected = false;
2990   FunctionDeclBits.HasImplicitReturnZero = false;
2991   FunctionDeclBits.IsLateTemplateParsed = false;
2992   FunctionDeclBits.ConstexprKind = static_cast<uint64_t>(ConstexprKind);
2993   FunctionDeclBits.InstantiationIsPending = false;
2994   FunctionDeclBits.UsesSEHTry = false;
2995   FunctionDeclBits.UsesFPIntrin = UsesFPIntrin;
2996   FunctionDeclBits.HasSkippedBody = false;
2997   FunctionDeclBits.WillHaveBody = false;
2998   FunctionDeclBits.IsMultiVersion = false;
2999   FunctionDeclBits.IsCopyDeductionCandidate = false;
3000   FunctionDeclBits.HasODRHash = false;
3001   FunctionDeclBits.FriendConstraintRefersToEnclosingTemplate = false;
3002   if (TrailingRequiresClause)
3003     setTrailingRequiresClause(TrailingRequiresClause);
3004 }
3005 
getNameForDiagnostic(raw_ostream & OS,const PrintingPolicy & Policy,bool Qualified) const3006 void FunctionDecl::getNameForDiagnostic(
3007     raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
3008   NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
3009   const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
3010   if (TemplateArgs)
3011     printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
3012 }
3013 
isVariadic() const3014 bool FunctionDecl::isVariadic() const {
3015   if (const auto *FT = getType()->getAs<FunctionProtoType>())
3016     return FT->isVariadic();
3017   return false;
3018 }
3019 
3020 FunctionDecl::DefaultedFunctionInfo *
Create(ASTContext & Context,ArrayRef<DeclAccessPair> Lookups)3021 FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
3022                                             ArrayRef<DeclAccessPair> Lookups) {
3023   DefaultedFunctionInfo *Info = new (Context.Allocate(
3024       totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
3025       std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
3026       DefaultedFunctionInfo;
3027   Info->NumLookups = Lookups.size();
3028   std::uninitialized_copy(Lookups.begin(), Lookups.end(),
3029                           Info->getTrailingObjects<DeclAccessPair>());
3030   return Info;
3031 }
3032 
setDefaultedFunctionInfo(DefaultedFunctionInfo * Info)3033 void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
3034   assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this");
3035   assert(!Body && "can't replace function body with defaulted function info");
3036 
3037   FunctionDeclBits.HasDefaultedFunctionInfo = true;
3038   DefaultedInfo = Info;
3039 }
3040 
3041 FunctionDecl::DefaultedFunctionInfo *
getDefaultedFunctionInfo() const3042 FunctionDecl::getDefaultedFunctionInfo() const {
3043   return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
3044 }
3045 
hasBody(const FunctionDecl * & Definition) const3046 bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
3047   for (auto *I : redecls()) {
3048     if (I->doesThisDeclarationHaveABody()) {
3049       Definition = I;
3050       return true;
3051     }
3052   }
3053 
3054   return false;
3055 }
3056 
hasTrivialBody() const3057 bool FunctionDecl::hasTrivialBody() const {
3058   Stmt *S = getBody();
3059   if (!S) {
3060     // Since we don't have a body for this function, we don't know if it's
3061     // trivial or not.
3062     return false;
3063   }
3064 
3065   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
3066     return true;
3067   return false;
3068 }
3069 
isThisDeclarationInstantiatedFromAFriendDefinition() const3070 bool FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition() const {
3071   if (!getFriendObjectKind())
3072     return false;
3073 
3074   // Check for a friend function instantiated from a friend function
3075   // definition in a templated class.
3076   if (const FunctionDecl *InstantiatedFrom =
3077           getInstantiatedFromMemberFunction())
3078     return InstantiatedFrom->getFriendObjectKind() &&
3079            InstantiatedFrom->isThisDeclarationADefinition();
3080 
3081   // Check for a friend function template instantiated from a friend
3082   // function template definition in a templated class.
3083   if (const FunctionTemplateDecl *Template = getDescribedFunctionTemplate()) {
3084     if (const FunctionTemplateDecl *InstantiatedFrom =
3085             Template->getInstantiatedFromMemberTemplate())
3086       return InstantiatedFrom->getFriendObjectKind() &&
3087              InstantiatedFrom->isThisDeclarationADefinition();
3088   }
3089 
3090   return false;
3091 }
3092 
isDefined(const FunctionDecl * & Definition,bool CheckForPendingFriendDefinition) const3093 bool FunctionDecl::isDefined(const FunctionDecl *&Definition,
3094                              bool CheckForPendingFriendDefinition) const {
3095   for (const FunctionDecl *FD : redecls()) {
3096     if (FD->isThisDeclarationADefinition()) {
3097       Definition = FD;
3098       return true;
3099     }
3100 
3101     // If this is a friend function defined in a class template, it does not
3102     // have a body until it is used, nevertheless it is a definition, see
3103     // [temp.inst]p2:
3104     //
3105     // ... for the purpose of determining whether an instantiated redeclaration
3106     // is valid according to [basic.def.odr] and [class.mem], a declaration that
3107     // corresponds to a definition in the template is considered to be a
3108     // definition.
3109     //
3110     // The following code must produce redefinition error:
3111     //
3112     //     template<typename T> struct C20 { friend void func_20() {} };
3113     //     C20<int> c20i;
3114     //     void func_20() {}
3115     //
3116     if (CheckForPendingFriendDefinition &&
3117         FD->isThisDeclarationInstantiatedFromAFriendDefinition()) {
3118       Definition = FD;
3119       return true;
3120     }
3121   }
3122 
3123   return false;
3124 }
3125 
getBody(const FunctionDecl * & Definition) const3126 Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
3127   if (!hasBody(Definition))
3128     return nullptr;
3129 
3130   assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
3131          "definition should not have a body");
3132   if (Definition->Body)
3133     return Definition->Body.get(getASTContext().getExternalSource());
3134 
3135   return nullptr;
3136 }
3137 
setBody(Stmt * B)3138 void FunctionDecl::setBody(Stmt *B) {
3139   FunctionDeclBits.HasDefaultedFunctionInfo = false;
3140   Body = LazyDeclStmtPtr(B);
3141   if (B)
3142     EndRangeLoc = B->getEndLoc();
3143 }
3144 
setPure(bool P)3145 void FunctionDecl::setPure(bool P) {
3146   FunctionDeclBits.IsPure = P;
3147   if (P)
3148     if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
3149       Parent->markedVirtualFunctionPure();
3150 }
3151 
3152 template<std::size_t Len>
isNamed(const NamedDecl * ND,const char (& Str)[Len])3153 static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
3154   IdentifierInfo *II = ND->getIdentifier();
3155   return II && II->isStr(Str);
3156 }
3157 
isMain() const3158 bool FunctionDecl::isMain() const {
3159   const TranslationUnitDecl *tunit =
3160     dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3161   return tunit &&
3162          !tunit->getASTContext().getLangOpts().Freestanding &&
3163          isNamed(this, "main");
3164 }
3165 
isMSVCRTEntryPoint() const3166 bool FunctionDecl::isMSVCRTEntryPoint() const {
3167   const TranslationUnitDecl *TUnit =
3168       dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
3169   if (!TUnit)
3170     return false;
3171 
3172   // Even though we aren't really targeting MSVCRT if we are freestanding,
3173   // semantic analysis for these functions remains the same.
3174 
3175   // MSVCRT entry points only exist on MSVCRT targets.
3176   if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
3177     return false;
3178 
3179   // Nameless functions like constructors cannot be entry points.
3180   if (!getIdentifier())
3181     return false;
3182 
3183   return llvm::StringSwitch<bool>(getName())
3184       .Cases("main",     // an ANSI console app
3185              "wmain",    // a Unicode console App
3186              "WinMain",  // an ANSI GUI app
3187              "wWinMain", // a Unicode GUI app
3188              "DllMain",  // a DLL
3189              true)
3190       .Default(false);
3191 }
3192 
isReservedGlobalPlacementOperator() const3193 bool FunctionDecl::isReservedGlobalPlacementOperator() const {
3194   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3195     return false;
3196   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3197       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3198       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3199       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3200     return false;
3201 
3202   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3203     return false;
3204 
3205   const auto *proto = getType()->castAs<FunctionProtoType>();
3206   if (proto->getNumParams() != 2 || proto->isVariadic())
3207     return false;
3208 
3209   ASTContext &Context =
3210     cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
3211       ->getASTContext();
3212 
3213   // The result type and first argument type are constant across all
3214   // these operators.  The second argument must be exactly void*.
3215   return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
3216 }
3217 
isReplaceableGlobalAllocationFunction(std::optional<unsigned> * AlignmentParam,bool * IsNothrow) const3218 bool FunctionDecl::isReplaceableGlobalAllocationFunction(
3219     std::optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
3220   if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
3221     return false;
3222   if (getDeclName().getCXXOverloadedOperator() != OO_New &&
3223       getDeclName().getCXXOverloadedOperator() != OO_Delete &&
3224       getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
3225       getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
3226     return false;
3227 
3228   if (isa<CXXRecordDecl>(getDeclContext()))
3229     return false;
3230 
3231   // This can only fail for an invalid 'operator new' declaration.
3232   if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3233     return false;
3234 
3235   const auto *FPT = getType()->castAs<FunctionProtoType>();
3236   if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
3237     return false;
3238 
3239   // If this is a single-parameter function, it must be a replaceable global
3240   // allocation or deallocation function.
3241   if (FPT->getNumParams() == 1)
3242     return true;
3243 
3244   unsigned Params = 1;
3245   QualType Ty = FPT->getParamType(Params);
3246   ASTContext &Ctx = getASTContext();
3247 
3248   auto Consume = [&] {
3249     ++Params;
3250     Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3251   };
3252 
3253   // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3254   bool IsSizedDelete = false;
3255   if (Ctx.getLangOpts().SizedDeallocation &&
3256       (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3257        getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3258       Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3259     IsSizedDelete = true;
3260     Consume();
3261   }
3262 
3263   // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3264   // new/delete.
3265   if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3266     Consume();
3267     if (AlignmentParam)
3268       *AlignmentParam = Params;
3269   }
3270 
3271   // Finally, if this is not a sized delete, the final parameter can
3272   // be a 'const std::nothrow_t&'.
3273   if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3274     Ty = Ty->getPointeeType();
3275     if (Ty.getCVRQualifiers() != Qualifiers::Const)
3276       return false;
3277     if (Ty->isNothrowT()) {
3278       if (IsNothrow)
3279         *IsNothrow = true;
3280       Consume();
3281     }
3282   }
3283 
3284   return Params == FPT->getNumParams();
3285 }
3286 
isInlineBuiltinDeclaration() const3287 bool FunctionDecl::isInlineBuiltinDeclaration() const {
3288   if (!getBuiltinID())
3289     return false;
3290 
3291   const FunctionDecl *Definition;
3292   return hasBody(Definition) && Definition->isInlineSpecified() &&
3293          Definition->hasAttr<AlwaysInlineAttr>() &&
3294          Definition->hasAttr<GNUInlineAttr>();
3295 }
3296 
isDestroyingOperatorDelete() const3297 bool FunctionDecl::isDestroyingOperatorDelete() const {
3298   // C++ P0722:
3299   //   Within a class C, a single object deallocation function with signature
3300   //     (T, std::destroying_delete_t, <more params>)
3301   //   is a destroying operator delete.
3302   if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3303       getNumParams() < 2)
3304     return false;
3305 
3306   auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3307   return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3308          RD->getIdentifier()->isStr("destroying_delete_t");
3309 }
3310 
getLanguageLinkage() const3311 LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3312   return getDeclLanguageLinkage(*this);
3313 }
3314 
isExternC() const3315 bool FunctionDecl::isExternC() const {
3316   return isDeclExternC(*this);
3317 }
3318 
isInExternCContext() const3319 bool FunctionDecl::isInExternCContext() const {
3320   if (hasAttr<OpenCLKernelAttr>())
3321     return true;
3322   return getLexicalDeclContext()->isExternCContext();
3323 }
3324 
isInExternCXXContext() const3325 bool FunctionDecl::isInExternCXXContext() const {
3326   return getLexicalDeclContext()->isExternCXXContext();
3327 }
3328 
isGlobal() const3329 bool FunctionDecl::isGlobal() const {
3330   if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3331     return Method->isStatic();
3332 
3333   if (getCanonicalDecl()->getStorageClass() == SC_Static)
3334     return false;
3335 
3336   for (const DeclContext *DC = getDeclContext();
3337        DC->isNamespace();
3338        DC = DC->getParent()) {
3339     if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3340       if (!Namespace->getDeclName())
3341         return false;
3342     }
3343   }
3344 
3345   return true;
3346 }
3347 
isNoReturn() const3348 bool FunctionDecl::isNoReturn() const {
3349   if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3350       hasAttr<C11NoReturnAttr>())
3351     return true;
3352 
3353   if (auto *FnTy = getType()->getAs<FunctionType>())
3354     return FnTy->getNoReturnAttr();
3355 
3356   return false;
3357 }
3358 
3359 
getMultiVersionKind() const3360 MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3361   if (hasAttr<TargetAttr>())
3362     return MultiVersionKind::Target;
3363   if (hasAttr<TargetVersionAttr>())
3364     return MultiVersionKind::TargetVersion;
3365   if (hasAttr<CPUDispatchAttr>())
3366     return MultiVersionKind::CPUDispatch;
3367   if (hasAttr<CPUSpecificAttr>())
3368     return MultiVersionKind::CPUSpecific;
3369   if (hasAttr<TargetClonesAttr>())
3370     return MultiVersionKind::TargetClones;
3371   return MultiVersionKind::None;
3372 }
3373 
isCPUDispatchMultiVersion() const3374 bool FunctionDecl::isCPUDispatchMultiVersion() const {
3375   return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3376 }
3377 
isCPUSpecificMultiVersion() const3378 bool FunctionDecl::isCPUSpecificMultiVersion() const {
3379   return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3380 }
3381 
isTargetMultiVersion() const3382 bool FunctionDecl::isTargetMultiVersion() const {
3383   return isMultiVersion() &&
3384          (hasAttr<TargetAttr>() || hasAttr<TargetVersionAttr>());
3385 }
3386 
isTargetClonesMultiVersion() const3387 bool FunctionDecl::isTargetClonesMultiVersion() const {
3388   return isMultiVersion() && hasAttr<TargetClonesAttr>();
3389 }
3390 
3391 void
setPreviousDeclaration(FunctionDecl * PrevDecl)3392 FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3393   redeclarable_base::setPreviousDecl(PrevDecl);
3394 
3395   if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3396     FunctionTemplateDecl *PrevFunTmpl
3397       = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3398     assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch");
3399     FunTmpl->setPreviousDecl(PrevFunTmpl);
3400   }
3401 
3402   if (PrevDecl && PrevDecl->isInlined())
3403     setImplicitlyInline(true);
3404 }
3405 
getCanonicalDecl()3406 FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3407 
3408 /// Returns a value indicating whether this function corresponds to a builtin
3409 /// function.
3410 ///
3411 /// The function corresponds to a built-in function if it is declared at
3412 /// translation scope or within an extern "C" block and its name matches with
3413 /// the name of a builtin. The returned value will be 0 for functions that do
3414 /// not correspond to a builtin, a value of type \c Builtin::ID if in the
3415 /// target-independent range \c [1,Builtin::First), or a target-specific builtin
3416 /// value.
3417 ///
3418 /// \param ConsiderWrapperFunctions If true, we should consider wrapper
3419 /// functions as their wrapped builtins. This shouldn't be done in general, but
3420 /// it's useful in Sema to diagnose calls to wrappers based on their semantics.
getBuiltinID(bool ConsiderWrapperFunctions) const3421 unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3422   unsigned BuiltinID = 0;
3423 
3424   if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3425     BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3426   } else if (const auto *BAA = getAttr<BuiltinAliasAttr>()) {
3427     BuiltinID = BAA->getBuiltinName()->getBuiltinID();
3428   } else if (const auto *A = getAttr<BuiltinAttr>()) {
3429     BuiltinID = A->getID();
3430   }
3431 
3432   if (!BuiltinID)
3433     return 0;
3434 
3435   // If the function is marked "overloadable", it has a different mangled name
3436   // and is not the C library function.
3437   if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3438       (!hasAttr<ArmBuiltinAliasAttr>() && !hasAttr<BuiltinAliasAttr>()))
3439     return 0;
3440 
3441   ASTContext &Context = getASTContext();
3442   if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3443     return BuiltinID;
3444 
3445   // This function has the name of a known C library
3446   // function. Determine whether it actually refers to the C library
3447   // function or whether it just has the same name.
3448 
3449   // If this is a static function, it's not a builtin.
3450   if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3451     return 0;
3452 
3453   // OpenCL v1.2 s6.9.f - The library functions defined in
3454   // the C99 standard headers are not available.
3455   if (Context.getLangOpts().OpenCL &&
3456       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3457     return 0;
3458 
3459   // CUDA does not have device-side standard library. printf and malloc are the
3460   // only special cases that are supported by device-side runtime.
3461   if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3462       !hasAttr<CUDAHostAttr>() &&
3463       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3464     return 0;
3465 
3466   // As AMDGCN implementation of OpenMP does not have a device-side standard
3467   // library, none of the predefined library functions except printf and malloc
3468   // should be treated as a builtin i.e. 0 should be returned for them.
3469   if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3470       Context.getLangOpts().OpenMPIsDevice &&
3471       Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3472       !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3473     return 0;
3474 
3475   return BuiltinID;
3476 }
3477 
3478 /// getNumParams - Return the number of parameters this function must have
3479 /// based on its FunctionType.  This is the length of the ParamInfo array
3480 /// after it has been created.
getNumParams() const3481 unsigned FunctionDecl::getNumParams() const {
3482   const auto *FPT = getType()->getAs<FunctionProtoType>();
3483   return FPT ? FPT->getNumParams() : 0;
3484 }
3485 
setParams(ASTContext & C,ArrayRef<ParmVarDecl * > NewParamInfo)3486 void FunctionDecl::setParams(ASTContext &C,
3487                              ArrayRef<ParmVarDecl *> NewParamInfo) {
3488   assert(!ParamInfo && "Already has param info!");
3489   assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!");
3490 
3491   // Zero params -> null pointer.
3492   if (!NewParamInfo.empty()) {
3493     ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3494     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3495   }
3496 }
3497 
3498 /// getMinRequiredArguments - Returns the minimum number of arguments
3499 /// needed to call this function. This may be fewer than the number of
3500 /// function parameters, if some of the parameters have default
3501 /// arguments (in C++) or are parameter packs (C++11).
getMinRequiredArguments() const3502 unsigned FunctionDecl::getMinRequiredArguments() const {
3503   if (!getASTContext().getLangOpts().CPlusPlus)
3504     return getNumParams();
3505 
3506   // Note that it is possible for a parameter with no default argument to
3507   // follow a parameter with a default argument.
3508   unsigned NumRequiredArgs = 0;
3509   unsigned MinParamsSoFar = 0;
3510   for (auto *Param : parameters()) {
3511     if (!Param->isParameterPack()) {
3512       ++MinParamsSoFar;
3513       if (!Param->hasDefaultArg())
3514         NumRequiredArgs = MinParamsSoFar;
3515     }
3516   }
3517   return NumRequiredArgs;
3518 }
3519 
hasOneParamOrDefaultArgs() const3520 bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3521   return getNumParams() == 1 ||
3522          (getNumParams() > 1 &&
3523           llvm::all_of(llvm::drop_begin(parameters()),
3524                        [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3525 }
3526 
3527 /// The combination of the extern and inline keywords under MSVC forces
3528 /// the function to be required.
3529 ///
3530 /// Note: This function assumes that we will only get called when isInlined()
3531 /// would return true for this FunctionDecl.
isMSExternInline() const3532 bool FunctionDecl::isMSExternInline() const {
3533   assert(isInlined() && "expected to get called on an inlined function!");
3534 
3535   const ASTContext &Context = getASTContext();
3536   if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3537       !hasAttr<DLLExportAttr>())
3538     return false;
3539 
3540   for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3541        FD = FD->getPreviousDecl())
3542     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3543       return true;
3544 
3545   return false;
3546 }
3547 
redeclForcesDefMSVC(const FunctionDecl * Redecl)3548 static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3549   if (Redecl->getStorageClass() != SC_Extern)
3550     return false;
3551 
3552   for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3553        FD = FD->getPreviousDecl())
3554     if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3555       return false;
3556 
3557   return true;
3558 }
3559 
RedeclForcesDefC99(const FunctionDecl * Redecl)3560 static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3561   // Only consider file-scope declarations in this test.
3562   if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3563     return false;
3564 
3565   // Only consider explicit declarations; the presence of a builtin for a
3566   // libcall shouldn't affect whether a definition is externally visible.
3567   if (Redecl->isImplicit())
3568     return false;
3569 
3570   if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3571     return true; // Not an inline definition
3572 
3573   return false;
3574 }
3575 
3576 /// For a function declaration in C or C++, determine whether this
3577 /// declaration causes the definition to be externally visible.
3578 ///
3579 /// For instance, this determines if adding the current declaration to the set
3580 /// of redeclarations of the given functions causes
3581 /// isInlineDefinitionExternallyVisible to change from false to true.
doesDeclarationForceExternallyVisibleDefinition() const3582 bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3583   assert(!doesThisDeclarationHaveABody() &&
3584          "Must have a declaration without a body.");
3585 
3586   ASTContext &Context = getASTContext();
3587 
3588   if (Context.getLangOpts().MSVCCompat) {
3589     const FunctionDecl *Definition;
3590     if (hasBody(Definition) && Definition->isInlined() &&
3591         redeclForcesDefMSVC(this))
3592       return true;
3593   }
3594 
3595   if (Context.getLangOpts().CPlusPlus)
3596     return false;
3597 
3598   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3599     // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3600     // an externally visible definition.
3601     //
3602     // FIXME: What happens if gnu_inline gets added on after the first
3603     // declaration?
3604     if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3605       return false;
3606 
3607     const FunctionDecl *Prev = this;
3608     bool FoundBody = false;
3609     while ((Prev = Prev->getPreviousDecl())) {
3610       FoundBody |= Prev->doesThisDeclarationHaveABody();
3611 
3612       if (Prev->doesThisDeclarationHaveABody()) {
3613         // If it's not the case that both 'inline' and 'extern' are
3614         // specified on the definition, then it is always externally visible.
3615         if (!Prev->isInlineSpecified() ||
3616             Prev->getStorageClass() != SC_Extern)
3617           return false;
3618       } else if (Prev->isInlineSpecified() &&
3619                  Prev->getStorageClass() != SC_Extern) {
3620         return false;
3621       }
3622     }
3623     return FoundBody;
3624   }
3625 
3626   // C99 6.7.4p6:
3627   //   [...] If all of the file scope declarations for a function in a
3628   //   translation unit include the inline function specifier without extern,
3629   //   then the definition in that translation unit is an inline definition.
3630   if (isInlineSpecified() && getStorageClass() != SC_Extern)
3631     return false;
3632   const FunctionDecl *Prev = this;
3633   bool FoundBody = false;
3634   while ((Prev = Prev->getPreviousDecl())) {
3635     FoundBody |= Prev->doesThisDeclarationHaveABody();
3636     if (RedeclForcesDefC99(Prev))
3637       return false;
3638   }
3639   return FoundBody;
3640 }
3641 
getFunctionTypeLoc() const3642 FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3643   const TypeSourceInfo *TSI = getTypeSourceInfo();
3644   return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3645              : FunctionTypeLoc();
3646 }
3647 
getReturnTypeSourceRange() const3648 SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3649   FunctionTypeLoc FTL = getFunctionTypeLoc();
3650   if (!FTL)
3651     return SourceRange();
3652 
3653   // Skip self-referential return types.
3654   const SourceManager &SM = getASTContext().getSourceManager();
3655   SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3656   SourceLocation Boundary = getNameInfo().getBeginLoc();
3657   if (RTRange.isInvalid() || Boundary.isInvalid() ||
3658       !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3659     return SourceRange();
3660 
3661   return RTRange;
3662 }
3663 
getParametersSourceRange() const3664 SourceRange FunctionDecl::getParametersSourceRange() const {
3665   unsigned NP = getNumParams();
3666   SourceLocation EllipsisLoc = getEllipsisLoc();
3667 
3668   if (NP == 0 && EllipsisLoc.isInvalid())
3669     return SourceRange();
3670 
3671   SourceLocation Begin =
3672       NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3673   SourceLocation End = EllipsisLoc.isValid()
3674                            ? EllipsisLoc
3675                            : ParamInfo[NP - 1]->getSourceRange().getEnd();
3676 
3677   return SourceRange(Begin, End);
3678 }
3679 
getExceptionSpecSourceRange() const3680 SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3681   FunctionTypeLoc FTL = getFunctionTypeLoc();
3682   return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3683 }
3684 
3685 /// For an inline function definition in C, or for a gnu_inline function
3686 /// in C++, determine whether the definition will be externally visible.
3687 ///
3688 /// Inline function definitions are always available for inlining optimizations.
3689 /// However, depending on the language dialect, declaration specifiers, and
3690 /// attributes, the definition of an inline function may or may not be
3691 /// "externally" visible to other translation units in the program.
3692 ///
3693 /// In C99, inline definitions are not externally visible by default. However,
3694 /// if even one of the global-scope declarations is marked "extern inline", the
3695 /// inline definition becomes externally visible (C99 6.7.4p6).
3696 ///
3697 /// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3698 /// definition, we use the GNU semantics for inline, which are nearly the
3699 /// opposite of C99 semantics. In particular, "inline" by itself will create
3700 /// an externally visible symbol, but "extern inline" will not create an
3701 /// externally visible symbol.
isInlineDefinitionExternallyVisible() const3702 bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3703   assert((doesThisDeclarationHaveABody() || willHaveBody() ||
3704           hasAttr<AliasAttr>()) &&
3705          "Must be a function definition");
3706   assert(isInlined() && "Function must be inline");
3707   ASTContext &Context = getASTContext();
3708 
3709   if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3710     // Note: If you change the logic here, please change
3711     // doesDeclarationForceExternallyVisibleDefinition as well.
3712     //
3713     // If it's not the case that both 'inline' and 'extern' are
3714     // specified on the definition, then this inline definition is
3715     // externally visible.
3716     if (Context.getLangOpts().CPlusPlus)
3717       return false;
3718     if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3719       return true;
3720 
3721     // If any declaration is 'inline' but not 'extern', then this definition
3722     // is externally visible.
3723     for (auto *Redecl : redecls()) {
3724       if (Redecl->isInlineSpecified() &&
3725           Redecl->getStorageClass() != SC_Extern)
3726         return true;
3727     }
3728 
3729     return false;
3730   }
3731 
3732   // The rest of this function is C-only.
3733   assert(!Context.getLangOpts().CPlusPlus &&
3734          "should not use C inline rules in C++");
3735 
3736   // C99 6.7.4p6:
3737   //   [...] If all of the file scope declarations for a function in a
3738   //   translation unit include the inline function specifier without extern,
3739   //   then the definition in that translation unit is an inline definition.
3740   for (auto *Redecl : redecls()) {
3741     if (RedeclForcesDefC99(Redecl))
3742       return true;
3743   }
3744 
3745   // C99 6.7.4p6:
3746   //   An inline definition does not provide an external definition for the
3747   //   function, and does not forbid an external definition in another
3748   //   translation unit.
3749   return false;
3750 }
3751 
3752 /// getOverloadedOperator - Which C++ overloaded operator this
3753 /// function represents, if any.
getOverloadedOperator() const3754 OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3755   if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3756     return getDeclName().getCXXOverloadedOperator();
3757   return OO_None;
3758 }
3759 
3760 /// getLiteralIdentifier - The literal suffix identifier this function
3761 /// represents, if any.
getLiteralIdentifier() const3762 const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3763   if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3764     return getDeclName().getCXXLiteralIdentifier();
3765   return nullptr;
3766 }
3767 
getTemplatedKind() const3768 FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3769   if (TemplateOrSpecialization.isNull())
3770     return TK_NonTemplate;
3771   if (const auto *ND = TemplateOrSpecialization.dyn_cast<NamedDecl *>()) {
3772     if (isa<FunctionDecl>(ND))
3773       return TK_DependentNonTemplate;
3774     assert(isa<FunctionTemplateDecl>(ND) &&
3775            "No other valid types in NamedDecl");
3776     return TK_FunctionTemplate;
3777   }
3778   if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3779     return TK_MemberSpecialization;
3780   if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3781     return TK_FunctionTemplateSpecialization;
3782   if (TemplateOrSpecialization.is
3783                                <DependentFunctionTemplateSpecializationInfo*>())
3784     return TK_DependentFunctionTemplateSpecialization;
3785 
3786   llvm_unreachable("Did we miss a TemplateOrSpecialization type?");
3787 }
3788 
getInstantiatedFromMemberFunction() const3789 FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3790   if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3791     return cast<FunctionDecl>(Info->getInstantiatedFrom());
3792 
3793   return nullptr;
3794 }
3795 
getMemberSpecializationInfo() const3796 MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3797   if (auto *MSI =
3798           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3799     return MSI;
3800   if (auto *FTSI = TemplateOrSpecialization
3801                        .dyn_cast<FunctionTemplateSpecializationInfo *>())
3802     return FTSI->getMemberSpecializationInfo();
3803   return nullptr;
3804 }
3805 
3806 void
setInstantiationOfMemberFunction(ASTContext & C,FunctionDecl * FD,TemplateSpecializationKind TSK)3807 FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3808                                                FunctionDecl *FD,
3809                                                TemplateSpecializationKind TSK) {
3810   assert(TemplateOrSpecialization.isNull() &&
3811          "Member function is already a specialization");
3812   MemberSpecializationInfo *Info
3813     = new (C) MemberSpecializationInfo(FD, TSK);
3814   TemplateOrSpecialization = Info;
3815 }
3816 
getDescribedFunctionTemplate() const3817 FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3818   return dyn_cast_or_null<FunctionTemplateDecl>(
3819       TemplateOrSpecialization.dyn_cast<NamedDecl *>());
3820 }
3821 
setDescribedFunctionTemplate(FunctionTemplateDecl * Template)3822 void FunctionDecl::setDescribedFunctionTemplate(
3823     FunctionTemplateDecl *Template) {
3824   assert(TemplateOrSpecialization.isNull() &&
3825          "Member function is already a specialization");
3826   TemplateOrSpecialization = Template;
3827 }
3828 
setInstantiatedFromDecl(FunctionDecl * FD)3829 void FunctionDecl::setInstantiatedFromDecl(FunctionDecl *FD) {
3830   assert(TemplateOrSpecialization.isNull() &&
3831          "Function is already a specialization");
3832   TemplateOrSpecialization = FD;
3833 }
3834 
getInstantiatedFromDecl() const3835 FunctionDecl *FunctionDecl::getInstantiatedFromDecl() const {
3836   return dyn_cast_or_null<FunctionDecl>(
3837       TemplateOrSpecialization.dyn_cast<NamedDecl *>());
3838 }
3839 
isImplicitlyInstantiable() const3840 bool FunctionDecl::isImplicitlyInstantiable() const {
3841   // If the function is invalid, it can't be implicitly instantiated.
3842   if (isInvalidDecl())
3843     return false;
3844 
3845   switch (getTemplateSpecializationKindForInstantiation()) {
3846   case TSK_Undeclared:
3847   case TSK_ExplicitInstantiationDefinition:
3848   case TSK_ExplicitSpecialization:
3849     return false;
3850 
3851   case TSK_ImplicitInstantiation:
3852     return true;
3853 
3854   case TSK_ExplicitInstantiationDeclaration:
3855     // Handled below.
3856     break;
3857   }
3858 
3859   // Find the actual template from which we will instantiate.
3860   const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3861   bool HasPattern = false;
3862   if (PatternDecl)
3863     HasPattern = PatternDecl->hasBody(PatternDecl);
3864 
3865   // C++0x [temp.explicit]p9:
3866   //   Except for inline functions, other explicit instantiation declarations
3867   //   have the effect of suppressing the implicit instantiation of the entity
3868   //   to which they refer.
3869   if (!HasPattern || !PatternDecl)
3870     return true;
3871 
3872   return PatternDecl->isInlined();
3873 }
3874 
isTemplateInstantiation() const3875 bool FunctionDecl::isTemplateInstantiation() const {
3876   // FIXME: Remove this, it's not clear what it means. (Which template
3877   // specialization kind?)
3878   return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3879 }
3880 
3881 FunctionDecl *
getTemplateInstantiationPattern(bool ForDefinition) const3882 FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3883   // If this is a generic lambda call operator specialization, its
3884   // instantiation pattern is always its primary template's pattern
3885   // even if its primary template was instantiated from another
3886   // member template (which happens with nested generic lambdas).
3887   // Since a lambda's call operator's body is transformed eagerly,
3888   // we don't have to go hunting for a prototype definition template
3889   // (i.e. instantiated-from-member-template) to use as an instantiation
3890   // pattern.
3891 
3892   if (isGenericLambdaCallOperatorSpecialization(
3893           dyn_cast<CXXMethodDecl>(this))) {
3894     assert(getPrimaryTemplate() && "not a generic lambda call operator?");
3895     return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3896   }
3897 
3898   // Check for a declaration of this function that was instantiated from a
3899   // friend definition.
3900   const FunctionDecl *FD = nullptr;
3901   if (!isDefined(FD, /*CheckForPendingFriendDefinition=*/true))
3902     FD = this;
3903 
3904   if (MemberSpecializationInfo *Info = FD->getMemberSpecializationInfo()) {
3905     if (ForDefinition &&
3906         !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3907       return nullptr;
3908     return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3909   }
3910 
3911   if (ForDefinition &&
3912       !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3913     return nullptr;
3914 
3915   if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3916     // If we hit a point where the user provided a specialization of this
3917     // template, we're done looking.
3918     while (!ForDefinition || !Primary->isMemberSpecialization()) {
3919       auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3920       if (!NewPrimary)
3921         break;
3922       Primary = NewPrimary;
3923     }
3924 
3925     return getDefinitionOrSelf(Primary->getTemplatedDecl());
3926   }
3927 
3928   return nullptr;
3929 }
3930 
getPrimaryTemplate() const3931 FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3932   if (FunctionTemplateSpecializationInfo *Info
3933         = TemplateOrSpecialization
3934             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3935     return Info->getTemplate();
3936   }
3937   return nullptr;
3938 }
3939 
3940 FunctionTemplateSpecializationInfo *
getTemplateSpecializationInfo() const3941 FunctionDecl::getTemplateSpecializationInfo() const {
3942   return TemplateOrSpecialization
3943       .dyn_cast<FunctionTemplateSpecializationInfo *>();
3944 }
3945 
3946 const TemplateArgumentList *
getTemplateSpecializationArgs() const3947 FunctionDecl::getTemplateSpecializationArgs() const {
3948   if (FunctionTemplateSpecializationInfo *Info
3949         = TemplateOrSpecialization
3950             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3951     return Info->TemplateArguments;
3952   }
3953   return nullptr;
3954 }
3955 
3956 const ASTTemplateArgumentListInfo *
getTemplateSpecializationArgsAsWritten() const3957 FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3958   if (FunctionTemplateSpecializationInfo *Info
3959         = TemplateOrSpecialization
3960             .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3961     return Info->TemplateArgumentsAsWritten;
3962   }
3963   return nullptr;
3964 }
3965 
3966 void
setFunctionTemplateSpecialization(ASTContext & C,FunctionTemplateDecl * Template,const TemplateArgumentList * TemplateArgs,void * InsertPos,TemplateSpecializationKind TSK,const TemplateArgumentListInfo * TemplateArgsAsWritten,SourceLocation PointOfInstantiation)3967 FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3968                                                 FunctionTemplateDecl *Template,
3969                                      const TemplateArgumentList *TemplateArgs,
3970                                                 void *InsertPos,
3971                                                 TemplateSpecializationKind TSK,
3972                         const TemplateArgumentListInfo *TemplateArgsAsWritten,
3973                                           SourceLocation PointOfInstantiation) {
3974   assert((TemplateOrSpecialization.isNull() ||
3975           TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&
3976          "Member function is already a specialization");
3977   assert(TSK != TSK_Undeclared &&
3978          "Must specify the type of function template specialization");
3979   assert((TemplateOrSpecialization.isNull() ||
3980           TSK == TSK_ExplicitSpecialization) &&
3981          "Member specialization must be an explicit specialization");
3982   FunctionTemplateSpecializationInfo *Info =
3983       FunctionTemplateSpecializationInfo::Create(
3984           C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3985           PointOfInstantiation,
3986           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3987   TemplateOrSpecialization = Info;
3988   Template->addSpecialization(Info, InsertPos);
3989 }
3990 
3991 void
setDependentTemplateSpecialization(ASTContext & Context,const UnresolvedSetImpl & Templates,const TemplateArgumentListInfo & TemplateArgs)3992 FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3993                                     const UnresolvedSetImpl &Templates,
3994                              const TemplateArgumentListInfo &TemplateArgs) {
3995   assert(TemplateOrSpecialization.isNull());
3996   DependentFunctionTemplateSpecializationInfo *Info =
3997       DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
3998                                                           TemplateArgs);
3999   TemplateOrSpecialization = Info;
4000 }
4001 
4002 DependentFunctionTemplateSpecializationInfo *
getDependentSpecializationInfo() const4003 FunctionDecl::getDependentSpecializationInfo() const {
4004   return TemplateOrSpecialization
4005       .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
4006 }
4007 
4008 DependentFunctionTemplateSpecializationInfo *
Create(ASTContext & Context,const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)4009 DependentFunctionTemplateSpecializationInfo::Create(
4010     ASTContext &Context, const UnresolvedSetImpl &Ts,
4011     const TemplateArgumentListInfo &TArgs) {
4012   void *Buffer = Context.Allocate(
4013       totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
4014           TArgs.size(), Ts.size()));
4015   return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
4016 }
4017 
4018 DependentFunctionTemplateSpecializationInfo::
DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl & Ts,const TemplateArgumentListInfo & TArgs)4019 DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
4020                                       const TemplateArgumentListInfo &TArgs)
4021   : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
4022   NumTemplates = Ts.size();
4023   NumArgs = TArgs.size();
4024 
4025   FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
4026   for (unsigned I = 0, E = Ts.size(); I != E; ++I)
4027     TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
4028 
4029   TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
4030   for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
4031     new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
4032 }
4033 
getTemplateSpecializationKind() const4034 TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
4035   // For a function template specialization, query the specialization
4036   // information object.
4037   if (FunctionTemplateSpecializationInfo *FTSInfo =
4038           TemplateOrSpecialization
4039               .dyn_cast<FunctionTemplateSpecializationInfo *>())
4040     return FTSInfo->getTemplateSpecializationKind();
4041 
4042   if (MemberSpecializationInfo *MSInfo =
4043           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4044     return MSInfo->getTemplateSpecializationKind();
4045 
4046   return TSK_Undeclared;
4047 }
4048 
4049 TemplateSpecializationKind
getTemplateSpecializationKindForInstantiation() const4050 FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
4051   // This is the same as getTemplateSpecializationKind(), except that for a
4052   // function that is both a function template specialization and a member
4053   // specialization, we prefer the member specialization information. Eg:
4054   //
4055   // template<typename T> struct A {
4056   //   template<typename U> void f() {}
4057   //   template<> void f<int>() {}
4058   // };
4059   //
4060   // For A<int>::f<int>():
4061   // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
4062   // * getTemplateSpecializationKindForInstantiation() will return
4063   //       TSK_ImplicitInstantiation
4064   //
4065   // This reflects the facts that A<int>::f<int> is an explicit specialization
4066   // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
4067   // from A::f<int> if a definition is needed.
4068   if (FunctionTemplateSpecializationInfo *FTSInfo =
4069           TemplateOrSpecialization
4070               .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
4071     if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
4072       return MSInfo->getTemplateSpecializationKind();
4073     return FTSInfo->getTemplateSpecializationKind();
4074   }
4075 
4076   if (MemberSpecializationInfo *MSInfo =
4077           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4078     return MSInfo->getTemplateSpecializationKind();
4079 
4080   return TSK_Undeclared;
4081 }
4082 
4083 void
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)4084 FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4085                                           SourceLocation PointOfInstantiation) {
4086   if (FunctionTemplateSpecializationInfo *FTSInfo
4087         = TemplateOrSpecialization.dyn_cast<
4088                                     FunctionTemplateSpecializationInfo*>()) {
4089     FTSInfo->setTemplateSpecializationKind(TSK);
4090     if (TSK != TSK_ExplicitSpecialization &&
4091         PointOfInstantiation.isValid() &&
4092         FTSInfo->getPointOfInstantiation().isInvalid()) {
4093       FTSInfo->setPointOfInstantiation(PointOfInstantiation);
4094       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4095         L->InstantiationRequested(this);
4096     }
4097   } else if (MemberSpecializationInfo *MSInfo
4098              = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
4099     MSInfo->setTemplateSpecializationKind(TSK);
4100     if (TSK != TSK_ExplicitSpecialization &&
4101         PointOfInstantiation.isValid() &&
4102         MSInfo->getPointOfInstantiation().isInvalid()) {
4103       MSInfo->setPointOfInstantiation(PointOfInstantiation);
4104       if (ASTMutationListener *L = getASTContext().getASTMutationListener())
4105         L->InstantiationRequested(this);
4106     }
4107   } else
4108     llvm_unreachable("Function cannot have a template specialization kind");
4109 }
4110 
getPointOfInstantiation() const4111 SourceLocation FunctionDecl::getPointOfInstantiation() const {
4112   if (FunctionTemplateSpecializationInfo *FTSInfo
4113         = TemplateOrSpecialization.dyn_cast<
4114                                         FunctionTemplateSpecializationInfo*>())
4115     return FTSInfo->getPointOfInstantiation();
4116   if (MemberSpecializationInfo *MSInfo =
4117           TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
4118     return MSInfo->getPointOfInstantiation();
4119 
4120   return SourceLocation();
4121 }
4122 
isOutOfLine() const4123 bool FunctionDecl::isOutOfLine() const {
4124   if (Decl::isOutOfLine())
4125     return true;
4126 
4127   // If this function was instantiated from a member function of a
4128   // class template, check whether that member function was defined out-of-line.
4129   if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
4130     const FunctionDecl *Definition;
4131     if (FD->hasBody(Definition))
4132       return Definition->isOutOfLine();
4133   }
4134 
4135   // If this function was instantiated from a function template,
4136   // check whether that function template was defined out-of-line.
4137   if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
4138     const FunctionDecl *Definition;
4139     if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
4140       return Definition->isOutOfLine();
4141   }
4142 
4143   return false;
4144 }
4145 
getSourceRange() const4146 SourceRange FunctionDecl::getSourceRange() const {
4147   return SourceRange(getOuterLocStart(), EndRangeLoc);
4148 }
4149 
getMemoryFunctionKind() const4150 unsigned FunctionDecl::getMemoryFunctionKind() const {
4151   IdentifierInfo *FnInfo = getIdentifier();
4152 
4153   if (!FnInfo)
4154     return 0;
4155 
4156   // Builtin handling.
4157   switch (getBuiltinID()) {
4158   case Builtin::BI__builtin_memset:
4159   case Builtin::BI__builtin___memset_chk:
4160   case Builtin::BImemset:
4161     return Builtin::BImemset;
4162 
4163   case Builtin::BI__builtin_memcpy:
4164   case Builtin::BI__builtin___memcpy_chk:
4165   case Builtin::BImemcpy:
4166     return Builtin::BImemcpy;
4167 
4168   case Builtin::BI__builtin_mempcpy:
4169   case Builtin::BI__builtin___mempcpy_chk:
4170   case Builtin::BImempcpy:
4171     return Builtin::BImempcpy;
4172 
4173   case Builtin::BI__builtin_memmove:
4174   case Builtin::BI__builtin___memmove_chk:
4175   case Builtin::BImemmove:
4176     return Builtin::BImemmove;
4177 
4178   case Builtin::BIstrlcpy:
4179   case Builtin::BI__builtin___strlcpy_chk:
4180     return Builtin::BIstrlcpy;
4181 
4182   case Builtin::BIstrlcat:
4183   case Builtin::BI__builtin___strlcat_chk:
4184     return Builtin::BIstrlcat;
4185 
4186   case Builtin::BI__builtin_memcmp:
4187   case Builtin::BImemcmp:
4188     return Builtin::BImemcmp;
4189 
4190   case Builtin::BI__builtin_bcmp:
4191   case Builtin::BIbcmp:
4192     return Builtin::BIbcmp;
4193 
4194   case Builtin::BI__builtin_strncpy:
4195   case Builtin::BI__builtin___strncpy_chk:
4196   case Builtin::BIstrncpy:
4197     return Builtin::BIstrncpy;
4198 
4199   case Builtin::BI__builtin_strncmp:
4200   case Builtin::BIstrncmp:
4201     return Builtin::BIstrncmp;
4202 
4203   case Builtin::BI__builtin_strncasecmp:
4204   case Builtin::BIstrncasecmp:
4205     return Builtin::BIstrncasecmp;
4206 
4207   case Builtin::BI__builtin_strncat:
4208   case Builtin::BI__builtin___strncat_chk:
4209   case Builtin::BIstrncat:
4210     return Builtin::BIstrncat;
4211 
4212   case Builtin::BI__builtin_strndup:
4213   case Builtin::BIstrndup:
4214     return Builtin::BIstrndup;
4215 
4216   case Builtin::BI__builtin_strlen:
4217   case Builtin::BIstrlen:
4218     return Builtin::BIstrlen;
4219 
4220   case Builtin::BI__builtin_bzero:
4221   case Builtin::BIbzero:
4222     return Builtin::BIbzero;
4223 
4224   case Builtin::BIfree:
4225     return Builtin::BIfree;
4226 
4227   default:
4228     if (isExternC()) {
4229       if (FnInfo->isStr("memset"))
4230         return Builtin::BImemset;
4231       if (FnInfo->isStr("memcpy"))
4232         return Builtin::BImemcpy;
4233       if (FnInfo->isStr("mempcpy"))
4234         return Builtin::BImempcpy;
4235       if (FnInfo->isStr("memmove"))
4236         return Builtin::BImemmove;
4237       if (FnInfo->isStr("memcmp"))
4238         return Builtin::BImemcmp;
4239       if (FnInfo->isStr("bcmp"))
4240         return Builtin::BIbcmp;
4241       if (FnInfo->isStr("strncpy"))
4242         return Builtin::BIstrncpy;
4243       if (FnInfo->isStr("strncmp"))
4244         return Builtin::BIstrncmp;
4245       if (FnInfo->isStr("strncasecmp"))
4246         return Builtin::BIstrncasecmp;
4247       if (FnInfo->isStr("strncat"))
4248         return Builtin::BIstrncat;
4249       if (FnInfo->isStr("strndup"))
4250         return Builtin::BIstrndup;
4251       if (FnInfo->isStr("strlen"))
4252         return Builtin::BIstrlen;
4253       if (FnInfo->isStr("bzero"))
4254         return Builtin::BIbzero;
4255     } else if (isInStdNamespace()) {
4256       if (FnInfo->isStr("free"))
4257         return Builtin::BIfree;
4258     }
4259     break;
4260   }
4261   return 0;
4262 }
4263 
getODRHash() const4264 unsigned FunctionDecl::getODRHash() const {
4265   assert(hasODRHash());
4266   return ODRHash;
4267 }
4268 
getODRHash()4269 unsigned FunctionDecl::getODRHash() {
4270   if (hasODRHash())
4271     return ODRHash;
4272 
4273   if (auto *FT = getInstantiatedFromMemberFunction()) {
4274     setHasODRHash(true);
4275     ODRHash = FT->getODRHash();
4276     return ODRHash;
4277   }
4278 
4279   class ODRHash Hash;
4280   Hash.AddFunctionDecl(this);
4281   setHasODRHash(true);
4282   ODRHash = Hash.CalculateHash();
4283   return ODRHash;
4284 }
4285 
4286 //===----------------------------------------------------------------------===//
4287 // FieldDecl Implementation
4288 //===----------------------------------------------------------------------===//
4289 
Create(const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,QualType T,TypeSourceInfo * TInfo,Expr * BW,bool Mutable,InClassInitStyle InitStyle)4290 FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4291                              SourceLocation StartLoc, SourceLocation IdLoc,
4292                              IdentifierInfo *Id, QualType T,
4293                              TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4294                              InClassInitStyle InitStyle) {
4295   return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4296                                BW, Mutable, InitStyle);
4297 }
4298 
CreateDeserialized(ASTContext & C,unsigned ID)4299 FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4300   return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4301                                SourceLocation(), nullptr, QualType(), nullptr,
4302                                nullptr, false, ICIS_NoInit);
4303 }
4304 
isAnonymousStructOrUnion() const4305 bool FieldDecl::isAnonymousStructOrUnion() const {
4306   if (!isImplicit() || getDeclName())
4307     return false;
4308 
4309   if (const auto *Record = getType()->getAs<RecordType>())
4310     return Record->getDecl()->isAnonymousStructOrUnion();
4311 
4312   return false;
4313 }
4314 
getBitWidthValue(const ASTContext & Ctx) const4315 unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4316   assert(isBitField() && "not a bitfield");
4317   return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4318 }
4319 
isZeroLengthBitField(const ASTContext & Ctx) const4320 bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4321   return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4322          getBitWidthValue(Ctx) == 0;
4323 }
4324 
isZeroSize(const ASTContext & Ctx) const4325 bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4326   if (isZeroLengthBitField(Ctx))
4327     return true;
4328 
4329   // C++2a [intro.object]p7:
4330   //   An object has nonzero size if it
4331   //     -- is not a potentially-overlapping subobject, or
4332   if (!hasAttr<NoUniqueAddressAttr>())
4333     return false;
4334 
4335   //     -- is not of class type, or
4336   const auto *RT = getType()->getAs<RecordType>();
4337   if (!RT)
4338     return false;
4339   const RecordDecl *RD = RT->getDecl()->getDefinition();
4340   if (!RD) {
4341     assert(isInvalidDecl() && "valid field has incomplete type");
4342     return false;
4343   }
4344 
4345   //     -- [has] virtual member functions or virtual base classes, or
4346   //     -- has subobjects of nonzero size or bit-fields of nonzero length
4347   const auto *CXXRD = cast<CXXRecordDecl>(RD);
4348   if (!CXXRD->isEmpty())
4349     return false;
4350 
4351   // Otherwise, [...] the circumstances under which the object has zero size
4352   // are implementation-defined.
4353   // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4354   // ABI will do.
4355   return true;
4356 }
4357 
getFieldIndex() const4358 unsigned FieldDecl::getFieldIndex() const {
4359   const FieldDecl *Canonical = getCanonicalDecl();
4360   if (Canonical != this)
4361     return Canonical->getFieldIndex();
4362 
4363   if (CachedFieldIndex) return CachedFieldIndex - 1;
4364 
4365   unsigned Index = 0;
4366   const RecordDecl *RD = getParent()->getDefinition();
4367   assert(RD && "requested index for field of struct with no definition");
4368 
4369   for (auto *Field : RD->fields()) {
4370     Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4371     ++Index;
4372   }
4373 
4374   assert(CachedFieldIndex && "failed to find field in parent");
4375   return CachedFieldIndex - 1;
4376 }
4377 
getSourceRange() const4378 SourceRange FieldDecl::getSourceRange() const {
4379   const Expr *FinalExpr = getInClassInitializer();
4380   if (!FinalExpr)
4381     FinalExpr = getBitWidth();
4382   if (FinalExpr)
4383     return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4384   return DeclaratorDecl::getSourceRange();
4385 }
4386 
setCapturedVLAType(const VariableArrayType * VLAType)4387 void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4388   assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&
4389          "capturing type in non-lambda or captured record.");
4390   assert(InitStorage.getInt() == ISK_NoInit &&
4391          InitStorage.getPointer() == nullptr &&
4392          "bit width, initializer or captured type already set");
4393   InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4394                                ISK_CapturedVLAType);
4395 }
4396 
4397 //===----------------------------------------------------------------------===//
4398 // TagDecl Implementation
4399 //===----------------------------------------------------------------------===//
4400 
TagDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,TagDecl * PrevDecl,SourceLocation StartL)4401 TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4402                  SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4403                  SourceLocation StartL)
4404     : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4405       TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4406   assert((DK != Enum || TK == TTK_Enum) &&
4407          "EnumDecl not matched with TTK_Enum");
4408   setPreviousDecl(PrevDecl);
4409   setTagKind(TK);
4410   setCompleteDefinition(false);
4411   setBeingDefined(false);
4412   setEmbeddedInDeclarator(false);
4413   setFreeStanding(false);
4414   setCompleteDefinitionRequired(false);
4415   TagDeclBits.IsThisDeclarationADemotedDefinition = false;
4416 }
4417 
getOuterLocStart() const4418 SourceLocation TagDecl::getOuterLocStart() const {
4419   return getTemplateOrInnerLocStart(this);
4420 }
4421 
getSourceRange() const4422 SourceRange TagDecl::getSourceRange() const {
4423   SourceLocation RBraceLoc = BraceRange.getEnd();
4424   SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4425   return SourceRange(getOuterLocStart(), E);
4426 }
4427 
getCanonicalDecl()4428 TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4429 
setTypedefNameForAnonDecl(TypedefNameDecl * TDD)4430 void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4431   TypedefNameDeclOrQualifier = TDD;
4432   if (const Type *T = getTypeForDecl()) {
4433     (void)T;
4434     assert(T->isLinkageValid());
4435   }
4436   assert(isLinkageValid());
4437 }
4438 
startDefinition()4439 void TagDecl::startDefinition() {
4440   setBeingDefined(true);
4441 
4442   if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4443     struct CXXRecordDecl::DefinitionData *Data =
4444       new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4445     for (auto *I : redecls())
4446       cast<CXXRecordDecl>(I)->DefinitionData = Data;
4447   }
4448 }
4449 
completeDefinition()4450 void TagDecl::completeDefinition() {
4451   assert((!isa<CXXRecordDecl>(this) ||
4452           cast<CXXRecordDecl>(this)->hasDefinition()) &&
4453          "definition completed but not started");
4454 
4455   setCompleteDefinition(true);
4456   setBeingDefined(false);
4457 
4458   if (ASTMutationListener *L = getASTMutationListener())
4459     L->CompletedTagDefinition(this);
4460 }
4461 
getDefinition() const4462 TagDecl *TagDecl::getDefinition() const {
4463   if (isCompleteDefinition())
4464     return const_cast<TagDecl *>(this);
4465 
4466   // If it's possible for us to have an out-of-date definition, check now.
4467   if (mayHaveOutOfDateDef()) {
4468     if (IdentifierInfo *II = getIdentifier()) {
4469       if (II->isOutOfDate()) {
4470         updateOutOfDate(*II);
4471       }
4472     }
4473   }
4474 
4475   if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4476     return CXXRD->getDefinition();
4477 
4478   for (auto *R : redecls())
4479     if (R->isCompleteDefinition())
4480       return R;
4481 
4482   return nullptr;
4483 }
4484 
setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)4485 void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4486   if (QualifierLoc) {
4487     // Make sure the extended qualifier info is allocated.
4488     if (!hasExtInfo())
4489       TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4490     // Set qualifier info.
4491     getExtInfo()->QualifierLoc = QualifierLoc;
4492   } else {
4493     // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4494     if (hasExtInfo()) {
4495       if (getExtInfo()->NumTemplParamLists == 0) {
4496         getASTContext().Deallocate(getExtInfo());
4497         TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4498       }
4499       else
4500         getExtInfo()->QualifierLoc = QualifierLoc;
4501     }
4502   }
4503 }
4504 
printName(raw_ostream & OS,const PrintingPolicy & Policy) const4505 void TagDecl::printName(raw_ostream &OS, const PrintingPolicy &Policy) const {
4506   DeclarationName Name = getDeclName();
4507   // If the name is supposed to have an identifier but does not have one, then
4508   // the tag is anonymous and we should print it differently.
4509   if (Name.isIdentifier() && !Name.getAsIdentifierInfo()) {
4510     // If the caller wanted to print a qualified name, they've already printed
4511     // the scope. And if the caller doesn't want that, the scope information
4512     // is already printed as part of the type.
4513     PrintingPolicy Copy(Policy);
4514     Copy.SuppressScope = true;
4515     getASTContext().getTagDeclType(this).print(OS, Copy);
4516     return;
4517   }
4518   // Otherwise, do the normal printing.
4519   Name.print(OS, Policy);
4520 }
4521 
setTemplateParameterListsInfo(ASTContext & Context,ArrayRef<TemplateParameterList * > TPLists)4522 void TagDecl::setTemplateParameterListsInfo(
4523     ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4524   assert(!TPLists.empty());
4525   // Make sure the extended decl info is allocated.
4526   if (!hasExtInfo())
4527     // Allocate external info struct.
4528     TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4529   // Set the template parameter lists info.
4530   getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4531 }
4532 
4533 //===----------------------------------------------------------------------===//
4534 // EnumDecl Implementation
4535 //===----------------------------------------------------------------------===//
4536 
EnumDecl(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool Scoped,bool ScopedUsingClassTag,bool Fixed)4537 EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4538                    SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4539                    bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4540     : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4541   assert(Scoped || !ScopedUsingClassTag);
4542   IntegerType = nullptr;
4543   setNumPositiveBits(0);
4544   setNumNegativeBits(0);
4545   setScoped(Scoped);
4546   setScopedUsingClassTag(ScopedUsingClassTag);
4547   setFixed(Fixed);
4548   setHasODRHash(false);
4549   ODRHash = 0;
4550 }
4551 
anchor()4552 void EnumDecl::anchor() {}
4553 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,EnumDecl * PrevDecl,bool IsScoped,bool IsScopedUsingClassTag,bool IsFixed)4554 EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4555                            SourceLocation StartLoc, SourceLocation IdLoc,
4556                            IdentifierInfo *Id,
4557                            EnumDecl *PrevDecl, bool IsScoped,
4558                            bool IsScopedUsingClassTag, bool IsFixed) {
4559   auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4560                                     IsScoped, IsScopedUsingClassTag, IsFixed);
4561   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4562   C.getTypeDeclType(Enum, PrevDecl);
4563   return Enum;
4564 }
4565 
CreateDeserialized(ASTContext & C,unsigned ID)4566 EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4567   EnumDecl *Enum =
4568       new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4569                            nullptr, nullptr, false, false, false);
4570   Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4571   return Enum;
4572 }
4573 
getIntegerTypeRange() const4574 SourceRange EnumDecl::getIntegerTypeRange() const {
4575   if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4576     return TI->getTypeLoc().getSourceRange();
4577   return SourceRange();
4578 }
4579 
completeDefinition(QualType NewType,QualType NewPromotionType,unsigned NumPositiveBits,unsigned NumNegativeBits)4580 void EnumDecl::completeDefinition(QualType NewType,
4581                                   QualType NewPromotionType,
4582                                   unsigned NumPositiveBits,
4583                                   unsigned NumNegativeBits) {
4584   assert(!isCompleteDefinition() && "Cannot redefine enums!");
4585   if (!IntegerType)
4586     IntegerType = NewType.getTypePtr();
4587   PromotionType = NewPromotionType;
4588   setNumPositiveBits(NumPositiveBits);
4589   setNumNegativeBits(NumNegativeBits);
4590   TagDecl::completeDefinition();
4591 }
4592 
isClosed() const4593 bool EnumDecl::isClosed() const {
4594   if (const auto *A = getAttr<EnumExtensibilityAttr>())
4595     return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4596   return true;
4597 }
4598 
isClosedFlag() const4599 bool EnumDecl::isClosedFlag() const {
4600   return isClosed() && hasAttr<FlagEnumAttr>();
4601 }
4602 
isClosedNonFlag() const4603 bool EnumDecl::isClosedNonFlag() const {
4604   return isClosed() && !hasAttr<FlagEnumAttr>();
4605 }
4606 
getTemplateSpecializationKind() const4607 TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4608   if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4609     return MSI->getTemplateSpecializationKind();
4610 
4611   return TSK_Undeclared;
4612 }
4613 
setTemplateSpecializationKind(TemplateSpecializationKind TSK,SourceLocation PointOfInstantiation)4614 void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4615                                          SourceLocation PointOfInstantiation) {
4616   MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4617   assert(MSI && "Not an instantiated member enumeration?");
4618   MSI->setTemplateSpecializationKind(TSK);
4619   if (TSK != TSK_ExplicitSpecialization &&
4620       PointOfInstantiation.isValid() &&
4621       MSI->getPointOfInstantiation().isInvalid())
4622     MSI->setPointOfInstantiation(PointOfInstantiation);
4623 }
4624 
getTemplateInstantiationPattern() const4625 EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4626   if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4627     if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4628       EnumDecl *ED = getInstantiatedFromMemberEnum();
4629       while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4630         ED = NewED;
4631       return getDefinitionOrSelf(ED);
4632     }
4633   }
4634 
4635   assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&
4636          "couldn't find pattern for enum instantiation");
4637   return nullptr;
4638 }
4639 
getInstantiatedFromMemberEnum() const4640 EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4641   if (SpecializationInfo)
4642     return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4643 
4644   return nullptr;
4645 }
4646 
setInstantiationOfMemberEnum(ASTContext & C,EnumDecl * ED,TemplateSpecializationKind TSK)4647 void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4648                                             TemplateSpecializationKind TSK) {
4649   assert(!SpecializationInfo && "Member enum is already a specialization");
4650   SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4651 }
4652 
getODRHash()4653 unsigned EnumDecl::getODRHash() {
4654   if (hasODRHash())
4655     return ODRHash;
4656 
4657   class ODRHash Hash;
4658   Hash.AddEnumDecl(this);
4659   setHasODRHash(true);
4660   ODRHash = Hash.CalculateHash();
4661   return ODRHash;
4662 }
4663 
getSourceRange() const4664 SourceRange EnumDecl::getSourceRange() const {
4665   auto Res = TagDecl::getSourceRange();
4666   // Set end-point to enum-base, e.g. enum foo : ^bar
4667   if (auto *TSI = getIntegerTypeSourceInfo()) {
4668     // TagDecl doesn't know about the enum base.
4669     if (!getBraceRange().getEnd().isValid())
4670       Res.setEnd(TSI->getTypeLoc().getEndLoc());
4671   }
4672   return Res;
4673 }
4674 
getValueRange(llvm::APInt & Max,llvm::APInt & Min) const4675 void EnumDecl::getValueRange(llvm::APInt &Max, llvm::APInt &Min) const {
4676   unsigned Bitwidth = getASTContext().getIntWidth(getIntegerType());
4677   unsigned NumNegativeBits = getNumNegativeBits();
4678   unsigned NumPositiveBits = getNumPositiveBits();
4679 
4680   if (NumNegativeBits) {
4681     unsigned NumBits = std::max(NumNegativeBits, NumPositiveBits + 1);
4682     Max = llvm::APInt(Bitwidth, 1) << (NumBits - 1);
4683     Min = -Max;
4684   } else {
4685     Max = llvm::APInt(Bitwidth, 1) << NumPositiveBits;
4686     Min = llvm::APInt::getZero(Bitwidth);
4687   }
4688 }
4689 
4690 //===----------------------------------------------------------------------===//
4691 // RecordDecl Implementation
4692 //===----------------------------------------------------------------------===//
4693 
RecordDecl(Kind DK,TagKind TK,const ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4694 RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4695                        DeclContext *DC, SourceLocation StartLoc,
4696                        SourceLocation IdLoc, IdentifierInfo *Id,
4697                        RecordDecl *PrevDecl)
4698     : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4699   assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!");
4700   setHasFlexibleArrayMember(false);
4701   setAnonymousStructOrUnion(false);
4702   setHasObjectMember(false);
4703   setHasVolatileMember(false);
4704   setHasLoadedFieldsFromExternalStorage(false);
4705   setNonTrivialToPrimitiveDefaultInitialize(false);
4706   setNonTrivialToPrimitiveCopy(false);
4707   setNonTrivialToPrimitiveDestroy(false);
4708   setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4709   setHasNonTrivialToPrimitiveDestructCUnion(false);
4710   setHasNonTrivialToPrimitiveCopyCUnion(false);
4711   setParamDestroyedInCallee(false);
4712   setArgPassingRestrictions(APK_CanPassInRegs);
4713   setIsRandomized(false);
4714   setODRHash(0);
4715 }
4716 
Create(const ASTContext & C,TagKind TK,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,RecordDecl * PrevDecl)4717 RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4718                                SourceLocation StartLoc, SourceLocation IdLoc,
4719                                IdentifierInfo *Id, RecordDecl* PrevDecl) {
4720   RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4721                                          StartLoc, IdLoc, Id, PrevDecl);
4722   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4723 
4724   C.getTypeDeclType(R, PrevDecl);
4725   return R;
4726 }
4727 
CreateDeserialized(const ASTContext & C,unsigned ID)4728 RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4729   RecordDecl *R =
4730       new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4731                              SourceLocation(), nullptr, nullptr);
4732   R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4733   return R;
4734 }
4735 
isInjectedClassName() const4736 bool RecordDecl::isInjectedClassName() const {
4737   return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4738     cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4739 }
4740 
isLambda() const4741 bool RecordDecl::isLambda() const {
4742   if (auto RD = dyn_cast<CXXRecordDecl>(this))
4743     return RD->isLambda();
4744   return false;
4745 }
4746 
isCapturedRecord() const4747 bool RecordDecl::isCapturedRecord() const {
4748   return hasAttr<CapturedRecordAttr>();
4749 }
4750 
setCapturedRecord()4751 void RecordDecl::setCapturedRecord() {
4752   addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4753 }
4754 
isOrContainsUnion() const4755 bool RecordDecl::isOrContainsUnion() const {
4756   if (isUnion())
4757     return true;
4758 
4759   if (const RecordDecl *Def = getDefinition()) {
4760     for (const FieldDecl *FD : Def->fields()) {
4761       const RecordType *RT = FD->getType()->getAs<RecordType>();
4762       if (RT && RT->getDecl()->isOrContainsUnion())
4763         return true;
4764     }
4765   }
4766 
4767   return false;
4768 }
4769 
field_begin() const4770 RecordDecl::field_iterator RecordDecl::field_begin() const {
4771   if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4772     LoadFieldsFromExternalStorage();
4773 
4774   return field_iterator(decl_iterator(FirstDecl));
4775 }
4776 
4777 /// completeDefinition - Notes that the definition of this type is now
4778 /// complete.
completeDefinition()4779 void RecordDecl::completeDefinition() {
4780   assert(!isCompleteDefinition() && "Cannot redefine record!");
4781   TagDecl::completeDefinition();
4782 
4783   ASTContext &Ctx = getASTContext();
4784 
4785   // Layouts are dumped when computed, so if we are dumping for all complete
4786   // types, we need to force usage to get types that wouldn't be used elsewhere.
4787   if (Ctx.getLangOpts().DumpRecordLayoutsComplete)
4788     (void)Ctx.getASTRecordLayout(this);
4789 }
4790 
4791 /// isMsStruct - Get whether or not this record uses ms_struct layout.
4792 /// This which can be turned on with an attribute, pragma, or the
4793 /// -mms-bitfields command-line option.
isMsStruct(const ASTContext & C) const4794 bool RecordDecl::isMsStruct(const ASTContext &C) const {
4795   return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4796 }
4797 
reorderDecls(const SmallVectorImpl<Decl * > & Decls)4798 void RecordDecl::reorderDecls(const SmallVectorImpl<Decl *> &Decls) {
4799   std::tie(FirstDecl, LastDecl) = DeclContext::BuildDeclChain(Decls, false);
4800   LastDecl->NextInContextAndBits.setPointer(nullptr);
4801   setIsRandomized(true);
4802 }
4803 
LoadFieldsFromExternalStorage() const4804 void RecordDecl::LoadFieldsFromExternalStorage() const {
4805   ExternalASTSource *Source = getASTContext().getExternalSource();
4806   assert(hasExternalLexicalStorage() && Source && "No external storage?");
4807 
4808   // Notify that we have a RecordDecl doing some initialization.
4809   ExternalASTSource::Deserializing TheFields(Source);
4810 
4811   SmallVector<Decl*, 64> Decls;
4812   setHasLoadedFieldsFromExternalStorage(true);
4813   Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4814     return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4815   }, Decls);
4816 
4817 #ifndef NDEBUG
4818   // Check that all decls we got were FieldDecls.
4819   for (unsigned i=0, e=Decls.size(); i != e; ++i)
4820     assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]));
4821 #endif
4822 
4823   if (Decls.empty())
4824     return;
4825 
4826   std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4827                                                  /*FieldsAlreadyLoaded=*/false);
4828 }
4829 
mayInsertExtraPadding(bool EmitRemark) const4830 bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4831   ASTContext &Context = getASTContext();
4832   const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4833       (SanitizerKind::Address | SanitizerKind::KernelAddress);
4834   if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4835     return false;
4836   const auto &NoSanitizeList = Context.getNoSanitizeList();
4837   const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4838   // We may be able to relax some of these requirements.
4839   int ReasonToReject = -1;
4840   if (!CXXRD || CXXRD->isExternCContext())
4841     ReasonToReject = 0;  // is not C++.
4842   else if (CXXRD->hasAttr<PackedAttr>())
4843     ReasonToReject = 1;  // is packed.
4844   else if (CXXRD->isUnion())
4845     ReasonToReject = 2;  // is a union.
4846   else if (CXXRD->isTriviallyCopyable())
4847     ReasonToReject = 3;  // is trivially copyable.
4848   else if (CXXRD->hasTrivialDestructor())
4849     ReasonToReject = 4;  // has trivial destructor.
4850   else if (CXXRD->isStandardLayout())
4851     ReasonToReject = 5;  // is standard layout.
4852   else if (NoSanitizeList.containsLocation(EnabledAsanMask, getLocation(),
4853                                            "field-padding"))
4854     ReasonToReject = 6;  // is in an excluded file.
4855   else if (NoSanitizeList.containsType(
4856                EnabledAsanMask, getQualifiedNameAsString(), "field-padding"))
4857     ReasonToReject = 7;  // The type is excluded.
4858 
4859   if (EmitRemark) {
4860     if (ReasonToReject >= 0)
4861       Context.getDiagnostics().Report(
4862           getLocation(),
4863           diag::remark_sanitize_address_insert_extra_padding_rejected)
4864           << getQualifiedNameAsString() << ReasonToReject;
4865     else
4866       Context.getDiagnostics().Report(
4867           getLocation(),
4868           diag::remark_sanitize_address_insert_extra_padding_accepted)
4869           << getQualifiedNameAsString();
4870   }
4871   return ReasonToReject < 0;
4872 }
4873 
findFirstNamedDataMember() const4874 const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4875   for (const auto *I : fields()) {
4876     if (I->getIdentifier())
4877       return I;
4878 
4879     if (const auto *RT = I->getType()->getAs<RecordType>())
4880       if (const FieldDecl *NamedDataMember =
4881               RT->getDecl()->findFirstNamedDataMember())
4882         return NamedDataMember;
4883   }
4884 
4885   // We didn't find a named data member.
4886   return nullptr;
4887 }
4888 
getODRHash()4889 unsigned RecordDecl::getODRHash() {
4890   if (hasODRHash())
4891     return RecordDeclBits.ODRHash;
4892 
4893   // Only calculate hash on first call of getODRHash per record.
4894   ODRHash Hash;
4895   Hash.AddRecordDecl(this);
4896   // For RecordDecl the ODRHash is stored in the remaining 26
4897   // bit of RecordDeclBits, adjust the hash to accomodate.
4898   setODRHash(Hash.CalculateHash() >> 6);
4899   return RecordDeclBits.ODRHash;
4900 }
4901 
4902 //===----------------------------------------------------------------------===//
4903 // BlockDecl Implementation
4904 //===----------------------------------------------------------------------===//
4905 
BlockDecl(DeclContext * DC,SourceLocation CaretLoc)4906 BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4907     : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4908   setIsVariadic(false);
4909   setCapturesCXXThis(false);
4910   setBlockMissingReturnType(true);
4911   setIsConversionFromLambda(false);
4912   setDoesNotEscape(false);
4913   setCanAvoidCopyToHeap(false);
4914 }
4915 
setParams(ArrayRef<ParmVarDecl * > NewParamInfo)4916 void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4917   assert(!ParamInfo && "Already has param info!");
4918 
4919   // Zero params -> null pointer.
4920   if (!NewParamInfo.empty()) {
4921     NumParams = NewParamInfo.size();
4922     ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4923     std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4924   }
4925 }
4926 
setCaptures(ASTContext & Context,ArrayRef<Capture> Captures,bool CapturesCXXThis)4927 void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4928                             bool CapturesCXXThis) {
4929   this->setCapturesCXXThis(CapturesCXXThis);
4930   this->NumCaptures = Captures.size();
4931 
4932   if (Captures.empty()) {
4933     this->Captures = nullptr;
4934     return;
4935   }
4936 
4937   this->Captures = Captures.copy(Context).data();
4938 }
4939 
capturesVariable(const VarDecl * variable) const4940 bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4941   for (const auto &I : captures())
4942     // Only auto vars can be captured, so no redeclaration worries.
4943     if (I.getVariable() == variable)
4944       return true;
4945 
4946   return false;
4947 }
4948 
getSourceRange() const4949 SourceRange BlockDecl::getSourceRange() const {
4950   return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4951 }
4952 
4953 //===----------------------------------------------------------------------===//
4954 // Other Decl Allocation/Deallocation Method Implementations
4955 //===----------------------------------------------------------------------===//
4956 
anchor()4957 void TranslationUnitDecl::anchor() {}
4958 
Create(ASTContext & C)4959 TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4960   return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4961 }
4962 
anchor()4963 void PragmaCommentDecl::anchor() {}
4964 
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation CommentLoc,PragmaMSCommentKind CommentKind,StringRef Arg)4965 PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4966                                              TranslationUnitDecl *DC,
4967                                              SourceLocation CommentLoc,
4968                                              PragmaMSCommentKind CommentKind,
4969                                              StringRef Arg) {
4970   PragmaCommentDecl *PCD =
4971       new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4972           PragmaCommentDecl(DC, CommentLoc, CommentKind);
4973   memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4974   PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4975   return PCD;
4976 }
4977 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned ArgSize)4978 PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4979                                                          unsigned ID,
4980                                                          unsigned ArgSize) {
4981   return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4982       PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4983 }
4984 
anchor()4985 void PragmaDetectMismatchDecl::anchor() {}
4986 
4987 PragmaDetectMismatchDecl *
Create(const ASTContext & C,TranslationUnitDecl * DC,SourceLocation Loc,StringRef Name,StringRef Value)4988 PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4989                                  SourceLocation Loc, StringRef Name,
4990                                  StringRef Value) {
4991   size_t ValueStart = Name.size() + 1;
4992   PragmaDetectMismatchDecl *PDMD =
4993       new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4994           PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4995   memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4996   PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4997   memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4998          Value.size());
4999   PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
5000   return PDMD;
5001 }
5002 
5003 PragmaDetectMismatchDecl *
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NameValueSize)5004 PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5005                                              unsigned NameValueSize) {
5006   return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
5007       PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
5008 }
5009 
anchor()5010 void ExternCContextDecl::anchor() {}
5011 
Create(const ASTContext & C,TranslationUnitDecl * DC)5012 ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
5013                                                TranslationUnitDecl *DC) {
5014   return new (C, DC) ExternCContextDecl(DC);
5015 }
5016 
anchor()5017 void LabelDecl::anchor() {}
5018 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II)5019 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5020                              SourceLocation IdentL, IdentifierInfo *II) {
5021   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
5022 }
5023 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdentL,IdentifierInfo * II,SourceLocation GnuLabelL)5024 LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
5025                              SourceLocation IdentL, IdentifierInfo *II,
5026                              SourceLocation GnuLabelL) {
5027   assert(GnuLabelL != IdentL && "Use this only for GNU local labels");
5028   return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
5029 }
5030 
CreateDeserialized(ASTContext & C,unsigned ID)5031 LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5032   return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
5033                                SourceLocation());
5034 }
5035 
setMSAsmLabel(StringRef Name)5036 void LabelDecl::setMSAsmLabel(StringRef Name) {
5037 char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
5038   memcpy(Buffer, Name.data(), Name.size());
5039   Buffer[Name.size()] = '\0';
5040   MSAsmName = Buffer;
5041 }
5042 
anchor()5043 void ValueDecl::anchor() {}
5044 
isWeak() const5045 bool ValueDecl::isWeak() const {
5046   auto *MostRecent = getMostRecentDecl();
5047   return MostRecent->hasAttr<WeakAttr>() ||
5048          MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
5049 }
5050 
isInitCapture() const5051 bool ValueDecl::isInitCapture() const {
5052   if (auto *Var = llvm::dyn_cast<VarDecl>(this))
5053     return Var->isInitCapture();
5054   return false;
5055 }
5056 
anchor()5057 void ImplicitParamDecl::anchor() {}
5058 
Create(ASTContext & C,DeclContext * DC,SourceLocation IdLoc,IdentifierInfo * Id,QualType Type,ImplicitParamKind ParamKind)5059 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
5060                                              SourceLocation IdLoc,
5061                                              IdentifierInfo *Id, QualType Type,
5062                                              ImplicitParamKind ParamKind) {
5063   return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
5064 }
5065 
Create(ASTContext & C,QualType Type,ImplicitParamKind ParamKind)5066 ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
5067                                              ImplicitParamKind ParamKind) {
5068   return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
5069 }
5070 
CreateDeserialized(ASTContext & C,unsigned ID)5071 ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
5072                                                          unsigned ID) {
5073   return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
5074 }
5075 
5076 FunctionDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,const DeclarationNameInfo & NameInfo,QualType T,TypeSourceInfo * TInfo,StorageClass SC,bool UsesFPIntrin,bool isInlineSpecified,bool hasWrittenPrototype,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)5077 FunctionDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
5078                      const DeclarationNameInfo &NameInfo, QualType T,
5079                      TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin,
5080                      bool isInlineSpecified, bool hasWrittenPrototype,
5081                      ConstexprSpecKind ConstexprKind,
5082                      Expr *TrailingRequiresClause) {
5083   FunctionDecl *New = new (C, DC) FunctionDecl(
5084       Function, C, DC, StartLoc, NameInfo, T, TInfo, SC, UsesFPIntrin,
5085       isInlineSpecified, ConstexprKind, TrailingRequiresClause);
5086   New->setHasWrittenPrototype(hasWrittenPrototype);
5087   return New;
5088 }
5089 
CreateDeserialized(ASTContext & C,unsigned ID)5090 FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5091   return new (C, ID) FunctionDecl(
5092       Function, C, nullptr, SourceLocation(), DeclarationNameInfo(), QualType(),
5093       nullptr, SC_None, false, false, ConstexprSpecKind::Unspecified, nullptr);
5094 }
5095 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)5096 BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5097   return new (C, DC) BlockDecl(DC, L);
5098 }
5099 
CreateDeserialized(ASTContext & C,unsigned ID)5100 BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5101   return new (C, ID) BlockDecl(nullptr, SourceLocation());
5102 }
5103 
CapturedDecl(DeclContext * DC,unsigned NumParams)5104 CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
5105     : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
5106       NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
5107 
Create(ASTContext & C,DeclContext * DC,unsigned NumParams)5108 CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
5109                                    unsigned NumParams) {
5110   return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5111       CapturedDecl(DC, NumParams);
5112 }
5113 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumParams)5114 CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5115                                                unsigned NumParams) {
5116   return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
5117       CapturedDecl(nullptr, NumParams);
5118 }
5119 
getBody() const5120 Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
setBody(Stmt * B)5121 void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
5122 
isNothrow() const5123 bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
setNothrow(bool Nothrow)5124 void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
5125 
Create(ASTContext & C,EnumDecl * CD,SourceLocation L,IdentifierInfo * Id,QualType T,Expr * E,const llvm::APSInt & V)5126 EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
5127                                            SourceLocation L,
5128                                            IdentifierInfo *Id, QualType T,
5129                                            Expr *E, const llvm::APSInt &V) {
5130   return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
5131 }
5132 
5133 EnumConstantDecl *
CreateDeserialized(ASTContext & C,unsigned ID)5134 EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5135   return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
5136                                       QualType(), nullptr, llvm::APSInt());
5137 }
5138 
anchor()5139 void IndirectFieldDecl::anchor() {}
5140 
IndirectFieldDecl(ASTContext & C,DeclContext * DC,SourceLocation L,DeclarationName N,QualType T,MutableArrayRef<NamedDecl * > CH)5141 IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
5142                                      SourceLocation L, DeclarationName N,
5143                                      QualType T,
5144                                      MutableArrayRef<NamedDecl *> CH)
5145     : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
5146       ChainingSize(CH.size()) {
5147   // In C++, indirect field declarations conflict with tag declarations in the
5148   // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
5149   if (C.getLangOpts().CPlusPlus)
5150     IdentifierNamespace |= IDNS_Tag;
5151 }
5152 
5153 IndirectFieldDecl *
Create(ASTContext & C,DeclContext * DC,SourceLocation L,IdentifierInfo * Id,QualType T,llvm::MutableArrayRef<NamedDecl * > CH)5154 IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
5155                           IdentifierInfo *Id, QualType T,
5156                           llvm::MutableArrayRef<NamedDecl *> CH) {
5157   return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
5158 }
5159 
CreateDeserialized(ASTContext & C,unsigned ID)5160 IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
5161                                                          unsigned ID) {
5162   return new (C, ID)
5163       IndirectFieldDecl(C, nullptr, SourceLocation(), DeclarationName(),
5164                         QualType(), std::nullopt);
5165 }
5166 
getSourceRange() const5167 SourceRange EnumConstantDecl::getSourceRange() const {
5168   SourceLocation End = getLocation();
5169   if (Init)
5170     End = Init->getEndLoc();
5171   return SourceRange(getLocation(), End);
5172 }
5173 
anchor()5174 void TypeDecl::anchor() {}
5175 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)5176 TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
5177                                  SourceLocation StartLoc, SourceLocation IdLoc,
5178                                  IdentifierInfo *Id, TypeSourceInfo *TInfo) {
5179   return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5180 }
5181 
anchor()5182 void TypedefNameDecl::anchor() {}
5183 
getAnonDeclWithTypedefName(bool AnyRedecl) const5184 TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
5185   if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
5186     auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
5187     auto *ThisTypedef = this;
5188     if (AnyRedecl && OwningTypedef) {
5189       OwningTypedef = OwningTypedef->getCanonicalDecl();
5190       ThisTypedef = ThisTypedef->getCanonicalDecl();
5191     }
5192     if (OwningTypedef == ThisTypedef)
5193       return TT->getDecl();
5194   }
5195 
5196   return nullptr;
5197 }
5198 
isTransparentTagSlow() const5199 bool TypedefNameDecl::isTransparentTagSlow() const {
5200   auto determineIsTransparent = [&]() {
5201     if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
5202       if (auto *TD = TT->getDecl()) {
5203         if (TD->getName() != getName())
5204           return false;
5205         SourceLocation TTLoc = getLocation();
5206         SourceLocation TDLoc = TD->getLocation();
5207         if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
5208           return false;
5209         SourceManager &SM = getASTContext().getSourceManager();
5210         return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
5211       }
5212     }
5213     return false;
5214   };
5215 
5216   bool isTransparent = determineIsTransparent();
5217   MaybeModedTInfo.setInt((isTransparent << 1) | 1);
5218   return isTransparent;
5219 }
5220 
CreateDeserialized(ASTContext & C,unsigned ID)5221 TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5222   return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
5223                                  nullptr, nullptr);
5224 }
5225 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,TypeSourceInfo * TInfo)5226 TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
5227                                      SourceLocation StartLoc,
5228                                      SourceLocation IdLoc, IdentifierInfo *Id,
5229                                      TypeSourceInfo *TInfo) {
5230   return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
5231 }
5232 
CreateDeserialized(ASTContext & C,unsigned ID)5233 TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5234   return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
5235                                    SourceLocation(), nullptr, nullptr);
5236 }
5237 
getSourceRange() const5238 SourceRange TypedefDecl::getSourceRange() const {
5239   SourceLocation RangeEnd = getLocation();
5240   if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
5241     if (typeIsPostfix(TInfo->getType()))
5242       RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5243   }
5244   return SourceRange(getBeginLoc(), RangeEnd);
5245 }
5246 
getSourceRange() const5247 SourceRange TypeAliasDecl::getSourceRange() const {
5248   SourceLocation RangeEnd = getBeginLoc();
5249   if (TypeSourceInfo *TInfo = getTypeSourceInfo())
5250     RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
5251   return SourceRange(getBeginLoc(), RangeEnd);
5252 }
5253 
anchor()5254 void FileScopeAsmDecl::anchor() {}
5255 
Create(ASTContext & C,DeclContext * DC,StringLiteral * Str,SourceLocation AsmLoc,SourceLocation RParenLoc)5256 FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
5257                                            StringLiteral *Str,
5258                                            SourceLocation AsmLoc,
5259                                            SourceLocation RParenLoc) {
5260   return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
5261 }
5262 
CreateDeserialized(ASTContext & C,unsigned ID)5263 FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
5264                                                        unsigned ID) {
5265   return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
5266                                       SourceLocation());
5267 }
5268 
anchor()5269 void TopLevelStmtDecl::anchor() {}
5270 
Create(ASTContext & C,Stmt * Statement)5271 TopLevelStmtDecl *TopLevelStmtDecl::Create(ASTContext &C, Stmt *Statement) {
5272   assert(Statement);
5273   assert(C.getLangOpts().IncrementalExtensions &&
5274          "Must be used only in incremental mode");
5275 
5276   SourceLocation BeginLoc = Statement->getBeginLoc();
5277   DeclContext *DC = C.getTranslationUnitDecl();
5278 
5279   return new (C, DC) TopLevelStmtDecl(DC, BeginLoc, Statement);
5280 }
5281 
CreateDeserialized(ASTContext & C,unsigned ID)5282 TopLevelStmtDecl *TopLevelStmtDecl::CreateDeserialized(ASTContext &C,
5283                                                        unsigned ID) {
5284   return new (C, ID)
5285       TopLevelStmtDecl(/*DC=*/nullptr, SourceLocation(), /*S=*/nullptr);
5286 }
5287 
getSourceRange() const5288 SourceRange TopLevelStmtDecl::getSourceRange() const {
5289   return SourceRange(getLocation(), Statement->getEndLoc());
5290 }
5291 
anchor()5292 void EmptyDecl::anchor() {}
5293 
Create(ASTContext & C,DeclContext * DC,SourceLocation L)5294 EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
5295   return new (C, DC) EmptyDecl(DC, L);
5296 }
5297 
CreateDeserialized(ASTContext & C,unsigned ID)5298 EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5299   return new (C, ID) EmptyDecl(nullptr, SourceLocation());
5300 }
5301 
HLSLBufferDecl(DeclContext * DC,bool CBuffer,SourceLocation KwLoc,IdentifierInfo * ID,SourceLocation IDLoc,SourceLocation LBrace)5302 HLSLBufferDecl::HLSLBufferDecl(DeclContext *DC, bool CBuffer,
5303                                SourceLocation KwLoc, IdentifierInfo *ID,
5304                                SourceLocation IDLoc, SourceLocation LBrace)
5305     : NamedDecl(Decl::Kind::HLSLBuffer, DC, IDLoc, DeclarationName(ID)),
5306       DeclContext(Decl::Kind::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
5307       IsCBuffer(CBuffer) {}
5308 
Create(ASTContext & C,DeclContext * LexicalParent,bool CBuffer,SourceLocation KwLoc,IdentifierInfo * ID,SourceLocation IDLoc,SourceLocation LBrace)5309 HLSLBufferDecl *HLSLBufferDecl::Create(ASTContext &C,
5310                                        DeclContext *LexicalParent, bool CBuffer,
5311                                        SourceLocation KwLoc, IdentifierInfo *ID,
5312                                        SourceLocation IDLoc,
5313                                        SourceLocation LBrace) {
5314   // For hlsl like this
5315   // cbuffer A {
5316   //     cbuffer B {
5317   //     }
5318   // }
5319   // compiler should treat it as
5320   // cbuffer A {
5321   // }
5322   // cbuffer B {
5323   // }
5324   // FIXME: support nested buffers if required for back-compat.
5325   DeclContext *DC = LexicalParent;
5326   HLSLBufferDecl *Result =
5327       new (C, DC) HLSLBufferDecl(DC, CBuffer, KwLoc, ID, IDLoc, LBrace);
5328   return Result;
5329 }
5330 
CreateDeserialized(ASTContext & C,unsigned ID)5331 HLSLBufferDecl *HLSLBufferDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5332   return new (C, ID) HLSLBufferDecl(nullptr, false, SourceLocation(), nullptr,
5333                                     SourceLocation(), SourceLocation());
5334 }
5335 
5336 //===----------------------------------------------------------------------===//
5337 // ImportDecl Implementation
5338 //===----------------------------------------------------------------------===//
5339 
5340 /// Retrieve the number of module identifiers needed to name the given
5341 /// module.
getNumModuleIdentifiers(Module * Mod)5342 static unsigned getNumModuleIdentifiers(Module *Mod) {
5343   unsigned Result = 1;
5344   while (Mod->Parent) {
5345     Mod = Mod->Parent;
5346     ++Result;
5347   }
5348   return Result;
5349 }
5350 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5351 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5352                        Module *Imported,
5353                        ArrayRef<SourceLocation> IdentifierLocs)
5354     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5355       NextLocalImportAndComplete(nullptr, true) {
5356   assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size());
5357   auto *StoredLocs = getTrailingObjects<SourceLocation>();
5358   std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
5359                           StoredLocs);
5360 }
5361 
ImportDecl(DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5362 ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
5363                        Module *Imported, SourceLocation EndLoc)
5364     : Decl(Import, DC, StartLoc), ImportedModule(Imported),
5365       NextLocalImportAndComplete(nullptr, false) {
5366   *getTrailingObjects<SourceLocation>() = EndLoc;
5367 }
5368 
Create(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,ArrayRef<SourceLocation> IdentifierLocs)5369 ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
5370                                SourceLocation StartLoc, Module *Imported,
5371                                ArrayRef<SourceLocation> IdentifierLocs) {
5372   return new (C, DC,
5373               additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
5374       ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
5375 }
5376 
CreateImplicit(ASTContext & C,DeclContext * DC,SourceLocation StartLoc,Module * Imported,SourceLocation EndLoc)5377 ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
5378                                        SourceLocation StartLoc,
5379                                        Module *Imported,
5380                                        SourceLocation EndLoc) {
5381   ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
5382       ImportDecl(DC, StartLoc, Imported, EndLoc);
5383   Import->setImplicit();
5384   return Import;
5385 }
5386 
CreateDeserialized(ASTContext & C,unsigned ID,unsigned NumLocations)5387 ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
5388                                            unsigned NumLocations) {
5389   return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
5390       ImportDecl(EmptyShell());
5391 }
5392 
getIdentifierLocs() const5393 ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
5394   if (!isImportComplete())
5395     return std::nullopt;
5396 
5397   const auto *StoredLocs = getTrailingObjects<SourceLocation>();
5398   return llvm::ArrayRef(StoredLocs,
5399                         getNumModuleIdentifiers(getImportedModule()));
5400 }
5401 
getSourceRange() const5402 SourceRange ImportDecl::getSourceRange() const {
5403   if (!isImportComplete())
5404     return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5405 
5406   return SourceRange(getLocation(), getIdentifierLocs().back());
5407 }
5408 
5409 //===----------------------------------------------------------------------===//
5410 // ExportDecl Implementation
5411 //===----------------------------------------------------------------------===//
5412 
anchor()5413 void ExportDecl::anchor() {}
5414 
Create(ASTContext & C,DeclContext * DC,SourceLocation ExportLoc)5415 ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5416                                SourceLocation ExportLoc) {
5417   return new (C, DC) ExportDecl(DC, ExportLoc);
5418 }
5419 
CreateDeserialized(ASTContext & C,unsigned ID)5420 ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5421   return new (C, ID) ExportDecl(nullptr, SourceLocation());
5422 }
5423