Coverage Report

Created: 2022-07-16 07:03

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/AST/DeclBase.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- DeclBase.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 and DeclContext classes.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/DeclBase.h"
14
#include "clang/AST/ASTContext.h"
15
#include "clang/AST/ASTLambda.h"
16
#include "clang/AST/ASTMutationListener.h"
17
#include "clang/AST/Attr.h"
18
#include "clang/AST/AttrIterator.h"
19
#include "clang/AST/Decl.h"
20
#include "clang/AST/DeclCXX.h"
21
#include "clang/AST/DeclContextInternals.h"
22
#include "clang/AST/DeclFriend.h"
23
#include "clang/AST/DeclObjC.h"
24
#include "clang/AST/DeclOpenMP.h"
25
#include "clang/AST/DeclTemplate.h"
26
#include "clang/AST/DependentDiagnostic.h"
27
#include "clang/AST/ExternalASTSource.h"
28
#include "clang/AST/Stmt.h"
29
#include "clang/AST/Type.h"
30
#include "clang/Basic/IdentifierTable.h"
31
#include "clang/Basic/LLVM.h"
32
#include "clang/Basic/LangOptions.h"
33
#include "clang/Basic/ObjCRuntime.h"
34
#include "clang/Basic/PartialDiagnostic.h"
35
#include "clang/Basic/SourceLocation.h"
36
#include "clang/Basic/TargetInfo.h"
37
#include "llvm/ADT/ArrayRef.h"
38
#include "llvm/ADT/PointerIntPair.h"
39
#include "llvm/ADT/SmallVector.h"
40
#include "llvm/ADT/StringRef.h"
41
#include "llvm/Support/Casting.h"
42
#include "llvm/Support/ErrorHandling.h"
43
#include "llvm/Support/MathExtras.h"
44
#include "llvm/Support/VersionTuple.h"
45
#include "llvm/Support/raw_ostream.h"
46
#include <algorithm>
47
#include <cassert>
48
#include <cstddef>
49
#include <string>
50
#include <tuple>
51
#include <utility>
52
53
using namespace clang;
54
55
//===----------------------------------------------------------------------===//
56
//  Statistics
57
//===----------------------------------------------------------------------===//
58
59
#define DECL(DERIVED, BASE) static int n##DERIVED##s = 0;
60
#define ABSTRACT_DECL(DECL)
61
#include "clang/AST/DeclNodes.inc"
62
63
0
void Decl::updateOutOfDate(IdentifierInfo &II) const {
64
0
  getASTContext().getExternalSource()->updateOutOfDateIdentifier(II);
65
0
}
66
67
#define DECL(DERIVED, BASE)                                                    \
68
  static_assert(alignof(Decl) >= alignof(DERIVED##Decl),                       \
69
                "Alignment sufficient after objects prepended to " #DERIVED);
70
#define ABSTRACT_DECL(DECL)
71
#include "clang/AST/DeclNodes.inc"
72
73
void *Decl::operator new(std::size_t Size, const ASTContext &Context,
74
10.1M
                         unsigned ID, std::size_t Extra) {
75
  // Allocate an extra 8 bytes worth of storage, which ensures that the
76
  // resulting pointer will still be 8-byte aligned.
77
10.1M
  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78
10.1M
                "Decl won't be misaligned");
79
10.1M
  void *Start = Context.Allocate(Size + Extra + 8);
80
10.1M
  void *Result = (char*)Start + 8;
81
82
10.1M
  unsigned *PrefixPtr = (unsigned *)Result - 2;
83
84
  // Zero out the first 4 bytes; this is used to store the owning module ID.
85
10.1M
  PrefixPtr[0] = 0;
86
87
  // Store the global declaration ID in the second 4 bytes.
88
10.1M
  PrefixPtr[1] = ID;
89
90
10.1M
  return Result;
91
10.1M
}
92
93
void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94
139M
                         DeclContext *Parent, std::size_t Extra) {
95
139M
  assert(!Parent || &Parent->getParentASTContext() == &Ctx);
96
  // With local visibility enabled, we track the owning module even for local
97
  // declarations. We create the TU decl early and may not yet know what the
98
  // LangOpts are, so conservatively allocate the storage.
99
139M
  if (Ctx.getLangOpts().trackLocalOwningModule() || 
!Parent132M
) {
100
    // Ensure required alignment of the resulting object by adding extra
101
    // padding at the start if required.
102
7.63M
    size_t ExtraAlign =
103
7.63M
        llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
104
7.63M
    auto *Buffer = reinterpret_cast<char *>(
105
7.63M
        ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106
7.63M
    Buffer += ExtraAlign;
107
7.63M
    auto *ParentModule =
108
7.63M
        Parent ? 
cast<Decl>(Parent)->getOwningModule()7.34M
:
nullptr283k
;
109
7.63M
    return new (Buffer) Module*(ParentModule) + 1;
110
7.63M
  }
111
132M
  return ::operator new(Size + Extra, Ctx);
112
139M
}
113
114
3.02M
Module *Decl::getOwningModuleSlow() const {
115
3.02M
  assert(isFromASTFile() && "Not from AST file?");
116
0
  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
117
3.02M
}
118
119
9.82M
bool Decl::hasLocalOwningModuleStorage() const {
120
9.82M
  return getASTContext().getLangOpts().trackLocalOwningModule();
121
9.82M
}
122
123
39.8k
const char *Decl::getDeclKindName() const {
124
39.8k
  switch (DeclKind) {
125
0
  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126
39.8k
#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127
0
#define ABSTRACT_DECL(DECL)
128
39.8k
#include 
"clang/AST/DeclNodes.inc"0
129
39.8k
  }
130
39.8k
}
131
132
272k
void Decl::setInvalidDecl(bool Invalid) {
133
272k
  InvalidDecl = Invalid;
134
272k
  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
135
272k
  if (!Invalid) {
136
226k
    return;
137
226k
  }
138
139
45.7k
  if (!isa<ParmVarDecl>(this)) {
140
    // Defensive maneuver for ill-formed code: we're likely not to make it to
141
    // a point where we set the access specifier, so default it to "public"
142
    // to avoid triggering asserts elsewhere in the front end.
143
42.5k
    setAccess(AS_public);
144
42.5k
  }
145
146
  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
147
  // are invalid too.
148
45.7k
  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
149
110
    for (auto *Binding : DD->bindings()) {
150
110
      Binding->setInvalidDecl();
151
110
    }
152
78
  }
153
45.7k
}
154
155
120
const char *DeclContext::getDeclKindName() const {
156
120
  switch (getDeclKind()) {
157
120
#define DECL(DERIVED, BASE) case Decl::DERIVED: return #DERIVED;
158
0
#define ABSTRACT_DECL(DECL)
159
120
#include 
"clang/AST/DeclNodes.inc"0
160
120
  }
161
0
  llvm_unreachable("Declaration context not in DeclNodes.inc!");
162
0
}
163
164
bool Decl::StatisticsEnabled = false;
165
4
void Decl::EnableStatistics() {
166
4
  StatisticsEnabled = true;
167
4
}
168
169
4
void Decl::PrintStats() {
170
4
  llvm::errs() << "\n*** Decl Stats:\n";
171
172
4
  int totalDecls = 0;
173
336
#define DECL(DERIVED, BASE) totalDecls += n##DERIVED##s;
174
4
#define ABSTRACT_DECL(DECL)
175
4
#include "clang/AST/DeclNodes.inc"
176
4
  llvm::errs() << "  " << totalDecls << " decls total.\n";
177
178
4
  int totalBytes = 0;
179
4
#define DECL(DERIVED, BASE)                                             \
180
336
  if (n##DERIVED##s > 0) {                                              \
181
30
    totalBytes += (int)(n##DERIVED##s * sizeof(DERIVED##Decl));         \
182
30
    llvm::errs() << "    " << n##DERIVED##s << " " #DERIVED " decls, "  \
183
30
                 << sizeof(DERIVED##Decl) << " each ("                  \
184
30
                 << n##DERIVED##s * sizeof(DERIVED##Decl)               \
185
30
                 << " bytes)\n";                                        \
186
30
  }
187
4
#define ABSTRACT_DECL(DECL)
188
4
#include "clang/AST/DeclNodes.inc"
189
190
4
  llvm::errs() << "Total bytes = " << totalBytes << "\n";
191
4
}
192
193
82
void Decl::add(Kind k) {
194
82
  switch (k) {
195
82
#define DECL(DERIVED, BASE) case DERIVED: ++n##DERIVED##s; break;
196
0
#define ABSTRACT_DECL(DECL)
197
82
#include 
"clang/AST/DeclNodes.inc"0
198
82
  }
199
82
}
200
201
54.1M
bool Decl::isTemplateParameterPack() const {
202
54.1M
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203
33.9M
    return TTP->isParameterPack();
204
20.2M
  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
205
6.93M
    return NTTP->isParameterPack();
206
13.2M
  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
207
110k
    return TTP->isParameterPack();
208
13.1M
  return false;
209
13.2M
}
210
211
30.3M
bool Decl::isParameterPack() const {
212
30.3M
  if (const auto *Var = dyn_cast<VarDecl>(this))
213
21.2M
    return Var->isParameterPack();
214
215
9.13M
  return isTemplateParameterPack();
216
30.3M
}
217
218
73.1M
FunctionDecl *Decl::getAsFunction() {
219
73.1M
  if (auto *FD = dyn_cast<FunctionDecl>(this))
220
66.7M
    return FD;
221
6.40M
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
222
4.71M
    return FTD->getTemplatedDecl();
223
1.68M
  return nullptr;
224
6.40M
}
225
226
4.54M
bool Decl::isTemplateDecl() const {
227
4.54M
  return isa<TemplateDecl>(this);
228
4.54M
}
229
230
18.1M
TemplateDecl *Decl::getDescribedTemplate() const {
231
18.1M
  if (auto *FD = dyn_cast<FunctionDecl>(this))
232
3.44M
    return FD->getDescribedFunctionTemplate();
233
14.6M
  if (auto *RD = dyn_cast<CXXRecordDecl>(this))
234
935k
    return RD->getDescribedClassTemplate();
235
13.7M
  if (auto *VD = dyn_cast<VarDecl>(this))
236
1.97M
    return VD->getDescribedVarTemplate();
237
11.7M
  if (auto *AD = dyn_cast<TypeAliasDecl>(this))
238
2.17k
    return AD->getDescribedAliasTemplate();
239
240
11.7M
  return nullptr;
241
11.7M
}
242
243
4.34M
const TemplateParameterList *Decl::getDescribedTemplateParams() const {
244
4.34M
  if (auto *TD = getDescribedTemplate())
245
446k
    return TD->getTemplateParameters();
246
3.89M
  if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
247
96.5k
    return CTPSD->getTemplateParameters();
248
3.80M
  if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
249
65
    return VTPSD->getTemplateParameters();
250
3.80M
  return nullptr;
251
3.80M
}
252
253
30.3M
bool Decl::isTemplated() const {
254
  // A declaration is templated if it is a template or a template pattern, or
255
  // is within (lexcially for a friend, semantically otherwise) a dependent
256
  // context.
257
  // FIXME: Should local extern declarations be treated like friends?
258
30.3M
  if (auto *AsDC = dyn_cast<DeclContext>(this))
259
25.8M
    return AsDC->isDependentContext();
260
4.55M
  auto *DC = getFriendObjectKind() ? 
getLexicalDeclContext()0
: getDeclContext();
261
4.55M
  return DC->isDependentContext() || 
isTemplateDecl()4.46M
||
262
4.55M
         
getDescribedTemplateParams()3.78M
;
263
30.3M
}
264
265
30.3k
unsigned Decl::getTemplateDepth() const {
266
30.3k
  if (auto *DC = dyn_cast<DeclContext>(this))
267
30.3k
    if (DC->isFileContext())
268
118
      return 0;
269
270
30.2k
  if (auto *TPL = getDescribedTemplateParams())
271
30.0k
    return TPL->getDepth() + 1;
272
273
  // If this is a dependent lambda, there might be an enclosing variable
274
  // template. In this case, the next step is not the parent DeclContext (or
275
  // even a DeclContext at all).
276
133
  auto *RD = dyn_cast<CXXRecordDecl>(this);
277
133
  if (RD && 
RD->isDependentLambda()122
)
278
0
    if (Decl *Context = RD->getLambdaContextDecl())
279
0
      return Context->getTemplateDepth();
280
281
133
  const DeclContext *DC =
282
133
      getFriendObjectKind() ? 
getLexicalDeclContext()0
: getDeclContext();
283
133
  return cast<Decl>(DC)->getTemplateDepth();
284
133
}
285
286
2.07M
const DeclContext *Decl::getParentFunctionOrMethod() const {
287
2.07M
  for (const DeclContext *DC = getDeclContext();
288
2.13M
       DC && 
!DC->isTranslationUnit()2.11M
&&
!DC->isNamespace()2.02M
;
289
2.07M
       
DC = DC->getParent()54.3k
)
290
90.0k
    if (DC->isFunctionOrMethod())
291
35.6k
      return DC;
292
293
2.04M
  return nullptr;
294
2.07M
}
295
296
//===----------------------------------------------------------------------===//
297
// PrettyStackTraceDecl Implementation
298
//===----------------------------------------------------------------------===//
299
300
0
void PrettyStackTraceDecl::print(raw_ostream &OS) const {
301
0
  SourceLocation TheLoc = Loc;
302
0
  if (TheLoc.isInvalid() && TheDecl)
303
0
    TheLoc = TheDecl->getLocation();
304
305
0
  if (TheLoc.isValid()) {
306
0
    TheLoc.print(OS, SM);
307
0
    OS << ": ";
308
0
  }
309
310
0
  OS << Message;
311
312
0
  if (const auto *DN = dyn_cast_or_null<NamedDecl>(TheDecl)) {
313
0
    OS << " '";
314
0
    DN->printQualifiedName(OS);
315
0
    OS << '\'';
316
0
  }
317
0
  OS << '\n';
318
0
}
319
320
//===----------------------------------------------------------------------===//
321
// Decl Implementation
322
//===----------------------------------------------------------------------===//
323
324
// Out-of-line virtual method providing a home for Decl.
325
10.1k
Decl::~Decl() = default;
326
327
93.4M
void Decl::setDeclContext(DeclContext *DC) {
328
93.4M
  DeclCtx = DC;
329
93.4M
}
330
331
33.5M
void Decl::setLexicalDeclContext(DeclContext *DC) {
332
33.5M
  if (DC == getLexicalDeclContext())
333
32.8M
    return;
334
335
709k
  if (isInSemaDC()) {
336
694k
    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
337
694k
  } else {
338
14.7k
    getMultipleDC()->LexicalDC = DC;
339
14.7k
  }
340
341
  // FIXME: We shouldn't be changing the lexical context of declarations
342
  // imported from AST files.
343
709k
  if (!isFromASTFile()) {
344
709k
    setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
345
709k
    if (hasOwningModule())
346
41.3k
      setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
347
709k
  }
348
349
709k
  assert(
350
709k
      (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
351
709k
       getOwningModule()) &&
352
709k
      "hidden declaration has no owning module");
353
709k
}
354
355
void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
356
10.5M
                               ASTContext &Ctx) {
357
10.5M
  if (SemaDC == LexicalDC) {
358
9.55M
    DeclCtx = SemaDC;
359
9.55M
  } else {
360
1.04M
    auto *MDC = new (Ctx) Decl::MultipleDC();
361
1.04M
    MDC->SemanticDC = SemaDC;
362
1.04M
    MDC->LexicalDC = LexicalDC;
363
1.04M
    DeclCtx = MDC;
364
1.04M
  }
365
10.5M
}
366
367
159k
bool Decl::isInLocalScopeForInstantiation() const {
368
159k
  const DeclContext *LDC = getLexicalDeclContext();
369
159k
  if (!LDC->isDependentContext())
370
13.6k
    return false;
371
292k
  
while (145k
true) {
372
292k
    if (LDC->isFunctionOrMethod())
373
25
      return true;
374
292k
    if (!isa<TagDecl>(LDC))
375
145k
      return false;
376
146k
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
377
146k
      if (CRD->isLambda())
378
24
        return true;
379
146k
    LDC = LDC->getLexicalParent();
380
146k
  }
381
0
  return false;
382
145k
}
383
384
8.30M
bool Decl::isInAnonymousNamespace() const {
385
22.8M
  for (const DeclContext *DC = getDeclContext(); DC; 
DC = DC->getParent()14.5M
) {
386
14.5M
    if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
387
4.62M
      if (ND->isAnonymousNamespace())
388
5.15k
        return true;
389
14.5M
  }
390
391
8.29M
  return false;
392
8.30M
}
393
394
3.12M
bool Decl::isInStdNamespace() const {
395
3.12M
  const DeclContext *DC = getDeclContext();
396
3.12M
  return DC && DC->isStdNamespace();
397
3.12M
}
398
399
3.05G
TranslationUnitDecl *Decl::getTranslationUnitDecl() {
400
3.05G
  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
401
254M
    return TUD;
402
403
2.79G
  DeclContext *DC = getDeclContext();
404
2.79G
  assert(DC && "This decl is not contained in a translation unit!");
405
406
5.27G
  while (!DC->isTranslationUnit()) {
407
2.48G
    DC = DC->getParent();
408
2.48G
    assert(DC && "This decl is not contained in a translation unit!");
409
2.48G
  }
410
411
2.79G
  return cast<TranslationUnitDecl>(DC);
412
3.05G
}
413
414
3.05G
ASTContext &Decl::getASTContext() const {
415
3.05G
  return getTranslationUnitDecl()->getASTContext();
416
3.05G
}
417
418
/// Helper to get the language options from the ASTContext.
419
/// Defined out of line to avoid depending on ASTContext.h.
420
1.54M
const LangOptions &Decl::getLangOpts() const {
421
1.54M
  return getASTContext().getLangOpts();
422
1.54M
}
423
424
46.1M
ASTMutationListener *Decl::getASTMutationListener() const {
425
46.1M
  return getASTContext().getASTMutationListener();
426
46.1M
}
427
428
4.10M
unsigned Decl::getMaxAlignment() const {
429
4.10M
  if (!hasAttrs())
430
3.77M
    return 0;
431
432
328k
  unsigned Align = 0;
433
328k
  const AttrVec &V = getAttrs();
434
328k
  ASTContext &Ctx = getASTContext();
435
328k
  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
436
343k
  for (; I != E; 
++I14.2k
) {
437
14.2k
    if (!I->isAlignmentErrorDependent())
438
14.2k
      Align = std::max(Align, I->getAlignment(Ctx));
439
14.2k
  }
440
328k
  return Align;
441
4.10M
}
442
443
100M
bool Decl::isUsed(bool CheckUsedAttr) const {
444
100M
  const Decl *CanonD = getCanonicalDecl();
445
100M
  if (CanonD->Used)
446
11.0M
    return true;
447
448
  // Check for used attribute.
449
  // Ask the most recent decl, since attributes accumulate in the redecl chain.
450
89.6M
  if (CheckUsedAttr && 
getMostRecentDecl()->hasAttr<UsedAttr>()50.8M
)
451
892
    return true;
452
453
  // The information may have not been deserialized yet. Force deserialization
454
  // to complete the needed information.
455
89.6M
  return getMostRecentDecl()->getCanonicalDecl()->Used;
456
89.6M
}
457
458
12.6M
void Decl::markUsed(ASTContext &C) {
459
12.6M
  if (isUsed(false))
460
3.85M
    return;
461
462
8.80M
  if (C.getASTMutationListener())
463
328k
    C.getASTMutationListener()->DeclarationMarkedUsed(this);
464
465
8.80M
  setIsUsed();
466
8.80M
}
467
468
118M
bool Decl::isReferenced() const {
469
118M
  if (Referenced)
470
27.4M
    return true;
471
472
  // Check redeclarations.
473
91.4M
  for (const auto *I : redecls())
474
137M
    if (I->Referenced)
475
8.72k
      return true;
476
477
91.4M
  return false;
478
91.4M
}
479
480
31.1k
ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
481
31.1k
  const Decl *Definition = nullptr;
482
31.1k
  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
483
1.51k
    Definition = ID->getDefinition();
484
29.6k
  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
485
187
    Definition = PD->getDefinition();
486
29.4k
  } else if (auto *TD = dyn_cast<TagDecl>(this)) {
487
14.7k
    Definition = TD->getDefinition();
488
14.7k
  }
