Coverage Report

Created: 2021-09-21 08:58

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