Bug Summary

File:clang/lib/AST/Decl.cpp
Warning:line 3853, 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 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/AST -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/AST -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/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/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../x86_64-linux-gnu/include -internal-isystem /usr/lib/llvm-13/lib/clang/13.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-13~++20210405022414+5f57793c4fe4/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4=. -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 -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-04-05-202135-9119-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/clang/lib/AST/Decl.cpp

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

/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/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
91// Just a little helper for transforming a type pack into the same
92// number of a different type. e.g.:
93// ExtractSecondType<Foo..., int>::type
94template <typename Ty1, typename Ty2> struct ExtractSecondType {
95 typedef Ty2 type;
96};
97
98// TrailingObjectsImpl is somewhat complicated, because it is a
99// recursively inheriting template, in order to handle the template
100// varargs. Each level of inheritance picks off a single trailing type
101// then recurses on the rest. The "Align", "BaseTy", and
102// "TopTrailingObj" arguments are passed through unchanged through the
103// recursion. "PrevTy" is, at each level, the type handled by the
104// level right above it.
105
106template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
107 typename... MoreTys>
108class TrailingObjectsImpl {
109 // The main template definition is never used -- the two
110 // specializations cover all possibilities.
111};
112
113template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy,
114 typename NextTy, typename... MoreTys>
115class TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy, NextTy,
116 MoreTys...>
117 : public TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy,
118 MoreTys...> {
119
120 typedef TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, NextTy, MoreTys...>
121 ParentType;
122
123 struct RequiresRealignment {
124 static const bool value = alignof(PrevTy) < alignof(NextTy);
125 };
126
127 static constexpr bool requiresRealignment() {
128 return RequiresRealignment::value;
129 }
130
131protected:
132 // Ensure the inherited getTrailingObjectsImpl is not hidden.
133 using ParentType::getTrailingObjectsImpl;
134
135 // These two functions are helper functions for
136 // TrailingObjects::getTrailingObjects. They recurse to the left --
137 // the result for each type in the list of trailing types depends on
138 // the result of calling the function on the type to the
139 // left. However, the function for the type to the left is
140 // implemented by a *subclass* of this class, so we invoke it via
141 // the TopTrailingObj, which is, via the
142 // curiously-recurring-template-pattern, the most-derived type in
143 // this recursion, and thus, contains all the overloads.
144 static const NextTy *
145 getTrailingObjectsImpl(const BaseTy *Obj,
146 TrailingObjectsBase::OverloadToken<NextTy>) {
147 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
148 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
149 TopTrailingObj::callNumTrailingObjects(
150 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
151
152 if (requiresRealignment())
153 return reinterpret_cast<const NextTy *>(
154 alignAddr(Ptr, Align::Of<NextTy>()));
155 else
156 return reinterpret_cast<const NextTy *>(Ptr);
157 }
158
159 static NextTy *
160 getTrailingObjectsImpl(BaseTy *Obj,
161 TrailingObjectsBase::OverloadToken<NextTy>) {
162 auto *Ptr = TopTrailingObj::getTrailingObjectsImpl(
10
'Ptr' initialized here
163 Obj, TrailingObjectsBase::OverloadToken<PrevTy>()) +
9
Passing value via 1st parameter 'Obj'
164 TopTrailingObj::callNumTrailingObjects(
165 Obj, TrailingObjectsBase::OverloadToken<PrevTy>());
166
167 if (requiresRealignment())
11
Taking false branch
168 return reinterpret_cast<NextTy *>(alignAddr(Ptr, Align::Of<NextTy>()));
169 else
170 return reinterpret_cast<NextTy *>(Ptr);
12
Returning pointer (loaded from 'Ptr')
171 }
172
173 // Helper function for TrailingObjects::additionalSizeToAlloc: this
174 // function recurses to superclasses, each of which requires one
175 // fewer size_t argument, and adds its own size.
176 static constexpr size_t additionalSizeToAllocImpl(
177 size_t SizeSoFar, size_t Count1,
178 typename ExtractSecondType<MoreTys, size_t>::type... MoreCounts) {
179 return ParentType::additionalSizeToAllocImpl(
180 (requiresRealignment() ? llvm::alignTo<alignof(NextTy)>(SizeSoFar)
181 : SizeSoFar) +
182 sizeof(NextTy) * Count1,
183 MoreCounts...);
184 }
185};
186
187// The base case of the TrailingObjectsImpl inheritance recursion,
188// when there's no more trailing types.
189template <int Align, typename BaseTy, typename TopTrailingObj, typename PrevTy>
190class alignas(Align) TrailingObjectsImpl<Align, BaseTy, TopTrailingObj, PrevTy>
191 : public TrailingObjectsBase {
192protected:
193 // This is a dummy method, only here so the "using" doesn't fail --
194 // it will never be called, because this function recurses backwards
195 // up the inheritance chain to subclasses.
196 static void getTrailingObjectsImpl();
197
198 static constexpr size_t additionalSizeToAllocImpl(size_t SizeSoFar) {
199 return SizeSoFar;
200 }
201
202 template <bool CheckAlignment> static void verifyTrailingObjectsAlignment() {}
203};
204
205} // end namespace trailing_objects_internal
206
207// Finally, the main type defined in this file, the one intended for users...
208
209/// See the file comment for details on the usage of the
210/// TrailingObjects type.
211template <typename BaseTy, typename... TrailingTys>
212class TrailingObjects : private trailing_objects_internal::TrailingObjectsImpl<
213 trailing_objects_internal::AlignmentCalcHelper<
214 TrailingTys...>::Alignment,
215 BaseTy, TrailingObjects<BaseTy, TrailingTys...>,
216 BaseTy, TrailingTys...> {
217
218 template <int A, typename B, typename T, typename P, typename... M>
219 friend class trailing_objects_internal::TrailingObjectsImpl;
220
221 template <typename... Tys> class Foo {};
222
223 typedef trailing_objects_internal::TrailingObjectsImpl<
224 trailing_objects_internal::AlignmentCalcHelper<TrailingTys...>::Alignment,
225 BaseTy, TrailingObjects<BaseTy, TrailingTys...>, BaseTy, TrailingTys...>
226 ParentType;
227 using TrailingObjectsBase = trailing_objects_internal::TrailingObjectsBase;
228
229 using ParentType::getTrailingObjectsImpl;
230
231 // This function contains only a static_assert BaseTy is final. The
232 // static_assert must be in a function, and not at class-level
233 // because BaseTy isn't complete at class instantiation time, but
234 // will be by the time this function is instantiated.
235 static void verifyTrailingObjectsAssertions() {
236 static_assert(std::is_final<BaseTy>(), "BaseTy must be final.");
237 }
238
239 // These two methods are the base of the recursion for this method.
240 static const BaseTy *
241 getTrailingObjectsImpl(const BaseTy *Obj,
242 TrailingObjectsBase::OverloadToken<BaseTy>) {
243 return Obj;
244 }
245
246 static BaseTy *
247 getTrailingObjectsImpl(BaseTy *Obj,
248 TrailingObjectsBase::OverloadToken<BaseTy>) {
249 return Obj;
250 }
251
252 // callNumTrailingObjects simply calls numTrailingObjects on the
253 // provided Obj -- except when the type being queried is BaseTy
254 // itself. There is always only one of the base object, so that case
255 // is handled here. (An additional benefit of indirecting through
256 // this function is that consumers only say "friend
257 // TrailingObjects", and thus, only this class itself can call the
258 // numTrailingObjects function.)
259 static size_t
260 callNumTrailingObjects(const BaseTy *Obj,
261 TrailingObjectsBase::OverloadToken<BaseTy>) {
262 return 1;
263 }
264
265 template <typename T>
266 static size_t callNumTrailingObjects(const BaseTy *Obj,
267 TrailingObjectsBase::OverloadToken<T>) {
268 return Obj->numTrailingObjects(TrailingObjectsBase::OverloadToken<T>());
269 }
270
271public:
272 // Make this (privately inherited) member public.
273#ifndef _MSC_VER
274 using ParentType::OverloadToken;
275#else
276 // An MSVC bug prevents the above from working, (last tested at CL version
277 // 19.28). "Class5" in TrailingObjectsTest.cpp tests the problematic case.
278 template <typename T>
279 using OverloadToken = typename ParentType::template OverloadToken<T>;
280#endif
281
282 /// Returns a pointer to the trailing object array of the given type
283 /// (which must be one of those specified in the class template). The
284 /// array may have zero or more elements in it.
285 template <typename T> const T *getTrailingObjects() const {
286 verifyTrailingObjectsAssertions();
287 // Forwards to an impl function with overloads, since member
288 // function templates can't be specialized.
289 return this->getTrailingObjectsImpl(
290 static_cast<const BaseTy *>(this),
291 TrailingObjectsBase::OverloadToken<T>());
292 }
293
294 /// Returns a pointer to the trailing object array of the given type
295 /// (which must be one of those specified in the class template). The
296 /// array may have zero or more elements in it.
297 template <typename T> T *getTrailingObjects() {
298 verifyTrailingObjectsAssertions();
299 // Forwards to an impl function with overloads, since member
300 // function templates can't be specialized.
301 return this->getTrailingObjectsImpl(
8
Calling 'TrailingObjectsImpl::getTrailingObjectsImpl'
13
Returning from 'TrailingObjectsImpl::getTrailingObjectsImpl'
14
Returning pointer
302 static_cast<BaseTy *>(this), TrailingObjectsBase::OverloadToken<T>());
7
Passing value via 1st parameter 'Obj'
303 }
304
305 /// Returns the size of the trailing data, if an object were
306 /// allocated with the given counts (The counts are in the same order
307 /// as the template arguments). This does not include the size of the
308 /// base object. The template arguments must be the same as those
309 /// used in the class; they are supplied here redundantly only so
310 /// that it's clear what the counts are counting in callers.
311 template <typename... Tys>
312 static constexpr std::enable_if_t<
313 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
314 additionalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
315 TrailingTys, size_t>::type... Counts) {
316 return ParentType::additionalSizeToAllocImpl(0, Counts...);
317 }
318
319 /// Returns the total size of an object if it were allocated with the
320 /// given trailing object counts. This is the same as
321 /// additionalSizeToAlloc, except it *does* include the size of the base
322 /// object.
323 template <typename... Tys>
324 static constexpr std::enable_if_t<
325 std::is_same<Foo<TrailingTys...>, Foo<Tys...>>::value, size_t>
326 totalSizeToAlloc(typename trailing_objects_internal::ExtractSecondType<
327 TrailingTys, size_t>::type... Counts) {
328 return sizeof(BaseTy) + ParentType::additionalSizeToAllocImpl(0, Counts...);
329 }
330
331 TrailingObjects() = default;
332 TrailingObjects(const TrailingObjects &) = delete;
333 TrailingObjects(TrailingObjects &&) = delete;
334 TrailingObjects &operator=(const TrailingObjects &) = delete;
335 TrailingObjects &operator=(TrailingObjects &&) = delete;
336
337 /// A type where its ::with_counts template member has a ::type member
338 /// suitable for use as uninitialized storage for an object with the given
339 /// trailing object counts. The template arguments are similar to those
340 /// of additionalSizeToAlloc.
341 ///
342 /// Use with FixedSizeStorageOwner, e.g.:
343 ///
344 /// \code{.cpp}
345 ///
346 /// MyObj::FixedSizeStorage<void *>::with_counts<1u>::type myStackObjStorage;
347 /// MyObj::FixedSizeStorageOwner
348 /// myStackObjOwner(new ((void *)&myStackObjStorage) MyObj);
349 /// MyObj *const myStackObjPtr = myStackObjOwner.get();
350 ///
351 /// \endcode
352 template <typename... Tys> struct FixedSizeStorage {
353 template <size_t... Counts> struct with_counts {
354 enum { Size = totalSizeToAlloc<Tys...>(Counts...) };
355 struct type {
356 alignas(BaseTy) char buffer[Size];
357 };
358 };
359 };
360
361 /// A type that acts as the owner for an object placed into fixed storage.
362 class FixedSizeStorageOwner {
363 public:
364 FixedSizeStorageOwner(BaseTy *p) : p(p) {}
365 ~FixedSizeStorageOwner() {
366 assert(p && "FixedSizeStorageOwner owns null?")((p && "FixedSizeStorageOwner owns null?") ? static_cast
<void> (0) : __assert_fail ("p && \"FixedSizeStorageOwner owns null?\""
, "/build/llvm-toolchain-snapshot-13~++20210405022414+5f57793c4fe4/llvm/include/llvm/Support/TrailingObjects.h"
, 366, __PRETTY_FUNCTION__))
;
367 p->~BaseTy();
368 }
369
370 BaseTy *get() { return p; }
371 const BaseTy *get() const { return p; }
372
373 private:
374 FixedSizeStorageOwner(const FixedSizeStorageOwner &) = delete;
375 FixedSizeStorageOwner(FixedSizeStorageOwner &&) = delete;
376 FixedSizeStorageOwner &operator=(const FixedSizeStorageOwner &) = delete;
377 FixedSizeStorageOwner &operator=(FixedSizeStorageOwner &&) = delete;
378
379 BaseTy *const p;
380 };
381};
382
383} // end namespace llvm
384
385#endif