489
31.1k
  if (!Definition)
490
14.9k
    Definition = this;
491
492
31.1k
  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
493
71
    return attr;
494
31.0k
  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
495
31.0k
    return dcd->getAttr<ExternalSourceSymbolAttr>();
496
31.0k
  }
497
498
0
  return nullptr;
499
31.0k
}
500
501
31.4M
bool Decl::hasDefiningAttr() const {
502
31.4M
  return hasAttr<AliasAttr>() || 
hasAttr<IFuncAttr>()31.4M
||
503
31.4M
         
hasAttr<LoaderUninitializedAttr>()31.4M
;
504
31.4M
}
505
506
166
const Attr *Decl::getDefiningAttr() const {
507
166
  if (auto *AA = getAttr<AliasAttr>())
508
146
    return AA;
509
20
  if (auto *IFA = getAttr<IFuncAttr>())
510
20
    return IFA;
511
0
  if (auto *NZA = getAttr<LoaderUninitializedAttr>())
512
0
    return NZA;
513
0
  return nullptr;
514
0
}
515
516
static StringRef getRealizedPlatform(const AvailabilityAttr *A,
517
4.28M
                                     const ASTContext &Context) {
518
  // Check if this is an App Extension "platform", and if so chop off
519
  // the suffix for matching with the actual platform.
520
4.28M
  StringRef RealizedPlatform = A->getPlatform()->getName();
521
4.28M
  if (!Context.getLangOpts().AppExt)
522
4.28M
    return RealizedPlatform;
523
75
  size_t suffix = RealizedPlatform.rfind("_app_extension");
524
75
  if (suffix != StringRef::npos)
525
55
    return RealizedPlatform.slice(0, suffix);
526
20
  return RealizedPlatform;
527
75
}
528
529
/// Determine the availability of the given declaration based on
530
/// the target platform.
531
///
532
/// When it returns an availability result other than \c AR_Available,
533
/// if the \p Message parameter is non-NULL, it will be set to a
534
/// string describing why the entity is unavailable.
535
///
536
/// FIXME: Make these strings localizable, since they end up in
537
/// diagnostics.
538
static AvailabilityResult CheckAvailability(ASTContext &Context,
539
                                            const AvailabilityAttr *A,
540
                                            std::string *Message,
541
4.28M
                                            VersionTuple EnclosingVersion) {
542
4.28M
  if (EnclosingVersion.empty())
543
4.28M
    EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
544
545
4.28M
  if (EnclosingVersion.empty())
546
35
    return AR_Available;
547
548
4.28M
  StringRef ActualPlatform = A->getPlatform()->getName();
549
4.28M
  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
550
551
  // Match the platform name.
552
4.28M
  if (getRealizedPlatform(A, Context) != TargetPlatform)
553
2.80M
    return AR_Available;
554
555
1.48M
  StringRef PrettyPlatformName
556
1.48M
    = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
557
558
1.48M
  if (PrettyPlatformName.empty())
559
0
    PrettyPlatformName = ActualPlatform;
560
561
1.48M
  std::string HintMessage;
562
1.48M
  if (!A->getMessage().empty()) {
563
291k
    HintMessage = " - ";
564
291k
    HintMessage += A->getMessage();
565
291k
  }
566
567
  // Make sure that this declaration has not been marked 'unavailable'.
568
1.48M
  if (A->getUnavailable()) {
569
124k
    if (Message) {
570
371
      Message->clear();
571
371
      llvm::raw_string_ostream Out(*Message);
572
371
      Out << "not available on " << PrettyPlatformName
573
371
          << HintMessage;
574
371
    }
575
576
124k
    return AR_Unavailable;
577
124k
  }
578
579
  // Make sure that this declaration has already been introduced.
580
1.35M
  if (!A->getIntroduced().empty() &&
581
1.35M
      
EnclosingVersion < A->getIntroduced()1.35M
) {
582
1.23k
    if (Message) {
583
427
      Message->clear();
584
427
      llvm::raw_string_ostream Out(*Message);
585
427
      VersionTuple VTI(A->getIntroduced());
586
427
      Out << "introduced in " << PrettyPlatformName << ' '
587
427
          << VTI << HintMessage;
588
427
    }
589
590
1.23k
    return A->getStrict() ? 
AR_Unavailable8
:
AR_NotYetIntroduced1.23k
;
591
1.23k
  }
592
593
  // Make sure that this declaration hasn't been obsoleted.
594
1.35M
  if (!A->getObsoleted().empty() && 
EnclosingVersion >= A->getObsoleted()50
) {
595
48
    if (Message) {
596
29
      Message->clear();
597
29
      llvm::raw_string_ostream Out(*Message);
598
29
      VersionTuple VTO(A->getObsoleted());
599
29
      Out << "obsoleted in " << PrettyPlatformName << ' '
600
29
          << VTO << HintMessage;
601
29
    }
602
603
48
    return AR_Unavailable;
604
48
  }
605
606
  // Make sure that this declaration hasn't been deprecated.
607
1.35M
  if (!A->getDeprecated().empty() && 
EnclosingVersion >= A->getDeprecated()772k
) {
608
760k
    if (Message) {
609
262k
      Message->clear();
610
262k
      llvm::raw_string_ostream Out(*Message);
611
262k
      VersionTuple VTD(A->getDeprecated());
612
262k
      Out << "first deprecated in " << PrettyPlatformName << ' '
613
262k
          << VTD << HintMessage;
614
262k
    }
615
616
760k
    return AR_Deprecated;
617
760k
  }
618
619
596k
  return AR_Available;
620
1.35M
}
621
622
AvailabilityResult Decl::getAvailability(std::string *Message,
623
                                         VersionTuple EnclosingVersion,
624
132M
                                         StringRef *RealizedPlatform) const {
625
132M
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
626
58.1k
    return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
627
58.1k
                                                    RealizedPlatform);
