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