Bug Summary

File:clang/lib/AST/Decl.cpp
Warning:line 3769, column 5
Storage provided to placement new is only 0 bytes, whereas the allocated type requires 32 bytes

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Decl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -fno-split-dwarf-inlining -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-12/lib/clang/12.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/include -I /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-12/lib/clang/12.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2020-10-27-053609-25509-1 -x c++ /build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp

/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp

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
74using namespace clang;
75
76Decl *clang::getPrimaryMergedDecl(Decl *D) {
77 return D->getASTContext().getPrimaryMergedDecl(D);
78}
79
80void 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.
99bool Decl::isOutOfLine() const {
100 return !getLexicalDeclContext()->Equals(getDeclContext());
101}
102
103TranslationUnitDecl::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?
159static 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.
165static LVComputationKind
166withExplicitVisibilityAlready(LVComputationKind Kind) {
167 Kind.IgnoreExplicitVisibility = true;
168 return Kind;
169}
170
171static Optional<Visibility> getExplicitVisibility(const NamedDecl *D,
172 LVComputationKind kind) {
173 assert(!kind.IgnoreExplicitVisibility &&((!kind.IgnoreExplicitVisibility && "asking for explicit visibility when we shouldn't be"
) ? static_cast<void> (0) : __assert_fail ("!kind.IgnoreExplicitVisibility && \"asking for explicit visibility when we shouldn't be\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 174, __PRETTY_FUNCTION__))
174 "asking for explicit visibility when we shouldn't be")((!kind.IgnoreExplicitVisibility && "asking for explicit visibility when we shouldn't be"
) ? static_cast<void> (0) : __assert_fail ("!kind.IgnoreExplicitVisibility && \"asking for explicit visibility when we shouldn't be\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 174, __PRETTY_FUNCTION__))
;
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?
180static 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?
188template <class T> static typename
189std::enable_if<!std::is_base_of<RedeclarableTemplateDecl, T>::value, bool>::type
190isExplicitMemberSpecialization(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.
201static bool isExplicitMemberSpecialization(const RedeclarableTemplateDecl *D) {
202 return D->isMemberSpecialization();
203}
204
205/// Given a visibility attribute, return the explicit visibility
206/// associated with it.
207template <class T>
208static 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")::llvm::llvm_unreachable_internal("bad visibility kind", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 217)
;
218}
219
220/// Return the explicit visibility of the given declaration.
221static 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
239LinkageInfo 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.
249LinkageInfo 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
302static 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.
318LinkageInfo
319LinkageComputer::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))((!usesTypeVisibility(ND)) ? static_cast<void> (0) : __assert_fail
("!usesTypeVisibility(ND)", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 336, __PRETTY_FUNCTION__))
;
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")::llvm::llvm_unreachable_internal("bad template argument kind"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 356)
;
357 }
358
359 return LV;
360}
361
362LinkageInfo
363LinkageComputer::getLVForTemplateArgumentList(const TemplateArgumentList &TArgs,
364 LVComputationKind computation) {
365 return getLVForTemplateArgumentList(TArgs.asArray(), computation);
366}
367
368static 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
387void 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?
408static 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?
419static 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.
455void 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.
483static 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.
507void 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
531static 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
559template <typename T> static bool isFirstInExternCContext(T *D) {
560 const T *First = D->getFirstDecl();
561 return First->isInExternCContext();
562}
563
564static 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.
572static bool isInModulePurview(const NamedDecl *D) {
573 if (auto *M = D->getOwningModule())
574 return M->isModulePurview();
575 return false;
576}
577
578static 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")::llvm::llvm_unreachable_internal("unexpected module ownership kind"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 588)
;
589}
590
591static 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
602static 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
614static 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
626LinkageInfo
627LinkageComputer::getLVForNamespaceScopeDecl(const NamedDecl *D,
628 LVComputationKind computation,
629 bool IgnoreVarTypeLinkage) {
630 assert(D->getDeclContext()->getRedeclContext()->isFileContext() &&((D->getDeclContext()->getRedeclContext()->isFileContext
() && "Not a name having namespace scope") ? static_cast
<void> (0) : __assert_fail ("D->getDeclContext()->getRedeclContext()->isFileContext() && \"Not a name having namespace scope\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 631, __PRETTY_FUNCTION__))
631 "Not a name having namespace scope")((D->getDeclContext()->getRedeclContext()->isFileContext
() && "Not a name having namespace scope") ? static_cast
<void> (0) : __assert_fail ("D->getDeclContext()->getRedeclContext()->isFileContext() && \"Not a name having namespace scope\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 631, __PRETTY_FUNCTION__))
;
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!")((VD && "Expected a VarDecl in this IndirectFieldDecl!"
) ? static_cast<void> (0) : __assert_fail ("VD && \"Expected a VarDecl in this IndirectFieldDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 681, __PRETTY_FUNCTION__))
;
682 return getLVForNamespaceScopeDecl(VD, computation, IgnoreVarTypeLinkage);
683 }
684 assert(!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!")((!isa<FieldDecl>(D) && "Didn't expect a FieldDecl!"
) ? static_cast<void> (0) : __assert_fail ("!isa<FieldDecl>(D) && \"Didn't expect a FieldDecl!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 684, __PRETTY_FUNCTION__))
;
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
916LinkageInfo
917LinkageComputer::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))((!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor
)) ? static_cast<void> (0) : __assert_fail ("!explicitSpecSuppressor || !isa<TemplateDecl>(explicitSpecSuppressor)"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1051, __PRETTY_FUNCTION__))
;
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
1069void NamedDecl::anchor() {}
1070
1071bool 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
1081ObjCStringFormatFamily 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
1094Linkage 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
1102LinkageInfo NamedDecl::getLinkageAndVisibility() const {
1103 return LinkageComputer{}.getDeclLinkageAndVisibility(this);
1104}
1105
1106static Optional<Visibility>
1107getExplicitVisibilityAux(const NamedDecl *ND,
1108 NamedDecl::ExplicitVisibilityKind kind,
1109 bool IsMostRecent) {
1110 assert(!IsMostRecent || ND == ND->getMostRecentDecl())((!IsMostRecent || ND == ND->getMostRecentDecl()) ? static_cast
<void> (0) : __assert_fail ("!IsMostRecent || ND == ND->getMostRecentDecl()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1110, __PRETTY_FUNCTION__))
;
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
1185Optional<Visibility>
1186NamedDecl::getExplicitVisibility(ExplicitVisibilityKind kind) const {
1187 return getExplicitVisibilityAux(this, kind, false);
1188}
1189
1190LinkageInfo 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
1224LinkageInfo 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())((cast<VarDecl>(D)->isStaticLocal()) ? static_cast<
void> (0) : __assert_fail ("cast<VarDecl>(D)->isStaticLocal()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1304, __PRETTY_FUNCTION__))
;
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
1326LinkageInfo 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
1400 // Handle linkage for namespace-scope names.
1401 if (D->getDeclContext()->getRedeclContext()->isFileContext())
1402 return getLVForNamespaceScopeDecl(D, computation, IgnoreVarTypeLinkage);
1403
1404 // C++ [basic.link]p5:
1405 // In addition, a member function, static data member, a named
1406 // class or enumeration of class scope, or an unnamed class or
1407 // enumeration defined in a class-scope typedef declaration such
1408 // that the class or enumeration has the typedef name for linkage
1409 // purposes (7.1.3), has external linkage if the name of the class
1410 // has external linkage.
1411 if (D->getDeclContext()->isRecord())
1412 return getLVForClassMember(D, computation, IgnoreVarTypeLinkage);
1413
1414 // C++ [basic.link]p6:
1415 // The name of a function declared in block scope and the name of
1416 // an object declared by a block scope extern declaration have
1417 // linkage. If there is a visible declaration of an entity with
1418 // linkage having the same name and type, ignoring entities
1419 // declared outside the innermost enclosing namespace scope, the
1420 // block scope declaration declares that same entity and receives
1421 // the linkage of the previous declaration. If there is more than
1422 // one such matching entity, the program is ill-formed. Otherwise,
1423 // if no matching entity is found, the block scope entity receives
1424 // external linkage.
1425 if (D->getDeclContext()->isFunctionOrMethod())
1426 return getLVForLocalDecl(D, computation);
1427
1428 // C++ [basic.link]p6:
1429 // Names not covered by these rules have no linkage.
1430 return LinkageInfo::none();
1431}
1432
1433/// getLVForDecl - Get the linkage and visibility for the given declaration.
1434LinkageInfo LinkageComputer::getLVForDecl(const NamedDecl *D,
1435 LVComputationKind computation) {
1436 // Internal_linkage attribute overrides other considerations.
1437 if (D->hasAttr<InternalLinkageAttr>())
1438 return getInternalLinkageFor(D);
1439
1440 if (computation.IgnoreAllVisibility && D->hasCachedLinkage())
1441 return LinkageInfo(D->getCachedLinkage(), DefaultVisibility, false);
1442
1443 if (llvm::Optional<LinkageInfo> LI = lookup(D, computation))
1444 return *LI;
1445
1446 LinkageInfo LV = computeLVForDecl(D, computation);
1447 if (D->hasCachedLinkage())
1448 assert(D->getCachedLinkage() == LV.getLinkage())((D->getCachedLinkage() == LV.getLinkage()) ? static_cast<
void> (0) : __assert_fail ("D->getCachedLinkage() == LV.getLinkage()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1448, __PRETTY_FUNCTION__))
;
1449
1450 D->setCachedLinkage(LV.getLinkage());
1451 cache(D, computation, LV);
1452
1453#ifndef NDEBUG
1454 // In C (because of gnu inline) and in c++ with microsoft extensions an
1455 // static can follow an extern, so we can have two decls with different
1456 // linkages.
1457 const LangOptions &Opts = D->getASTContext().getLangOpts();
1458 if (!Opts.CPlusPlus || Opts.MicrosoftExt)
1459 return LV;
1460
1461 // We have just computed the linkage for this decl. By induction we know
1462 // that all other computed linkages match, check that the one we just
1463 // computed also does.
1464 NamedDecl *Old = nullptr;
1465 for (auto I : D->redecls()) {
1466 auto *T = cast<NamedDecl>(I);
1467 if (T == D)
1468 continue;
1469 if (!T->isInvalidDecl() && T->hasCachedLinkage()) {
1470 Old = T;
1471 break;
1472 }
1473 }
1474 assert(!Old || Old->getCachedLinkage() == D->getCachedLinkage())((!Old || Old->getCachedLinkage() == D->getCachedLinkage
()) ? static_cast<void> (0) : __assert_fail ("!Old || Old->getCachedLinkage() == D->getCachedLinkage()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1474, __PRETTY_FUNCTION__))
;
1475#endif
1476
1477 return LV;
1478}
1479
1480LinkageInfo LinkageComputer::getDeclLinkageAndVisibility(const NamedDecl *D) {
1481 return getLVForDecl(D,
1482 LVComputationKind(usesTypeVisibility(D)
1483 ? NamedDecl::VisibilityForType
1484 : NamedDecl::VisibilityForValue));
1485}
1486
1487Module *Decl::getOwningModuleForLinkage(bool IgnoreLinkage) const {
1488 Module *M = getOwningModule();
1489 if (!M)
1490 return nullptr;
1491
1492 switch (M->Kind) {
1493 case Module::ModuleMapModule:
1494 // Module map modules have no special linkage semantics.
1495 return nullptr;
1496
1497 case Module::ModuleInterfaceUnit:
1498 return M;
1499
1500 case Module::GlobalModuleFragment: {
1501 // External linkage declarations in the global module have no owning module
1502 // for linkage purposes. But internal linkage declarations in the global
1503 // module fragment of a particular module are owned by that module for
1504 // linkage purposes.
1505 if (IgnoreLinkage)
1506 return nullptr;
1507 bool InternalLinkage;
1508 if (auto *ND = dyn_cast<NamedDecl>(this))
1509 InternalLinkage = !ND->hasExternalFormalLinkage();
1510 else {
1511 auto *NSD = dyn_cast<NamespaceDecl>(this);
1512 InternalLinkage = (NSD && NSD->isAnonymousNamespace()) ||
1513 isInAnonymousNamespace();
1514 }
1515 return InternalLinkage ? M->Parent : nullptr;
1516 }
1517
1518 case Module::PrivateModuleFragment:
1519 // The private module fragment is part of its containing module for linkage
1520 // purposes.
1521 return M->Parent;
1522 }
1523
1524 llvm_unreachable("unknown module kind")::llvm::llvm_unreachable_internal("unknown module kind", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1524)
;
1525}
1526
1527void NamedDecl::printName(raw_ostream &os) const {
1528 os << Name;
1529}
1530
1531std::string NamedDecl::getQualifiedNameAsString() const {
1532 std::string QualName;
1533 llvm::raw_string_ostream OS(QualName);
1534 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1535 return OS.str();
1536}
1537
1538void NamedDecl::printQualifiedName(raw_ostream &OS) const {
1539 printQualifiedName(OS, getASTContext().getPrintingPolicy());
1540}
1541
1542void NamedDecl::printQualifiedName(raw_ostream &OS,
1543 const PrintingPolicy &P) const {
1544 if (getDeclContext()->isFunctionOrMethod()) {
1545 // We do not print '(anonymous)' for function parameters without name.
1546 printName(OS);
1547 return;
1548 }
1549 printNestedNameSpecifier(OS, P);
1550 if (getDeclName())
1551 OS << *this;
1552 else {
1553 // Give the printName override a chance to pick a different name before we
1554 // fall back to "(anonymous)".
1555 SmallString<64> NameBuffer;
1556 llvm::raw_svector_ostream NameOS(NameBuffer);
1557 printName(NameOS);
1558 if (NameBuffer.empty())
1559 OS << "(anonymous)";
1560 else
1561 OS << NameBuffer;
1562 }
1563}
1564
1565void NamedDecl::printNestedNameSpecifier(raw_ostream &OS) const {
1566 printNestedNameSpecifier(OS, getASTContext().getPrintingPolicy());
1567}
1568
1569void NamedDecl::printNestedNameSpecifier(raw_ostream &OS,
1570 const PrintingPolicy &P) const {
1571 const DeclContext *Ctx = getDeclContext();
1572
1573 // For ObjC methods and properties, look through categories and use the
1574 // interface as context.
1575 if (auto *MD = dyn_cast<ObjCMethodDecl>(this)) {
1576 if (auto *ID = MD->getClassInterface())
1577 Ctx = ID;
1578 } else if (auto *PD = dyn_cast<ObjCPropertyDecl>(this)) {
1579 if (auto *MD = PD->getGetterMethodDecl())
1580 if (auto *ID = MD->getClassInterface())
1581 Ctx = ID;
1582 } else if (auto *ID = dyn_cast<ObjCIvarDecl>(this)) {
1583 if (auto *CI = ID->getContainingInterface())
1584 Ctx = CI;
1585 }
1586
1587 if (Ctx->isFunctionOrMethod())
1588 return;
1589
1590 using ContextsTy = SmallVector<const DeclContext *, 8>;
1591 ContextsTy Contexts;
1592
1593 // Collect named contexts.
1594 while (Ctx) {
1595 if (isa<NamedDecl>(Ctx))
1596 Contexts.push_back(Ctx);
1597 Ctx = Ctx->getParent();
1598 }
1599
1600 for (const DeclContext *DC : llvm::reverse(Contexts)) {
1601 if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(DC)) {
1602 OS << Spec->getName();
1603 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
1604 printTemplateArgumentList(OS, TemplateArgs.asArray(), P);
1605 } else if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
1606 if (P.SuppressUnwrittenScope &&
1607 (ND->isAnonymousNamespace() || ND->isInline()))
1608 continue;
1609 if (ND->isAnonymousNamespace()) {
1610 OS << (P.MSVCFormatting ? "`anonymous namespace\'"
1611 : "(anonymous namespace)");
1612 }
1613 else
1614 OS << *ND;
1615 } else if (const auto *RD = dyn_cast<RecordDecl>(DC)) {
1616 if (!RD->getIdentifier())
1617 OS << "(anonymous " << RD->getKindName() << ')';
1618 else
1619 OS << *RD;
1620 } else if (const auto *FD = dyn_cast<FunctionDecl>(DC)) {
1621 const FunctionProtoType *FT = nullptr;
1622 if (FD->hasWrittenPrototype())
1623 FT = dyn_cast<FunctionProtoType>(FD->getType()->castAs<FunctionType>());
1624
1625 OS << *FD << '(';
1626 if (FT) {
1627 unsigned NumParams = FD->getNumParams();
1628 for (unsigned i = 0; i < NumParams; ++i) {
1629 if (i)
1630 OS << ", ";
1631 OS << FD->getParamDecl(i)->getType().stream(P);
1632 }
1633
1634 if (FT->isVariadic()) {
1635 if (NumParams > 0)
1636 OS << ", ";
1637 OS << "...";
1638 }
1639 }
1640 OS << ')';
1641 } else if (const auto *ED = dyn_cast<EnumDecl>(DC)) {
1642 // C++ [dcl.enum]p10: Each enum-name and each unscoped
1643 // enumerator is declared in the scope that immediately contains
1644 // the enum-specifier. Each scoped enumerator is declared in the
1645 // scope of the enumeration.
1646 // For the case of unscoped enumerator, do not include in the qualified
1647 // name any information about its enum enclosing scope, as its visibility
1648 // is global.
1649 if (ED->isScoped())
1650 OS << *ED;
1651 else
1652 continue;
1653 } else {
1654 OS << *cast<NamedDecl>(DC);
1655 }
1656 OS << "::";
1657 }
1658}
1659
1660void NamedDecl::getNameForDiagnostic(raw_ostream &OS,
1661 const PrintingPolicy &Policy,
1662 bool Qualified) const {
1663 if (Qualified)
1664 printQualifiedName(OS, Policy);
1665 else
1666 printName(OS);
1667}
1668
1669template<typename T> static bool isRedeclarableImpl(Redeclarable<T> *) {
1670 return true;
1671}
1672static bool isRedeclarableImpl(...) { return false; }
1673static bool isRedeclarable(Decl::Kind K) {
1674 switch (K) {
1675#define DECL(Type, Base) \
1676 case Decl::Type: \
1677 return isRedeclarableImpl((Type##Decl *)nullptr);
1678#define ABSTRACT_DECL(DECL)
1679#include "clang/AST/DeclNodes.inc"
1680 }
1681 llvm_unreachable("unknown decl kind")::llvm::llvm_unreachable_internal("unknown decl kind", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1681)
;
1682}
1683
1684bool NamedDecl::declarationReplaces(NamedDecl *OldD, bool IsKnownNewer) const {
1685 assert(getDeclName() == OldD->getDeclName() && "Declaration name mismatch")((getDeclName() == OldD->getDeclName() && "Declaration name mismatch"
) ? static_cast<void> (0) : __assert_fail ("getDeclName() == OldD->getDeclName() && \"Declaration name mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1685, __PRETTY_FUNCTION__))
;
1686
1687 // Never replace one imported declaration with another; we need both results
1688 // when re-exporting.
1689 if (OldD->isFromASTFile() && isFromASTFile())
1690 return false;
1691
1692 // A kind mismatch implies that the declaration is not replaced.
1693 if (OldD->getKind() != getKind())
1694 return false;
1695
1696 // For method declarations, we never replace. (Why?)
1697 if (isa<ObjCMethodDecl>(this))
1698 return false;
1699
1700 // For parameters, pick the newer one. This is either an error or (in
1701 // Objective-C) permitted as an extension.
1702 if (isa<ParmVarDecl>(this))
1703 return true;
1704
1705 // Inline namespaces can give us two declarations with the same
1706 // name and kind in the same scope but different contexts; we should
1707 // keep both declarations in this case.
1708 if (!this->getDeclContext()->getRedeclContext()->Equals(
1709 OldD->getDeclContext()->getRedeclContext()))
1710 return false;
1711
1712 // Using declarations can be replaced if they import the same name from the
1713 // same context.
1714 if (auto *UD = dyn_cast<UsingDecl>(this)) {
1715 ASTContext &Context = getASTContext();
1716 return Context.getCanonicalNestedNameSpecifier(UD->getQualifier()) ==
1717 Context.getCanonicalNestedNameSpecifier(
1718 cast<UsingDecl>(OldD)->getQualifier());
1719 }
1720 if (auto *UUVD = dyn_cast<UnresolvedUsingValueDecl>(this)) {
1721 ASTContext &Context = getASTContext();
1722 return Context.getCanonicalNestedNameSpecifier(UUVD->getQualifier()) ==
1723 Context.getCanonicalNestedNameSpecifier(
1724 cast<UnresolvedUsingValueDecl>(OldD)->getQualifier());
1725 }
1726
1727 if (isRedeclarable(getKind())) {
1728 if (getCanonicalDecl() != OldD->getCanonicalDecl())
1729 return false;
1730
1731 if (IsKnownNewer)
1732 return true;
1733
1734 // Check whether this is actually newer than OldD. We want to keep the
1735 // newer declaration. This loop will usually only iterate once, because
1736 // OldD is usually the previous declaration.
1737 for (auto D : redecls()) {
1738 if (D == OldD)
1739 break;
1740
1741 // If we reach the canonical declaration, then OldD is not actually older
1742 // than this one.
1743 //
1744 // FIXME: In this case, we should not add this decl to the lookup table.
1745 if (D->isCanonicalDecl())
1746 return false;
1747 }
1748
1749 // It's a newer declaration of the same kind of declaration in the same
1750 // scope: we want this decl instead of the existing one.
1751 return true;
1752 }
1753
1754 // In all other cases, we need to keep both declarations in case they have
1755 // different visibility. Any attempt to use the name will result in an
1756 // ambiguity if more than one is visible.
1757 return false;
1758}
1759
1760bool NamedDecl::hasLinkage() const {
1761 return getFormalLinkage() != NoLinkage;
1762}
1763
1764NamedDecl *NamedDecl::getUnderlyingDeclImpl() {
1765 NamedDecl *ND = this;
1766 while (auto *UD = dyn_cast<UsingShadowDecl>(ND))
1767 ND = UD->getTargetDecl();
1768
1769 if (auto *AD = dyn_cast<ObjCCompatibleAliasDecl>(ND))
1770 return AD->getClassInterface();
1771
1772 if (auto *AD = dyn_cast<NamespaceAliasDecl>(ND))
1773 return AD->getNamespace();
1774
1775 return ND;
1776}
1777
1778bool NamedDecl::isCXXInstanceMember() const {
1779 if (!isCXXClassMember())
1780 return false;
1781
1782 const NamedDecl *D = this;
1783 if (isa<UsingShadowDecl>(D))
1784 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1785
1786 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
1787 return true;
1788 if (const auto *MD = dyn_cast_or_null<CXXMethodDecl>(D->getAsFunction()))
1789 return MD->isInstance();
1790 return false;
1791}
1792
1793//===----------------------------------------------------------------------===//
1794// DeclaratorDecl Implementation
1795//===----------------------------------------------------------------------===//
1796
1797template <typename DeclT>
1798static SourceLocation getTemplateOrInnerLocStart(const DeclT *decl) {
1799 if (decl->getNumTemplateParameterLists() > 0)
1800 return decl->getTemplateParameterList(0)->getTemplateLoc();
1801 else
1802 return decl->getInnerLocStart();
1803}
1804
1805SourceLocation DeclaratorDecl::getTypeSpecStartLoc() const {
1806 TypeSourceInfo *TSI = getTypeSourceInfo();
1807 if (TSI) return TSI->getTypeLoc().getBeginLoc();
1808 return SourceLocation();
1809}
1810
1811SourceLocation DeclaratorDecl::getTypeSpecEndLoc() const {
1812 TypeSourceInfo *TSI = getTypeSourceInfo();
1813 if (TSI) return TSI->getTypeLoc().getEndLoc();
1814 return SourceLocation();
1815}
1816
1817void DeclaratorDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
1818 if (QualifierLoc) {
1819 // Make sure the extended decl info is allocated.
1820 if (!hasExtInfo()) {
1821 // Save (non-extended) type source info pointer.
1822 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1823 // Allocate external info struct.
1824 DeclInfo = new (getASTContext()) ExtInfo;
1825 // Restore savedTInfo into (extended) decl info.
1826 getExtInfo()->TInfo = savedTInfo;
1827 }
1828 // Set qualifier info.
1829 getExtInfo()->QualifierLoc = QualifierLoc;
1830 } else if (hasExtInfo()) {
1831 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
1832 getExtInfo()->QualifierLoc = QualifierLoc;
1833 }
1834}
1835
1836void DeclaratorDecl::setTrailingRequiresClause(Expr *TrailingRequiresClause) {
1837 assert(TrailingRequiresClause)((TrailingRequiresClause) ? static_cast<void> (0) : __assert_fail
("TrailingRequiresClause", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1837, __PRETTY_FUNCTION__))
;
1838 // Make sure the extended decl info is allocated.
1839 if (!hasExtInfo()) {
1840 // Save (non-extended) type source info pointer.
1841 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1842 // Allocate external info struct.
1843 DeclInfo = new (getASTContext()) ExtInfo;
1844 // Restore savedTInfo into (extended) decl info.
1845 getExtInfo()->TInfo = savedTInfo;
1846 }
1847 // Set requires clause info.
1848 getExtInfo()->TrailingRequiresClause = TrailingRequiresClause;
1849}
1850
1851void DeclaratorDecl::setTemplateParameterListsInfo(
1852 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1853 assert(!TPLists.empty())((!TPLists.empty()) ? static_cast<void> (0) : __assert_fail
("!TPLists.empty()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1853, __PRETTY_FUNCTION__))
;
1854 // Make sure the extended decl info is allocated.
1855 if (!hasExtInfo()) {
1856 // Save (non-extended) type source info pointer.
1857 auto *savedTInfo = DeclInfo.get<TypeSourceInfo*>();
1858 // Allocate external info struct.
1859 DeclInfo = new (getASTContext()) ExtInfo;
1860 // Restore savedTInfo into (extended) decl info.
1861 getExtInfo()->TInfo = savedTInfo;
1862 }
1863 // Set the template parameter lists info.
1864 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
1865}
1866
1867SourceLocation DeclaratorDecl::getOuterLocStart() const {
1868 return getTemplateOrInnerLocStart(this);
1869}
1870
1871// Helper function: returns true if QT is or contains a type
1872// having a postfix component.
1873static bool typeIsPostfix(QualType QT) {
1874 while (true) {
1875 const Type* T = QT.getTypePtr();
1876 switch (T->getTypeClass()) {
1877 default:
1878 return false;
1879 case Type::Pointer:
1880 QT = cast<PointerType>(T)->getPointeeType();
1881 break;
1882 case Type::BlockPointer:
1883 QT = cast<BlockPointerType>(T)->getPointeeType();
1884 break;
1885 case Type::MemberPointer:
1886 QT = cast<MemberPointerType>(T)->getPointeeType();
1887 break;
1888 case Type::LValueReference:
1889 case Type::RValueReference:
1890 QT = cast<ReferenceType>(T)->getPointeeType();
1891 break;
1892 case Type::PackExpansion:
1893 QT = cast<PackExpansionType>(T)->getPattern();
1894 break;
1895 case Type::Paren:
1896 case Type::ConstantArray:
1897 case Type::DependentSizedArray:
1898 case Type::IncompleteArray:
1899 case Type::VariableArray:
1900 case Type::FunctionProto:
1901 case Type::FunctionNoProto:
1902 return true;
1903 }
1904 }
1905}
1906
1907SourceRange DeclaratorDecl::getSourceRange() const {
1908 SourceLocation RangeEnd = getLocation();
1909 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
1910 // If the declaration has no name or the type extends past the name take the
1911 // end location of the type.
1912 if (!getDeclName() || typeIsPostfix(TInfo->getType()))
1913 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
1914 }
1915 return SourceRange(getOuterLocStart(), RangeEnd);
1916}
1917
1918void QualifierInfo::setTemplateParameterListsInfo(
1919 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
1920 // Free previous template parameters (if any).
1921 if (NumTemplParamLists > 0) {
1922 Context.Deallocate(TemplParamLists);
1923 TemplParamLists = nullptr;
1924 NumTemplParamLists = 0;
1925 }
1926 // Set info on matched template parameter lists (if any).
1927 if (!TPLists.empty()) {
1928 TemplParamLists = new (Context) TemplateParameterList *[TPLists.size()];
1929 NumTemplParamLists = TPLists.size();
1930 std::copy(TPLists.begin(), TPLists.end(), TemplParamLists);
1931 }
1932}
1933
1934//===----------------------------------------------------------------------===//
1935// VarDecl Implementation
1936//===----------------------------------------------------------------------===//
1937
1938const char *VarDecl::getStorageClassSpecifierString(StorageClass SC) {
1939 switch (SC) {
1940 case SC_None: break;
1941 case SC_Auto: return "auto";
1942 case SC_Extern: return "extern";
1943 case SC_PrivateExtern: return "__private_extern__";
1944 case SC_Register: return "register";
1945 case SC_Static: return "static";
1946 }
1947
1948 llvm_unreachable("Invalid storage class")::llvm::llvm_unreachable_internal("Invalid storage class", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1948)
;
1949}
1950
1951VarDecl::VarDecl(Kind DK, ASTContext &C, DeclContext *DC,
1952 SourceLocation StartLoc, SourceLocation IdLoc,
1953 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1954 StorageClass SC)
1955 : DeclaratorDecl(DK, DC, IdLoc, Id, T, TInfo, StartLoc),
1956 redeclarable_base(C) {
1957 static_assert(sizeof(VarDeclBitfields) <= sizeof(unsigned),
1958 "VarDeclBitfields too large!");
1959 static_assert(sizeof(ParmVarDeclBitfields) <= sizeof(unsigned),
1960 "ParmVarDeclBitfields too large!");
1961 static_assert(sizeof(NonParmVarDeclBitfields) <= sizeof(unsigned),
1962 "NonParmVarDeclBitfields too large!");
1963 AllBits = 0;
1964 VarDeclBits.SClass = SC;
1965 // Everything else is implicitly initialized to false.
1966}
1967
1968VarDecl *VarDecl::Create(ASTContext &C, DeclContext *DC,
1969 SourceLocation StartL, SourceLocation IdL,
1970 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1971 StorageClass S) {
1972 return new (C, DC) VarDecl(Var, C, DC, StartL, IdL, Id, T, TInfo, S);
1973}
1974
1975VarDecl *VarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
1976 return new (C, ID)
1977 VarDecl(Var, C, nullptr, SourceLocation(), SourceLocation(), nullptr,
1978 QualType(), nullptr, SC_None);
1979}
1980
1981void VarDecl::setStorageClass(StorageClass SC) {
1982 assert(isLegalForVariable(SC))((isLegalForVariable(SC)) ? static_cast<void> (0) : __assert_fail
("isLegalForVariable(SC)", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 1982, __PRETTY_FUNCTION__))
;
1983 VarDeclBits.SClass = SC;
1984}
1985
1986VarDecl::TLSKind VarDecl::getTLSKind() const {
1987 switch (VarDeclBits.TSCSpec) {
1988 case TSCS_unspecified:
1989 if (!hasAttr<ThreadAttr>() &&
1990 !(getASTContext().getLangOpts().OpenMPUseTLS &&
1991 getASTContext().getTargetInfo().isTLSSupported() &&
1992 hasAttr<OMPThreadPrivateDeclAttr>()))
1993 return TLS_None;
1994 return ((getASTContext().getLangOpts().isCompatibleWithMSVC(
1995 LangOptions::MSVC2015)) ||
1996 hasAttr<OMPThreadPrivateDeclAttr>())
1997 ? TLS_Dynamic
1998 : TLS_Static;
1999 case TSCS___thread: // Fall through.
2000 case TSCS__Thread_local:
2001 return TLS_Static;
2002 case TSCS_thread_local:
2003 return TLS_Dynamic;
2004 }
2005 llvm_unreachable("Unknown thread storage class specifier!")::llvm::llvm_unreachable_internal("Unknown thread storage class specifier!"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2005)
;
2006}
2007
2008SourceRange VarDecl::getSourceRange() const {
2009 if (const Expr *Init = getInit()) {
2010 SourceLocation InitEnd = Init->getEndLoc();
2011 // If Init is implicit, ignore its source range and fallback on
2012 // DeclaratorDecl::getSourceRange() to handle postfix elements.
2013 if (InitEnd.isValid() && InitEnd != getLocation())
2014 return SourceRange(getOuterLocStart(), InitEnd);
2015 }
2016 return DeclaratorDecl::getSourceRange();
2017}
2018
2019template<typename T>
2020static LanguageLinkage getDeclLanguageLinkage(const T &D) {
2021 // C++ [dcl.link]p1: All function types, function names with external linkage,
2022 // and variable names with external linkage have a language linkage.
2023 if (!D.hasExternalFormalLinkage())
2024 return NoLanguageLinkage;
2025
2026 // Language linkage is a C++ concept, but saying that everything else in C has
2027 // C language linkage fits the implementation nicely.
2028 ASTContext &Context = D.getASTContext();
2029 if (!Context.getLangOpts().CPlusPlus)
2030 return CLanguageLinkage;
2031
2032 // C++ [dcl.link]p4: A C language linkage is ignored in determining the
2033 // language linkage of the names of class members and the function type of
2034 // class member functions.
2035 const DeclContext *DC = D.getDeclContext();
2036 if (DC->isRecord())
2037 return CXXLanguageLinkage;
2038
2039 // If the first decl is in an extern "C" context, any other redeclaration
2040 // will have C language linkage. If the first one is not in an extern "C"
2041 // context, we would have reported an error for any other decl being in one.
2042 if (isFirstInExternCContext(&D))
2043 return CLanguageLinkage;
2044 return CXXLanguageLinkage;
2045}
2046
2047template<typename T>
2048static bool isDeclExternC(const T &D) {
2049 // Since the context is ignored for class members, they can only have C++
2050 // language linkage or no language linkage.
2051 const DeclContext *DC = D.getDeclContext();
2052 if (DC->isRecord()) {
2053 assert(D.getASTContext().getLangOpts().CPlusPlus)((D.getASTContext().getLangOpts().CPlusPlus) ? static_cast<
void> (0) : __assert_fail ("D.getASTContext().getLangOpts().CPlusPlus"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2053, __PRETTY_FUNCTION__))
;
2054 return false;
2055 }
2056
2057 return D.getLanguageLinkage() == CLanguageLinkage;
2058}
2059
2060LanguageLinkage VarDecl::getLanguageLinkage() const {
2061 return getDeclLanguageLinkage(*this);
2062}
2063
2064bool VarDecl::isExternC() const {
2065 return isDeclExternC(*this);
2066}
2067
2068bool VarDecl::isInExternCContext() const {
2069 return getLexicalDeclContext()->isExternCContext();
2070}
2071
2072bool VarDecl::isInExternCXXContext() const {
2073 return getLexicalDeclContext()->isExternCXXContext();
2074}
2075
2076VarDecl *VarDecl::getCanonicalDecl() { return getFirstDecl(); }
2077
2078VarDecl::DefinitionKind
2079VarDecl::isThisDeclarationADefinition(ASTContext &C) const {
2080 if (isThisDeclarationADemotedDefinition())
2081 return DeclarationOnly;
2082
2083 // C++ [basic.def]p2:
2084 // A declaration is a definition unless [...] it contains the 'extern'
2085 // specifier or a linkage-specification and neither an initializer [...],
2086 // it declares a non-inline static data member in a class declaration [...],
2087 // it declares a static data member outside a class definition and the variable
2088 // was defined within the class with the constexpr specifier [...],
2089 // C++1y [temp.expl.spec]p15:
2090 // An explicit specialization of a static data member or an explicit
2091 // specialization of a static data member template is a definition if the
2092 // declaration includes an initializer; otherwise, it is a declaration.
2093 //
2094 // FIXME: How do you declare (but not define) a partial specialization of
2095 // a static data member template outside the containing class?
2096 if (isStaticDataMember()) {
2097 if (isOutOfLine() &&
2098 !(getCanonicalDecl()->isInline() &&
2099 getCanonicalDecl()->isConstexpr()) &&
2100 (hasInit() ||
2101 // If the first declaration is out-of-line, this may be an
2102 // instantiation of an out-of-line partial specialization of a variable
2103 // template for which we have not yet instantiated the initializer.
2104 (getFirstDecl()->isOutOfLine()
2105 ? getTemplateSpecializationKind() == TSK_Undeclared
2106 : getTemplateSpecializationKind() !=
2107 TSK_ExplicitSpecialization) ||
2108 isa<VarTemplatePartialSpecializationDecl>(this)))
2109 return Definition;
2110 else if (!isOutOfLine() && isInline())
2111 return Definition;
2112 else
2113 return DeclarationOnly;
2114 }
2115 // C99 6.7p5:
2116 // A definition of an identifier is a declaration for that identifier that
2117 // [...] causes storage to be reserved for that object.
2118 // Note: that applies for all non-file-scope objects.
2119 // C99 6.9.2p1:
2120 // If the declaration of an identifier for an object has file scope and an
2121 // initializer, the declaration is an external definition for the identifier
2122 if (hasInit())
2123 return Definition;
2124
2125 if (hasDefiningAttr())
2126 return Definition;
2127
2128 if (const auto *SAA = getAttr<SelectAnyAttr>())
2129 if (!SAA->isInherited())
2130 return Definition;
2131
2132 // A variable template specialization (other than a static data member
2133 // template or an explicit specialization) is a declaration until we
2134 // instantiate its initializer.
2135 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(this)) {
2136 if (VTSD->getTemplateSpecializationKind() != TSK_ExplicitSpecialization &&
2137 !isa<VarTemplatePartialSpecializationDecl>(VTSD) &&
2138 !VTSD->IsCompleteDefinition)
2139 return DeclarationOnly;
2140 }
2141
2142 if (hasExternalStorage())
2143 return DeclarationOnly;
2144
2145 // [dcl.link] p7:
2146 // A declaration directly contained in a linkage-specification is treated
2147 // as if it contains the extern specifier for the purpose of determining
2148 // the linkage of the declared name and whether it is a definition.
2149 if (isSingleLineLanguageLinkage(*this))
2150 return DeclarationOnly;
2151
2152 // C99 6.9.2p2:
2153 // A declaration of an object that has file scope without an initializer,
2154 // and without a storage class specifier or the scs 'static', constitutes
2155 // a tentative definition.
2156 // No such thing in C++.
2157 if (!C.getLangOpts().CPlusPlus && isFileVarDecl())
2158 return TentativeDefinition;
2159
2160 // What's left is (in C, block-scope) declarations without initializers or
2161 // external storage. These are definitions.
2162 return Definition;
2163}
2164
2165VarDecl *VarDecl::getActingDefinition() {
2166 DefinitionKind Kind = isThisDeclarationADefinition();
2167 if (Kind != TentativeDefinition)
2168 return nullptr;
2169
2170 VarDecl *LastTentative = nullptr;
2171 VarDecl *First = getFirstDecl();
2172 for (auto I : First->redecls()) {
2173 Kind = I->isThisDeclarationADefinition();
2174 if (Kind == Definition)
2175 return nullptr;
2176 else if (Kind == TentativeDefinition)
2177 LastTentative = I;
2178 }
2179 return LastTentative;
2180}
2181
2182VarDecl *VarDecl::getDefinition(ASTContext &C) {
2183 VarDecl *First = getFirstDecl();
2184 for (auto I : First->redecls()) {
2185 if (I->isThisDeclarationADefinition(C) == Definition)
2186 return I;
2187 }
2188 return nullptr;
2189}
2190
2191VarDecl::DefinitionKind VarDecl::hasDefinition(ASTContext &C) const {
2192 DefinitionKind Kind = DeclarationOnly;
2193
2194 const VarDecl *First = getFirstDecl();
2195 for (auto I : First->redecls()) {
2196 Kind = std::max(Kind, I->isThisDeclarationADefinition(C));
2197 if (Kind == Definition)
2198 break;
2199 }
2200
2201 return Kind;
2202}
2203
2204const Expr *VarDecl::getAnyInitializer(const VarDecl *&D) const {
2205 for (auto I : redecls()) {
2206 if (auto Expr = I->getInit()) {
2207 D = I;
2208 return Expr;
2209 }
2210 }
2211 return nullptr;
2212}
2213
2214bool VarDecl::hasInit() const {
2215 if (auto *P = dyn_cast<ParmVarDecl>(this))
2216 if (P->hasUnparsedDefaultArg() || P->hasUninstantiatedDefaultArg())
2217 return false;
2218
2219 return !Init.isNull();
2220}
2221
2222Expr *VarDecl::getInit() {
2223 if (!hasInit())
2224 return nullptr;
2225
2226 if (auto *S = Init.dyn_cast<Stmt *>())
2227 return cast<Expr>(S);
2228
2229 return cast_or_null<Expr>(Init.get<EvaluatedStmt *>()->Value);
2230}
2231
2232Stmt **VarDecl::getInitAddress() {
2233 if (auto *ES = Init.dyn_cast<EvaluatedStmt *>())
2234 return &ES->Value;
2235
2236 return Init.getAddrOfPtr1();
2237}
2238
2239VarDecl *VarDecl::getInitializingDeclaration() {
2240 VarDecl *Def = nullptr;
2241 for (auto I : redecls()) {
2242 if (I->hasInit())
2243 return I;
2244
2245 if (I->isThisDeclarationADefinition()) {
2246 if (isStaticDataMember())
2247 return I;
2248 else
2249 Def = I;
2250 }
2251 }
2252 return Def;
2253}
2254
2255bool VarDecl::isOutOfLine() const {
2256 if (Decl::isOutOfLine())
2257 return true;
2258
2259 if (!isStaticDataMember())
2260 return false;
2261
2262 // If this static data member was instantiated from a static data member of
2263 // a class template, check whether that static data member was defined
2264 // out-of-line.
2265 if (VarDecl *VD = getInstantiatedFromStaticDataMember())
2266 return VD->isOutOfLine();
2267
2268 return false;
2269}
2270
2271void VarDecl::setInit(Expr *I) {
2272 if (auto *Eval = Init.dyn_cast<EvaluatedStmt *>()) {
2273 Eval->~EvaluatedStmt();
2274 getASTContext().Deallocate(Eval);
2275 }
2276
2277 Init = I;
2278}
2279
2280bool VarDecl::mightBeUsableInConstantExpressions(const ASTContext &C) const {
2281 const LangOptions &Lang = C.getLangOpts();
2282
2283 // OpenCL permits const integral variables to be used in constant
2284 // expressions, like in C++98.
2285 if (!Lang.CPlusPlus && !Lang.OpenCL)
2286 return false;
2287
2288 // Function parameters are never usable in constant expressions.
2289 if (isa<ParmVarDecl>(this))
2290 return false;
2291
2292 // The values of weak variables are never usable in constant expressions.
2293 if (isWeak())
2294 return false;
2295
2296 // In C++11, any variable of reference type can be used in a constant
2297 // expression if it is initialized by a constant expression.
2298 if (Lang.CPlusPlus11 && getType()->isReferenceType())
2299 return true;
2300
2301 // Only const objects can be used in constant expressions in C++. C++98 does
2302 // not require the variable to be non-volatile, but we consider this to be a
2303 // defect.
2304 if (!getType().isConstant(C) || getType().isVolatileQualified())
2305 return false;
2306
2307 // In C++, const, non-volatile variables of integral or enumeration types
2308 // can be used in constant expressions.
2309 if (getType()->isIntegralOrEnumerationType())
2310 return true;
2311
2312 // Additionally, in C++11, non-volatile constexpr variables can be used in
2313 // constant expressions.
2314 return Lang.CPlusPlus11 && isConstexpr();
2315}
2316
2317bool VarDecl::isUsableInConstantExpressions(const ASTContext &Context) const {
2318 // C++2a [expr.const]p3:
2319 // A variable is usable in constant expressions after its initializing
2320 // declaration is encountered...
2321 const VarDecl *DefVD = nullptr;
2322 const Expr *Init = getAnyInitializer(DefVD);
2323 if (!Init || Init->isValueDependent() || getType()->isDependentType())
2324 return false;
2325 // ... if it is a constexpr variable, or it is of reference type or of
2326 // const-qualified integral or enumeration type, ...
2327 if (!DefVD->mightBeUsableInConstantExpressions(Context))
2328 return false;
2329 // ... and its initializer is a constant initializer.
2330 if (Context.getLangOpts().CPlusPlus && !DefVD->hasConstantInitialization())
2331 return false;
2332 // C++98 [expr.const]p1:
2333 // An integral constant-expression can involve only [...] const variables
2334 // or static data members of integral or enumeration types initialized with
2335 // [integer] constant expressions (dcl.init)
2336 if ((Context.getLangOpts().CPlusPlus || Context.getLangOpts().OpenCL) &&
2337 !Context.getLangOpts().CPlusPlus11 && !DefVD->hasICEInitializer(Context))
2338 return false;
2339 return true;
2340}
2341
2342/// Convert the initializer for this declaration to the elaborated EvaluatedStmt
2343/// form, which contains extra information on the evaluated value of the
2344/// initializer.
2345EvaluatedStmt *VarDecl::ensureEvaluatedStmt() const {
2346 auto *Eval = Init.dyn_cast<EvaluatedStmt *>();
2347 if (!Eval) {
2348 // Note: EvaluatedStmt contains an APValue, which usually holds
2349 // resources not allocated from the ASTContext. We need to do some
2350 // work to avoid leaking those, but we do so in VarDecl::evaluateValue
2351 // where we can detect whether there's anything to clean up or not.
2352 Eval = new (getASTContext()) EvaluatedStmt;
2353 Eval->Value = Init.get<Stmt *>();
2354 Init = Eval;
2355 }
2356 return Eval;
2357}
2358
2359EvaluatedStmt *VarDecl::getEvaluatedStmt() const {
2360 return Init.dyn_cast<EvaluatedStmt *>();
2361}
2362
2363APValue *VarDecl::evaluateValue() const {
2364 SmallVector<PartialDiagnosticAt, 8> Notes;
2365 return evaluateValueImpl(Notes, hasConstantInitialization());
2366}
2367
2368APValue *VarDecl::evaluateValueImpl(SmallVectorImpl<PartialDiagnosticAt> &Notes,
2369 bool IsConstantInitialization) const {
2370 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2371
2372 const auto *Init = cast<Expr>(Eval->Value);
2373 assert(!Init->isValueDependent())((!Init->isValueDependent()) ? static_cast<void> (0)
: __assert_fail ("!Init->isValueDependent()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2373, __PRETTY_FUNCTION__))
;
2374
2375 // We only produce notes indicating why an initializer is non-constant the
2376 // first time it is evaluated. FIXME: The notes won't always be emitted the
2377 // first time we try evaluation, so might not be produced at all.
2378 if (Eval->WasEvaluated)
2379 return Eval->Evaluated.isAbsent() ? nullptr : &Eval->Evaluated;
2380
2381 if (Eval->IsEvaluating) {
2382 // FIXME: Produce a diagnostic for self-initialization.
2383 return nullptr;
2384 }
2385
2386 Eval->IsEvaluating = true;
2387
2388 ASTContext &Ctx = getASTContext();
2389 bool Result = Init->EvaluateAsInitializer(Eval->Evaluated, Ctx, this, Notes,
2390 IsConstantInitialization);
2391
2392 // In C++11, this isn't a constant initializer if we produced notes. In that
2393 // case, we can't keep the result, because it may only be correct under the
2394 // assumption that the initializer is a constant context.
2395 if (IsConstantInitialization && Ctx.getLangOpts().CPlusPlus11 &&
2396 !Notes.empty())
2397 Result = false;
2398
2399 // Ensure the computed APValue is cleaned up later if evaluation succeeded,
2400 // or that it's empty (so that there's nothing to clean up) if evaluation
2401 // failed.
2402 if (!Result)
2403 Eval->Evaluated = APValue();
2404 else if (Eval->Evaluated.needsCleanup())
2405 Ctx.addDestruction(&Eval->Evaluated);
2406
2407 Eval->IsEvaluating = false;
2408 Eval->WasEvaluated = true;
2409
2410 return Result ? &Eval->Evaluated : nullptr;
2411}
2412
2413APValue *VarDecl::getEvaluatedValue() const {
2414 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2415 if (Eval->WasEvaluated)
2416 return &Eval->Evaluated;
2417
2418 return nullptr;
2419}
2420
2421bool VarDecl::hasICEInitializer(const ASTContext &Context) const {
2422 const Expr *Init = getInit();
2423 assert(Init && "no initializer")((Init && "no initializer") ? static_cast<void>
(0) : __assert_fail ("Init && \"no initializer\"", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2423, __PRETTY_FUNCTION__))
;
2424
2425 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2426 if (!Eval->CheckedForICEInit) {
2427 Eval->CheckedForICEInit = true;
2428 Eval->HasICEInit = Init->isIntegerConstantExpr(Context);
2429 }
2430 return Eval->HasICEInit;
2431}
2432
2433bool VarDecl::hasConstantInitialization() const {
2434 // In C, all globals (and only globals) have constant initialization.
2435 if (hasGlobalStorage() && !getASTContext().getLangOpts().CPlusPlus)
2436 return true;
2437
2438 // In C++, it depends on whether the evaluation at the point of definition
2439 // was evaluatable as a constant initializer.
2440 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2441 return Eval->HasConstantInitialization;
2442
2443 return false;
2444}
2445
2446bool VarDecl::checkForConstantInitialization(
2447 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
2448 EvaluatedStmt *Eval = ensureEvaluatedStmt();
2449 // If we ask for the value before we know whether we have a constant
2450 // initializer, we can compute the wrong value (for example, due to
2451 // std::is_constant_evaluated()).
2452 assert(!Eval->WasEvaluated &&((!Eval->WasEvaluated && "already evaluated var value before checking for constant init"
) ? static_cast<void> (0) : __assert_fail ("!Eval->WasEvaluated && \"already evaluated var value before checking for constant init\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2453, __PRETTY_FUNCTION__))
2453 "already evaluated var value before checking for constant init")((!Eval->WasEvaluated && "already evaluated var value before checking for constant init"
) ? static_cast<void> (0) : __assert_fail ("!Eval->WasEvaluated && \"already evaluated var value before checking for constant init\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2453, __PRETTY_FUNCTION__))
;
2454 assert(getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++")((getASTContext().getLangOpts().CPlusPlus && "only meaningful in C++"
) ? static_cast<void> (0) : __assert_fail ("getASTContext().getLangOpts().CPlusPlus && \"only meaningful in C++\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2454, __PRETTY_FUNCTION__))
;
2455
2456 assert(!cast<Expr>(Eval->Value)->isValueDependent())((!cast<Expr>(Eval->Value)->isValueDependent()) ?
static_cast<void> (0) : __assert_fail ("!cast<Expr>(Eval->Value)->isValueDependent()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2456, __PRETTY_FUNCTION__))
;
2457
2458 // Evaluate the initializer to check whether it's a constant expression.
2459 Eval->HasConstantInitialization =
2460 evaluateValueImpl(Notes, true) && Notes.empty();
2461
2462 // If evaluation as a constant initializer failed, allow re-evaluation as a
2463 // non-constant initializer if we later find we want the value.
2464 if (!Eval->HasConstantInitialization)
2465 Eval->WasEvaluated = false;
2466
2467 return Eval->HasConstantInitialization;
2468}
2469
2470bool VarDecl::isParameterPack() const {
2471 return isa<PackExpansionType>(getType());
2472}
2473
2474template<typename DeclT>
2475static DeclT *getDefinitionOrSelf(DeclT *D) {
2476 assert(D)((D) ? static_cast<void> (0) : __assert_fail ("D", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2476, __PRETTY_FUNCTION__))
;
2477 if (auto *Def = D->getDefinition())
2478 return Def;
2479 return D;
2480}
2481
2482bool VarDecl::isEscapingByref() const {
2483 return hasAttr<BlocksAttr>() && NonParmVarDeclBits.EscapingByref;
2484}
2485
2486bool VarDecl::isNonEscapingByref() const {
2487 return hasAttr<BlocksAttr>() && !NonParmVarDeclBits.EscapingByref;
2488}
2489
2490VarDecl *VarDecl::getTemplateInstantiationPattern() const {
2491 const VarDecl *VD = this;
2492
2493 // If this is an instantiated member, walk back to the template from which
2494 // it was instantiated.
2495 if (MemberSpecializationInfo *MSInfo = VD->getMemberSpecializationInfo()) {
2496 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
2497 VD = VD->getInstantiatedFromStaticDataMember();
2498 while (auto *NewVD = VD->getInstantiatedFromStaticDataMember())
2499 VD = NewVD;
2500 }
2501 }
2502
2503 // If it's an instantiated variable template specialization, find the
2504 // template or partial specialization from which it was instantiated.
2505 if (auto *VDTemplSpec = dyn_cast<VarTemplateSpecializationDecl>(VD)) {
2506 if (isTemplateInstantiation(VDTemplSpec->getTemplateSpecializationKind())) {
2507 auto From = VDTemplSpec->getInstantiatedFrom();
2508 if (auto *VTD = From.dyn_cast<VarTemplateDecl *>()) {
2509 while (!VTD->isMemberSpecialization()) {
2510 auto *NewVTD = VTD->getInstantiatedFromMemberTemplate();
2511 if (!NewVTD)
2512 break;
2513 VTD = NewVTD;
2514 }
2515 return getDefinitionOrSelf(VTD->getTemplatedDecl());
2516 }
2517 if (auto *VTPSD =
2518 From.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
2519 while (!VTPSD->isMemberSpecialization()) {
2520 auto *NewVTPSD = VTPSD->getInstantiatedFromMember();
2521 if (!NewVTPSD)
2522 break;
2523 VTPSD = NewVTPSD;
2524 }
2525 return getDefinitionOrSelf<VarDecl>(VTPSD);
2526 }
2527 }
2528 }
2529
2530 // If this is the pattern of a variable template, find where it was
2531 // instantiated from. FIXME: Is this necessary?
2532 if (VarTemplateDecl *VarTemplate = VD->getDescribedVarTemplate()) {
2533 while (!VarTemplate->isMemberSpecialization()) {
2534 auto *NewVT = VarTemplate->getInstantiatedFromMemberTemplate();
2535 if (!NewVT)
2536 break;
2537 VarTemplate = NewVT;
2538 }
2539
2540 return getDefinitionOrSelf(VarTemplate->getTemplatedDecl());
2541 }
2542
2543 if (VD == this)
2544 return nullptr;
2545 return getDefinitionOrSelf(const_cast<VarDecl*>(VD));
2546}
2547
2548VarDecl *VarDecl::getInstantiatedFromStaticDataMember() const {
2549 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2550 return cast<VarDecl>(MSI->getInstantiatedFrom());
2551
2552 return nullptr;
2553}
2554
2555TemplateSpecializationKind VarDecl::getTemplateSpecializationKind() const {
2556 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2557 return Spec->getSpecializationKind();
2558
2559 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2560 return MSI->getTemplateSpecializationKind();
2561
2562 return TSK_Undeclared;
2563}
2564
2565TemplateSpecializationKind
2566VarDecl::getTemplateSpecializationKindForInstantiation() const {
2567 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2568 return MSI->getTemplateSpecializationKind();
2569
2570 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2571 return Spec->getSpecializationKind();
2572
2573 return TSK_Undeclared;
2574}
2575
2576SourceLocation VarDecl::getPointOfInstantiation() const {
2577 if (const auto *Spec = dyn_cast<VarTemplateSpecializationDecl>(this))
2578 return Spec->getPointOfInstantiation();
2579
2580 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
2581 return MSI->getPointOfInstantiation();
2582
2583 return SourceLocation();
2584}
2585
2586VarTemplateDecl *VarDecl::getDescribedVarTemplate() const {
2587 return getASTContext().getTemplateOrSpecializationInfo(this)
2588 .dyn_cast<VarTemplateDecl *>();
2589}
2590
2591void VarDecl::setDescribedVarTemplate(VarTemplateDecl *Template) {
2592 getASTContext().setTemplateOrSpecializationInfo(this, Template);
2593}
2594
2595bool VarDecl::isKnownToBeDefined() const {
2596 const auto &LangOpts = getASTContext().getLangOpts();
2597 // In CUDA mode without relocatable device code, variables of form 'extern
2598 // __shared__ Foo foo[]' are pointers to the base of the GPU core's shared
2599 // memory pool. These are never undefined variables, even if they appear
2600 // inside of an anon namespace or static function.
2601 //
2602 // With CUDA relocatable device code enabled, these variables don't get
2603 // special handling; they're treated like regular extern variables.
2604 if (LangOpts.CUDA && !LangOpts.GPURelocatableDeviceCode &&
2605 hasExternalStorage() && hasAttr<CUDASharedAttr>() &&
2606 isa<IncompleteArrayType>(getType()))
2607 return true;
2608
2609 return hasDefinition();
2610}
2611
2612bool VarDecl::isNoDestroy(const ASTContext &Ctx) const {
2613 return hasGlobalStorage() && (hasAttr<NoDestroyAttr>() ||
2614 (!Ctx.getLangOpts().RegisterStaticDestructors &&
2615 !hasAttr<AlwaysDestroyAttr>()));
2616}
2617
2618QualType::DestructionKind
2619VarDecl::needsDestruction(const ASTContext &Ctx) const {
2620 if (EvaluatedStmt *Eval = getEvaluatedStmt())
2621 if (Eval->HasConstantDestruction)
2622 return QualType::DK_none;
2623
2624 if (isNoDestroy(Ctx))
2625 return QualType::DK_none;
2626
2627 return getType().isDestructedType();
2628}
2629
2630MemberSpecializationInfo *VarDecl::getMemberSpecializationInfo() const {
2631 if (isStaticDataMember())
2632 // FIXME: Remove ?
2633 // return getASTContext().getInstantiatedFromStaticDataMember(this);
2634 return getASTContext().getTemplateOrSpecializationInfo(this)
2635 .dyn_cast<MemberSpecializationInfo *>();
2636 return nullptr;
2637}
2638
2639void VarDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
2640 SourceLocation PointOfInstantiation) {
2641 assert((isa<VarTemplateSpecializationDecl>(this) ||(((isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo
()) && "not a variable or static data member template specialization"
) ? static_cast<void> (0) : __assert_fail ("(isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2643, __PRETTY_FUNCTION__))
2642 getMemberSpecializationInfo()) &&(((isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo
()) && "not a variable or static data member template specialization"
) ? static_cast<void> (0) : __assert_fail ("(isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2643, __PRETTY_FUNCTION__))
2643 "not a variable or static data member template specialization")(((isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo
()) && "not a variable or static data member template specialization"
) ? static_cast<void> (0) : __assert_fail ("(isa<VarTemplateSpecializationDecl>(this) || getMemberSpecializationInfo()) && \"not a variable or static data member template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2643, __PRETTY_FUNCTION__))
;
2644
2645 if (VarTemplateSpecializationDecl *Spec =
2646 dyn_cast<VarTemplateSpecializationDecl>(this)) {
2647 Spec->setSpecializationKind(TSK);
2648 if (TSK != TSK_ExplicitSpecialization &&
2649 PointOfInstantiation.isValid() &&
2650 Spec->getPointOfInstantiation().isInvalid()) {
2651 Spec->setPointOfInstantiation(PointOfInstantiation);
2652 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2653 L->InstantiationRequested(this);
2654 }
2655 } else if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo()) {
2656 MSI->setTemplateSpecializationKind(TSK);
2657 if (TSK != TSK_ExplicitSpecialization && PointOfInstantiation.isValid() &&
2658 MSI->getPointOfInstantiation().isInvalid()) {
2659 MSI->setPointOfInstantiation(PointOfInstantiation);
2660 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
2661 L->InstantiationRequested(this);
2662 }
2663 }
2664}
2665
2666void
2667VarDecl::setInstantiationOfStaticDataMember(VarDecl *VD,
2668 TemplateSpecializationKind TSK) {
2669 assert(getASTContext().getTemplateOrSpecializationInfo(this).isNull() &&((getASTContext().getTemplateOrSpecializationInfo(this).isNull
() && "Previous template or instantiation?") ? static_cast
<void> (0) : __assert_fail ("getASTContext().getTemplateOrSpecializationInfo(this).isNull() && \"Previous template or instantiation?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2670, __PRETTY_FUNCTION__))
2670 "Previous template or instantiation?")((getASTContext().getTemplateOrSpecializationInfo(this).isNull
() && "Previous template or instantiation?") ? static_cast
<void> (0) : __assert_fail ("getASTContext().getTemplateOrSpecializationInfo(this).isNull() && \"Previous template or instantiation?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2670, __PRETTY_FUNCTION__))
;
2671 getASTContext().setInstantiatedFromStaticDataMember(this, VD, TSK);
2672}
2673
2674//===----------------------------------------------------------------------===//
2675// ParmVarDecl Implementation
2676//===----------------------------------------------------------------------===//
2677
2678ParmVarDecl *ParmVarDecl::Create(ASTContext &C, DeclContext *DC,
2679 SourceLocation StartLoc,
2680 SourceLocation IdLoc, IdentifierInfo *Id,
2681 QualType T, TypeSourceInfo *TInfo,
2682 StorageClass S, Expr *DefArg) {
2683 return new (C, DC) ParmVarDecl(ParmVar, C, DC, StartLoc, IdLoc, Id, T, TInfo,
2684 S, DefArg);
2685}
2686
2687QualType ParmVarDecl::getOriginalType() const {
2688 TypeSourceInfo *TSI = getTypeSourceInfo();
2689 QualType T = TSI ? TSI->getType() : getType();
2690 if (const auto *DT = dyn_cast<DecayedType>(T))
2691 return DT->getOriginalType();
2692 return T;
2693}
2694
2695ParmVarDecl *ParmVarDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
2696 return new (C, ID)
2697 ParmVarDecl(ParmVar, C, nullptr, SourceLocation(), SourceLocation(),
2698 nullptr, QualType(), nullptr, SC_None, nullptr);
2699}
2700
2701SourceRange ParmVarDecl::getSourceRange() const {
2702 if (!hasInheritedDefaultArg()) {
2703 SourceRange ArgRange = getDefaultArgRange();
2704 if (ArgRange.isValid())
2705 return SourceRange(getOuterLocStart(), ArgRange.getEnd());
2706 }
2707
2708 // DeclaratorDecl considers the range of postfix types as overlapping with the
2709 // declaration name, but this is not the case with parameters in ObjC methods.
2710 if (isa<ObjCMethodDecl>(getDeclContext()))
2711 return SourceRange(DeclaratorDecl::getBeginLoc(), getLocation());
2712
2713 return DeclaratorDecl::getSourceRange();
2714}
2715
2716Expr *ParmVarDecl::getDefaultArg() {
2717 assert(!hasUnparsedDefaultArg() && "Default argument is not yet parsed!")((!hasUnparsedDefaultArg() && "Default argument is not yet parsed!"
) ? static_cast<void> (0) : __assert_fail ("!hasUnparsedDefaultArg() && \"Default argument is not yet parsed!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2717, __PRETTY_FUNCTION__))
;
2718 assert(!hasUninstantiatedDefaultArg() &&((!hasUninstantiatedDefaultArg() && "Default argument is not yet instantiated!"
) ? static_cast<void> (0) : __assert_fail ("!hasUninstantiatedDefaultArg() && \"Default argument is not yet instantiated!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2719, __PRETTY_FUNCTION__))
2719 "Default argument is not yet instantiated!")((!hasUninstantiatedDefaultArg() && "Default argument is not yet instantiated!"
) ? static_cast<void> (0) : __assert_fail ("!hasUninstantiatedDefaultArg() && \"Default argument is not yet instantiated!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2719, __PRETTY_FUNCTION__))
;
2720
2721 Expr *Arg = getInit();
2722 if (auto *E = dyn_cast_or_null<FullExpr>(Arg))
2723 return E->getSubExpr();
2724
2725 return Arg;
2726}
2727
2728void ParmVarDecl::setDefaultArg(Expr *defarg) {
2729 ParmVarDeclBits.DefaultArgKind = DAK_Normal;
2730 Init = defarg;
2731}
2732
2733SourceRange ParmVarDecl::getDefaultArgRange() const {
2734 switch (ParmVarDeclBits.DefaultArgKind) {
2735 case DAK_None:
2736 case DAK_Unparsed:
2737 // Nothing we can do here.
2738 return SourceRange();
2739
2740 case DAK_Uninstantiated:
2741 return getUninstantiatedDefaultArg()->getSourceRange();
2742
2743 case DAK_Normal:
2744 if (const Expr *E = getInit())
2745 return E->getSourceRange();
2746
2747 // Missing an actual expression, may be invalid.
2748 return SourceRange();
2749 }
2750 llvm_unreachable("Invalid default argument kind.")::llvm::llvm_unreachable_internal("Invalid default argument kind."
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2750)
;
2751}
2752
2753void ParmVarDecl::setUninstantiatedDefaultArg(Expr *arg) {
2754 ParmVarDeclBits.DefaultArgKind = DAK_Uninstantiated;
2755 Init = arg;
2756}
2757
2758Expr *ParmVarDecl::getUninstantiatedDefaultArg() {
2759 assert(hasUninstantiatedDefaultArg() &&((hasUninstantiatedDefaultArg() && "Wrong kind of initialization expression!"
) ? static_cast<void> (0) : __assert_fail ("hasUninstantiatedDefaultArg() && \"Wrong kind of initialization expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2760, __PRETTY_FUNCTION__))
2760 "Wrong kind of initialization expression!")((hasUninstantiatedDefaultArg() && "Wrong kind of initialization expression!"
) ? static_cast<void> (0) : __assert_fail ("hasUninstantiatedDefaultArg() && \"Wrong kind of initialization expression!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2760, __PRETTY_FUNCTION__))
;
2761 return cast_or_null<Expr>(Init.get<Stmt *>());
2762}
2763
2764bool ParmVarDecl::hasDefaultArg() const {
2765 // FIXME: We should just return false for DAK_None here once callers are
2766 // prepared for the case that we encountered an invalid default argument and
2767 // were unable to even build an invalid expression.
2768 return hasUnparsedDefaultArg() || hasUninstantiatedDefaultArg() ||
2769 !Init.isNull();
2770}
2771
2772void ParmVarDecl::setParameterIndexLarge(unsigned parameterIndex) {
2773 getASTContext().setParameterIndex(this, parameterIndex);
2774 ParmVarDeclBits.ParameterIndex = ParameterIndexSentinel;
2775}
2776
2777unsigned ParmVarDecl::getParameterIndexLarge() const {
2778 return getASTContext().getParameterIndex(this);
2779}
2780
2781//===----------------------------------------------------------------------===//
2782// FunctionDecl Implementation
2783//===----------------------------------------------------------------------===//
2784
2785FunctionDecl::FunctionDecl(Kind DK, ASTContext &C, DeclContext *DC,
2786 SourceLocation StartLoc,
2787 const DeclarationNameInfo &NameInfo, QualType T,
2788 TypeSourceInfo *TInfo, StorageClass S,
2789 bool isInlineSpecified,
2790 ConstexprSpecKind ConstexprKind,
2791 Expr *TrailingRequiresClause)
2792 : DeclaratorDecl(DK, DC, NameInfo.getLoc(), NameInfo.getName(), T, TInfo,
2793 StartLoc),
2794 DeclContext(DK), redeclarable_base(C), Body(), ODRHash(0),
2795 EndRangeLoc(NameInfo.getEndLoc()), DNLoc(NameInfo.getInfo()) {
2796 assert(T.isNull() || T->isFunctionType())((T.isNull() || T->isFunctionType()) ? static_cast<void
> (0) : __assert_fail ("T.isNull() || T->isFunctionType()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2796, __PRETTY_FUNCTION__))
;
2797 FunctionDeclBits.SClass = S;
2798 FunctionDeclBits.IsInline = isInlineSpecified;
2799 FunctionDeclBits.IsInlineSpecified = isInlineSpecified;
2800 FunctionDeclBits.IsVirtualAsWritten = false;
2801 FunctionDeclBits.IsPure = false;
2802 FunctionDeclBits.HasInheritedPrototype = false;
2803 FunctionDeclBits.HasWrittenPrototype = true;
2804 FunctionDeclBits.IsDeleted = false;
2805 FunctionDeclBits.IsTrivial = false;
2806 FunctionDeclBits.IsTrivialForCall = false;
2807 FunctionDeclBits.IsDefaulted = false;
2808 FunctionDeclBits.IsExplicitlyDefaulted = false;
2809 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2810 FunctionDeclBits.HasImplicitReturnZero = false;
2811 FunctionDeclBits.IsLateTemplateParsed = false;
2812 FunctionDeclBits.ConstexprKind = ConstexprKind;
2813 FunctionDeclBits.InstantiationIsPending = false;
2814 FunctionDeclBits.UsesSEHTry = false;
2815 FunctionDeclBits.UsesFPIntrin = false;
2816 FunctionDeclBits.HasSkippedBody = false;
2817 FunctionDeclBits.WillHaveBody = false;
2818 FunctionDeclBits.IsMultiVersion = false;
2819 FunctionDeclBits.IsCopyDeductionCandidate = false;
2820 FunctionDeclBits.HasODRHash = false;
2821 if (TrailingRequiresClause)
2822 setTrailingRequiresClause(TrailingRequiresClause);
2823}
2824
2825void FunctionDecl::getNameForDiagnostic(
2826 raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const {
2827 NamedDecl::getNameForDiagnostic(OS, Policy, Qualified);
2828 const TemplateArgumentList *TemplateArgs = getTemplateSpecializationArgs();
2829 if (TemplateArgs)
2830 printTemplateArgumentList(OS, TemplateArgs->asArray(), Policy);
2831}
2832
2833bool FunctionDecl::isVariadic() const {
2834 if (const auto *FT = getType()->getAs<FunctionProtoType>())
2835 return FT->isVariadic();
2836 return false;
2837}
2838
2839FunctionDecl::DefaultedFunctionInfo *
2840FunctionDecl::DefaultedFunctionInfo::Create(ASTContext &Context,
2841 ArrayRef<DeclAccessPair> Lookups) {
2842 DefaultedFunctionInfo *Info = new (Context.Allocate(
2843 totalSizeToAlloc<DeclAccessPair>(Lookups.size()),
2844 std::max(alignof(DefaultedFunctionInfo), alignof(DeclAccessPair))))
2845 DefaultedFunctionInfo;
2846 Info->NumLookups = Lookups.size();
2847 std::uninitialized_copy(Lookups.begin(), Lookups.end(),
2848 Info->getTrailingObjects<DeclAccessPair>());
2849 return Info;
2850}
2851
2852void FunctionDecl::setDefaultedFunctionInfo(DefaultedFunctionInfo *Info) {
2853 assert(!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this")((!FunctionDeclBits.HasDefaultedFunctionInfo && "already have this"
) ? static_cast<void> (0) : __assert_fail ("!FunctionDeclBits.HasDefaultedFunctionInfo && \"already have this\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2853, __PRETTY_FUNCTION__))
;
2854 assert(!Body && "can't replace function body with defaulted function info")((!Body && "can't replace function body with defaulted function info"
) ? static_cast<void> (0) : __assert_fail ("!Body && \"can't replace function body with defaulted function info\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2854, __PRETTY_FUNCTION__))
;
2855
2856 FunctionDeclBits.HasDefaultedFunctionInfo = true;
2857 DefaultedInfo = Info;
2858}
2859
2860FunctionDecl::DefaultedFunctionInfo *
2861FunctionDecl::getDefaultedFunctionInfo() const {
2862 return FunctionDeclBits.HasDefaultedFunctionInfo ? DefaultedInfo : nullptr;
2863}
2864
2865bool FunctionDecl::hasBody(const FunctionDecl *&Definition) const {
2866 for (auto I : redecls()) {
2867 if (I->doesThisDeclarationHaveABody()) {
2868 Definition = I;
2869 return true;
2870 }
2871 }
2872
2873 return false;
2874}
2875
2876bool FunctionDecl::hasTrivialBody() const {
2877 Stmt *S = getBody();
2878 if (!S) {
2879 // Since we don't have a body for this function, we don't know if it's
2880 // trivial or not.
2881 return false;
2882 }
2883
2884 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
2885 return true;
2886 return false;
2887}
2888
2889bool FunctionDecl::isDefined(const FunctionDecl *&Definition) const {
2890 for (auto I : redecls()) {
2891 if (I->isThisDeclarationADefinition()) {
2892 Definition = I;
2893 return true;
2894 }
2895 }
2896
2897 return false;
2898}
2899
2900Stmt *FunctionDecl::getBody(const FunctionDecl *&Definition) const {
2901 if (!hasBody(Definition))
2902 return nullptr;
2903
2904 assert(!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&((!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
"definition should not have a body") ? static_cast<void>
(0) : __assert_fail ("!Definition->FunctionDeclBits.HasDefaultedFunctionInfo && \"definition should not have a body\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2905, __PRETTY_FUNCTION__))
2905 "definition should not have a body")((!Definition->FunctionDeclBits.HasDefaultedFunctionInfo &&
"definition should not have a body") ? static_cast<void>
(0) : __assert_fail ("!Definition->FunctionDeclBits.HasDefaultedFunctionInfo && \"definition should not have a body\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2905, __PRETTY_FUNCTION__))
;
2906 if (Definition->Body)
2907 return Definition->Body.get(getASTContext().getExternalSource());
2908
2909 return nullptr;
2910}
2911
2912void FunctionDecl::setBody(Stmt *B) {
2913 FunctionDeclBits.HasDefaultedFunctionInfo = false;
2914 Body = LazyDeclStmtPtr(B);
2915 if (B)
2916 EndRangeLoc = B->getEndLoc();
2917}
2918
2919void FunctionDecl::setPure(bool P) {
2920 FunctionDeclBits.IsPure = P;
2921 if (P)
2922 if (auto *Parent = dyn_cast<CXXRecordDecl>(getDeclContext()))
2923 Parent->markedVirtualFunctionPure();
2924}
2925
2926template<std::size_t Len>
2927static bool isNamed(const NamedDecl *ND, const char (&Str)[Len]) {
2928 IdentifierInfo *II = ND->getIdentifier();
2929 return II && II->isStr(Str);
2930}
2931
2932bool FunctionDecl::isMain() const {
2933 const TranslationUnitDecl *tunit =
2934 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2935 return tunit &&
2936 !tunit->getASTContext().getLangOpts().Freestanding &&
2937 isNamed(this, "main");
2938}
2939
2940bool FunctionDecl::isMSVCRTEntryPoint() const {
2941 const TranslationUnitDecl *TUnit =
2942 dyn_cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext());
2943 if (!TUnit)
2944 return false;
2945
2946 // Even though we aren't really targeting MSVCRT if we are freestanding,
2947 // semantic analysis for these functions remains the same.
2948
2949 // MSVCRT entry points only exist on MSVCRT targets.
2950 if (!TUnit->getASTContext().getTargetInfo().getTriple().isOSMSVCRT())
2951 return false;
2952
2953 // Nameless functions like constructors cannot be entry points.
2954 if (!getIdentifier())
2955 return false;
2956
2957 return llvm::StringSwitch<bool>(getName())
2958 .Cases("main", // an ANSI console app
2959 "wmain", // a Unicode console App
2960 "WinMain", // an ANSI GUI app
2961 "wWinMain", // a Unicode GUI app
2962 "DllMain", // a DLL
2963 true)
2964 .Default(false);
2965}
2966
2967bool FunctionDecl::isReservedGlobalPlacementOperator() const {
2968 assert(getDeclName().getNameKind() == DeclarationName::CXXOperatorName)((getDeclName().getNameKind() == DeclarationName::CXXOperatorName
) ? static_cast<void> (0) : __assert_fail ("getDeclName().getNameKind() == DeclarationName::CXXOperatorName"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2968, __PRETTY_FUNCTION__))
;
2969 assert(getDeclName().getCXXOverloadedOperator() == OO_New ||((getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName
().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator
() == OO_Array_New || getDeclName().getCXXOverloadedOperator(
) == OO_Array_Delete) ? static_cast<void> (0) : __assert_fail
("getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator() == OO_Array_New || getDeclName().getCXXOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2972, __PRETTY_FUNCTION__))
2970 getDeclName().getCXXOverloadedOperator() == OO_Delete ||((getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName
().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator
() == OO_Array_New || getDeclName().getCXXOverloadedOperator(
) == OO_Array_Delete) ? static_cast<void> (0) : __assert_fail
("getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator() == OO_Array_New || getDeclName().getCXXOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2972, __PRETTY_FUNCTION__))
2971 getDeclName().getCXXOverloadedOperator() == OO_Array_New ||((getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName
().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator
() == OO_Array_New || getDeclName().getCXXOverloadedOperator(
) == OO_Array_Delete) ? static_cast<void> (0) : __assert_fail
("getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator() == OO_Array_New || getDeclName().getCXXOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2972, __PRETTY_FUNCTION__))
2972 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)((getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName
().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator
() == OO_Array_New || getDeclName().getCXXOverloadedOperator(
) == OO_Array_Delete) ? static_cast<void> (0) : __assert_fail
("getDeclName().getCXXOverloadedOperator() == OO_New || getDeclName().getCXXOverloadedOperator() == OO_Delete || getDeclName().getCXXOverloadedOperator() == OO_Array_New || getDeclName().getCXXOverloadedOperator() == OO_Array_Delete"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 2972, __PRETTY_FUNCTION__))
;
2973
2974 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
2975 return false;
2976
2977 const auto *proto = getType()->castAs<FunctionProtoType>();
2978 if (proto->getNumParams() != 2 || proto->isVariadic())
2979 return false;
2980
2981 ASTContext &Context =
2982 cast<TranslationUnitDecl>(getDeclContext()->getRedeclContext())
2983 ->getASTContext();
2984
2985 // The result type and first argument type are constant across all
2986 // these operators. The second argument must be exactly void*.
2987 return (proto->getParamType(1).getCanonicalType() == Context.VoidPtrTy);
2988}
2989
2990bool FunctionDecl::isReplaceableGlobalAllocationFunction(
2991 Optional<unsigned> *AlignmentParam, bool *IsNothrow) const {
2992 if (getDeclName().getNameKind() != DeclarationName::CXXOperatorName)
2993 return false;
2994 if (getDeclName().getCXXOverloadedOperator() != OO_New &&
2995 getDeclName().getCXXOverloadedOperator() != OO_Delete &&
2996 getDeclName().getCXXOverloadedOperator() != OO_Array_New &&
2997 getDeclName().getCXXOverloadedOperator() != OO_Array_Delete)
2998 return false;
2999
3000 if (isa<CXXRecordDecl>(getDeclContext()))
3001 return false;
3002
3003 // This can only fail for an invalid 'operator new' declaration.
3004 if (!getDeclContext()->getRedeclContext()->isTranslationUnit())
3005 return false;
3006
3007 const auto *FPT = getType()->castAs<FunctionProtoType>();
3008 if (FPT->getNumParams() == 0 || FPT->getNumParams() > 3 || FPT->isVariadic())
3009 return false;
3010
3011 // If this is a single-parameter function, it must be a replaceable global
3012 // allocation or deallocation function.
3013 if (FPT->getNumParams() == 1)
3014 return true;
3015
3016 unsigned Params = 1;
3017 QualType Ty = FPT->getParamType(Params);
3018 ASTContext &Ctx = getASTContext();
3019
3020 auto Consume = [&] {
3021 ++Params;
3022 Ty = Params < FPT->getNumParams() ? FPT->getParamType(Params) : QualType();
3023 };
3024
3025 // In C++14, the next parameter can be a 'std::size_t' for sized delete.
3026 bool IsSizedDelete = false;
3027 if (Ctx.getLangOpts().SizedDeallocation &&
3028 (getDeclName().getCXXOverloadedOperator() == OO_Delete ||
3029 getDeclName().getCXXOverloadedOperator() == OO_Array_Delete) &&
3030 Ctx.hasSameType(Ty, Ctx.getSizeType())) {
3031 IsSizedDelete = true;
3032 Consume();
3033 }
3034
3035 // In C++17, the next parameter can be a 'std::align_val_t' for aligned
3036 // new/delete.
3037 if (Ctx.getLangOpts().AlignedAllocation && !Ty.isNull() && Ty->isAlignValT()) {
3038 Consume();
3039 if (AlignmentParam)
3040 *AlignmentParam = Params;
3041 }
3042
3043 // Finally, if this is not a sized delete, the final parameter can
3044 // be a 'const std::nothrow_t&'.
3045 if (!IsSizedDelete && !Ty.isNull() && Ty->isReferenceType()) {
3046 Ty = Ty->getPointeeType();
3047 if (Ty.getCVRQualifiers() != Qualifiers::Const)
3048 return false;
3049 if (Ty->isNothrowT()) {
3050 if (IsNothrow)
3051 *IsNothrow = true;
3052 Consume();
3053 }
3054 }
3055
3056 return Params == FPT->getNumParams();
3057}
3058
3059bool FunctionDecl::isInlineBuiltinDeclaration() const {
3060 if (!getBuiltinID())
3061 return false;
3062
3063 const FunctionDecl *Definition;
3064 return hasBody(Definition) && Definition->isInlineSpecified();
3065}
3066
3067bool FunctionDecl::isDestroyingOperatorDelete() const {
3068 // C++ P0722:
3069 // Within a class C, a single object deallocation function with signature
3070 // (T, std::destroying_delete_t, <more params>)
3071 // is a destroying operator delete.
3072 if (!isa<CXXMethodDecl>(this) || getOverloadedOperator() != OO_Delete ||
3073 getNumParams() < 2)
3074 return false;
3075
3076 auto *RD = getParamDecl(1)->getType()->getAsCXXRecordDecl();
3077 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
3078 RD->getIdentifier()->isStr("destroying_delete_t");
3079}
3080
3081LanguageLinkage FunctionDecl::getLanguageLinkage() const {
3082 return getDeclLanguageLinkage(*this);
3083}
3084
3085bool FunctionDecl::isExternC() const {
3086 return isDeclExternC(*this);
3087}
3088
3089bool FunctionDecl::isInExternCContext() const {
3090 if (hasAttr<OpenCLKernelAttr>())
3091 return true;
3092 return getLexicalDeclContext()->isExternCContext();
3093}
3094
3095bool FunctionDecl::isInExternCXXContext() const {
3096 return getLexicalDeclContext()->isExternCXXContext();
3097}
3098
3099bool FunctionDecl::isGlobal() const {
3100 if (const auto *Method = dyn_cast<CXXMethodDecl>(this))
3101 return Method->isStatic();
3102
3103 if (getCanonicalDecl()->getStorageClass() == SC_Static)
3104 return false;
3105
3106 for (const DeclContext *DC = getDeclContext();
3107 DC->isNamespace();
3108 DC = DC->getParent()) {
3109 if (const auto *Namespace = cast<NamespaceDecl>(DC)) {
3110 if (!Namespace->getDeclName())
3111 return false;
3112 break;
3113 }
3114 }
3115
3116 return true;
3117}
3118
3119bool FunctionDecl::isNoReturn() const {
3120 if (hasAttr<NoReturnAttr>() || hasAttr<CXX11NoReturnAttr>() ||
3121 hasAttr<C11NoReturnAttr>())
3122 return true;
3123
3124 if (auto *FnTy = getType()->getAs<FunctionType>())
3125 return FnTy->getNoReturnAttr();
3126
3127 return false;
3128}
3129
3130
3131MultiVersionKind FunctionDecl::getMultiVersionKind() const {
3132 if (hasAttr<TargetAttr>())
3133 return MultiVersionKind::Target;
3134 if (hasAttr<CPUDispatchAttr>())
3135 return MultiVersionKind::CPUDispatch;
3136 if (hasAttr<CPUSpecificAttr>())
3137 return MultiVersionKind::CPUSpecific;
3138 return MultiVersionKind::None;
3139}
3140
3141bool FunctionDecl::isCPUDispatchMultiVersion() const {
3142 return isMultiVersion() && hasAttr<CPUDispatchAttr>();
3143}
3144
3145bool FunctionDecl::isCPUSpecificMultiVersion() const {
3146 return isMultiVersion() && hasAttr<CPUSpecificAttr>();
3147}
3148
3149bool FunctionDecl::isTargetMultiVersion() const {
3150 return isMultiVersion() && hasAttr<TargetAttr>();
3151}
3152
3153void
3154FunctionDecl::setPreviousDeclaration(FunctionDecl *PrevDecl) {
3155 redeclarable_base::setPreviousDecl(PrevDecl);
3156
3157 if (FunctionTemplateDecl *FunTmpl = getDescribedFunctionTemplate()) {
3158 FunctionTemplateDecl *PrevFunTmpl
3159 = PrevDecl? PrevDecl->getDescribedFunctionTemplate() : nullptr;
3160 assert((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch")(((!PrevDecl || PrevFunTmpl) && "Function/function template mismatch"
) ? static_cast<void> (0) : __assert_fail ("(!PrevDecl || PrevFunTmpl) && \"Function/function template mismatch\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3160, __PRETTY_FUNCTION__))
;
3161 FunTmpl->setPreviousDecl(PrevFunTmpl);
3162 }
3163
3164 if (PrevDecl && PrevDecl->isInlined())
3165 setImplicitlyInline(true);
3166}
3167
3168FunctionDecl *FunctionDecl::getCanonicalDecl() { return getFirstDecl(); }
3169
3170/// Returns a value indicating whether this function corresponds to a builtin
3171/// function.
3172///
3173/// The function corresponds to a built-in function if it is declared at
3174/// translation scope or within an extern "C" block and its name matches with
3175/// the name of a builtin. The returned value will be 0 for functions that do
3176/// not correspond to a builtin, a value of type \c Builtin::ID if in the
3177/// target-independent range \c [1,Builtin::First), or a target-specific builtin
3178/// value.
3179///
3180/// \param ConsiderWrapperFunctions If true, we should consider wrapper
3181/// functions as their wrapped builtins. This shouldn't be done in general, but
3182/// it's useful in Sema to diagnose calls to wrappers based on their semantics.
3183unsigned FunctionDecl::getBuiltinID(bool ConsiderWrapperFunctions) const {
3184 unsigned BuiltinID = 0;
3185
3186 if (const auto *ABAA = getAttr<ArmBuiltinAliasAttr>()) {
3187 BuiltinID = ABAA->getBuiltinName()->getBuiltinID();
3188 } else if (const auto *A = getAttr<BuiltinAttr>()) {
3189 BuiltinID = A->getID();
3190 }
3191
3192 if (!BuiltinID)
3193 return 0;
3194
3195 // If the function is marked "overloadable", it has a different mangled name
3196 // and is not the C library function.
3197 if (!ConsiderWrapperFunctions && hasAttr<OverloadableAttr>() &&
3198 !hasAttr<ArmBuiltinAliasAttr>())
3199 return 0;
3200
3201 ASTContext &Context = getASTContext();
3202 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3203 return BuiltinID;
3204
3205 // This function has the name of a known C library
3206 // function. Determine whether it actually refers to the C library
3207 // function or whether it just has the same name.
3208
3209 // If this is a static function, it's not a builtin.
3210 if (!ConsiderWrapperFunctions && getStorageClass() == SC_Static)
3211 return 0;
3212
3213 // OpenCL v1.2 s6.9.f - The library functions defined in
3214 // the C99 standard headers are not available.
3215 if (Context.getLangOpts().OpenCL &&
3216 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
3217 return 0;
3218
3219 // CUDA does not have device-side standard library. printf and malloc are the
3220 // only special cases that are supported by device-side runtime.
3221 if (Context.getLangOpts().CUDA && hasAttr<CUDADeviceAttr>() &&
3222 !hasAttr<CUDAHostAttr>() &&
3223 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3224 return 0;
3225
3226 // As AMDGCN implementation of OpenMP does not have a device-side standard
3227 // library, none of the predefined library functions except printf and malloc
3228 // should be treated as a builtin i.e. 0 should be returned for them.
3229 if (Context.getTargetInfo().getTriple().isAMDGCN() &&
3230 Context.getLangOpts().OpenMPIsDevice &&
3231 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
3232 !(BuiltinID == Builtin::BIprintf || BuiltinID == Builtin::BImalloc))
3233 return 0;
3234
3235 return BuiltinID;
3236}
3237
3238/// getNumParams - Return the number of parameters this function must have
3239/// based on its FunctionType. This is the length of the ParamInfo array
3240/// after it has been created.
3241unsigned FunctionDecl::getNumParams() const {
3242 const auto *FPT = getType()->getAs<FunctionProtoType>();
3243 return FPT ? FPT->getNumParams() : 0;
3244}
3245
3246void FunctionDecl::setParams(ASTContext &C,
3247 ArrayRef<ParmVarDecl *> NewParamInfo) {
3248 assert(!ParamInfo && "Already has param info!")((!ParamInfo && "Already has param info!") ? static_cast
<void> (0) : __assert_fail ("!ParamInfo && \"Already has param info!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3248, __PRETTY_FUNCTION__))
;
3249 assert(NewParamInfo.size() == getNumParams() && "Parameter count mismatch!")((NewParamInfo.size() == getNumParams() && "Parameter count mismatch!"
) ? static_cast<void> (0) : __assert_fail ("NewParamInfo.size() == getNumParams() && \"Parameter count mismatch!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3249, __PRETTY_FUNCTION__))
;
3250
3251 // Zero params -> null pointer.
3252 if (!NewParamInfo.empty()) {
3253 ParamInfo = new (C) ParmVarDecl*[NewParamInfo.size()];
3254 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
3255 }
3256}
3257
3258/// getMinRequiredArguments - Returns the minimum number of arguments
3259/// needed to call this function. This may be fewer than the number of
3260/// function parameters, if some of the parameters have default
3261/// arguments (in C++) or are parameter packs (C++11).
3262unsigned FunctionDecl::getMinRequiredArguments() const {
3263 if (!getASTContext().getLangOpts().CPlusPlus)
3264 return getNumParams();
3265
3266 // Note that it is possible for a parameter with no default argument to
3267 // follow a parameter with a default argument.
3268 unsigned NumRequiredArgs = 0;
3269 unsigned MinParamsSoFar = 0;
3270 for (auto *Param : parameters()) {
3271 if (!Param->isParameterPack()) {
3272 ++MinParamsSoFar;
3273 if (!Param->hasDefaultArg())
3274 NumRequiredArgs = MinParamsSoFar;
3275 }
3276 }
3277 return NumRequiredArgs;
3278}
3279
3280bool FunctionDecl::hasOneParamOrDefaultArgs() const {
3281 return getNumParams() == 1 ||
3282 (getNumParams() > 1 &&
3283 std::all_of(param_begin() + 1, param_end(),
3284 [](ParmVarDecl *P) { return P->hasDefaultArg(); }));
3285}
3286
3287/// The combination of the extern and inline keywords under MSVC forces
3288/// the function to be required.
3289///
3290/// Note: This function assumes that we will only get called when isInlined()
3291/// would return true for this FunctionDecl.
3292bool FunctionDecl::isMSExternInline() const {
3293 assert(isInlined() && "expected to get called on an inlined function!")((isInlined() && "expected to get called on an inlined function!"
) ? static_cast<void> (0) : __assert_fail ("isInlined() && \"expected to get called on an inlined function!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3293, __PRETTY_FUNCTION__))
;
3294
3295 const ASTContext &Context = getASTContext();
3296 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
3297 !hasAttr<DLLExportAttr>())
3298 return false;
3299
3300 for (const FunctionDecl *FD = getMostRecentDecl(); FD;
3301 FD = FD->getPreviousDecl())
3302 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3303 return true;
3304
3305 return false;
3306}
3307
3308static bool redeclForcesDefMSVC(const FunctionDecl *Redecl) {
3309 if (Redecl->getStorageClass() != SC_Extern)
3310 return false;
3311
3312 for (const FunctionDecl *FD = Redecl->getPreviousDecl(); FD;
3313 FD = FD->getPreviousDecl())
3314 if (!FD->isImplicit() && FD->getStorageClass() == SC_Extern)
3315 return false;
3316
3317 return true;
3318}
3319
3320static bool RedeclForcesDefC99(const FunctionDecl *Redecl) {
3321 // Only consider file-scope declarations in this test.
3322 if (!Redecl->getLexicalDeclContext()->isTranslationUnit())
3323 return false;
3324
3325 // Only consider explicit declarations; the presence of a builtin for a
3326 // libcall shouldn't affect whether a definition is externally visible.
3327 if (Redecl->isImplicit())
3328 return false;
3329
3330 if (!Redecl->isInlineSpecified() || Redecl->getStorageClass() == SC_Extern)
3331 return true; // Not an inline definition
3332
3333 return false;
3334}
3335
3336/// For a function declaration in C or C++, determine whether this
3337/// declaration causes the definition to be externally visible.
3338///
3339/// For instance, this determines if adding the current declaration to the set
3340/// of redeclarations of the given functions causes
3341/// isInlineDefinitionExternallyVisible to change from false to true.
3342bool FunctionDecl::doesDeclarationForceExternallyVisibleDefinition() const {
3343 assert(!doesThisDeclarationHaveABody() &&((!doesThisDeclarationHaveABody() && "Must have a declaration without a body."
) ? static_cast<void> (0) : __assert_fail ("!doesThisDeclarationHaveABody() && \"Must have a declaration without a body.\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3344, __PRETTY_FUNCTION__))
3344 "Must have a declaration without a body.")((!doesThisDeclarationHaveABody() && "Must have a declaration without a body."
) ? static_cast<void> (0) : __assert_fail ("!doesThisDeclarationHaveABody() && \"Must have a declaration without a body.\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3344, __PRETTY_FUNCTION__))
;
3345
3346 ASTContext &Context = getASTContext();
3347
3348 if (Context.getLangOpts().MSVCCompat) {
3349 const FunctionDecl *Definition;
3350 if (hasBody(Definition) && Definition->isInlined() &&
3351 redeclForcesDefMSVC(this))
3352 return true;
3353 }
3354
3355 if (Context.getLangOpts().CPlusPlus)
3356 return false;
3357
3358 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3359 // With GNU inlining, a declaration with 'inline' but not 'extern', forces
3360 // an externally visible definition.
3361 //
3362 // FIXME: What happens if gnu_inline gets added on after the first
3363 // declaration?
3364 if (!isInlineSpecified() || getStorageClass() == SC_Extern)
3365 return false;
3366
3367 const FunctionDecl *Prev = this;
3368 bool FoundBody = false;
3369 while ((Prev = Prev->getPreviousDecl())) {
3370 FoundBody |= Prev->doesThisDeclarationHaveABody();
3371
3372 if (Prev->doesThisDeclarationHaveABody()) {
3373 // If it's not the case that both 'inline' and 'extern' are
3374 // specified on the definition, then it is always externally visible.
3375 if (!Prev->isInlineSpecified() ||
3376 Prev->getStorageClass() != SC_Extern)
3377 return false;
3378 } else if (Prev->isInlineSpecified() &&
3379 Prev->getStorageClass() != SC_Extern) {
3380 return false;
3381 }
3382 }
3383 return FoundBody;
3384 }
3385
3386 // C99 6.7.4p6:
3387 // [...] If all of the file scope declarations for a function in a
3388 // translation unit include the inline function specifier without extern,
3389 // then the definition in that translation unit is an inline definition.
3390 if (isInlineSpecified() && getStorageClass() != SC_Extern)
3391 return false;
3392 const FunctionDecl *Prev = this;
3393 bool FoundBody = false;
3394 while ((Prev = Prev->getPreviousDecl())) {
3395 FoundBody |= Prev->doesThisDeclarationHaveABody();
3396 if (RedeclForcesDefC99(Prev))
3397 return false;
3398 }
3399 return FoundBody;
3400}
3401
3402FunctionTypeLoc FunctionDecl::getFunctionTypeLoc() const {
3403 const TypeSourceInfo *TSI = getTypeSourceInfo();
3404 return TSI ? TSI->getTypeLoc().IgnoreParens().getAs<FunctionTypeLoc>()
3405 : FunctionTypeLoc();
3406}
3407
3408SourceRange FunctionDecl::getReturnTypeSourceRange() const {
3409 FunctionTypeLoc FTL = getFunctionTypeLoc();
3410 if (!FTL)
3411 return SourceRange();
3412
3413 // Skip self-referential return types.
3414 const SourceManager &SM = getASTContext().getSourceManager();
3415 SourceRange RTRange = FTL.getReturnLoc().getSourceRange();
3416 SourceLocation Boundary = getNameInfo().getBeginLoc();
3417 if (RTRange.isInvalid() || Boundary.isInvalid() ||
3418 !SM.isBeforeInTranslationUnit(RTRange.getEnd(), Boundary))
3419 return SourceRange();
3420
3421 return RTRange;
3422}
3423
3424SourceRange FunctionDecl::getParametersSourceRange() const {
3425 unsigned NP = getNumParams();
3426 SourceLocation EllipsisLoc = getEllipsisLoc();
3427
3428 if (NP == 0 && EllipsisLoc.isInvalid())
3429 return SourceRange();
3430
3431 SourceLocation Begin =
3432 NP > 0 ? ParamInfo[0]->getSourceRange().getBegin() : EllipsisLoc;
3433 SourceLocation End = EllipsisLoc.isValid()
3434 ? EllipsisLoc
3435 : ParamInfo[NP - 1]->getSourceRange().getEnd();
3436
3437 return SourceRange(Begin, End);
3438}
3439
3440SourceRange FunctionDecl::getExceptionSpecSourceRange() const {
3441 FunctionTypeLoc FTL = getFunctionTypeLoc();
3442 return FTL ? FTL.getExceptionSpecRange() : SourceRange();
3443}
3444
3445/// For an inline function definition in C, or for a gnu_inline function
3446/// in C++, determine whether the definition will be externally visible.
3447///
3448/// Inline function definitions are always available for inlining optimizations.
3449/// However, depending on the language dialect, declaration specifiers, and
3450/// attributes, the definition of an inline function may or may not be
3451/// "externally" visible to other translation units in the program.
3452///
3453/// In C99, inline definitions are not externally visible by default. However,
3454/// if even one of the global-scope declarations is marked "extern inline", the
3455/// inline definition becomes externally visible (C99 6.7.4p6).
3456///
3457/// In GNU89 mode, or if the gnu_inline attribute is attached to the function
3458/// definition, we use the GNU semantics for inline, which are nearly the
3459/// opposite of C99 semantics. In particular, "inline" by itself will create
3460/// an externally visible symbol, but "extern inline" will not create an
3461/// externally visible symbol.
3462bool FunctionDecl::isInlineDefinitionExternallyVisible() const {
3463 assert((doesThisDeclarationHaveABody() || willHaveBody() ||(((doesThisDeclarationHaveABody() || willHaveBody() || hasAttr
<AliasAttr>()) && "Must be a function definition"
) ? static_cast<void> (0) : __assert_fail ("(doesThisDeclarationHaveABody() || willHaveBody() || hasAttr<AliasAttr>()) && \"Must be a function definition\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3465, __PRETTY_FUNCTION__))
3464 hasAttr<AliasAttr>()) &&(((doesThisDeclarationHaveABody() || willHaveBody() || hasAttr
<AliasAttr>()) && "Must be a function definition"
) ? static_cast<void> (0) : __assert_fail ("(doesThisDeclarationHaveABody() || willHaveBody() || hasAttr<AliasAttr>()) && \"Must be a function definition\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3465, __PRETTY_FUNCTION__))
3465 "Must be a function definition")(((doesThisDeclarationHaveABody() || willHaveBody() || hasAttr
<AliasAttr>()) && "Must be a function definition"
) ? static_cast<void> (0) : __assert_fail ("(doesThisDeclarationHaveABody() || willHaveBody() || hasAttr<AliasAttr>()) && \"Must be a function definition\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3465, __PRETTY_FUNCTION__))
;
3466 assert(isInlined() && "Function must be inline")((isInlined() && "Function must be inline") ? static_cast
<void> (0) : __assert_fail ("isInlined() && \"Function must be inline\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3466, __PRETTY_FUNCTION__))
;
3467 ASTContext &Context = getASTContext();
3468
3469 if (Context.getLangOpts().GNUInline || hasAttr<GNUInlineAttr>()) {
3470 // Note: If you change the logic here, please change
3471 // doesDeclarationForceExternallyVisibleDefinition as well.
3472 //
3473 // If it's not the case that both 'inline' and 'extern' are
3474 // specified on the definition, then this inline definition is
3475 // externally visible.
3476 if (Context.getLangOpts().CPlusPlus)
3477 return false;
3478 if (!(isInlineSpecified() && getStorageClass() == SC_Extern))
3479 return true;
3480
3481 // If any declaration is 'inline' but not 'extern', then this definition
3482 // is externally visible.
3483 for (auto Redecl : redecls()) {
3484 if (Redecl->isInlineSpecified() &&
3485 Redecl->getStorageClass() != SC_Extern)
3486 return true;
3487 }
3488
3489 return false;
3490 }
3491
3492 // The rest of this function is C-only.
3493 assert(!Context.getLangOpts().CPlusPlus &&((!Context.getLangOpts().CPlusPlus && "should not use C inline rules in C++"
) ? static_cast<void> (0) : __assert_fail ("!Context.getLangOpts().CPlusPlus && \"should not use C inline rules in C++\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3494, __PRETTY_FUNCTION__))
3494 "should not use C inline rules in C++")((!Context.getLangOpts().CPlusPlus && "should not use C inline rules in C++"
) ? static_cast<void> (0) : __assert_fail ("!Context.getLangOpts().CPlusPlus && \"should not use C inline rules in C++\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3494, __PRETTY_FUNCTION__))
;
3495
3496 // C99 6.7.4p6:
3497 // [...] If all of the file scope declarations for a function in a
3498 // translation unit include the inline function specifier without extern,
3499 // then the definition in that translation unit is an inline definition.
3500 for (auto Redecl : redecls()) {
3501 if (RedeclForcesDefC99(Redecl))
3502 return true;
3503 }
3504
3505 // C99 6.7.4p6:
3506 // An inline definition does not provide an external definition for the
3507 // function, and does not forbid an external definition in another
3508 // translation unit.
3509 return false;
3510}
3511
3512/// getOverloadedOperator - Which C++ overloaded operator this
3513/// function represents, if any.
3514OverloadedOperatorKind FunctionDecl::getOverloadedOperator() const {
3515 if (getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
3516 return getDeclName().getCXXOverloadedOperator();
3517 else
3518 return OO_None;
3519}
3520
3521/// getLiteralIdentifier - The literal suffix identifier this function
3522/// represents, if any.
3523const IdentifierInfo *FunctionDecl::getLiteralIdentifier() const {
3524 if (getDeclName().getNameKind() == DeclarationName::CXXLiteralOperatorName)
3525 return getDeclName().getCXXLiteralIdentifier();
3526 else
3527 return nullptr;
3528}
3529
3530FunctionDecl::TemplatedKind FunctionDecl::getTemplatedKind() const {
3531 if (TemplateOrSpecialization.isNull())
3532 return TK_NonTemplate;
3533 if (TemplateOrSpecialization.is<FunctionTemplateDecl *>())
3534 return TK_FunctionTemplate;
3535 if (TemplateOrSpecialization.is<MemberSpecializationInfo *>())
3536 return TK_MemberSpecialization;
3537 if (TemplateOrSpecialization.is<FunctionTemplateSpecializationInfo *>())
3538 return TK_FunctionTemplateSpecialization;
3539 if (TemplateOrSpecialization.is
3540 <DependentFunctionTemplateSpecializationInfo*>())
3541 return TK_DependentFunctionTemplateSpecialization;
3542
3543 llvm_unreachable("Did we miss a TemplateOrSpecialization type?")::llvm::llvm_unreachable_internal("Did we miss a TemplateOrSpecialization type?"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3543)
;
3544}
3545
3546FunctionDecl *FunctionDecl::getInstantiatedFromMemberFunction() const {
3547 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo())
3548 return cast<FunctionDecl>(Info->getInstantiatedFrom());
3549
3550 return nullptr;
3551}
3552
3553MemberSpecializationInfo *FunctionDecl::getMemberSpecializationInfo() const {
3554 if (auto *MSI =
3555 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3556 return MSI;
3557 if (auto *FTSI = TemplateOrSpecialization
3558 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3559 return FTSI->getMemberSpecializationInfo();
3560 return nullptr;
3561}
3562
3563void
3564FunctionDecl::setInstantiationOfMemberFunction(ASTContext &C,
3565 FunctionDecl *FD,
3566 TemplateSpecializationKind TSK) {
3567 assert(TemplateOrSpecialization.isNull() &&((TemplateOrSpecialization.isNull() && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3568, __PRETTY_FUNCTION__))
3568 "Member function is already a specialization")((TemplateOrSpecialization.isNull() && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3568, __PRETTY_FUNCTION__))
;
3569 MemberSpecializationInfo *Info
3570 = new (C) MemberSpecializationInfo(FD, TSK);
3571 TemplateOrSpecialization = Info;
3572}
3573
3574FunctionTemplateDecl *FunctionDecl::getDescribedFunctionTemplate() const {
3575 return TemplateOrSpecialization.dyn_cast<FunctionTemplateDecl *>();
3576}
3577
3578void FunctionDecl::setDescribedFunctionTemplate(FunctionTemplateDecl *Template) {
3579 assert(TemplateOrSpecialization.isNull() &&((TemplateOrSpecialization.isNull() && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3580, __PRETTY_FUNCTION__))
3580 "Member function is already a specialization")((TemplateOrSpecialization.isNull() && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("TemplateOrSpecialization.isNull() && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3580, __PRETTY_FUNCTION__))
;
3581 TemplateOrSpecialization = Template;
3582}
3583
3584bool FunctionDecl::isImplicitlyInstantiable() const {
3585 // If the function is invalid, it can't be implicitly instantiated.
3586 if (isInvalidDecl())
3587 return false;
3588
3589 switch (getTemplateSpecializationKindForInstantiation()) {
3590 case TSK_Undeclared:
3591 case TSK_ExplicitInstantiationDefinition:
3592 case TSK_ExplicitSpecialization:
3593 return false;
3594
3595 case TSK_ImplicitInstantiation:
3596 return true;
3597
3598 case TSK_ExplicitInstantiationDeclaration:
3599 // Handled below.
3600 break;
3601 }
3602
3603 // Find the actual template from which we will instantiate.
3604 const FunctionDecl *PatternDecl = getTemplateInstantiationPattern();
3605 bool HasPattern = false;
3606 if (PatternDecl)
3607 HasPattern = PatternDecl->hasBody(PatternDecl);
3608
3609 // C++0x [temp.explicit]p9:
3610 // Except for inline functions, other explicit instantiation declarations
3611 // have the effect of suppressing the implicit instantiation of the entity
3612 // to which they refer.
3613 if (!HasPattern || !PatternDecl)
3614 return true;
3615
3616 return PatternDecl->isInlined();
3617}
3618
3619bool FunctionDecl::isTemplateInstantiation() const {
3620 // FIXME: Remove this, it's not clear what it means. (Which template
3621 // specialization kind?)
3622 return clang::isTemplateInstantiation(getTemplateSpecializationKind());
3623}
3624
3625FunctionDecl *
3626FunctionDecl::getTemplateInstantiationPattern(bool ForDefinition) const {
3627 // If this is a generic lambda call operator specialization, its
3628 // instantiation pattern is always its primary template's pattern
3629 // even if its primary template was instantiated from another
3630 // member template (which happens with nested generic lambdas).
3631 // Since a lambda's call operator's body is transformed eagerly,
3632 // we don't have to go hunting for a prototype definition template
3633 // (i.e. instantiated-from-member-template) to use as an instantiation
3634 // pattern.
3635
3636 if (isGenericLambdaCallOperatorSpecialization(
3637 dyn_cast<CXXMethodDecl>(this))) {
3638 assert(getPrimaryTemplate() && "not a generic lambda call operator?")((getPrimaryTemplate() && "not a generic lambda call operator?"
) ? static_cast<void> (0) : __assert_fail ("getPrimaryTemplate() && \"not a generic lambda call operator?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3638, __PRETTY_FUNCTION__))
;
3639 return getDefinitionOrSelf(getPrimaryTemplate()->getTemplatedDecl());
3640 }
3641
3642 if (MemberSpecializationInfo *Info = getMemberSpecializationInfo()) {
3643 if (ForDefinition &&
3644 !clang::isTemplateInstantiation(Info->getTemplateSpecializationKind()))
3645 return nullptr;
3646 return getDefinitionOrSelf(cast<FunctionDecl>(Info->getInstantiatedFrom()));
3647 }
3648
3649 if (ForDefinition &&
3650 !clang::isTemplateInstantiation(getTemplateSpecializationKind()))
3651 return nullptr;
3652
3653 if (FunctionTemplateDecl *Primary = getPrimaryTemplate()) {
3654 // If we hit a point where the user provided a specialization of this
3655 // template, we're done looking.
3656 while (!ForDefinition || !Primary->isMemberSpecialization()) {
3657 auto *NewPrimary = Primary->getInstantiatedFromMemberTemplate();
3658 if (!NewPrimary)
3659 break;
3660 Primary = NewPrimary;
3661 }
3662
3663 return getDefinitionOrSelf(Primary->getTemplatedDecl());
3664 }
3665
3666 return nullptr;
3667}
3668
3669FunctionTemplateDecl *FunctionDecl::getPrimaryTemplate() const {
3670 if (FunctionTemplateSpecializationInfo *Info
3671 = TemplateOrSpecialization
3672 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3673 return Info->getTemplate();
3674 }
3675 return nullptr;
3676}
3677
3678FunctionTemplateSpecializationInfo *
3679FunctionDecl::getTemplateSpecializationInfo() const {
3680 return TemplateOrSpecialization
3681 .dyn_cast<FunctionTemplateSpecializationInfo *>();
3682}
3683
3684const TemplateArgumentList *
3685FunctionDecl::getTemplateSpecializationArgs() const {
3686 if (FunctionTemplateSpecializationInfo *Info
3687 = TemplateOrSpecialization
3688 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3689 return Info->TemplateArguments;
3690 }
3691 return nullptr;
3692}
3693
3694const ASTTemplateArgumentListInfo *
3695FunctionDecl::getTemplateSpecializationArgsAsWritten() const {
3696 if (FunctionTemplateSpecializationInfo *Info
3697 = TemplateOrSpecialization
3698 .dyn_cast<FunctionTemplateSpecializationInfo*>()) {
3699 return Info->TemplateArgumentsAsWritten;
3700 }
3701 return nullptr;
3702}
3703
3704void
3705FunctionDecl::setFunctionTemplateSpecialization(ASTContext &C,
3706 FunctionTemplateDecl *Template,
3707 const TemplateArgumentList *TemplateArgs,
3708 void *InsertPos,
3709 TemplateSpecializationKind TSK,
3710 const TemplateArgumentListInfo *TemplateArgsAsWritten,
3711 SourceLocation PointOfInstantiation) {
3712 assert((TemplateOrSpecialization.isNull() ||(((TemplateOrSpecialization.isNull() || TemplateOrSpecialization
.is<MemberSpecializationInfo *>()) && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3714, __PRETTY_FUNCTION__))
3713 TemplateOrSpecialization.is<MemberSpecializationInfo *>()) &&(((TemplateOrSpecialization.isNull() || TemplateOrSpecialization
.is<MemberSpecializationInfo *>()) && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3714, __PRETTY_FUNCTION__))
3714 "Member function is already a specialization")(((TemplateOrSpecialization.isNull() || TemplateOrSpecialization
.is<MemberSpecializationInfo *>()) && "Member function is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TemplateOrSpecialization.is<MemberSpecializationInfo *>()) && \"Member function is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3714, __PRETTY_FUNCTION__))
;
3715 assert(TSK != TSK_Undeclared &&((TSK != TSK_Undeclared && "Must specify the type of function template specialization"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Must specify the type of function template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3716, __PRETTY_FUNCTION__))
3716 "Must specify the type of function template specialization")((TSK != TSK_Undeclared && "Must specify the type of function template specialization"
) ? static_cast<void> (0) : __assert_fail ("TSK != TSK_Undeclared && \"Must specify the type of function template specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3716, __PRETTY_FUNCTION__))
;
3717 assert((TemplateOrSpecialization.isNull() ||(((TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization
) && "Member specialization must be an explicit specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization) && \"Member specialization must be an explicit specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3719, __PRETTY_FUNCTION__))
3718 TSK == TSK_ExplicitSpecialization) &&(((TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization
) && "Member specialization must be an explicit specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization) && \"Member specialization must be an explicit specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3719, __PRETTY_FUNCTION__))
3719 "Member specialization must be an explicit specialization")(((TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization
) && "Member specialization must be an explicit specialization"
) ? static_cast<void> (0) : __assert_fail ("(TemplateOrSpecialization.isNull() || TSK == TSK_ExplicitSpecialization) && \"Member specialization must be an explicit specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3719, __PRETTY_FUNCTION__))
;
3720 FunctionTemplateSpecializationInfo *Info =
3721 FunctionTemplateSpecializationInfo::Create(
3722 C, this, Template, TSK, TemplateArgs, TemplateArgsAsWritten,
3723 PointOfInstantiation,
3724 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>());
3725 TemplateOrSpecialization = Info;
3726 Template->addSpecialization(Info, InsertPos);
3727}
3728
3729void
3730FunctionDecl::setDependentTemplateSpecialization(ASTContext &Context,
3731 const UnresolvedSetImpl &Templates,
3732 const TemplateArgumentListInfo &TemplateArgs) {
3733 assert(TemplateOrSpecialization.isNull())((TemplateOrSpecialization.isNull()) ? static_cast<void>
(0) : __assert_fail ("TemplateOrSpecialization.isNull()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3733, __PRETTY_FUNCTION__))
;
1
'?' condition is true
3734 DependentFunctionTemplateSpecializationInfo *Info =
3735 DependentFunctionTemplateSpecializationInfo::Create(Context, Templates,
2
Calling 'DependentFunctionTemplateSpecializationInfo::Create'
3736 TemplateArgs);
3737 TemplateOrSpecialization = Info;
3738}
3739
3740DependentFunctionTemplateSpecializationInfo *
3741FunctionDecl::getDependentSpecializationInfo() const {
3742 return TemplateOrSpecialization
3743 .dyn_cast<DependentFunctionTemplateSpecializationInfo *>();
3744}
3745
3746DependentFunctionTemplateSpecializationInfo *
3747DependentFunctionTemplateSpecializationInfo::Create(
3748 ASTContext &Context, const UnresolvedSetImpl &Ts,
3749 const TemplateArgumentListInfo &TArgs) {
3750 void *Buffer = Context.Allocate(
3751 totalSizeToAlloc<TemplateArgumentLoc, FunctionTemplateDecl *>(
3752 TArgs.size(), Ts.size()));
3753 return new (Buffer) DependentFunctionTemplateSpecializationInfo(Ts, TArgs);
3
Calling constructor for 'DependentFunctionTemplateSpecializationInfo'
3754}
3755
3756DependentFunctionTemplateSpecializationInfo::
3757DependentFunctionTemplateSpecializationInfo(const UnresolvedSetImpl &Ts,
3758 const TemplateArgumentListInfo &TArgs)
3759 : AngleLocs(TArgs.getLAngleLoc(), TArgs.getRAngleLoc()) {
3760 NumTemplates = Ts.size();
3761 NumArgs = TArgs.size();
3762
3763 FunctionTemplateDecl **TsArray = getTrailingObjects<FunctionTemplateDecl *>();
3764 for (unsigned I = 0, E = Ts.size(); I != E; ++I)
4
Assuming 'I' is equal to 'E'
5
Loop condition is false. Execution continues on line 3767
3765 TsArray[I] = cast<FunctionTemplateDecl>(Ts[I]->getUnderlyingDecl());
3766
3767 TemplateArgumentLoc *ArgsArray = getTrailingObjects<TemplateArgumentLoc>();
6
Calling 'TrailingObjects::getTrailingObjects'
15
Returning from 'TrailingObjects::getTrailingObjects'
16
'ArgsArray' initialized here
3768 for (unsigned I = 0, E = TArgs.size(); I != E; ++I)
17
Assuming 'I' is not equal to 'E'
18
Loop condition is true. Entering loop body
3769 new (&ArgsArray[I]) TemplateArgumentLoc(TArgs[I]);
19
Storage provided to placement new is only 0 bytes, whereas the allocated type requires 32 bytes
3770}
3771
3772TemplateSpecializationKind FunctionDecl::getTemplateSpecializationKind() const {
3773 // For a function template specialization, query the specialization
3774 // information object.
3775 if (FunctionTemplateSpecializationInfo *FTSInfo =
3776 TemplateOrSpecialization
3777 .dyn_cast<FunctionTemplateSpecializationInfo *>())
3778 return FTSInfo->getTemplateSpecializationKind();
3779
3780 if (MemberSpecializationInfo *MSInfo =
3781 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3782 return MSInfo->getTemplateSpecializationKind();
3783
3784 return TSK_Undeclared;
3785}
3786
3787TemplateSpecializationKind
3788FunctionDecl::getTemplateSpecializationKindForInstantiation() const {
3789 // This is the same as getTemplateSpecializationKind(), except that for a
3790 // function that is both a function template specialization and a member
3791 // specialization, we prefer the member specialization information. Eg:
3792 //
3793 // template<typename T> struct A {
3794 // template<typename U> void f() {}
3795 // template<> void f<int>() {}
3796 // };
3797 //
3798 // For A<int>::f<int>():
3799 // * getTemplateSpecializationKind() will return TSK_ExplicitSpecialization
3800 // * getTemplateSpecializationKindForInstantiation() will return
3801 // TSK_ImplicitInstantiation
3802 //
3803 // This reflects the facts that A<int>::f<int> is an explicit specialization
3804 // of A<int>::f, and that A<int>::f<int> should be implicitly instantiated
3805 // from A::f<int> if a definition is needed.
3806 if (FunctionTemplateSpecializationInfo *FTSInfo =
3807 TemplateOrSpecialization
3808 .dyn_cast<FunctionTemplateSpecializationInfo *>()) {
3809 if (auto *MSInfo = FTSInfo->getMemberSpecializationInfo())
3810 return MSInfo->getTemplateSpecializationKind();
3811 return FTSInfo->getTemplateSpecializationKind();
3812 }
3813
3814 if (MemberSpecializationInfo *MSInfo =
3815 TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo *>())
3816 return MSInfo->getTemplateSpecializationKind();
3817
3818 return TSK_Undeclared;
3819}
3820
3821void
3822FunctionDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
3823 SourceLocation PointOfInstantiation) {
3824 if (FunctionTemplateSpecializationInfo *FTSInfo
3825 = TemplateOrSpecialization.dyn_cast<
3826 FunctionTemplateSpecializationInfo*>()) {
3827 FTSInfo->setTemplateSpecializationKind(TSK);
3828 if (TSK != TSK_ExplicitSpecialization &&
3829 PointOfInstantiation.isValid() &&
3830 FTSInfo->getPointOfInstantiation().isInvalid()) {
3831 FTSInfo->setPointOfInstantiation(PointOfInstantiation);
3832 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3833 L->InstantiationRequested(this);
3834 }
3835 } else if (MemberSpecializationInfo *MSInfo
3836 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>()) {
3837 MSInfo->setTemplateSpecializationKind(TSK);
3838 if (TSK != TSK_ExplicitSpecialization &&
3839 PointOfInstantiation.isValid() &&
3840 MSInfo->getPointOfInstantiation().isInvalid()) {
3841 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3842 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
3843 L->InstantiationRequested(this);
3844 }
3845 } else
3846 llvm_unreachable("Function cannot have a template specialization kind")::llvm::llvm_unreachable_internal("Function cannot have a template specialization kind"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3846)
;
3847}
3848
3849SourceLocation FunctionDecl::getPointOfInstantiation() const {
3850 if (FunctionTemplateSpecializationInfo *FTSInfo
3851 = TemplateOrSpecialization.dyn_cast<
3852 FunctionTemplateSpecializationInfo*>())
3853 return FTSInfo->getPointOfInstantiation();
3854 else if (MemberSpecializationInfo *MSInfo
3855 = TemplateOrSpecialization.dyn_cast<MemberSpecializationInfo*>())
3856 return MSInfo->getPointOfInstantiation();
3857
3858 return SourceLocation();
3859}
3860
3861bool FunctionDecl::isOutOfLine() const {
3862 if (Decl::isOutOfLine())
3863 return true;
3864
3865 // If this function was instantiated from a member function of a
3866 // class template, check whether that member function was defined out-of-line.
3867 if (FunctionDecl *FD = getInstantiatedFromMemberFunction()) {
3868 const FunctionDecl *Definition;
3869 if (FD->hasBody(Definition))
3870 return Definition->isOutOfLine();
3871 }
3872
3873 // If this function was instantiated from a function template,
3874 // check whether that function template was defined out-of-line.
3875 if (FunctionTemplateDecl *FunTmpl = getPrimaryTemplate()) {
3876 const FunctionDecl *Definition;
3877 if (FunTmpl->getTemplatedDecl()->hasBody(Definition))
3878 return Definition->isOutOfLine();
3879 }
3880
3881 return false;
3882}
3883
3884SourceRange FunctionDecl::getSourceRange() const {
3885 return SourceRange(getOuterLocStart(), EndRangeLoc);
3886}
3887
3888unsigned FunctionDecl::getMemoryFunctionKind() const {
3889 IdentifierInfo *FnInfo = getIdentifier();
3890
3891 if (!FnInfo)
3892 return 0;
3893
3894 // Builtin handling.
3895 switch (getBuiltinID()) {
3896 case Builtin::BI__builtin_memset:
3897 case Builtin::BI__builtin___memset_chk:
3898 case Builtin::BImemset:
3899 return Builtin::BImemset;
3900
3901 case Builtin::BI__builtin_memcpy:
3902 case Builtin::BI__builtin___memcpy_chk:
3903 case Builtin::BImemcpy:
3904 return Builtin::BImemcpy;
3905
3906 case Builtin::BI__builtin_mempcpy:
3907 case Builtin::BI__builtin___mempcpy_chk:
3908 case Builtin::BImempcpy:
3909 return Builtin::BImempcpy;
3910
3911 case Builtin::BI__builtin_memmove:
3912 case Builtin::BI__builtin___memmove_chk:
3913 case Builtin::BImemmove:
3914 return Builtin::BImemmove;
3915
3916// case Builtin::BIstrlcpy:
3917// case Builtin::BI__builtin___strlcpy_chk:
3918// return Builtin::BIstrlcpy;
3919
3920// case Builtin::BIstrlcat:
3921// case Builtin::BI__builtin___strlcat_chk:
3922// return Builtin::BIstrlcat;
3923
3924 case Builtin::BI__builtin_memcmp:
3925 case Builtin::BImemcmp:
3926 return Builtin::BImemcmp;
3927
3928 case Builtin::BI__builtin_bcmp:
3929 case Builtin::BIbcmp:
3930 return Builtin::BIbcmp;
3931
3932 case Builtin::BI__builtin_strncpy:
3933 case Builtin::BI__builtin___strncpy_chk:
3934 case Builtin::BIstrncpy:
3935 return Builtin::BIstrncpy;
3936
3937 case Builtin::BI__builtin_strncmp:
3938 case Builtin::BIstrncmp:
3939 return Builtin::BIstrncmp;
3940
3941 case Builtin::BI__builtin_strncasecmp:
3942 case Builtin::BIstrncasecmp:
3943 return Builtin::BIstrncasecmp;
3944
3945 case Builtin::BI__builtin_strncat:
3946 case Builtin::BI__builtin___strncat_chk:
3947 case Builtin::BIstrncat:
3948 return Builtin::BIstrncat;
3949
3950 case Builtin::BI__builtin_strndup:
3951 case Builtin::BIstrndup:
3952 return Builtin::BIstrndup;
3953
3954 case Builtin::BI__builtin_strlen:
3955 case Builtin::BIstrlen:
3956 return Builtin::BIstrlen;
3957
3958 case Builtin::BI__builtin_bzero:
3959 case Builtin::BIbzero:
3960 return Builtin::BIbzero;
3961
3962 default:
3963 if (isExternC()) {
3964 if (FnInfo->isStr("memset"))
3965 return Builtin::BImemset;
3966 else if (FnInfo->isStr("memcpy"))
3967 return Builtin::BImemcpy;
3968 else if (FnInfo->isStr("mempcpy"))
3969 return Builtin::BImempcpy;
3970 else if (FnInfo->isStr("memmove"))
3971 return Builtin::BImemmove;
3972 else if (FnInfo->isStr("memcmp"))
3973 return Builtin::BImemcmp;
3974 else if (FnInfo->isStr("bcmp"))
3975 return Builtin::BIbcmp;
3976 else if (FnInfo->isStr("strncpy"))
3977 return Builtin::BIstrncpy;
3978 else if (FnInfo->isStr("strncmp"))
3979 return Builtin::BIstrncmp;
3980 else if (FnInfo->isStr("strncasecmp"))
3981 return Builtin::BIstrncasecmp;
3982 else if (FnInfo->isStr("strncat"))
3983 return Builtin::BIstrncat;
3984 else if (FnInfo->isStr("strndup"))
3985 return Builtin::BIstrndup;
3986 else if (FnInfo->isStr("strlen"))
3987 return Builtin::BIstrlen;
3988 else if (FnInfo->isStr("bzero"))
3989 return Builtin::BIbzero;
3990 }
3991 break;
3992 }
3993 return 0;
3994}
3995
3996unsigned FunctionDecl::getODRHash() const {
3997 assert(hasODRHash())((hasODRHash()) ? static_cast<void> (0) : __assert_fail
("hasODRHash()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 3997, __PRETTY_FUNCTION__))
;
3998 return ODRHash;
3999}
4000
4001unsigned FunctionDecl::getODRHash() {
4002 if (hasODRHash())
4003 return ODRHash;
4004
4005 if (auto *FT = getInstantiatedFromMemberFunction()) {
4006 setHasODRHash(true);
4007 ODRHash = FT->getODRHash();
4008 return ODRHash;
4009 }
4010
4011 class ODRHash Hash;
4012 Hash.AddFunctionDecl(this);
4013 setHasODRHash(true);
4014 ODRHash = Hash.CalculateHash();
4015 return ODRHash;
4016}
4017
4018//===----------------------------------------------------------------------===//
4019// FieldDecl Implementation
4020//===----------------------------------------------------------------------===//
4021
4022FieldDecl *FieldDecl::Create(const ASTContext &C, DeclContext *DC,
4023 SourceLocation StartLoc, SourceLocation IdLoc,
4024 IdentifierInfo *Id, QualType T,
4025 TypeSourceInfo *TInfo, Expr *BW, bool Mutable,
4026 InClassInitStyle InitStyle) {
4027 return new (C, DC) FieldDecl(Decl::Field, DC, StartLoc, IdLoc, Id, T, TInfo,
4028 BW, Mutable, InitStyle);
4029}
4030
4031FieldDecl *FieldDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4032 return new (C, ID) FieldDecl(Field, nullptr, SourceLocation(),
4033 SourceLocation(), nullptr, QualType(), nullptr,
4034 nullptr, false, ICIS_NoInit);
4035}
4036
4037bool FieldDecl::isAnonymousStructOrUnion() const {
4038 if (!isImplicit() || getDeclName())
4039 return false;
4040
4041 if (const auto *Record = getType()->getAs<RecordType>())
4042 return Record->getDecl()->isAnonymousStructOrUnion();
4043
4044 return false;
4045}
4046
4047unsigned FieldDecl::getBitWidthValue(const ASTContext &Ctx) const {
4048 assert(isBitField() && "not a bitfield")((isBitField() && "not a bitfield") ? static_cast<
void> (0) : __assert_fail ("isBitField() && \"not a bitfield\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4048, __PRETTY_FUNCTION__))
;
4049 return getBitWidth()->EvaluateKnownConstInt(Ctx).getZExtValue();
4050}
4051
4052bool FieldDecl::isZeroLengthBitField(const ASTContext &Ctx) const {
4053 return isUnnamedBitfield() && !getBitWidth()->isValueDependent() &&
4054 getBitWidthValue(Ctx) == 0;
4055}
4056
4057bool FieldDecl::isZeroSize(const ASTContext &Ctx) const {
4058 if (isZeroLengthBitField(Ctx))
4059 return true;
4060
4061 // C++2a [intro.object]p7:
4062 // An object has nonzero size if it
4063 // -- is not a potentially-overlapping subobject, or
4064 if (!hasAttr<NoUniqueAddressAttr>())
4065 return false;
4066
4067 // -- is not of class type, or
4068 const auto *RT = getType()->getAs<RecordType>();
4069 if (!RT)
4070 return false;
4071 const RecordDecl *RD = RT->getDecl()->getDefinition();
4072 if (!RD) {
4073 assert(isInvalidDecl() && "valid field has incomplete type")((isInvalidDecl() && "valid field has incomplete type"
) ? static_cast<void> (0) : __assert_fail ("isInvalidDecl() && \"valid field has incomplete type\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4073, __PRETTY_FUNCTION__))
;
4074 return false;
4075 }
4076
4077 // -- [has] virtual member functions or virtual base classes, or
4078 // -- has subobjects of nonzero size or bit-fields of nonzero length
4079 const auto *CXXRD = cast<CXXRecordDecl>(RD);
4080 if (!CXXRD->isEmpty())
4081 return false;
4082
4083 // Otherwise, [...] the circumstances under which the object has zero size
4084 // are implementation-defined.
4085 // FIXME: This might be Itanium ABI specific; we don't yet know what the MS
4086 // ABI will do.
4087 return true;
4088}
4089
4090unsigned FieldDecl::getFieldIndex() const {
4091 const FieldDecl *Canonical = getCanonicalDecl();
4092 if (Canonical != this)
4093 return Canonical->getFieldIndex();
4094
4095 if (CachedFieldIndex) return CachedFieldIndex - 1;
4096
4097 unsigned Index = 0;
4098 const RecordDecl *RD = getParent()->getDefinition();
4099 assert(RD && "requested index for field of struct with no definition")((RD && "requested index for field of struct with no definition"
) ? static_cast<void> (0) : __assert_fail ("RD && \"requested index for field of struct with no definition\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4099, __PRETTY_FUNCTION__))
;
4100
4101 for (auto *Field : RD->fields()) {
4102 Field->getCanonicalDecl()->CachedFieldIndex = Index + 1;
4103 ++Index;
4104 }
4105
4106 assert(CachedFieldIndex && "failed to find field in parent")((CachedFieldIndex && "failed to find field in parent"
) ? static_cast<void> (0) : __assert_fail ("CachedFieldIndex && \"failed to find field in parent\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4106, __PRETTY_FUNCTION__))
;
4107 return CachedFieldIndex - 1;
4108}
4109
4110SourceRange FieldDecl::getSourceRange() const {
4111 const Expr *FinalExpr = getInClassInitializer();
4112 if (!FinalExpr)
4113 FinalExpr = getBitWidth();
4114 if (FinalExpr)
4115 return SourceRange(getInnerLocStart(), FinalExpr->getEndLoc());
4116 return DeclaratorDecl::getSourceRange();
4117}
4118
4119void FieldDecl::setCapturedVLAType(const VariableArrayType *VLAType) {
4120 assert((getParent()->isLambda() || getParent()->isCapturedRecord()) &&(((getParent()->isLambda() || getParent()->isCapturedRecord
()) && "capturing type in non-lambda or captured record."
) ? static_cast<void> (0) : __assert_fail ("(getParent()->isLambda() || getParent()->isCapturedRecord()) && \"capturing type in non-lambda or captured record.\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4121, __PRETTY_FUNCTION__))
4121 "capturing type in non-lambda or captured record.")(((getParent()->isLambda() || getParent()->isCapturedRecord
()) && "capturing type in non-lambda or captured record."
) ? static_cast<void> (0) : __assert_fail ("(getParent()->isLambda() || getParent()->isCapturedRecord()) && \"capturing type in non-lambda or captured record.\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4121, __PRETTY_FUNCTION__))
;
4122 assert(InitStorage.getInt() == ISK_NoInit &&((InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer
() == nullptr && "bit width, initializer or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4124, __PRETTY_FUNCTION__))
4123 InitStorage.getPointer() == nullptr &&((InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer
() == nullptr && "bit width, initializer or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4124, __PRETTY_FUNCTION__))
4124 "bit width, initializer or captured type already set")((InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer
() == nullptr && "bit width, initializer or captured type already set"
) ? static_cast<void> (0) : __assert_fail ("InitStorage.getInt() == ISK_NoInit && InitStorage.getPointer() == nullptr && \"bit width, initializer or captured type already set\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4124, __PRETTY_FUNCTION__))
;
4125 InitStorage.setPointerAndInt(const_cast<VariableArrayType *>(VLAType),
4126 ISK_CapturedVLAType);
4127}
4128
4129//===----------------------------------------------------------------------===//
4130// TagDecl Implementation
4131//===----------------------------------------------------------------------===//
4132
4133TagDecl::TagDecl(Kind DK, TagKind TK, const ASTContext &C, DeclContext *DC,
4134 SourceLocation L, IdentifierInfo *Id, TagDecl *PrevDecl,
4135 SourceLocation StartL)
4136 : TypeDecl(DK, DC, L, Id, StartL), DeclContext(DK), redeclarable_base(C),
4137 TypedefNameDeclOrQualifier((TypedefNameDecl *)nullptr) {
4138 assert((DK != Enum || TK == TTK_Enum) &&(((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum"
) ? static_cast<void> (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4139, __PRETTY_FUNCTION__))
4139 "EnumDecl not matched with TTK_Enum")(((DK != Enum || TK == TTK_Enum) && "EnumDecl not matched with TTK_Enum"
) ? static_cast<void> (0) : __assert_fail ("(DK != Enum || TK == TTK_Enum) && \"EnumDecl not matched with TTK_Enum\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4139, __PRETTY_FUNCTION__))
;
4140 setPreviousDecl(PrevDecl);
4141 setTagKind(TK);
4142 setCompleteDefinition(false);
4143 setBeingDefined(false);
4144 setEmbeddedInDeclarator(false);
4145 setFreeStanding(false);
4146 setCompleteDefinitionRequired(false);
4147}
4148
4149SourceLocation TagDecl::getOuterLocStart() const {
4150 return getTemplateOrInnerLocStart(this);
4151}
4152
4153SourceRange TagDecl::getSourceRange() const {
4154 SourceLocation RBraceLoc = BraceRange.getEnd();
4155 SourceLocation E = RBraceLoc.isValid() ? RBraceLoc : getLocation();
4156 return SourceRange(getOuterLocStart(), E);
4157}
4158
4159TagDecl *TagDecl::getCanonicalDecl() { return getFirstDecl(); }
4160
4161void TagDecl::setTypedefNameForAnonDecl(TypedefNameDecl *TDD) {
4162 TypedefNameDeclOrQualifier = TDD;
4163 if (const Type *T = getTypeForDecl()) {
4164 (void)T;
4165 assert(T->isLinkageValid())((T->isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("T->isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4165, __PRETTY_FUNCTION__))
;
4166 }
4167 assert(isLinkageValid())((isLinkageValid()) ? static_cast<void> (0) : __assert_fail
("isLinkageValid()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4167, __PRETTY_FUNCTION__))
;
4168}
4169
4170void TagDecl::startDefinition() {
4171 setBeingDefined(true);
4172
4173 if (auto *D = dyn_cast<CXXRecordDecl>(this)) {
4174 struct CXXRecordDecl::DefinitionData *Data =
4175 new (getASTContext()) struct CXXRecordDecl::DefinitionData(D);
4176 for (auto I : redecls())
4177 cast<CXXRecordDecl>(I)->DefinitionData = Data;
4178 }
4179}
4180
4181void TagDecl::completeDefinition() {
4182 assert((!isa<CXXRecordDecl>(this) ||(((!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>
(this)->hasDefinition()) && "definition completed but not started"
) ? static_cast<void> (0) : __assert_fail ("(!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>(this)->hasDefinition()) && \"definition completed but not started\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4184, __PRETTY_FUNCTION__))
4183 cast<CXXRecordDecl>(this)->hasDefinition()) &&(((!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>
(this)->hasDefinition()) && "definition completed but not started"
) ? static_cast<void> (0) : __assert_fail ("(!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>(this)->hasDefinition()) && \"definition completed but not started\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4184, __PRETTY_FUNCTION__))
4184 "definition completed but not started")(((!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>
(this)->hasDefinition()) && "definition completed but not started"
) ? static_cast<void> (0) : __assert_fail ("(!isa<CXXRecordDecl>(this) || cast<CXXRecordDecl>(this)->hasDefinition()) && \"definition completed but not started\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4184, __PRETTY_FUNCTION__))
;
4185
4186 setCompleteDefinition(true);
4187 setBeingDefined(false);
4188
4189 if (ASTMutationListener *L = getASTMutationListener())
4190 L->CompletedTagDefinition(this);
4191}
4192
4193TagDecl *TagDecl::getDefinition() const {
4194 if (isCompleteDefinition())
4195 return const_cast<TagDecl *>(this);
4196
4197 // If it's possible for us to have an out-of-date definition, check now.
4198 if (mayHaveOutOfDateDef()) {
4199 if (IdentifierInfo *II = getIdentifier()) {
4200 if (II->isOutOfDate()) {
4201 updateOutOfDate(*II);
4202 }
4203 }
4204 }
4205
4206 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(this))
4207 return CXXRD->getDefinition();
4208
4209 for (auto R : redecls())
4210 if (R->isCompleteDefinition())
4211 return R;
4212
4213 return nullptr;
4214}
4215
4216void TagDecl::setQualifierInfo(NestedNameSpecifierLoc QualifierLoc) {
4217 if (QualifierLoc) {
4218 // Make sure the extended qualifier info is allocated.
4219 if (!hasExtInfo())
4220 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4221 // Set qualifier info.
4222 getExtInfo()->QualifierLoc = QualifierLoc;
4223 } else {
4224 // Here Qualifier == 0, i.e., we are removing the qualifier (if any).
4225 if (hasExtInfo()) {
4226 if (getExtInfo()->NumTemplParamLists == 0) {
4227 getASTContext().Deallocate(getExtInfo());
4228 TypedefNameDeclOrQualifier = (TypedefNameDecl *)nullptr;
4229 }
4230 else
4231 getExtInfo()->QualifierLoc = QualifierLoc;
4232 }
4233 }
4234}
4235
4236void TagDecl::setTemplateParameterListsInfo(
4237 ASTContext &Context, ArrayRef<TemplateParameterList *> TPLists) {
4238 assert(!TPLists.empty())((!TPLists.empty()) ? static_cast<void> (0) : __assert_fail
("!TPLists.empty()", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4238, __PRETTY_FUNCTION__))
;
4239 // Make sure the extended decl info is allocated.
4240 if (!hasExtInfo())
4241 // Allocate external info struct.
4242 TypedefNameDeclOrQualifier = new (getASTContext()) ExtInfo;
4243 // Set the template parameter lists info.
4244 getExtInfo()->setTemplateParameterListsInfo(Context, TPLists);
4245}
4246
4247//===----------------------------------------------------------------------===//
4248// EnumDecl Implementation
4249//===----------------------------------------------------------------------===//
4250
4251EnumDecl::EnumDecl(ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
4252 SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl,
4253 bool Scoped, bool ScopedUsingClassTag, bool Fixed)
4254 : TagDecl(Enum, TTK_Enum, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4255 assert(Scoped || !ScopedUsingClassTag)((Scoped || !ScopedUsingClassTag) ? static_cast<void> (
0) : __assert_fail ("Scoped || !ScopedUsingClassTag", "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4255, __PRETTY_FUNCTION__))
;
4256 IntegerType = nullptr;
4257 setNumPositiveBits(0);
4258 setNumNegativeBits(0);
4259 setScoped(Scoped);
4260 setScopedUsingClassTag(ScopedUsingClassTag);
4261 setFixed(Fixed);
4262 setHasODRHash(false);
4263 ODRHash = 0;
4264}
4265
4266void EnumDecl::anchor() {}
4267
4268EnumDecl *EnumDecl::Create(ASTContext &C, DeclContext *DC,
4269 SourceLocation StartLoc, SourceLocation IdLoc,
4270 IdentifierInfo *Id,
4271 EnumDecl *PrevDecl, bool IsScoped,
4272 bool IsScopedUsingClassTag, bool IsFixed) {
4273 auto *Enum = new (C, DC) EnumDecl(C, DC, StartLoc, IdLoc, Id, PrevDecl,
4274 IsScoped, IsScopedUsingClassTag, IsFixed);
4275 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4276 C.getTypeDeclType(Enum, PrevDecl);
4277 return Enum;
4278}
4279
4280EnumDecl *EnumDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4281 EnumDecl *Enum =
4282 new (C, ID) EnumDecl(C, nullptr, SourceLocation(), SourceLocation(),
4283 nullptr, nullptr, false, false, false);
4284 Enum->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4285 return Enum;
4286}
4287
4288SourceRange EnumDecl::getIntegerTypeRange() const {
4289 if (const TypeSourceInfo *TI = getIntegerTypeSourceInfo())
4290 return TI->getTypeLoc().getSourceRange();
4291 return SourceRange();
4292}
4293
4294void EnumDecl::completeDefinition(QualType NewType,
4295 QualType NewPromotionType,
4296 unsigned NumPositiveBits,
4297 unsigned NumNegativeBits) {
4298 assert(!isCompleteDefinition() && "Cannot redefine enums!")((!isCompleteDefinition() && "Cannot redefine enums!"
) ? static_cast<void> (0) : __assert_fail ("!isCompleteDefinition() && \"Cannot redefine enums!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4298, __PRETTY_FUNCTION__))
;
4299 if (!IntegerType)
4300 IntegerType = NewType.getTypePtr();
4301 PromotionType = NewPromotionType;
4302 setNumPositiveBits(NumPositiveBits);
4303 setNumNegativeBits(NumNegativeBits);
4304 TagDecl::completeDefinition();
4305}
4306
4307bool EnumDecl::isClosed() const {
4308 if (const auto *A = getAttr<EnumExtensibilityAttr>())
4309 return A->getExtensibility() == EnumExtensibilityAttr::Closed;
4310 return true;
4311}
4312
4313bool EnumDecl::isClosedFlag() const {
4314 return isClosed() && hasAttr<FlagEnumAttr>();
4315}
4316
4317bool EnumDecl::isClosedNonFlag() const {
4318 return isClosed() && !hasAttr<FlagEnumAttr>();
4319}
4320
4321TemplateSpecializationKind EnumDecl::getTemplateSpecializationKind() const {
4322 if (MemberSpecializationInfo *MSI = getMemberSpecializationInfo())
4323 return MSI->getTemplateSpecializationKind();
4324
4325 return TSK_Undeclared;
4326}
4327
4328void EnumDecl::setTemplateSpecializationKind(TemplateSpecializationKind TSK,
4329 SourceLocation PointOfInstantiation) {
4330 MemberSpecializationInfo *MSI = getMemberSpecializationInfo();
4331 assert(MSI && "Not an instantiated member enumeration?")((MSI && "Not an instantiated member enumeration?") ?
static_cast<void> (0) : __assert_fail ("MSI && \"Not an instantiated member enumeration?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4331, __PRETTY_FUNCTION__))
;
4332 MSI->setTemplateSpecializationKind(TSK);
4333 if (TSK != TSK_ExplicitSpecialization &&
4334 PointOfInstantiation.isValid() &&
4335 MSI->getPointOfInstantiation().isInvalid())
4336 MSI->setPointOfInstantiation(PointOfInstantiation);
4337}
4338
4339EnumDecl *EnumDecl::getTemplateInstantiationPattern() const {
4340 if (MemberSpecializationInfo *MSInfo = getMemberSpecializationInfo()) {
4341 if (isTemplateInstantiation(MSInfo->getTemplateSpecializationKind())) {
4342 EnumDecl *ED = getInstantiatedFromMemberEnum();
4343 while (auto *NewED = ED->getInstantiatedFromMemberEnum())
4344 ED = NewED;
4345 return getDefinitionOrSelf(ED);
4346 }
4347 }
4348
4349 assert(!isTemplateInstantiation(getTemplateSpecializationKind()) &&((!isTemplateInstantiation(getTemplateSpecializationKind()) &&
"couldn't find pattern for enum instantiation") ? static_cast
<void> (0) : __assert_fail ("!isTemplateInstantiation(getTemplateSpecializationKind()) && \"couldn't find pattern for enum instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4350, __PRETTY_FUNCTION__))
4350 "couldn't find pattern for enum instantiation")((!isTemplateInstantiation(getTemplateSpecializationKind()) &&
"couldn't find pattern for enum instantiation") ? static_cast
<void> (0) : __assert_fail ("!isTemplateInstantiation(getTemplateSpecializationKind()) && \"couldn't find pattern for enum instantiation\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4350, __PRETTY_FUNCTION__))
;
4351 return nullptr;
4352}
4353
4354EnumDecl *EnumDecl::getInstantiatedFromMemberEnum() const {
4355 if (SpecializationInfo)
4356 return cast<EnumDecl>(SpecializationInfo->getInstantiatedFrom());
4357
4358 return nullptr;
4359}
4360
4361void EnumDecl::setInstantiationOfMemberEnum(ASTContext &C, EnumDecl *ED,
4362 TemplateSpecializationKind TSK) {
4363 assert(!SpecializationInfo && "Member enum is already a specialization")((!SpecializationInfo && "Member enum is already a specialization"
) ? static_cast<void> (0) : __assert_fail ("!SpecializationInfo && \"Member enum is already a specialization\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4363, __PRETTY_FUNCTION__))
;
4364 SpecializationInfo = new (C) MemberSpecializationInfo(ED, TSK);
4365}
4366
4367unsigned EnumDecl::getODRHash() {
4368 if (hasODRHash())
4369 return ODRHash;
4370
4371 class ODRHash Hash;
4372 Hash.AddEnumDecl(this);
4373 setHasODRHash(true);
4374 ODRHash = Hash.CalculateHash();
4375 return ODRHash;
4376}
4377
4378//===----------------------------------------------------------------------===//
4379// RecordDecl Implementation
4380//===----------------------------------------------------------------------===//
4381
4382RecordDecl::RecordDecl(Kind DK, TagKind TK, const ASTContext &C,
4383 DeclContext *DC, SourceLocation StartLoc,
4384 SourceLocation IdLoc, IdentifierInfo *Id,
4385 RecordDecl *PrevDecl)
4386 : TagDecl(DK, TK, C, DC, IdLoc, Id, PrevDecl, StartLoc) {
4387 assert(classof(static_cast<Decl *>(this)) && "Invalid Kind!")((classof(static_cast<Decl *>(this)) && "Invalid Kind!"
) ? static_cast<void> (0) : __assert_fail ("classof(static_cast<Decl *>(this)) && \"Invalid Kind!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4387, __PRETTY_FUNCTION__))
;
4388 setHasFlexibleArrayMember(false);
4389 setAnonymousStructOrUnion(false);
4390 setHasObjectMember(false);
4391 setHasVolatileMember(false);
4392 setHasLoadedFieldsFromExternalStorage(false);
4393 setNonTrivialToPrimitiveDefaultInitialize(false);
4394 setNonTrivialToPrimitiveCopy(false);
4395 setNonTrivialToPrimitiveDestroy(false);
4396 setHasNonTrivialToPrimitiveDefaultInitializeCUnion(false);
4397 setHasNonTrivialToPrimitiveDestructCUnion(false);
4398 setHasNonTrivialToPrimitiveCopyCUnion(false);
4399 setParamDestroyedInCallee(false);
4400 setArgPassingRestrictions(APK_CanPassInRegs);
4401}
4402
4403RecordDecl *RecordDecl::Create(const ASTContext &C, TagKind TK, DeclContext *DC,
4404 SourceLocation StartLoc, SourceLocation IdLoc,
4405 IdentifierInfo *Id, RecordDecl* PrevDecl) {
4406 RecordDecl *R = new (C, DC) RecordDecl(Record, TK, C, DC,
4407 StartLoc, IdLoc, Id, PrevDecl);
4408 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4409
4410 C.getTypeDeclType(R, PrevDecl);
4411 return R;
4412}
4413
4414RecordDecl *RecordDecl::CreateDeserialized(const ASTContext &C, unsigned ID) {
4415 RecordDecl *R =
4416 new (C, ID) RecordDecl(Record, TTK_Struct, C, nullptr, SourceLocation(),
4417 SourceLocation(), nullptr, nullptr);
4418 R->setMayHaveOutOfDateDef(C.getLangOpts().Modules);
4419 return R;
4420}
4421
4422bool RecordDecl::isInjectedClassName() const {
4423 return isImplicit() && getDeclName() && getDeclContext()->isRecord() &&
4424 cast<RecordDecl>(getDeclContext())->getDeclName() == getDeclName();
4425}
4426
4427bool RecordDecl::isLambda() const {
4428 if (auto RD = dyn_cast<CXXRecordDecl>(this))
4429 return RD->isLambda();
4430 return false;
4431}
4432
4433bool RecordDecl::isCapturedRecord() const {
4434 return hasAttr<CapturedRecordAttr>();
4435}
4436
4437void RecordDecl::setCapturedRecord() {
4438 addAttr(CapturedRecordAttr::CreateImplicit(getASTContext()));
4439}
4440
4441bool RecordDecl::isOrContainsUnion() const {
4442 if (isUnion())
4443 return true;
4444
4445 if (const RecordDecl *Def = getDefinition()) {
4446 for (const FieldDecl *FD : Def->fields()) {
4447 const RecordType *RT = FD->getType()->getAs<RecordType>();
4448 if (RT && RT->getDecl()->isOrContainsUnion())
4449 return true;
4450 }
4451 }
4452
4453 return false;
4454}
4455
4456RecordDecl::field_iterator RecordDecl::field_begin() const {
4457 if (hasExternalLexicalStorage() && !hasLoadedFieldsFromExternalStorage())
4458 LoadFieldsFromExternalStorage();
4459
4460 return field_iterator(decl_iterator(FirstDecl));
4461}
4462
4463/// completeDefinition - Notes that the definition of this type is now
4464/// complete.
4465void RecordDecl::completeDefinition() {
4466 assert(!isCompleteDefinition() && "Cannot redefine record!")((!isCompleteDefinition() && "Cannot redefine record!"
) ? static_cast<void> (0) : __assert_fail ("!isCompleteDefinition() && \"Cannot redefine record!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4466, __PRETTY_FUNCTION__))
;
4467 TagDecl::completeDefinition();
4468}
4469
4470/// isMsStruct - Get whether or not this record uses ms_struct layout.
4471/// This which can be turned on with an attribute, pragma, or the
4472/// -mms-bitfields command-line option.
4473bool RecordDecl::isMsStruct(const ASTContext &C) const {
4474 return hasAttr<MSStructAttr>() || C.getLangOpts().MSBitfields == 1;
4475}
4476
4477void RecordDecl::LoadFieldsFromExternalStorage() const {
4478 ExternalASTSource *Source = getASTContext().getExternalSource();
4479 assert(hasExternalLexicalStorage() && Source && "No external storage?")((hasExternalLexicalStorage() && Source && "No external storage?"
) ? static_cast<void> (0) : __assert_fail ("hasExternalLexicalStorage() && Source && \"No external storage?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4479, __PRETTY_FUNCTION__))
;
4480
4481 // Notify that we have a RecordDecl doing some initialization.
4482 ExternalASTSource::Deserializing TheFields(Source);
4483
4484 SmallVector<Decl*, 64> Decls;
4485 setHasLoadedFieldsFromExternalStorage(true);
4486 Source->FindExternalLexicalDecls(this, [](Decl::Kind K) {
4487 return FieldDecl::classofKind(K) || IndirectFieldDecl::classofKind(K);
4488 }, Decls);
4489
4490#ifndef NDEBUG
4491 // Check that all decls we got were FieldDecls.
4492 for (unsigned i=0, e=Decls.size(); i != e; ++i)
4493 assert(isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i]))((isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>
(Decls[i])) ? static_cast<void> (0) : __assert_fail ("isa<FieldDecl>(Decls[i]) || isa<IndirectFieldDecl>(Decls[i])"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4493, __PRETTY_FUNCTION__))
;
4494#endif
4495
4496 if (Decls.empty())
4497 return;
4498
4499 std::tie(FirstDecl, LastDecl) = BuildDeclChain(Decls,
4500 /*FieldsAlreadyLoaded=*/false);
4501}
4502
4503bool RecordDecl::mayInsertExtraPadding(bool EmitRemark) const {
4504 ASTContext &Context = getASTContext();
4505 const SanitizerMask EnabledAsanMask = Context.getLangOpts().Sanitize.Mask &
4506 (SanitizerKind::Address | SanitizerKind::KernelAddress);
4507 if (!EnabledAsanMask || !Context.getLangOpts().SanitizeAddressFieldPadding)
4508 return false;
4509 const auto &Blacklist = Context.getSanitizerBlacklist();
4510 const auto *CXXRD = dyn_cast<CXXRecordDecl>(this);
4511 // We may be able to relax some of these requirements.
4512 int ReasonToReject = -1;
4513 if (!CXXRD || CXXRD->isExternCContext())
4514 ReasonToReject = 0; // is not C++.
4515 else if (CXXRD->hasAttr<PackedAttr>())
4516 ReasonToReject = 1; // is packed.
4517 else if (CXXRD->isUnion())
4518 ReasonToReject = 2; // is a union.
4519 else if (CXXRD->isTriviallyCopyable())
4520 ReasonToReject = 3; // is trivially copyable.
4521 else if (CXXRD->hasTrivialDestructor())
4522 ReasonToReject = 4; // has trivial destructor.
4523 else if (CXXRD->isStandardLayout())
4524 ReasonToReject = 5; // is standard layout.
4525 else if (Blacklist.isBlacklistedLocation(EnabledAsanMask, getLocation(),
4526 "field-padding"))
4527 ReasonToReject = 6; // is in an excluded file.
4528 else if (Blacklist.isBlacklistedType(EnabledAsanMask,
4529 getQualifiedNameAsString(),
4530 "field-padding"))
4531 ReasonToReject = 7; // The type is excluded.
4532
4533 if (EmitRemark) {
4534 if (ReasonToReject >= 0)
4535 Context.getDiagnostics().Report(
4536 getLocation(),
4537 diag::remark_sanitize_address_insert_extra_padding_rejected)
4538 << getQualifiedNameAsString() << ReasonToReject;
4539 else
4540 Context.getDiagnostics().Report(
4541 getLocation(),
4542 diag::remark_sanitize_address_insert_extra_padding_accepted)
4543 << getQualifiedNameAsString();
4544 }
4545 return ReasonToReject < 0;
4546}
4547
4548const FieldDecl *RecordDecl::findFirstNamedDataMember() const {
4549 for (const auto *I : fields()) {
4550 if (I->getIdentifier())
4551 return I;
4552
4553 if (const auto *RT = I->getType()->getAs<RecordType>())
4554 if (const FieldDecl *NamedDataMember =
4555 RT->getDecl()->findFirstNamedDataMember())
4556 return NamedDataMember;
4557 }
4558
4559 // We didn't find a named data member.
4560 return nullptr;
4561}
4562
4563//===----------------------------------------------------------------------===//
4564// BlockDecl Implementation
4565//===----------------------------------------------------------------------===//
4566
4567BlockDecl::BlockDecl(DeclContext *DC, SourceLocation CaretLoc)
4568 : Decl(Block, DC, CaretLoc), DeclContext(Block) {
4569 setIsVariadic(false);
4570 setCapturesCXXThis(false);
4571 setBlockMissingReturnType(true);
4572 setIsConversionFromLambda(false);
4573 setDoesNotEscape(false);
4574 setCanAvoidCopyToHeap(false);
4575}
4576
4577void BlockDecl::setParams(ArrayRef<ParmVarDecl *> NewParamInfo) {
4578 assert(!ParamInfo && "Already has param info!")((!ParamInfo && "Already has param info!") ? static_cast
<void> (0) : __assert_fail ("!ParamInfo && \"Already has param info!\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4578, __PRETTY_FUNCTION__))
;
4579
4580 // Zero params -> null pointer.
4581 if (!NewParamInfo.empty()) {
4582 NumParams = NewParamInfo.size();
4583 ParamInfo = new (getASTContext()) ParmVarDecl*[NewParamInfo.size()];
4584 std::copy(NewParamInfo.begin(), NewParamInfo.end(), ParamInfo);
4585 }
4586}
4587
4588void BlockDecl::setCaptures(ASTContext &Context, ArrayRef<Capture> Captures,
4589 bool CapturesCXXThis) {
4590 this->setCapturesCXXThis(CapturesCXXThis);
4591 this->NumCaptures = Captures.size();
4592
4593 if (Captures.empty()) {
4594 this->Captures = nullptr;
4595 return;
4596 }
4597
4598 this->Captures = Captures.copy(Context).data();
4599}
4600
4601bool BlockDecl::capturesVariable(const VarDecl *variable) const {
4602 for (const auto &I : captures())
4603 // Only auto vars can be captured, so no redeclaration worries.
4604 if (I.getVariable() == variable)
4605 return true;
4606
4607 return false;
4608}
4609
4610SourceRange BlockDecl::getSourceRange() const {
4611 return SourceRange(getLocation(), Body ? Body->getEndLoc() : getLocation());
4612}
4613
4614//===----------------------------------------------------------------------===//
4615// Other Decl Allocation/Deallocation Method Implementations
4616//===----------------------------------------------------------------------===//
4617
4618void TranslationUnitDecl::anchor() {}
4619
4620TranslationUnitDecl *TranslationUnitDecl::Create(ASTContext &C) {
4621 return new (C, (DeclContext *)nullptr) TranslationUnitDecl(C);
4622}
4623
4624void PragmaCommentDecl::anchor() {}
4625
4626PragmaCommentDecl *PragmaCommentDecl::Create(const ASTContext &C,
4627 TranslationUnitDecl *DC,
4628 SourceLocation CommentLoc,
4629 PragmaMSCommentKind CommentKind,
4630 StringRef Arg) {
4631 PragmaCommentDecl *PCD =
4632 new (C, DC, additionalSizeToAlloc<char>(Arg.size() + 1))
4633 PragmaCommentDecl(DC, CommentLoc, CommentKind);
4634 memcpy(PCD->getTrailingObjects<char>(), Arg.data(), Arg.size());
4635 PCD->getTrailingObjects<char>()[Arg.size()] = '\0';
4636 return PCD;
4637}
4638
4639PragmaCommentDecl *PragmaCommentDecl::CreateDeserialized(ASTContext &C,
4640 unsigned ID,
4641 unsigned ArgSize) {
4642 return new (C, ID, additionalSizeToAlloc<char>(ArgSize + 1))
4643 PragmaCommentDecl(nullptr, SourceLocation(), PCK_Unknown);
4644}
4645
4646void PragmaDetectMismatchDecl::anchor() {}
4647
4648PragmaDetectMismatchDecl *
4649PragmaDetectMismatchDecl::Create(const ASTContext &C, TranslationUnitDecl *DC,
4650 SourceLocation Loc, StringRef Name,
4651 StringRef Value) {
4652 size_t ValueStart = Name.size() + 1;
4653 PragmaDetectMismatchDecl *PDMD =
4654 new (C, DC, additionalSizeToAlloc<char>(ValueStart + Value.size() + 1))
4655 PragmaDetectMismatchDecl(DC, Loc, ValueStart);
4656 memcpy(PDMD->getTrailingObjects<char>(), Name.data(), Name.size());
4657 PDMD->getTrailingObjects<char>()[Name.size()] = '\0';
4658 memcpy(PDMD->getTrailingObjects<char>() + ValueStart, Value.data(),
4659 Value.size());
4660 PDMD->getTrailingObjects<char>()[ValueStart + Value.size()] = '\0';
4661 return PDMD;
4662}
4663
4664PragmaDetectMismatchDecl *
4665PragmaDetectMismatchDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4666 unsigned NameValueSize) {
4667 return new (C, ID, additionalSizeToAlloc<char>(NameValueSize + 1))
4668 PragmaDetectMismatchDecl(nullptr, SourceLocation(), 0);
4669}
4670
4671void ExternCContextDecl::anchor() {}
4672
4673ExternCContextDecl *ExternCContextDecl::Create(const ASTContext &C,
4674 TranslationUnitDecl *DC) {
4675 return new (C, DC) ExternCContextDecl(DC);
4676}
4677
4678void LabelDecl::anchor() {}
4679
4680LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4681 SourceLocation IdentL, IdentifierInfo *II) {
4682 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, IdentL);
4683}
4684
4685LabelDecl *LabelDecl::Create(ASTContext &C, DeclContext *DC,
4686 SourceLocation IdentL, IdentifierInfo *II,
4687 SourceLocation GnuLabelL) {
4688 assert(GnuLabelL != IdentL && "Use this only for GNU local labels")((GnuLabelL != IdentL && "Use this only for GNU local labels"
) ? static_cast<void> (0) : __assert_fail ("GnuLabelL != IdentL && \"Use this only for GNU local labels\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4688, __PRETTY_FUNCTION__))
;
4689 return new (C, DC) LabelDecl(DC, IdentL, II, nullptr, GnuLabelL);
4690}
4691
4692LabelDecl *LabelDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4693 return new (C, ID) LabelDecl(nullptr, SourceLocation(), nullptr, nullptr,
4694 SourceLocation());
4695}
4696
4697void LabelDecl::setMSAsmLabel(StringRef Name) {
4698char *Buffer = new (getASTContext(), 1) char[Name.size() + 1];
4699 memcpy(Buffer, Name.data(), Name.size());
4700 Buffer[Name.size()] = '\0';
4701 MSAsmName = Buffer;
4702}
4703
4704void ValueDecl::anchor() {}
4705
4706bool ValueDecl::isWeak() const {
4707 auto *MostRecent = getMostRecentDecl();
4708 return MostRecent->hasAttr<WeakAttr>() ||
4709 MostRecent->hasAttr<WeakRefAttr>() || isWeakImported();
4710}
4711
4712void ImplicitParamDecl::anchor() {}
4713
4714ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, DeclContext *DC,
4715 SourceLocation IdLoc,
4716 IdentifierInfo *Id, QualType Type,
4717 ImplicitParamKind ParamKind) {
4718 return new (C, DC) ImplicitParamDecl(C, DC, IdLoc, Id, Type, ParamKind);
4719}
4720
4721ImplicitParamDecl *ImplicitParamDecl::Create(ASTContext &C, QualType Type,
4722 ImplicitParamKind ParamKind) {
4723 return new (C, nullptr) ImplicitParamDecl(C, Type, ParamKind);
4724}
4725
4726ImplicitParamDecl *ImplicitParamDecl::CreateDeserialized(ASTContext &C,
4727 unsigned ID) {
4728 return new (C, ID) ImplicitParamDecl(C, QualType(), ImplicitParamKind::Other);
4729}
4730
4731FunctionDecl *FunctionDecl::Create(ASTContext &C, DeclContext *DC,
4732 SourceLocation StartLoc,
4733 const DeclarationNameInfo &NameInfo,
4734 QualType T, TypeSourceInfo *TInfo,
4735 StorageClass SC, bool isInlineSpecified,
4736 bool hasWrittenPrototype,
4737 ConstexprSpecKind ConstexprKind,
4738 Expr *TrailingRequiresClause) {
4739 FunctionDecl *New =
4740 new (C, DC) FunctionDecl(Function, C, DC, StartLoc, NameInfo, T, TInfo,
4741 SC, isInlineSpecified, ConstexprKind,
4742 TrailingRequiresClause);
4743 New->setHasWrittenPrototype(hasWrittenPrototype);
4744 return New;
4745}
4746
4747FunctionDecl *FunctionDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4748 return new (C, ID) FunctionDecl(Function, C, nullptr, SourceLocation(),
4749 DeclarationNameInfo(), QualType(), nullptr,
4750 SC_None, false, CSK_unspecified, nullptr);
4751}
4752
4753BlockDecl *BlockDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4754 return new (C, DC) BlockDecl(DC, L);
4755}
4756
4757BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4758 return new (C, ID) BlockDecl(nullptr, SourceLocation());
4759}
4760
4761CapturedDecl::CapturedDecl(DeclContext *DC, unsigned NumParams)
4762 : Decl(Captured, DC, SourceLocation()), DeclContext(Captured),
4763 NumParams(NumParams), ContextParam(0), BodyAndNothrow(nullptr, false) {}
4764
4765CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
4766 unsigned NumParams) {
4767 return new (C, DC, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4768 CapturedDecl(DC, NumParams);
4769}
4770
4771CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4772 unsigned NumParams) {
4773 return new (C, ID, additionalSizeToAlloc<ImplicitParamDecl *>(NumParams))
4774 CapturedDecl(nullptr, NumParams);
4775}
4776
4777Stmt *CapturedDecl::getBody() const { return BodyAndNothrow.getPointer(); }
4778void CapturedDecl::setBody(Stmt *B) { BodyAndNothrow.setPointer(B); }
4779
4780bool CapturedDecl::isNothrow() const { return BodyAndNothrow.getInt(); }
4781void CapturedDecl::setNothrow(bool Nothrow) { BodyAndNothrow.setInt(Nothrow); }
4782
4783EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
4784 SourceLocation L,
4785 IdentifierInfo *Id, QualType T,
4786 Expr *E, const llvm::APSInt &V) {
4787 return new (C, CD) EnumConstantDecl(CD, L, Id, T, E, V);
4788}
4789
4790EnumConstantDecl *
4791EnumConstantDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4792 return new (C, ID) EnumConstantDecl(nullptr, SourceLocation(), nullptr,
4793 QualType(), nullptr, llvm::APSInt());
4794}
4795
4796void IndirectFieldDecl::anchor() {}
4797
4798IndirectFieldDecl::IndirectFieldDecl(ASTContext &C, DeclContext *DC,
4799 SourceLocation L, DeclarationName N,
4800 QualType T,
4801 MutableArrayRef<NamedDecl *> CH)
4802 : ValueDecl(IndirectField, DC, L, N, T), Chaining(CH.data()),
4803 ChainingSize(CH.size()) {
4804 // In C++, indirect field declarations conflict with tag declarations in the
4805 // same scope, so add them to IDNS_Tag so that tag redeclaration finds them.
4806 if (C.getLangOpts().CPlusPlus)
4807 IdentifierNamespace |= IDNS_Tag;
4808}
4809
4810IndirectFieldDecl *
4811IndirectFieldDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L,
4812 IdentifierInfo *Id, QualType T,
4813 llvm::MutableArrayRef<NamedDecl *> CH) {
4814 return new (C, DC) IndirectFieldDecl(C, DC, L, Id, T, CH);
4815}
4816
4817IndirectFieldDecl *IndirectFieldDecl::CreateDeserialized(ASTContext &C,
4818 unsigned ID) {
4819 return new (C, ID) IndirectFieldDecl(C, nullptr, SourceLocation(),
4820 DeclarationName(), QualType(), None);
4821}
4822
4823SourceRange EnumConstantDecl::getSourceRange() const {
4824 SourceLocation End = getLocation();
4825 if (Init)
4826 End = Init->getEndLoc();
4827 return SourceRange(getLocation(), End);
4828}
4829
4830void TypeDecl::anchor() {}
4831
4832TypedefDecl *TypedefDecl::Create(ASTContext &C, DeclContext *DC,
4833 SourceLocation StartLoc, SourceLocation IdLoc,
4834 IdentifierInfo *Id, TypeSourceInfo *TInfo) {
4835 return new (C, DC) TypedefDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4836}
4837
4838void TypedefNameDecl::anchor() {}
4839
4840TagDecl *TypedefNameDecl::getAnonDeclWithTypedefName(bool AnyRedecl) const {
4841 if (auto *TT = getTypeSourceInfo()->getType()->getAs<TagType>()) {
4842 auto *OwningTypedef = TT->getDecl()->getTypedefNameForAnonDecl();
4843 auto *ThisTypedef = this;
4844 if (AnyRedecl && OwningTypedef) {
4845 OwningTypedef = OwningTypedef->getCanonicalDecl();
4846 ThisTypedef = ThisTypedef->getCanonicalDecl();
4847 }
4848 if (OwningTypedef == ThisTypedef)
4849 return TT->getDecl();
4850 }
4851
4852 return nullptr;
4853}
4854
4855bool TypedefNameDecl::isTransparentTagSlow() const {
4856 auto determineIsTransparent = [&]() {
4857 if (auto *TT = getUnderlyingType()->getAs<TagType>()) {
4858 if (auto *TD = TT->getDecl()) {
4859 if (TD->getName() != getName())
4860 return false;
4861 SourceLocation TTLoc = getLocation();
4862 SourceLocation TDLoc = TD->getLocation();
4863 if (!TTLoc.isMacroID() || !TDLoc.isMacroID())
4864 return false;
4865 SourceManager &SM = getASTContext().getSourceManager();
4866 return SM.getSpellingLoc(TTLoc) == SM.getSpellingLoc(TDLoc);
4867 }
4868 }
4869 return false;
4870 };
4871
4872 bool isTransparent = determineIsTransparent();
4873 MaybeModedTInfo.setInt((isTransparent << 1) | 1);
4874 return isTransparent;
4875}
4876
4877TypedefDecl *TypedefDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4878 return new (C, ID) TypedefDecl(C, nullptr, SourceLocation(), SourceLocation(),
4879 nullptr, nullptr);
4880}
4881
4882TypeAliasDecl *TypeAliasDecl::Create(ASTContext &C, DeclContext *DC,
4883 SourceLocation StartLoc,
4884 SourceLocation IdLoc, IdentifierInfo *Id,
4885 TypeSourceInfo *TInfo) {
4886 return new (C, DC) TypeAliasDecl(C, DC, StartLoc, IdLoc, Id, TInfo);
4887}
4888
4889TypeAliasDecl *TypeAliasDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4890 return new (C, ID) TypeAliasDecl(C, nullptr, SourceLocation(),
4891 SourceLocation(), nullptr, nullptr);
4892}
4893
4894SourceRange TypedefDecl::getSourceRange() const {
4895 SourceLocation RangeEnd = getLocation();
4896 if (TypeSourceInfo *TInfo = getTypeSourceInfo()) {
4897 if (typeIsPostfix(TInfo->getType()))
4898 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4899 }
4900 return SourceRange(getBeginLoc(), RangeEnd);
4901}
4902
4903SourceRange TypeAliasDecl::getSourceRange() const {
4904 SourceLocation RangeEnd = getBeginLoc();
4905 if (TypeSourceInfo *TInfo = getTypeSourceInfo())
4906 RangeEnd = TInfo->getTypeLoc().getSourceRange().getEnd();
4907 return SourceRange(getBeginLoc(), RangeEnd);
4908}
4909
4910void FileScopeAsmDecl::anchor() {}
4911
4912FileScopeAsmDecl *FileScopeAsmDecl::Create(ASTContext &C, DeclContext *DC,
4913 StringLiteral *Str,
4914 SourceLocation AsmLoc,
4915 SourceLocation RParenLoc) {
4916 return new (C, DC) FileScopeAsmDecl(DC, Str, AsmLoc, RParenLoc);
4917}
4918
4919FileScopeAsmDecl *FileScopeAsmDecl::CreateDeserialized(ASTContext &C,
4920 unsigned ID) {
4921 return new (C, ID) FileScopeAsmDecl(nullptr, nullptr, SourceLocation(),
4922 SourceLocation());
4923}
4924
4925void EmptyDecl::anchor() {}
4926
4927EmptyDecl *EmptyDecl::Create(ASTContext &C, DeclContext *DC, SourceLocation L) {
4928 return new (C, DC) EmptyDecl(DC, L);
4929}
4930
4931EmptyDecl *EmptyDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
4932 return new (C, ID) EmptyDecl(nullptr, SourceLocation());
4933}
4934
4935//===----------------------------------------------------------------------===//
4936// ImportDecl Implementation
4937//===----------------------------------------------------------------------===//
4938
4939/// Retrieve the number of module identifiers needed to name the given
4940/// module.
4941static unsigned getNumModuleIdentifiers(Module *Mod) {
4942 unsigned Result = 1;
4943 while (Mod->Parent) {
4944 Mod = Mod->Parent;
4945 ++Result;
4946 }
4947 return Result;
4948}
4949
4950ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4951 Module *Imported,
4952 ArrayRef<SourceLocation> IdentifierLocs)
4953 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4954 NextLocalImportAndComplete(nullptr, true) {
4955 assert(getNumModuleIdentifiers(Imported) == IdentifierLocs.size())((getNumModuleIdentifiers(Imported) == IdentifierLocs.size())
? static_cast<void> (0) : __assert_fail ("getNumModuleIdentifiers(Imported) == IdentifierLocs.size()"
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/clang/lib/AST/Decl.cpp"
, 4955, __PRETTY_FUNCTION__))
;
4956 auto *StoredLocs = getTrailingObjects<SourceLocation>();
4957 std::uninitialized_copy(IdentifierLocs.begin(), IdentifierLocs.end(),
4958 StoredLocs);
4959}
4960
4961ImportDecl::ImportDecl(DeclContext *DC, SourceLocation StartLoc,
4962 Module *Imported, SourceLocation EndLoc)
4963 : Decl(Import, DC, StartLoc), ImportedModule(Imported),
4964 NextLocalImportAndComplete(nullptr, false) {
4965 *getTrailingObjects<SourceLocation>() = EndLoc;
4966}
4967
4968ImportDecl *ImportDecl::Create(ASTContext &C, DeclContext *DC,
4969 SourceLocation StartLoc, Module *Imported,
4970 ArrayRef<SourceLocation> IdentifierLocs) {
4971 return new (C, DC,
4972 additionalSizeToAlloc<SourceLocation>(IdentifierLocs.size()))
4973 ImportDecl(DC, StartLoc, Imported, IdentifierLocs);
4974}
4975
4976ImportDecl *ImportDecl::CreateImplicit(ASTContext &C, DeclContext *DC,
4977 SourceLocation StartLoc,
4978 Module *Imported,
4979 SourceLocation EndLoc) {
4980 ImportDecl *Import = new (C, DC, additionalSizeToAlloc<SourceLocation>(1))
4981 ImportDecl(DC, StartLoc, Imported, EndLoc);
4982 Import->setImplicit();
4983 return Import;
4984}
4985
4986ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
4987 unsigned NumLocations) {
4988 return new (C, ID, additionalSizeToAlloc<SourceLocation>(NumLocations))
4989 ImportDecl(EmptyShell());
4990}
4991
4992ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
4993 if (!isImportComplete())
4994 return None;
4995
4996 const auto *StoredLocs = getTrailingObjects<SourceLocation>();
4997 return llvm::makeArrayRef(StoredLocs,
4998 getNumModuleIdentifiers(getImportedModule()));
4999}
5000
5001SourceRange ImportDecl::getSourceRange() const {
5002 if (!isImportComplete())
5003 return SourceRange(getLocation(), *getTrailingObjects<SourceLocation>());
5004
5005 return SourceRange(getLocation(), getIdentifierLocs().back());
5006}
5007
5008//===----------------------------------------------------------------------===//
5009// ExportDecl Implementation
5010//===----------------------------------------------------------------------===//
5011
5012void ExportDecl::anchor() {}
5013
5014ExportDecl *ExportDecl::Create(ASTContext &C, DeclContext *DC,
5015 SourceLocation ExportLoc) {
5016 return new (C, DC) ExportDecl(DC, ExportLoc);
5017}
5018
5019ExportDecl *ExportDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
5020 return new (C, ID) ExportDecl(nullptr, SourceLocation());
5021}

/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/llvm/include/llvm/Support/TrailingObjects.h

1//===--- TrailingObjects.h - Variable-length classes ------------*- C++ -*-===//
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/// \file
10/// This header defines support for implementing classes that have
11/// some trailing object (or arrays of objects) appended to them. The
12/// main purpose is to make it obvious where this idiom is being used,
13/// and to make the usage more idiomatic and more difficult to get
14/// wrong.
15///
16/// The TrailingObject template abstracts away the reinterpret_cast,
17/// pointer arithmetic, and size calculations used for the allocation
18/// and access of appended arrays of objects, and takes care that they
19/// are all allocated at their required alignment. Additionally, it
20/// ensures that the base type is final -- deriving from a class that
21/// expects data appended immediately after it is typically not safe.
22///
23/// Users are expected to derive from this template, and provide
24/// numTrailingObjects implementations for each trailing type except
25/// the last, e.g. like this sample:
26///
27/// \code
28/// class VarLengthObj : private TrailingObjects<VarLengthObj, int, double> {
29/// friend TrailingObjects;
30///
31/// unsigned NumInts, NumDoubles;
32/// size_t numTrailingObjects(OverloadToken<int>) const { return NumInts; }
33/// };
34/// \endcode
35///
36/// You can access the appended arrays via 'getTrailingObjects', and
37/// determine the size needed for allocation via
38/// 'additionalSizeToAlloc' and 'totalSizeToAlloc'.
39///
40/// All the methods implemented by this class are are intended for use
41/// by the implementation of the class, not as part of its interface
42/// (thus, private inheritance is suggested).
43///
44//===----------------------------------------------------------------------===//
45
46#ifndef LLVM_SUPPORT_TRAILINGOBJECTS_H
47#define LLVM_SUPPORT_TRAILINGOBJECTS_H
48
49#include "llvm/Support/AlignOf.h"
50#include "llvm/Support/Alignment.h"
51#include "llvm/Support/Compiler.h"
52#include "llvm/Support/MathExtras.h"
53#include "llvm/Support/type_traits.h"
54#include <new>
55#include <type_traits>
56
57namespace llvm {
58
59namespace trailing_objects_internal {
60/// Helper template to calculate the max alignment requirement for a set of
61/// objects.
62template <typename First, typename... Rest> class AlignmentCalcHelper {
63private:
64 enum {
65 FirstAlignment = alignof(First),
66 RestAlignment = AlignmentCalcHelper<Rest...>::Alignment,
67 };
68
69public:
70 enum {
71 Alignment = FirstAlignment > RestAlignment ? FirstAlignment : RestAlignment
72 };
73};
74
75template <typename First> class AlignmentCalcHelper<First> {
76public:
77 enum { Alignment = alignof(First) };
78};
79
80/// The base class for TrailingObjects* classes.
81class TrailingObjectsBase {
82protected:
83 /// OverloadToken's purpose is to allow specifying function overloads
84 /// for different types, without actually taking the types as
85 /// parameters. (Necessary because member function templates cannot
86 /// be specialized, so overloads must be used instead of
87 /// specialization.)
88 template <typename T> struct OverloadToken {};
89};
90
91template <int Align>
92class TrailingObjectsAligner : public TrailingObjectsBase {};
93template <>
94class alignas(1) TrailingObjectsAligner<1> : public TrailingObjectsBase {};
95template <>
96class alignas(2) TrailingObjectsAligner<2> : public TrailingObjectsBase {};
97template <>
98class alignas(4) TrailingObjectsAligner<4> : public TrailingObjectsBase {};
99template <>
100class alignas(8) TrailingObjectsAligner<8> : public TrailingObjectsBase {};
101template <>
102class alignas(16) TrailingObjectsAligner<16> : public TrailingObjectsBase {
103};
104template <>
105class alignas(32) TrailingObjectsAligner<32> : public TrailingObjectsBase {
106};
107
108// Just a little helper for transforming a type pack into the same
109// number of a different type. e.g.:
110// ExtractSecondType<Foo..., int>::type
111template <typename Ty1, typename Ty2> struct ExtractSecondType {
112 typedef Ty2 type;
113};
114
115// TrailingObjectsImpl is somewhat complicated, because it is a
116// recursively inheriting template, in order to handle the template
117// varargs. Each level of inheritance picks off a single trailing type
118// then recurses on the rest. The "Align", "BaseTy", and
119// "TopTrailingObj" arguments are passed through unchanged through the
120// recursion. "PrevTy" is, at each level, the type handled by the
121// level right above it.
122
123template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
124 typename... MoreTys>
125class TrailingObjectsImpl {
126 // The main template definition is never used -- the two
127 // specializations cover all possibilities.
128};
129
130template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
131 typename NextTy, typename... MoreTys>
132class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
133 MoreTys...>
134 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
135 MoreTys...> {
136
137 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
138 ParentType;
139
140 struct RequiresRealignment {
141 static const bool value = alignof(PrevTy) < alignof(NextTy);
142 };
143
144 static constexpr bool requiresRealignment() {
145 return RequiresRealignment::value;
146 }
147
148protected:
149 // Ensure the inherited getTrailingObjectsImpl is not hidden.
150 using ParentType::getTrailingObjectsImpl;
151
152 // These two functions are helper functions for
153 // TrailingObjects::getTrailingObjects. They recurse to the left --
154 // the result for each type in the list of trailing types depends on
155 // the result of calling the function on the type to the
156 // left. However, the function for the type to the left is
157 // implemented by a *subclass* of this class, so we invoke it via
158 // the TopTrailingObj, which is, via the
159 // curiously-recurring-template-pattern, the most-derived type in
160 // this recursion, and thus, contains all the overloads.
161 static const NextTy *
162 getTrailingObjectsImpl(const BaseTy *Obj,
163 TrailingObjectsBase::OverloadToken<NextTy>) {
164 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
165 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
166 TopTrailingObj::callNumTrailingObjects(
167 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
168
169 if (requiresRealignment())
170 return reinterpret_cast<const NextTy *>(
171 alignAddr(Ptr, Align::Of<NextTy>()));
172 else
173 return reinterpret_cast<const NextTy *>(Ptr);
174 }
175
176 static NextTy *
177 getTrailingObjectsImpl(BaseTy *Obj,
178 TrailingObjectsBase::OverloadToken<NextTy>) {
179 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
10
'Ptr' initialized here
180 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
9
Passing value via 1st parameter 'Obj'
181 TopTrailingObj::callNumTrailingObjects(
182 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
183
184 if (requiresRealignment())
11
Taking false branch
185 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
186 else
187 return reinterpret_cast<NextTy *>(Ptr);
12
Returning pointer (loaded from 'Ptr')
188 }
189
190 // Helper function for TrailingObjects::additionalSizeToAlloc: this
191 // function recurses to superclasses, each of which requires one
192 // fewer size_t argument, and adds its own size.
193 static constexpr size_t additionalSizeToAllocImpl(
194 size_t SizeSoFar, size_t Count1,
195 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
196 return ParentType::additionalSizeToAllocImpl(
197 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
198 : SizeSoFar) +
199 sizeof(NextTy) * Count1,
200 MoreCounts...);
201 }
202};
203
204// The base case of the TrailingObjectsImpl inheritance recursion,
205// when there's no more trailing types.
206template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
207class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
208 : public TrailingObjectsAligner<Align> {
209protected:
210 // This is a dummy method, only here so the "using" doesn't fail --
211 // it will never be called, because this function recurses backwards
212 // up the inheritance chain to subclasses.
213 static void getTrailingObjectsImpl();
214
215 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
216 return SizeSoFar;
217 }
218
219 template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
220};
221
222} // end namespace trailing_objects_internal
223
224// Finally, the main type defined in this file, the one intended for users...
225
226/// See the file comment for details on the usage of the
227/// TrailingObjects type.
228template <typename BaseTy, typename... TrailingTys>
229class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
230 trailing_objects_internal::AlignmentCalcHelper<
231 TrailingTys...>::Alignment,
232 BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
233 BaseTy, TrailingTys...> {
234
235 template <int A, typename B, typename T, typename P, typename... M>
236 friend class trailing_objects_internal::TrailingObjectsImpl;
237
238 template <typename... Tys> class Foo {};
239
240 typedef trailing_objects_internal::TrailingObjectsImpl<
241 trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
242 BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
243 ParentType;
244 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
245
246 using ParentType::getTrailingObjectsImpl;
247
248 // This function contains only a static_assert BaseTy is final. The
249 // static_assert must be in a function, and not at class-level
250 // because BaseTy isn't complete at class instantiation time, but
251 // will be by the time this function is instantiated.
252 static void verifyTrailingObjectsAssertions() {
253 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
254 }
255
256 // These two methods are the base of the recursion for this method.
257 static const BaseTy *
258 getTrailingObjectsImpl(const BaseTy *Obj,
259 TrailingObjectsBase::OverloadToken<BaseTy>) {
260 return Obj;
261 }
262
263 static BaseTy *
264 getTrailingObjectsImpl(BaseTy *Obj,
265 TrailingObjectsBase::OverloadToken<BaseTy>) {
266 return Obj;
267 }
268
269 // callNumTrailingObjects simply calls numTrailingObjects on the
270 // provided Obj -- except when the type being queried is BaseTy
271 // itself. There is always only one of the base object, so that case
272 // is handled here. (An additional benefit of indirecting through
273 // this function is that consumers only say "friend
274 // TrailingObjects", and thus, only this class itself can call the
275 // numTrailingObjects function.)
276 static size_t
277 callNumTrailingObjects(const BaseTy *Obj,
278 TrailingObjectsBase::OverloadToken<BaseTy>) {
279 return 1;
280 }
281
282 template <typename T>
283 static size_t callNumTrailingObjects(const BaseTy *Obj,
284 TrailingObjectsBase::OverloadToken<T>) {
285 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
286 }
287
288public:
289 // Make this (privately inherited) member public.
290#ifndef _MSC_VER
291 using ParentType::OverloadToken;
292#else
293 // MSVC bug prevents the above from working, at least up through CL
294 // 19.10.24629.
295 template <typename T>
296 using OverloadToken = typename ParentType::template OverloadToken<T>;
297#endif
298
299 /// Returns a pointer to the trailing object array of the given type
300 /// (which must be one of those specified in the class template). The
301 /// array may have zero or more elements in it.
302 template <typename T> const T *getTrailingObjects() const {
303 verifyTrailingObjectsAssertions();
304 // Forwards to an impl function with overloads, since member
305 // function templates can't be specialized.
306 return this->getTrailingObjectsImpl(
307 static_cast<const BaseTy *>(this),
308 TrailingObjectsBase::OverloadToken<T>());
309 }
310
311 /// Returns a pointer to the trailing object array of the given type
312 /// (which must be one of those specified in the class template). The
313 /// array may have zero or more elements in it.
314 template <typename T> T *getTrailingObjects() {
315 verifyTrailingObjectsAssertions();
316 // Forwards to an impl function with overloads, since member
317 // function templates can't be specialized.
318 return this->getTrailingObjectsImpl(
8
Calling 'TrailingObjectsImpl::getTrailingObjectsImpl'
13
Returning from 'TrailingObjectsImpl::getTrailingObjectsImpl'
14
Returning pointer
319 static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
7
Passing value via 1st parameter 'Obj'
320 }
321
322 /// Returns the size of the trailing data, if an object were
323 /// allocated with the given counts (The counts are in the same order
324 /// as the template arguments). This does not include the size of the
325 /// base object. The template arguments must be the same as those
326 /// used in the class; they are supplied here redundantly only so
327 /// that it's clear what the counts are counting in callers.
328 template <typename... Tys>
329 static constexpr std::enable_if_t<
330 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
331 additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
332 TrailingTys, size_t>::type... Counts) {
333 return ParentType::additionalSizeToAllocImpl(0, Counts...);
334 }
335
336 /// Returns the total size of an object if it were allocated with the
337 /// given trailing object counts. This is the same as
338 /// additionalSizeToAlloc, except it *does* include the size of the base
339 /// object.
340 template <typename... Tys>
341 static constexpr std::enable_if_t<
342 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
343 totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
344 TrailingTys, size_t>::type... Counts) {
345 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
346 }
347
348 /// A type where its ::with_counts template member has a ::type member
349 /// suitable for use as uninitialized storage for an object with the given
350 /// trailing object counts. The template arguments are similar to those
351 /// of additionalSizeToAlloc.
352 ///
353 /// Use with FixedSizeStorageOwner, e.g.:
354 ///
355 /// \code{.cpp}
356 ///
357 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
358 /// MyObj::FixedSizeStorageOwner
359 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
360 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
361 ///
362 /// \endcode
363 template <typename... Tys> struct FixedSizeStorage {
364 template <size_t... Counts> struct with_counts {
365 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
366 struct type {
367 alignas(BaseTy) char buffer[Size];
368 };
369 };
370 };
371
372 /// A type that acts as the owner for an object placed into fixed storage.
373 class FixedSizeStorageOwner {
374 public:
375 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
376 ~FixedSizeStorageOwner() {
377 assert(p && "FixedSizeStorageOwner owns null?")((p && "FixedSizeStorageOwner owns null?") ? static_cast
<void> (0) : __assert_fail ("p && \"FixedSizeStorageOwner owns null?\""
, "/build/llvm-toolchain-snapshot-12~++20201026111116+d3205bbca3e/llvm/include/llvm/Support/TrailingObjects.h"
, 377, __PRETTY_FUNCTION__))
;
378 p->~BaseTy();
379 }
380
381 BaseTy *get() { return p; }
382 const BaseTy *get() const { return p; }
383
384 private:
385 FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
386 FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
387 FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
388 FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
389
390 BaseTy *const p;
391 };
392};
393
394} // end namespace llvm
395
396#endif