628
629
132M
  AvailabilityResult Result = AR_Available;
630
132M
  std::string ResultMessage;
631
632
132M
  for (const auto *A : attrs()) {
633
22.5M
    if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
634
13.7k
      if (Result >= AR_Deprecated)
635
82
        continue;
636
637
13.6k
      if (Message)
638
12.5k
        ResultMessage = std::string(Deprecated->getMessage());
639
640
13.6k
      Result = AR_Deprecated;
641
13.6k
      continue;
642
13.7k
    }
643
644
22.4M
    if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
645
61.2k
      if (Message)
646
435
        *Message = std::string(Unavailable->getMessage());
647
61.2k
      return AR_Unavailable;
648
61.2k
    }
649
650
22.4M
    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
651
4.25M
      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
652
4.25M
                                                Message, EnclosingVersion);
653
654
4.25M
      if (AR == AR_Unavailable) {
655
124k
        if (RealizedPlatform)
656
5
          *RealizedPlatform = Availability->getPlatform()->getName();
657
124k
        return AR_Unavailable;
658
124k
      }
659
660
4.12M
      if (AR > Result) {
661
761k
        Result = AR;
662
761k
        if (Message)
663
263k
          ResultMessage.swap(*Message);
664
761k
      }
665
4.12M
      continue;
666
4.25M
    }
667
22.4M
  }
668
669
132M
  if (Message)
670
129M
    Message->swap(ResultMessage);
671
132M
  return Result;
672
132M
}
673
674
5
VersionTuple Decl::getVersionIntroduced() const {
675
5
  const ASTContext &Context = getASTContext();
676
5
  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
677
5
  for (const auto *A : attrs()) {
678
5
    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
679
5
      if (getRealizedPlatform(Availability, Context) != TargetPlatform)
680
0
        continue;
681
5
      if (!Availability->getIntroduced().empty())
682
5
        return Availability->getIntroduced();
683
5
    }
684
5
  }
685
0
  return {};
686
5
}
687
688
21.3M
bool Decl::canBeWeakImported(bool &IsDefinition) const {
689
21.3M
  IsDefinition = false;
690
691
  // Variables, if they aren't definitions.
692
21.3M
  if (const auto *Var = dyn_cast<VarDecl>(this)) {
693
20.9M
    if (Var->isThisDeclarationADefinition()) {
694
15.7M
      IsDefinition = true;
695
15.7M
      return false;
696
15.7M
    }
697
5.22M
    return true;
698
20.9M
  }
699
  // Functions, if they aren't definitions.
700
458k
  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
701
426k
    if (FD->hasBody()) {
702
279k
      IsDefinition = true;
703
279k
      return false;
704
279k
    }
705
146k
    return true;
706
707
426k
  }
708
  // Objective-C classes, if this is the non-fragile runtime.
709
31.4k
  if (isa<ObjCInterfaceDecl>(this) &&
710
31.4k
             
getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()22.9k
) {
711
22.7k
    return true;
712
22.7k
  }
713
  // Nothing else.
714
8.70k
  return false;
715
31.4k
}
716
717
21.3M
bool Decl::isWeakImported() const {
718
21.3M
  bool IsDefinition;
719
21.3M
  if (!canBeWeakImported(IsDefinition))
720
16.0M
    return false;
721
722
5.38M
  for (const auto *A : getMostRecentDecl()->attrs()) {
723
150k
    if (isa<WeakImportAttr>(A))
724
159
      return true;
725
726
149k
    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
727
31.5k
      if (CheckAvailability(getASTContext(), Availability, nullptr,
728
31.5k
                            VersionTuple()) == AR_NotYetIntroduced)
729
46
        return true;
730
31.5k
    }
731
149k
  }
732
733
5.38M
  return false;
734
5.38M
}
735
736
149M
unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
737
149M
  switch (DeclKind) {
738
25.4M
    case Function:
739
25.4M
    case CXXDeductionGuide:
740
29.0M
    case CXXMethod:
741
30.3M
    case CXXConstructor:
742
30.3M
    case ConstructorUsingShadow:
743
30.5M
    case CXXDestructor:
744
30.5M
    case CXXConversion:
745
34.4M
    case EnumConstant:
746
39.1M
    case Var:
747
44.1M
    case ImplicitParam:
748
118M
    case ParmVar:
749
119M
    case ObjCMethod:
750
119M
    case ObjCProperty:
751
119M
    case MSProperty:
752
119M
      return IDNS_Ordinary;
753
4.59k
    case Label:
754
4.59k
      return IDNS_Label;
755
17.8k
    case IndirectField:
756
17.8k
      return IDNS_Ordinary | IDNS_Member;
757
758
1.06k
    case Binding:
759
714k
    case NonTypeTemplateParm:
760
719k
    case VarTemplate:
761
720k
    case Concept:
762
      // These (C++-only) declarations are found by redeclaration lookup for
763
      // tag types, so we include them in the tag namespace.
764
720k
      return IDNS_Ordinary | IDNS_Tag;
765
766
246
    case ObjCCompatibleAlias:
767
286k
    case ObjCInterface:
768
286k
      return IDNS_Ordinary | IDNS_Type;
769
770
4.08M
    case Typedef:
771
4.45M
    case TypeAlias:
772
9.71M
    case TemplateTypeParm:
773
9.78M
    case ObjCTypeParam:
774
9.78M
      return IDNS_Ordinary | IDNS_Type;
775
776
1.24k
    case UnresolvedUsingTypename:
777
1.24k
      return IDNS_Ordinary | IDNS_Type | IDNS_Using;
778
779
450k
    case UsingShadow:
780
450k
      return 0; // we'll actually overwrite this later
781
782
1.52k
    case UnresolvedUsingValue:
783
1.52k
      return IDNS_Ordinary | IDNS_Using;
784
785
246k
    case Using:
786
246k
    case UsingPack:
787
246k
    case UsingEnum:
788
246k
      return IDNS_Using;
789
790
26.1k
    case ObjCProtocol:
791
26.1k
      return IDNS_ObjCProtocol;
792
793
4.27M
    case Field:
794
4.27M
    case ObjCAtDefsField:
795
4.41M
    case ObjCIvar:
796
4.41M
      return IDNS_Member;
797
798
551k
    case Record:
799
4.38M
    case CXXRecord:
800
4.93M
    case Enum:
801
4.93M
      return IDNS_Tag | IDNS_Type;
802
803
1.64M
    case Namespace:
804
1.64M
    case NamespaceAlias:
805
1.64M
      return IDNS_Namespace;
806
807
1.53M
    case FunctionTemplate:
808
1.53M
      return IDNS_Ordinary;
809
810
674k
    case ClassTemplate:
811
718k
    case TemplateTemplateParm:
812
833k
    case TypeAliasTemplate:
813
833k
      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
814
815
1.54k
    case UnresolvedUsingIfExists:
816
1.54k
      return IDNS_Type | IDNS_Ordinary;
817
818
918
    case OMPDeclareReduction:
819
918
      return IDNS_OMPReduction;
820
821
419
    case OMPDeclareMapper:
822
419
      return IDNS_OMPMapper;
823
824
    // Never have names.
825
177k
    case Friend:
826
177k
    case FriendTemplate:
827
707k
    case AccessSpec:
828
1.09M
    case LinkageSpec:
829
1.09M
    case Export:
830
1.09M
    case FileScopeAsm:
831
1.25M
    case StaticAssert:
832
1.25M
    case ObjCPropertyImpl:
833
1.25M
    case PragmaComment:
834
1.25M
    case PragmaDetectMismatch:
835
1.26M
    case Block:
836
1.91M
    case Captured:
837
2.00M
    case TranslationUnit:
838
2.07M
    case ExternCContext:
839
2.07M
    case Decomposition:
840
2.07M
    case MSGuid:
841
2.07M
    case UnnamedGlobalConstant:
842
2.07M
    case TemplateParamObject:
843
844
2.08M
    case UsingDirective:
845
2.08M
    case BuiltinTemplate:
846
4.42M
    case ClassTemplateSpecialization:
847
4.65M
    case ClassTemplatePartialSpecialization:
848
4.65M
    case ClassScopeFunctionSpecialization:
849
4.65M
    case VarTemplateSpecialization:
850
4.65M
    case VarTemplatePartialSpecialization:
851
4.66M
    case ObjCImplementation:
852
4.71M
    case ObjCCategory:
853
4.71M
    case ObjCCategoryImpl:
854
4.86M
    case Import:
855
4.86M
    case OMPThreadPrivate:
856
4.86M
    case OMPAllocate:
857
4.86M
    case OMPRequires:
858
4.94M
    case OMPCapturedExpr:
859
4.94M
    case Empty:
860
4.95M
    case LifetimeExtendedTemporary:
861
4.95M
    case RequiresExprBody:
862
      // Never looked up by name.
863
4.95M
      return 0;
864
149M
  }
