Coverage Report

Created: 2022-01-25 06:29

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