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