865
866
0
  llvm_unreachable("Invalid DeclKind!");
867
0
}
868
869
32.3M
void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
870
32.3M
  assert(!HasAttrs && "Decl already contains attrs.");
871
872
0
  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
873
32.3M
  assert(AttrBlank.empty() && "HasAttrs was wrong?");
874
875
0
  AttrBlank = attrs;
876
32.3M
  HasAttrs = true;
877
32.3M
}
878
879
4.53k
void Decl::dropAttrs() {
880
4.53k
  if (!HasAttrs) 
return0
;
881
882
4.53k
  HasAttrs = false;
883
4.53k
  getASTContext().eraseDeclAttrs(this);
884
4.53k
}
885
886
107M
void Decl::addAttr(Attr *A) {
887
107M
  if (!hasAttrs()) {
888
30.8M
    setAttrs(AttrVec(1, A));
889
30.8M
    return;
890
30.8M
  }
891
892
76.7M
  AttrVec &Attrs = getAttrs();
893
76.7M
  if (!A->isInherited()) {
894
76.2M
    Attrs.push_back(A);
895
76.2M
    return;
896
76.2M
  }
897
898
  // Attribute inheritance is processed after attribute parsing. To keep the
899
  // order as in the source code, add inherited attributes before non-inherited
900
  // ones.
901
520k
  auto I = Attrs.begin(), E = Attrs.end();
902
849k
  for (; I != E; 
++I328k
) {
903
375k
    if (!(*I)->isInherited())
904
46.7k
      break;
905
375k
  }
906
520k
  Attrs.insert(I, A);
907
520k
}
908
909
1.90G
const AttrVec &Decl::getAttrs() const {
910
1.90G
  assert(HasAttrs && "No attrs to get!");
911
0
  return getASTContext().getDeclAttrs(this);
912
1.90G
}
913
914
4.24G
Decl *Decl::castFromDeclContext (const DeclContext *D) {
915
4.24G
  Decl::Kind DK = D->getDeclKind();
916
4.24G
  switch(DK) {
917
0
#define DECL(NAME, BASE)
918
0
#define DECL_CONTEXT(NAME) \
919
3.14G
    case Decl::NAME:       \
920
3.14G
      return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
921
0
#define DECL_CONTEXT_BASE(NAME)
922
0
#include "clang/AST/DeclNodes.inc"
923
1.09G
    default:
924
1.09G
#define DECL(NAME, BASE)
925
1.09G
#define DECL_CONTEXT_BASE(NAME)                  \
926
1.85G
      if (DK >= first##NAME && 
DK <= last1.09G
##NAME) \
927
1.85G
        
return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D))1.09G
;
928
1.09G
#include "clang/AST/DeclNodes.inc"
929
18.4E
      llvm_unreachable("a decl that inherits DeclContext isn't handled");
930
4.24G
  }
931
4.24G
}
932
933
60.0M
DeclContext *Decl::castToDeclContext(const Decl *D) {
934
60.0M
  Decl::Kind DK = D->getKind();
935
60.0M
  switch(DK) {
936
0
#define DECL(NAME, BASE)
937
0
#define DECL_CONTEXT(NAME) \
938
8.19M
    case Decl::NAME:       \
939
8.19M
      return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
940
0
#define DECL_CONTEXT_BASE(NAME)
941
0
#include "clang/AST/DeclNodes.inc"
942
51.8M
    default:
943
51.8M
#define DECL(NAME, BASE)
944
51.8M
#define DECL_CONTEXT_BASE(NAME)                                   \
945
69.9M
      if (DK >= first##NAME && 
DK <= last51.8M
##NAME) \
946
69.9M
        
return static_cast<NAME##Decl *>(const_cast<Decl *>(D))51.8M
;
947
51.8M
#include "clang/AST/DeclNodes.inc"
948
60.0M
      
llvm_unreachable0
("a decl that inherits DeclContext isn't handled");
949
60.0M
  }
950
60.0M
}
951
952
26.6k
SourceLocation Decl::getBodyRBrace() const {
953
  // Special handling of FunctionDecl to avoid de-serializing the body from PCH.
954
  // FunctionDecl stores EndRangeLoc for this purpose.
955
26.6k
  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
956
183
    const FunctionDecl *Definition;
957
183
    if (FD->hasBody(Definition))
958
183
      return Definition->getSourceRange().getEnd();
959
0
    return {};
960
183
  }
961
962
26.5k
  if (Stmt *Body = getBody())
963
26.5k
    return Body->getSourceRange().getEnd();
964
965
0
  return {};
966
26.5k
}
967
968
345M
bool Decl::AccessDeclContextCheck() const {
969
345M
#ifndef NDEBUG
970
  // Suppress this check if any of the following hold:
971
  // 1. this is the translation unit (and thus has no parent)
972
  // 2. this is a template parameter (and thus doesn't belong to its context)
973
  // 3. this is a non-type template parameter
974
  // 4. the context is not a record
975
  // 5. it's invalid
976
  // 6. it's a C++0x static_assert.
977
  // 7. it's a block literal declaration
978
  // 8. it's a temporary with lifetime extended due to being default value.
979
345M
  if (
isa<TranslationUnitDecl>(this)345M
|| isa<TemplateTypeParmDecl>(this) ||
980
345M
      
isa<NonTypeTemplateParmDecl>(this)335M
||
!getDeclContext()334M
||
981
345M
      
!isa<CXXRecordDecl>(getDeclContext())334M
||
isInvalidDecl()53.9M
||
982
345M
      
isa<StaticAssertDecl>(this)53.9M
||
isa<BlockDecl>(this)53.9M
||
983
      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
984
      // as DeclContext (?).
985
345M
      
isa<ParmVarDecl>(this)53.9M
||
986
      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
987
      // AS_none as access specifier.
988
345M
      
isa<CXXRecordDecl>(this)53.9M
||
989
345M
      
isa<ClassScopeFunctionSpecializationDecl>(this)49.0M
||
990
345M
      
isa<LifetimeExtendedTemporaryDecl>(this)49.0M
)
991
296M
    return true;
992
993
49.0M
  assert(Access != AS_none &&
994
49.0M
         "Access specifier is AS_none inside a record decl");
995
0
#endif
996
0
  return true;
997
345M
}
998
999
509k
bool Decl::isInExportDeclContext() const {
1000
509k
  const DeclContext *DC = getLexicalDeclContext();
1001
1002
1.30M
  while (DC && 
!isa<ExportDecl>(DC)799k
)
1003
799k
    DC = DC->getLexicalParent();
1004
1005
509k
  return DC && 
isa<ExportDecl>(DC)36
;
1006
509k
}
1007
1008
305k
static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
1009
88.0k
static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
1010
1011
0
int64_t Decl::getID() const {
1012
0
  return getASTContext().getAllocator().identifyKnownAlignedObject<Decl>(this);
1013
0
}
1014
1015
20.0M
const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1016
20.0M
  QualType Ty;
1017
20.0M
  if (const auto *D = dyn_cast<ValueDecl>(this))
1018
19.9M
    Ty = D->getType();
1019
35.1k
  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1020
1.90k
    Ty = D->getUnderlyingType();
1021
33.2k
  else
1022
33.2k
    return nullptr;
1023
1024
19.9M
  if (Ty->isFunctionPointerType())
1025
348
    Ty = Ty->castAs<PointerType>()->getPointeeType();
1026
19.9M
  else if (Ty->isFunctionReferenceType())
1027
4
    Ty = Ty->castAs<ReferenceType>()->getPointeeType();
1028
19.9M
  else if (BlocksToo && 
Ty->isBlockPointerType()1.12M
)
1029
1.87k
    Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1030
1031
19.9M
  return Ty->getAs<FunctionType>();
