Bug Summary

File:clang/lib/AST/Decl.cpp
Warning:line 3922, 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 -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name Decl.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/AST -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2022-01-16-232930-107970-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/clang/lib/AST/Decl.cpp

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

/build/llvm-toolchain-snapshot-14~++20220116100644+5f782d25a742/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?")(static_cast <bool> (p && "FixedSizeStorageOwner owns null?"
) ? void (0) : __assert_fail ("p && \"FixedSizeStorageOwner owns null?\""
, "llvm/include/llvm/Support/TrailingObjects.h", 366, __extension__
__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