1032
20.0M
}
1033
1034
/// Starting at a given context (a Decl or DeclContext), look for a
1035
/// code context that is not a closure (a lambda, block, etc.).
1036
393k
template <class T> static Decl *getNonClosureContext(T *D) {
1037
393k
  if (getKind(D) == Decl::CXXMethod) {
1038
57.6k
    auto *MD = cast<CXXMethodDecl>(D);
1039
57.6k
    if (MD->getOverloadedOperator() == OO_Call &&
1040
57.6k
        
MD->getParent()->isLambda()5.14k
)
1041
3.12k
      return getNonClosureContext(MD->getParent()->getParent());
1042
54.5k
    return MD;
1043
57.6k
  }
1044
335k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
256k
    return FD;
1046
79.6k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1047
6.51k
    return MD;
1048
73.1k
  if (auto *BD = dyn_cast<BlockDecl>(D))
1049
1.61k
    return getNonClosureContext(BD->getParent());
1050
71.5k
  if (auto *CD = dyn_cast<CapturedDecl>(D))
1051
64.9k
    return getNonClosureContext(CD->getParent());
1052
6.59k
  return nullptr;
1053
71.5k
}
DeclBase.cpp:clang::Decl* getNonClosureContext<clang::Decl>(clang::Decl*)
Line
Count
Source
1036
305k
template <class T> static Decl *getNonClosureContext(T *D) {
1037
305k
  if (getKind(D) == Decl::CXXMethod) {
1038
52.8k
    auto *MD = cast<CXXMethodDecl>(D);
1039
52.8k
    if (MD->getOverloadedOperator() == OO_Call &&
1040
52.8k
        
MD->getParent()->isLambda()3.65k
)
1041
1.64k
      return getNonClosureContext(MD->getParent()->getParent());
1042
51.2k
    return MD;
1043
52.8k
  }
1044
252k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
216k
    return FD;
1046
35.5k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1047
2.58k
    return MD;
1048
32.9k
  if (auto *BD = dyn_cast<BlockDecl>(D))
1049
1.22k
    return getNonClosureContext(BD->getParent());
1050
31.7k
  if (auto *CD = dyn_cast<CapturedDecl>(D))
1051
25.3k
    return getNonClosureContext(CD->getParent());
1052
6.42k
  return nullptr;
1053
31.7k
}
DeclBase.cpp:clang::Decl* getNonClosureContext<clang::DeclContext>(clang::DeclContext*)
Line
Count
Source
1036
88.0k
template <class T> static Decl *getNonClosureContext(T *D) {
1037
88.0k
  if (getKind(D) == Decl::CXXMethod) {
1038
4.75k
    auto *MD = cast<CXXMethodDecl>(D);
1039
4.75k
    if (MD->getOverloadedOperator() == OO_Call &&
1040
4.75k
        
MD->getParent()->isLambda()1.48k
)
1041
1.47k
      return getNonClosureContext(MD->getParent()->getParent());
1042
3.27k
    return MD;
1043
4.75k
  }
1044
83.3k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
39.2k
    return FD;
1046
44.1k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1047
3.93k
    return MD;
1048
40.1k
  if (auto *BD = dyn_cast<BlockDecl>(D))
1049
392
    return getNonClosureContext(BD->getParent());
1050
39.7k
  if (auto *CD = dyn_cast<CapturedDecl>(D))
1051
39.6k
    return getNonClosureContext(CD->getParent());
1052
171
  return nullptr;
1053
39.7k
}
1054
1055
305k
Decl *Decl::getNonClosureContext() {
1056
305k
  return ::getNonClosureContext(this);
1057
305k
}
1058
1059
18.4k
Decl *DeclContext::getNonClosureAncestor() {
1060
18.4k
  return ::getNonClosureContext(this);
1061
18.4k
}
1062
1063
//===----------------------------------------------------------------------===//
1064
// DeclContext Implementation
1065
//===----------------------------------------------------------------------===//
1066
1067
42.4M
DeclContext::DeclContext(Decl::Kind K) {
1068
42.4M
  DeclContextBits.DeclKind = K;
1069
42.4M
  setHasExternalLexicalStorage(false);
1070
42.4M
  setHasExternalVisibleStorage(false);
1071
42.4M
  setNeedToReconcileExternalVisibleStorage(false);
1072
42.4M
  setHasLazyLocalLexicalLookups(false);
1073
42.4M
  setHasLazyExternalLexicalLookups(false);
1074
42.4M
  setUseQualifiedLookup(false);
1075
42.4M
}
1076
1077
87.4M
bool DeclContext::classof(const Decl *D) {
1078
87.4M
  switch (D->getKind()) {
1079
0
#define DECL(NAME, BASE)
1080
66.3M
#define DECL_CONTEXT(NAME) case Decl::NAME:
1081
0
#define DECL_CONTEXT_BASE(NAME)
1082
12.6M
#include 
"clang/AST/DeclNodes.inc"0
1083
12.6M
      return true;
1084
74.7M
    default:
1085
74.7M
#define DECL(NAME, BASE)
1086
74.7M
#define DECL_CONTEXT_BASE(NAME)                 \
1087
133M
      if (D->getKind() >= Decl::first##NAME &&  \
1088
133M
          
D->getKind() <= Decl::last98.3M
##NAME) \
1089
133M
        
return true56.4M
;
1090
74.7M
#include "clang/AST/DeclNodes.inc"
1091
18.3M
      return false;
1092
87.4M
  }
1093
87.4M
}
1094
1095
0
DeclContext::~DeclContext() = default;
1096
1097
/// Find the parent context of this context that will be
1098
/// used for unqualified name lookup.
1099
///
1100
/// Generally, the parent lookup context is the semantic context. However, for
1101
/// a friend function the parent lookup context is the lexical context, which
1102
/// is the class in which the friend is declared.
1103
76.7M
DeclContext *DeclContext::getLookupParent() {
1104
  // FIXME: Find a better way to identify friends.
1105
76.7M
  if (isa<FunctionDecl>(this))
1106
11.2M
    if (getParent()->getRedeclContext()->isFileContext() &&
1107
11.2M
        
getLexicalParent()->getRedeclContext()->isRecord()5.78M
)
1108
37.3k
      return getLexicalParent();
1109
1110
  // A lookup within the call operator of a lambda never looks in the lambda
1111
  // class; instead, skip to the context in which that closure type is
1112
  // declared.
1113
76.7M
  if (isLambdaCallOperator(this))
1114
22.2k
    return getParent()->getParent();
1115
1116
76.7M
  return getParent();
1117
76.7M
}
1118
1119
263
const BlockDecl *DeclContext::getInnermostBlockDecl() const {
1120
263
  const DeclContext *Ctx = this;
1121
1122
743
  do {
1123
743
    if (Ctx->isClosure())
1124
25
      return cast<BlockDecl>(Ctx);
1125
718
    Ctx = Ctx->getParent();
1126
718
  } while (Ctx);
1127
1128
238
  return nullptr;
1129
263
}
1130
1131
57.7M
bool DeclContext::isInlineNamespace() const {
1132
57.7M
  return isNamespace() &&
1133
57.7M
         
cast<NamespaceDecl>(this)->isInline()8.72M
;
1134
57.7M
}
1135
1136
3.97M
bool DeclContext::isStdNamespace() const {
1137
3.97M
  if (!isNamespace())
1138
2.22M
    return false;
1139
1140
1.74M
  const auto *ND = cast<NamespaceDecl>(this);
1141
1.74M
  if (ND->isInline()) {
1142
784k
    return ND->getParent()->isStdNamespace();
1143
784k
  }
1144
1145
957k
  if (!getParent()->getRedeclContext()->isTranslationUnit())
1146
46.5k
    return false;
1147
1148
910k
  const IdentifierInfo *II = ND->getIdentifier();
1149
910k
  return II && 
II->isStr("std")910k
;
1150
957k
}
1151
1152
428M
bool DeclContext::isDependentContext() const {
1153
428M
  if (isFileContext())
1154
218M
    return false;
1155
1156
209M
  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1157
7.75M
    return true;
1158
1159
201M
  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1160
78.3M
    if (Record->getDescribedClassTemplate())
1161
27.9M
      return true;
1162
1163
50.4M
    if (Record->isDependentLambda())
1164
28.3k
      return true;
1165
50.3M
    if (Record->isNeverDependentLambda())
1166
554
      return false;
1167
50.3M
  }
1168
1169
173M
  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1170
66.9M
    if (Function->getDescribedFunctionTemplate())
1171
6.96M
      return true;
1172
1173
    // Friend function declarations are dependent if their *lexical*
1174
    // context is dependent.
1175
59.9M
    if (cast<Decl>(this)->getFriendObjectKind())
1176
131k
      return getLexicalParent()->isDependentContext();
1177
59.9M
  }
1178
1179
  // FIXME: A variable template is a dependent context, but is not a
1180
  // DeclContext. A context within it (such as a lambda-expression)
1181
  // should be considered dependent.
1182
1183
166M
  
return 166M
getParent()166M
&& getParent()->isDependentContext();
1184
173M
}
1185
1186
1.48G
bool DeclContext::isTransparentContext() const {
1187
1.48G
  if (getDeclKind() == Decl::Enum)
1188
8.61M
    return !cast<EnumDecl>(this)->isScoped();
1189
1190
1.47G
  return getDeclKind() == Decl::LinkageSpec || 
getDeclKind() == Decl::Export1.15G
;
1191
1.48G
}
1192
1193
static bool isLinkageSpecContext(const DeclContext *DC,
1194
38.5M
                                 LinkageSpecDecl::LanguageIDs ID) {
1195
70.8M
  while (DC->getDeclKind() != Decl::TranslationUnit) {
1196
55.2M
    if (DC->getDeclKind() == Decl::LinkageSpec)
1197
22.8M
      return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1198
32.3M
    DC = DC->getLexicalParent();
1199
32.3M
  }
1200
15.6M
  return false;
1201
38.5M
}
1202
1203
38.5M
bool DeclContext::isExternCContext() const {
1204
38.5M
  return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1205
38.5M
}
1206
1207
34
const LinkageSpecDecl *DeclContext::getExternCContext() const {
1208
34
  const DeclContext *DC = this;
1209
38
  while (DC->getDeclKind() != Decl::TranslationUnit) {
1210
38
    if (DC->getDeclKind() == Decl::LinkageSpec &&
1211
38
        
cast<LinkageSpecDecl>(DC)->getLanguage() == LinkageSpecDecl::lang_c34
)
1212
34
      return cast<LinkageSpecDecl>(DC);
1213
4
    DC = DC->getLexicalParent();
1214
4
  }
1215
0
  return nullptr;
1216
34
}
1217
1218
22.1k
bool DeclContext::isExternCXXContext() const {
1219
22.1k
  return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1220
22.1k
}
1221
1222
34.9M
bool DeclContext::Encloses(const DeclContext *DC) const {
1223
34.9M
  if (getPrimaryContext() != this)
1224
11.7M
    return getPrimaryContext()->Encloses(DC);
1225
1226
57.3M
  
for (; 23.1M
DC;
DC = DC->getParent()34.1M
)
1227
46.0M
    if (!isa<LinkageSpecDecl>(DC) && 
!isa<ExportDecl>(DC)46.0M
&&
1228
46.0M
        
DC->getPrimaryContext() == this46.0M
)
1229
11.8M
      return true;
1230
11.2M
  return false;
1231
23.1M
}
1232
1233
7.21M
DeclContext *DeclContext::getNonTransparentContext() {
1234
7.21M
  DeclContext *DC = this;
1235
7.67M
  while (DC->isTransparentContext()) {
1236
459k
    DC = DC->getParent();
1237
459k
    assert(DC && "All transparent contexts should have a parent!");
1238
459k
  }
1239
7.21M
  return DC;
1240
7.21M
}
1241
1242
1.57G
DeclContext *DeclContext::getPrimaryContext() {
1243
1.57G
  switch (getDeclKind()) {
1244
27.1M
  case Decl::ExternCContext:
1245
115M
  case Decl::LinkageSpec:
1246
115M
  case Decl::Export:
1247
115M
  case Decl::Block:
1248
126M
  case Decl::Captured:
1249
126M
  case Decl::OMPDeclareReduction:
1250
126M
  case Decl::OMPDeclareMapper:
1251
126M
  case Decl::RequiresExprBody:
1252
    // There is only one DeclContext for these entities.
1253
126M
    return this;
1254
1255
703M
  case Decl::TranslationUnit:
1256
703M
    return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
1257
382M
  case Decl::Namespace:
1258
    // The original namespace is our primary context.
1259
382M
    return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1260
1261
403k
  case Decl::ObjCMethod:
1262
403k
    return this;
1263
1264
7.23M
  case Decl::ObjCInterface:
1265
7.23M
    if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1266
7.23M
      if (auto *Def = OID->getDefinition())
1267
7.23M
        return Def;
1268
1.08k
    return this;
1269
1270
2.68M
  case Decl::ObjCProtocol:
1271
2.68M
    if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1272
2.68M
      if (auto *Def = OPD->getDefinition())
1273
2.68M
        return Def;
1274
145
    return this;
1275
1276
9.35M
  case Decl::ObjCCategory:
1277
9.35M
    return this;
1278
1279
98.6k
  case Decl::ObjCImplementation:
1280
105k
  case Decl::ObjCCategoryImpl:
1281
105k
    return this;
1282
1283
342M
  default:
1284
342M
    if (getDeclKind() >= Decl::firstTag && getDeclKind() <= Decl::lastTag) {
1285
      // If this is a tag type that has a definition or is currently
1286
      // being defined, that definition is our primary context.
1287
294M
      auto *Tag = cast<TagDecl>(this);
1288
1289
294M
      if (TagDecl *Def = Tag->getDefinition())
1290
280M
        return Def;
1291
1292
13.7M
      if (const auto *TagTy = dyn_cast<TagType>(Tag->getTypeForDecl())) {
1293
        // Note, TagType::getDecl returns the (partial) definition one exists.
1294
13.5M
        TagDecl *PossiblePartialDef = TagTy->getDecl();
1295
13.5M
        if (PossiblePartialDef->isBeingDefined())
1296
12.9M
          return PossiblePartialDef;
1297
13.5M
      } else {
1298
192k
        assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1299
192k
      }
1300
1301
752k
      return Tag;
1302
13.7M
    }
1303
1304
48.7M
    assert(getDeclKind() >= Decl::firstFunction &&
1305
48.7M
           getDeclKind() <= Decl::lastFunction &&
1306
48.7M
          "Unknown DeclContext kind");
1307
0
    return this;
1308
1.57G
  }
1309
1.57G
}
1310
1311
template <typename T>
1312
86.4k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
175k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()89.3k
)
1314
89.3k
    Contexts.push_back(D);
1315
1316
86.4k
  std::reverse(Contexts.begin(), Contexts.end());
1317
86.4k
}
void collectAllContextsImpl<clang::TranslationUnitDecl>(clang::TranslationUnitDecl*, llvm::SmallVectorImpl<clang::DeclContext*>&)
Line
Count
Source
1312
52.3k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
104k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()52.3k
)
1314
52.3k
    Contexts.push_back(D);
1315
1316
52.3k
  std::reverse(Contexts.begin(), Contexts.end());
1317
52.3k
}
void collectAllContextsImpl<clang::NamespaceDecl>(clang::NamespaceDecl*, llvm::SmallVectorImpl<clang::DeclContext*>&)
Line
Count
Source
1312
34.1k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
71.1k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()36.9k
)
1314
36.9k
    Contexts.push_back(D);
1315
1316
34.1k
  std::reverse(Contexts.begin(), Contexts.end());
1317
34.1k
}
1318
1319
2.23M
void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) {
1320
2.23M
  Contexts.clear();
1321
1322
2.23M
  Decl::Kind Kind = getDeclKind();
1323
1324
2.23M
  if (Kind == Decl::TranslationUnit)
1325
52.3k
    collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
1326
2.18M
  else if (Kind == Decl::Namespace)
1327
34.1k
    collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
1328
2.14M
  else
1329
2.14M
    Contexts.push_back(this);
1330
2.23M
}
1331
1332
std::pair<Decl *, Decl *>
1333
DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1334
156k
                            bool FieldsAlreadyLoaded) {
1335
  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1336
156k
  Decl *FirstNewDecl = nullptr;
1337
156k
  Decl *PrevDecl = nullptr;
1338
1.35M
  for (auto *D : Decls) {
1339
1.35M
    if (FieldsAlreadyLoaded && 
isa<FieldDecl>(D)73.0k
)
1340
0
      continue;
1341
1342
1.35M
    if (PrevDecl)
1343
1.19M
      PrevDecl->NextInContextAndBits.setPointer(D);
1344
156k
    else
1345
156k
      FirstNewDecl = D;
1346
1347
1.35M
    PrevDecl = D;
1348
1.35M
  }
1349
1350
156k
  return std::make_pair(FirstNewDecl, PrevDecl);
1351
156k
}
1352
1353
/// We have just acquired external visible storage, and we already have
1354
/// built a lookup map. For every name in the map, pull in the new names from
1355
/// the external storage.
1356
32.2k
void DeclContext::reconcileExternalVisibleStorage() const {
1357
32.2k
  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1358
0
  setNeedToReconcileExternalVisibleStorage(false);
1359
1360
32.2k
  for (auto &Lookup : *LookupPtr)
1361
1.39M
    Lookup.second.setHasExternalDecls();
1362
32.2k
}
1363
1364
/// Load the declarations within this lexical storage from an
1365
/// external source.
1366
/// \return \c true if any declarations were added.
1367
bool
1368
261k
DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1369
261k
  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1370
261k
  assert(hasExternalLexicalStorage() && Source && "No external storage?");
1371
1372
  // Notify that we have a DeclContext that is initializing.
1373
0
  ExternalASTSource::Deserializing ADeclContext(Source);
1374
1375
  // Load the external declarations, if any.
1376
261k
  SmallVector<Decl*, 64> Decls;
1377
261k
  setHasExternalLexicalStorage(false);
1378
261k
  Source->FindExternalLexicalDecls(this, Decls);
1379
1380
261k
  if (Decls.empty())
1381
115k
    return false;
1382
1383
  // We may have already loaded just the fields of this record, in which case
1384
  // we need to ignore them.
1385
146k
  bool FieldsAlreadyLoaded = false;
1386
146k
  if (const auto *RD = dyn_cast<RecordDecl>(this))
1387
140k
    FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1388
1389
  // Splice the newly-read declarations into the beginning of the list
1390
  // of declarations.
1391
146k
  Decl *ExternalFirst, *ExternalLast;
1392
146k
  std::tie(ExternalFirst, ExternalLast) =
1393
146k
      BuildDeclChain(Decls, FieldsAlreadyLoaded);
1394
146k
  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1395
146k
  FirstDecl = ExternalFirst;
1396
146k
  if (!LastDecl)
1397
143k
    LastDecl = ExternalLast;
1398
146k
  return true;
1399
261k
}
1400
1401
DeclContext::lookup_result
1402
ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1403
411k
                                                    DeclarationName Name) {
1404
411k
  ASTContext &Context = DC->getParentASTContext();
1405
411k
  StoredDeclsMap *Map;
1406
411k
  if (!(Map = DC->LookupPtr))
1407
0
    Map = DC->CreateStoredDeclsMap(Context);
1408
411k
  if (DC->hasNeedToReconcileExternalVisibleStorage())
1409
0
    DC->reconcileExternalVisibleStorage();
1410
1411
411k
  (*Map)[Name].removeExternalDecls();
1412
1413
411k
  return DeclContext::lookup_result();
1414
411k
}
1415
1416
DeclContext::lookup_result
1417
ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1418
                                                  DeclarationName Name,
1419
1.77M
                                                  ArrayRef<NamedDecl*> Decls) {
1420
1.77M
  ASTContext &Context = DC->getParentASTContext();
1421
1.77M
  StoredDeclsMap *Map;
1422
1.77M
  if (!(Map = DC->LookupPtr))
1423
19
    Map = DC->CreateStoredDeclsMap(Context);
1424
1.77M
  if (DC->hasNeedToReconcileExternalVisibleStorage())
1425
16.0k
    DC->reconcileExternalVisibleStorage();
1426
1427
1.77M
  StoredDeclsList &List = (*Map)[Name];
1428
1.77M
  List.replaceExternalDecls(Decls);
1429
1.77M
  return List.getLookupResult();
1430
1.77M
}
1431
1432
18.0M
DeclContext::decl_iterator DeclContext::decls_begin() const {
1433
18.0M
  if (hasExternalLexicalStorage())
1434
149k
    LoadLexicalDeclsFromExternalStorage();
1435
18.0M
  return decl_iterator(FirstDecl);
1436
18.0M
}
1437
1438
890k
bool DeclContext::decls_empty() const {
1439
890k
  if (hasExternalLexicalStorage())
1440
19
    LoadLexicalDeclsFromExternalStorage();
1441
1442
890k
  return !FirstDecl;
1443
890k
}
1444
1445
109k
bool DeclContext::containsDecl(Decl *D) const {
1446
109k
  return (D->getLexicalDeclContext() == this &&
1447
109k
          
(108k
D->NextInContextAndBits.getPointer()108k
||
D == LastDecl8.12k
));
1448
109k
}
1449
1450
8.02k
bool DeclContext::containsDeclAndLoad(Decl *D) const {
1451
8.02k
  if (hasExternalLexicalStorage())
1452
10
    LoadLexicalDeclsFromExternalStorage();
1453
8.02k
  return containsDecl(D);
1454
8.02k
}
1455
1456
/// shouldBeHidden - Determine whether a declaration which was declared
1457
/// within its semantic context should be invisible to qualified name lookup.
1458
58.9M
static bool shouldBeHidden(NamedDecl *D) {
1459
  // Skip unnamed declarations.
1460
58.9M
  if (!D->getDeclName())
1461
1.10M
    return true;
1462
1463
  // Skip entities that can't be found by name lookup into a particular
1464
  // context.
1465
57.8M
  if ((D->getIdentifierNamespace() == 0 && 
!isa<UsingDirectiveDecl>(D)387k
) ||
1466
57.8M
      
D->isTemplateParameter()57.4M
)
1467
383k
    return true;
1468
1469
  // Skip friends and local extern declarations unless they're the first
1470
  // declaration of the entity.
1471
57.4M
  if ((D->isLocalExternDecl() || 
D->getFriendObjectKind()57.4M
) &&
1472
57.4M
      
D != D->getCanonicalDecl()69.4k
)
1473
20.9k
    return true;
1474
1475
  // Skip template specializations.
1476
  // FIXME: This feels like a hack. Should DeclarationName support
1477
  // template-ids, or is there a better way to keep specializations
1478
  // from being visible?
1479
57.4M
  if (isa<ClassTemplateSpecializationDecl>(D))
1480
0
    return true;
1481
57.4M
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1482
28.5M
    if (FD->isFunctionTemplateSpecialization())
1483
21.7k
      return true;
1484
1485
  // Hide destructors that are invalid. There should always be one destructor,
1486
  // but if it is an invalid decl, another one is created. We need to hide the
1487
  // invalid one from places that expect exactly one destructor, like the
1488
  // serialization code.
1489
57.4M
  if (isa<CXXDestructorDecl>(D) && 
D->isInvalidDecl()185k
)
1490
35
    return true;
1491
1492
57.4M
  return false;
1493
57.4M
}
1494
1495
99.4k
void DeclContext::removeDecl(Decl *D) {
1496
99.4k
  assert(D->getLexicalDeclContext() == this &&
1497
99.4k
         "decl being removed from non-lexical context");
1498
0
  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1499
99.4k
         "decl is not in decls list");
1500
1501
  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1502
99.4k
  if (D == FirstDecl) {
1503
13.5k
    if (D == LastDecl)
1504
731
      FirstDecl = LastDecl = nullptr;
1505
12.8k
    else
1506
12.8k
      FirstDecl = D->NextInContextAndBits.getPointer();
1507
85.8k
  } else {
1508
3.59M
    for (Decl *I = FirstDecl; true; 
I = I->NextInContextAndBits.getPointer()3.51M
) {
1509
3.59M
      assert(I && "decl not found in linked list");
1510
3.59M
      if (I->NextInContextAndBits.getPointer() == D) {
1511
85.8k
        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1512
85.8k
        if (D == LastDecl) 
LastDecl = I2.00k
;
1513
85.8k
        break;
1514
85.8k
      }
1515
3.59M
    }
1516
85.8k
  }
1517
1518
  // Mark that D is no longer in the decl chain.
1519
99.4k
  D->NextInContextAndBits.setPointer(nullptr);
1520
1521
  // Remove D from the lookup table if necessary.
1522
99.4k
  if (isa<NamedDecl>(D)) {
1523
62.7k
    auto *ND = cast<NamedDecl>(D);
1524
1525
    // Do not try to remove the declaration if that is invisible to qualified
1526
    // lookup.  E.g. template specializations are skipped.
1527
62.7k
    if (shouldBeHidden(ND))
1528
1.55k
      return;
1529
1530
    // Remove only decls that have a name
1531
61.2k
    if (!ND->getDeclName())
1532
0
      return;
1533
1534
61.2k
    auto *DC = D->getDeclContext();
1535
61.2k
    do {
1536
61.2k
      StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1537
61.2k
      if (Map) {
1538
58.6k
        StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1539
58.6k
        assert(Pos != Map->end() && "no lookup entry for decl");
1540
0
        StoredDeclsList &List = Pos->second;
1541
58.6k
        List.remove(ND);
1542
        // Clean up the entry if there are no more decls.
1543
58.6k
        if (List.isNull())
1544
58.3k
          Map->erase(Pos);
1545
58.6k
      }
1546
61.2k
    } while (DC->isTransparentContext() && 
(DC = DC->getParent())0
);
1547
61.2k
  }
1548
99.4k
}
1549
1550
63.8M
void DeclContext::addHiddenDecl(Decl *D) {
1551
63.8M
  assert(D->getLexicalDeclContext() == this &&
1552
63.8M
         "Decl inserted into wrong lexical context");
1553
0
  assert(!D->getNextDeclInContext() && D != LastDecl &&
1554
63.8M
         "Decl already inserted into a DeclContext");
1555
1556
63.8M
  if (FirstDecl) {
1557
54.8M
    LastDecl->NextInContextAndBits.setPointer(D);
1558
54.8M
    LastDecl = D;
1559
54.8M
  } else {
1560
8.97M
    FirstDecl = LastDecl = D;
1561
8.97M
  }
1562
1563
  // Notify a C++ record declaration that we've added a member, so it can
1564
  // update its class-specific state.
1565
63.8M
  if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1566
10.5M
    Record->addedMember(D);
1567
1568
  // If this is a newly-created (not de-serialized) import declaration, wire
1569
  // it in to the list of local import declarations.
1570
63.8M
  if (!D->isFromASTFile()) {
1571
63.8M
    if (auto *Import = dyn_cast<ImportDecl>(D))
1572
140k
      D->getASTContext().addedLocalImportDecl(Import);
1573
63.8M
  }
1574
63.8M
}
1575
1576
59.4M
void DeclContext::addDecl(Decl *D) {
1577
59.4M
  addHiddenDecl(D);
1578
1579
59.4M
  if (auto *ND = dyn_cast<NamedDecl>(D))
1580
58.1M
    ND->getDeclContext()->getPrimaryContext()->
1581
58.1M
        makeDeclVisibleInContextWithFlags(ND, false, true);
1582
59.4M
}
1583
1584
3.54M
void DeclContext::addDeclInternal(Decl *D) {
1585
3.54M
  addHiddenDecl(D);
1586
1587
3.54M
  if (auto *ND = dyn_cast<NamedDecl>(D))
1588
3.35M
    ND->getDeclContext()->getPrimaryContext()->
1589
3.35M
        makeDeclVisibleInContextWithFlags(ND, true, true);
1590
3.54M
}
1591
1592
/// buildLookup - Build the lookup data structure with all of the
1593
/// declarations in this DeclContext (and any other contexts linked
1594
/// to it or transparent contexts nested within it) and return it.
1595
///
1596
/// Note that the produced map may miss out declarations from an
1597
/// external source. If it does, those entries will be marked with
1598
/// the 'hasExternalDecls' flag.
1599
26.0M
StoredDeclsMap *DeclContext::buildLookup() {
1600
26.0M
  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1601
1602
26.0M
  if (!hasLazyLocalLexicalLookups() &&
1603
26.0M
      
!hasLazyExternalLexicalLookups()24.0M
)
1604
23.8M
    return LookupPtr;
1605
1606
2.12M
  SmallVector<DeclContext *, 2> Contexts;
1607
2.12M
  collectAllContexts(Contexts);
1608
1609
2.12M
  if (hasLazyExternalLexicalLookups()) {
1610
111k
    setHasLazyExternalLexicalLookups(false);
1611
111k
    for (auto *DC : Contexts) {
1612
111k
      if (DC->hasExternalLexicalStorage()) {
1613
111k
        bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1614
111k
        setHasLazyLocalLexicalLookups(
1615
111k
            hasLazyLocalLexicalLookups() | LoadedDecls );
1616
111k
      }
1617
111k
    }
1618
1619
111k
    if (!hasLazyLocalLexicalLookups())
1620
104k
      return LookupPtr;
1621
111k
  }
1622
1623
2.02M
  for (auto *DC : Contexts)
1624
2.02M
    buildLookupImpl(DC, hasExternalVisibleStorage());
1625
1626
  // We no longer have any lazy decls.
1627
2.02M
  setHasLazyLocalLexicalLookups(false);
1628
2.02M
  return LookupPtr;
1629
2.12M
}
1630
1631
/// buildLookupImpl - Build part of the lookup data structure for the
1632
/// declarations contained within DCtx, which will either be this
1633
/// DeclContext, a DeclContext linked to it, or a transparent context
1634
/// nested within it.
1635
2.14M
void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1636
3.97M
  for (auto *D : DCtx->noload_decls()) {
1637
    // Insert this declaration into the lookup structure, but only if
1638
    // it's semantically within its decl context. Any other decls which
1639
    // should be found in this context are added eagerly.
1640
    //
1641
    // If it's from an AST file, don't add it now. It'll get handled by
1642
    // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1643
    // in C++, we do not track external visible decls for the TU, so in
1644
    // that case we need to collect them all here.
1645
3.97M
    if (auto *ND = dyn_cast<NamedDecl>(D))
1646
3.72M
      if (ND->getDeclContext() == DCtx && 
!shouldBeHidden(ND)3.71M
&&
1647
3.72M
          
(3.67M
!ND->isFromASTFile()3.67M
||
1648
3.67M
           
(246k
isTranslationUnit()246k
&&
1649
246k
            
!getParentASTContext().getLangOpts().CPlusPlus6.44k
)))
1650
3.42M
        makeDeclVisibleInContextImpl(ND, Internal);
1651
1652
    // If this declaration is itself a transparent declaration context
1653
    // or inline namespace, add the members of this declaration of that
1654
    // context (recursively).
1655
3.97M
    if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1656
2.10M
      if (InnerCtx->isTransparentContext() || 
InnerCtx->isInlineNamespace()2.08M
)
1657
16.9k
        buildLookupImpl(InnerCtx, Internal);
1658
3.97M
  }
1659
2.14M
}
1660
1661
DeclContext::lookup_result
1662
324M
DeclContext::lookup(DeclarationName Name) const {
1663
  // For transparent DeclContext, we should lookup in their enclosing context.
1664
324M
  if (getDeclKind() == Decl::LinkageSpec || 
getDeclKind() == Decl::Export324M
)
1665
4
    return getParent()->lookup(Name);
1666
1667
324M
  const DeclContext *PrimaryContext = getPrimaryContext();
1668
324M
  if (PrimaryContext != this)
1669
55.4M
    return PrimaryContext->lookup(Name);
1670
1671
  // If we have an external source, ensure that any later redeclarations of this
1672
  // context have been loaded, since they may add names to the result of this
1673
  // lookup (or add external visible storage).
1674
269M
  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1675
269M
  if (Source)
1676
21.7M
    (void)cast<Decl>(this)->getMostRecentDecl();
1677
1678
269M
  if (hasExternalVisibleStorage()) {
1679
8.87M
    assert(Source && "external visible storage but no external source?");
1680
1681
8.87M
    if (hasNeedToReconcileExternalVisibleStorage())
1682
16.1k
      reconcileExternalVisibleStorage();
1683
1684
8.87M
    StoredDeclsMap *Map = LookupPtr;
1685
1686
8.87M
    if (hasLazyLocalLexicalLookups() ||
1687
8.87M
        
hasLazyExternalLexicalLookups()8.87M
)
1688
      // FIXME: Make buildLookup const?
1689
542
      Map = const_cast<DeclContext*>(this)->buildLookup();
1690
1691
8.87M
    if (!Map)
1692
42.4k
      Map = CreateStoredDeclsMap(getParentASTContext());
1693
1694
    // If we have a lookup result with no external decls, we are done.
1695
8.87M
    std::pair<StoredDeclsMap::iterator, bool> R =
1696
8.87M
        Map->insert(std::make_pair(Name, StoredDeclsList()));
1697
8.87M
    if (!R.second && 
!R.first->second.hasExternalDecls()7.77M
)
1698
6.86M
      return R.first->second.getLookupResult();
1699
1700
2.00M
    if (Source->FindExternalVisibleDeclsByName(this, Name) || 
!R.second1.08M
) {
1701
1.02M
      if (StoredDeclsMap *Map = LookupPtr) {
1702
1.02M
        StoredDeclsMap::iterator I = Map->find(Name);
1703
1.02M
        if (I != Map->end())
1704
1.02M
          return I->second.getLookupResult();
1705
1.02M
      }
1706
1.02M
    }
1707
1708
983k
    return {};
1709
2.00M
  }
1710
1711
260M
  StoredDeclsMap *Map = LookupPtr;
1712
260M
  if (hasLazyLocalLexicalLookups() ||
1713
260M
      
hasLazyExternalLexicalLookups()258M
)
1714
2.01M
    Map = const_cast<DeclContext*>(this)->buildLookup();
1715
1716
260M
  if (!Map)
1717
16.0M
    return {};
1718
1719
244M
  StoredDeclsMap::iterator I = Map->find(Name);
1720
244M
  if (I == Map->end())
1721
161M
    return {};
1722
1723
82.9M
  return I->second.getLookupResult();
1724
244M
}
1725
1726
DeclContext::lookup_result
1727
5.33M
DeclContext::noload_lookup(DeclarationName Name) {
1728
5.33M
  assert(getDeclKind() != Decl::LinkageSpec &&
1729
5.33M
         getDeclKind() != Decl::Export &&
1730
5.33M
         "should not perform lookups into transparent contexts");
1731
1732
0
  DeclContext *PrimaryContext = getPrimaryContext();
1733
5.33M
  if (PrimaryContext != this)
1734
159
    return PrimaryContext->noload_lookup(Name);
1735
1736
5.33M
  loadLazyLocalLexicalLookups();
1737
5.33M
  StoredDeclsMap *Map = LookupPtr;
1738
5.33M
  if (!Map)
1739
419k
    return {};
1740
1741
4.91M
  StoredDeclsMap::iterator I = Map->find(Name);
1742
4.91M
  return I != Map->end() ? 
I->second.getLookupResult()2.70M
1743
4.91M
                         : 
lookup_result()2.21M
;
1744
5.33M
}
1745
1746
// If we have any lazy lexical declarations not in our lookup map, add them
1747
// now. Don't import any external declarations, not even if we know we have
1748
// some missing from the external visible lookups.
1749
5.33M
void DeclContext::loadLazyLocalLexicalLookups() {
1750
5.33M
  if (hasLazyLocalLexicalLookups()) {
1751
104k
    SmallVector<DeclContext *, 2> Contexts;
1752
104k
    collectAllContexts(Contexts);
1753
104k
    for (auto *Context : Contexts)
1754
104k
      buildLookupImpl(Context, hasExternalVisibleStorage());
1755
104k
    setHasLazyLocalLexicalLookups(false);
1756
104k
  }
1757
5.33M
}
1758
1759
void DeclContext::localUncachedLookup(DeclarationName Name,
1760
1.39M
                                      SmallVectorImpl<NamedDecl *> &Results) {
1761
1.39M
  Results.clear();
1762
1763
  // If there's no external storage, just perform a normal lookup and copy
1764
  // the results.
1765
1.39M
  if (!hasExternalVisibleStorage() && 
!hasExternalLexicalStorage()1.14M
&&
Name914k
) {
1766
911k
    lookup_result LookupResults = lookup(Name);
1767
911k
    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1768
911k
    return;
1769
911k
  }
1770
1771
  // If we have a lookup table, check there first. Maybe we'll get lucky.
1772
  // FIXME: Should we be checking these flags on the primary context?
1773
479k
  if (Name && 
!hasLazyLocalLexicalLookups()476k
&&
1774
479k
      
!hasLazyExternalLexicalLookups()476k
) {
1775
265k
    if (StoredDeclsMap *Map = LookupPtr) {
1776
256k
      StoredDeclsMap::iterator Pos = Map->find(Name);
1777
256k
      if (Pos != Map->end()) {
1778
1.12k
        Results.insert(Results.end(),
1779
1.12k
                       Pos->second.getLookupResult().begin(),
1780
1.12k
                       Pos->second.getLookupResult().end());
1781
1.12k
        return;
1782
1.12k
      }
1783
256k
    }
1784
265k
  }
1785
1786
  // Slow case: grovel through the declarations in our chain looking for
1787
  // matches.
1788
  // FIXME: If we have lazy external declarations, this will not find them!
1789
  // FIXME: Should we CollectAllContexts and walk them all here?
1790
205M
  
for (Decl *D = FirstDecl; 478k
D;
D = D->getNextDeclInContext()204M
) {
1791
204M
    if (auto *ND = dyn_cast<NamedDecl>(D))
1792
204M
      if (ND->getDeclName() == Name)
1793
12.8k
        Results.push_back(ND);
1794
204M
  }
1795
478k
}
1796
1797
920M
DeclContext *DeclContext::getRedeclContext() {
1798
920M
  DeclContext *Ctx = this;
1799
1800
  // In C, a record type is the redeclaration context for its fields only. If
1801
  // we arrive at a record context after skipping anything else, we should skip
1802
  // the record as well. Currently, this means skipping enumerations because
1803
  // they're the only transparent context that can exist within a struct or
1804
  // union.
1805
920M
  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1806
920M
                     
!getParentASTContext().getLangOpts().CPlusPlus806k
;
1807
1808
  // Skip through contexts to get to the redeclaration context. Transparent
1809
  // contexts are always skipped.
1810
1.17G
  while ((SkipRecords && 
Ctx->isRecord()1.23M
) ||
Ctx->isTransparentContext()1.17G
)
1811
251M
    Ctx = Ctx->getParent();
1812
920M
  return Ctx;
1813
920M
}
1814
1815
88.1k
DeclContext *DeclContext::getEnclosingNamespaceContext() {
1816
88.1k
  DeclContext *Ctx = this;
1817
  // Skip through non-namespace, non-translation-unit contexts.
1818
136k
  while (!Ctx->isFileContext())
1819
48.3k
    Ctx = Ctx->getParent();
1820
88.1k
  return Ctx->getPrimaryContext();
1821
88.1k
}
1822
1823
18
RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1824
  // Loop until we find a non-record context.
1825
18
  RecordDecl *OutermostRD = nullptr;
1826
18
  DeclContext *DC = this;
1827
45
  while (DC->isRecord()) {
1828
27
    OutermostRD = cast<RecordDecl>(DC);
1829
27
    DC = DC->getLexicalParent();
1830
27
  }
1831
18
  return OutermostRD;
1832
18
}
1833
1834
1.23M
bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1835
  // For non-file contexts, this is equivalent to Equals.
1836
1.23M
  if (!isFileContext())
1837
1.16M
    return O->Equals(this);
1838
1839
71.3k
  
do 71.2k
{
1840
71.3k
    if (O->Equals(this))
1841
71.2k
      return true;
1842
1843
124
    const auto *NS = dyn_cast<NamespaceDecl>(O);
1844
124
    if (!NS || 
!NS->isInline()109
)
1845
53
      break;
1846
71
    O = NS->getParent();
1847
71
  } while (O);
1848
1849
53
  return false;
1850
71.2k
}
1851
1852
1.43M
void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1853
1.43M
  DeclContext *PrimaryDC = this->getPrimaryContext();
1854
1.43M
  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1855
  // If the decl is being added outside of its semantic decl context, we
1856
  // need to ensure that we eagerly build the lookup information for it.
1857
1.43M
  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1858
1.43M
}
1859
1860
void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1861
78.1M
                                                    bool Recoverable) {
1862
78.1M
  assert(this == getPrimaryContext() && "expected a primary DC");
1863
1864
78.1M
  if (!isLookupContext()) {
1865
22.9M
    if (isTransparentContext())
1866
9.87M
      getParent()->getPrimaryContext()
1867
9.87M
        ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1868
22.9M
    return;
1869
22.9M
  }
1870
1871
  // Skip declarations which should be invisible to name lookup.
1872
55.1M
  if (shouldBeHidden(D))
1873
1.49M
    return;
1874
1875
  // If we already have a lookup data structure, perform the insertion into
1876
  // it. If we might have externally-stored decls with this name, look them
1877
  // up and perform the insertion. If this decl was declared outside its
1878
  // semantic context, buildLookup won't add it, so add it now.
1879
  //
1880
  // FIXME: As a performance hack, don't add such decls into the translation
1881
  // unit unless we're in C++, since qualified lookup into the TU is never
1882
  // performed.
1883
53.6M
  if (LookupPtr || 
hasExternalVisibleStorage()30.1M
||
1884
53.6M
      
(30.0M
(30.0M
!Recoverable30.0M
||
D->getDeclContext() != D->getLexicalDeclContext()30.0M
) &&
1885
30.0M
       
(24.0k
getParentASTContext().getLangOpts().CPlusPlus24.0k
||
1886
23.6M
        
!isTranslationUnit()4.24k
))) {
1887
    // If we have lazily omitted any decls, they might have the same name as
1888
    // the decl which we are adding, so build a full lookup table before adding
1889
    // this decl.
1890
23.6M
    buildLookup();
1891
23.6M
    makeDeclVisibleInContextImpl(D, Internal);
1892
30.0M
  } else {
1893
30.0M
    setHasLazyLocalLexicalLookups(true);
1894
30.0M
  }
1895
1896
  // If we are a transparent context or inline namespace, insert into our
1897
  // parent context, too. This operation is recursive.
1898
53.6M
  if (isTransparentContext() || 
isInlineNamespace()49.8M
)
1899
5.33M
    getParent()->getPrimaryContext()->
1900
5.33M
        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1901
1902
53.6M
  auto *DCAsDecl = cast<Decl>(this);
1903
  // Notify that a decl was made visible unless we are a Tag being defined.
1904
53.6M
  if (!(isa<TagDecl>(DCAsDecl) && 
cast<TagDecl>(DCAsDecl)->isBeingDefined()15.5M
))
1905
40.3M
    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1906
934k
      L->AddedVisibleDecl(this, D);
1907
53.6M
}
1908
1909
28.7M
void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1910
  // Find or create the stored declaration map.
1911
28.7M
  StoredDeclsMap *Map = LookupPtr;
1912
28.7M
  if (!Map) {
1913
2.33M
    ASTContext *C = &getParentASTContext();
1914
2.33M
    Map = CreateStoredDeclsMap(*C);
1915
2.33M
  }
1916
1917
  // If there is an external AST source, load any declarations it knows about
1918
  // with this declaration's name.
1919
  // If the lookup table contains an entry about this name it means that we
1920
  // have already checked the external source.
1921
28.7M
  if (!Internal)
1922
25.2M
    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1923
2.54M
      if (hasExternalVisibleStorage() &&
1924
2.54M
          
Map->find(D->getDeclName()) == Map->end()731k
)
1925
171k
        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1926
1927
  // Insert this declaration into the map.
1928
28.7M
  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1929
1930
28.7M
  if (Internal) {
1931
    // If this is being added as part of loading an external declaration,
1932
    // this may not be the only external declaration with this name.
1933
    // In this case, we never try to replace an existing declaration; we'll
1934
    // handle that when we finalize the list of declarations for this name.
1935
3.49M
    DeclNameEntries.setHasExternalDecls();
1936
3.49M
    DeclNameEntries.prependDeclNoReplace(D);
1937
3.49M
    return;
1938
3.49M
  }
1939
1940
25.2M
  DeclNameEntries.addOrReplaceDecl(D);
1941
25.2M
}
1942
1943
22.4M
UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1944
22.4M
  return cast<UsingDirectiveDecl>(*I);
1945
22.4M
}
1946
1947
/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1948
/// this context.
1949
108M
DeclContext::udir_range DeclContext::using_directives() const {
1950
  // FIXME: Use something more efficient than normal lookup for using
1951
  // directives. In C++, using directives are looked up more than anything else.
1952
108M
  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1953
108M
  return udir_range(Result.begin(), Result.end());
1954
108M
}
1955
1956
//===----------------------------------------------------------------------===//
1957
// Creation and Destruction of StoredDeclsMaps.                               //
1958
//===----------------------------------------------------------------------===//
1959
1960
2.38M
StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1961
2.38M
  assert(!LookupPtr && "context already has a decls map");
1962
0
  assert(getPrimaryContext() == this &&
1963
2.38M
         "creating decls map on non-primary context");
1964
1965
0
  StoredDeclsMap *M;
1966
2.38M
  bool Dependent = isDependentContext();
1967
2.38M
  if (Dependent)
1968
545k
    M = new DependentStoredDeclsMap();
1969
1.83M
  else
1970
1.83M
    M = new StoredDeclsMap();
1971
2.38M
  M->Previous = C.LastSDM;
1972
2.38M
  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1973
2.38M
  LookupPtr = M;
1974
2.38M
  return M;
1975
2.38M
}
1976
1977
95.8k
void ASTContext::ReleaseDeclContextMaps() {
1978
  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1979
  // pointer because the subclass doesn't add anything that needs to
1980
  // be deleted.
1981
95.8k
  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1982
95.8k
  LastSDM.setPointer(nullptr);
1983
95.8k
}
1984
1985
95.8k
void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1986
2.47M
  while (Map) {
1987
    // Advance the iteration before we invalidate memory.
1988
2.37M
    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1989
1990
2.37M
    if (Dependent)
1991
544k
      delete static_cast<DependentStoredDeclsMap*>(Map);
1992
1.83M
    else
1993
1.83M
      delete Map;
1994
1995
2.37M
    Map = Next.getPointer();
1996
2.37M
    Dependent = Next.getInt();
1997
2.37M
  }
1998
95.8k
}
1999
2000
DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
2001
                                                 DeclContext *Parent,
2002
97
                                           const PartialDiagnostic &PDiag) {
2003
97
  assert(Parent->isDependentContext()
2004
97
         && "cannot iterate dependent diagnostics of non-dependent context");
2005
0
  Parent = Parent->getPrimaryContext();
2006
97
  if (!Parent->LookupPtr)
2007
87
    Parent->CreateStoredDeclsMap(C);
2008
2009
97
  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2010
2011
  // Allocate the copy of the PartialDiagnostic via the ASTContext's
2012
  // BumpPtrAllocator, rather than the ASTContext itself.
2013
97
  DiagnosticStorage *DiagStorage = nullptr;
2014
97
  if (PDiag.hasStorage())
2015
2
    DiagStorage = new (C) DiagnosticStorage;
2016
2017
97
  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2018
2019
  // TODO: Maybe we shouldn't reverse the order during insertion.
2020
97
  DD->NextDiagnostic = Map->FirstDiagnostic;
2021
97
  Map->FirstDiagnostic = DD;
2022
2023
97
  return DD;
2024
97
}