Coverage Report

Created: 2022-05-17 06:19

/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
9.49M
                         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
9.49M
  static_assert(sizeof(unsigned) * 2 >= alignof(Decl),
78
9.49M
                "Decl won't be misaligned");
79
9.49M
  void *Start = Context.Allocate(Size + Extra + 8);
80
9.49M
  void *Result = (char*)Start + 8;
81
82
9.49M
  unsigned *PrefixPtr = (unsigned *)Result - 2;
83
84
  // Zero out the first 4 bytes; this is used to store the owning module ID.
85
9.49M
  PrefixPtr[0] = 0;
86
87
  // Store the global declaration ID in the second 4 bytes.
88
9.49M
  PrefixPtr[1] = ID;
89
90
9.49M
  return Result;
91
9.49M
}
92
93
void *Decl::operator new(std::size_t Size, const ASTContext &Ctx,
94
133M
                         DeclContext *Parent, std::size_t Extra) {
95
133M
  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
133M
  if (Ctx.getLangOpts().trackLocalOwningModule() || 
!Parent126M
) {
100
    // Ensure required alignment of the resulting object by adding extra
101
    // padding at the start if required.
102
7.07M
    size_t ExtraAlign =
103
7.07M
        llvm::offsetToAlignment(sizeof(Module *), llvm::Align(alignof(Decl)));
104
7.07M
    auto *Buffer = reinterpret_cast<char *>(
105
7.07M
        ::operator new(ExtraAlign + sizeof(Module *) + Size + Extra, Ctx));
106
7.07M
    Buffer += ExtraAlign;
107
7.07M
    auto *ParentModule =
108
7.07M
        Parent ? 
cast<Decl>(Parent)->getOwningModule()6.80M
:
nullptr271k
;
109
7.07M
    return new (Buffer) Module*(ParentModule) + 1;
110
7.07M
  }
111
126M
  return ::operator new(Size + Extra, Ctx);
112
133M
}
113
114
2.89M
Module *Decl::getOwningModuleSlow() const {
115
2.89M
  assert(isFromASTFile() && "Not from AST file?");
116
0
  return getASTContext().getExternalSource()->getModule(getOwningModuleID());
117
2.89M
}
118
119
8.08M
bool Decl::hasLocalOwningModuleStorage() const {
120
8.08M
  return getASTContext().getLangOpts().trackLocalOwningModule();
121
8.08M
}
122
123
38.4k
const char *Decl::getDeclKindName() const {
124
38.4k
  switch (DeclKind) {
125
0
  default: llvm_unreachable("Declaration not in DeclNodes.inc!");
126
38.4k
#define DECL(DERIVED, BASE) case DERIVED: return #DERIVED;
127
0
#define ABSTRACT_DECL(DECL)
128
38.4k
#include 
"clang/AST/DeclNodes.inc"0
129
38.4k
  }
130
38.4k
}
131
132
258k
void Decl::setInvalidDecl(bool Invalid) {
133
258k
  InvalidDecl = Invalid;
134
258k
  assert(!isa<TagDecl>(this) || !cast<TagDecl>(this)->isCompleteDefinition());
135
258k
  if (!Invalid) {
136
215k
    return;
137
215k
  }
138
139
43.4k
  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
40.2k
    setAccess(AS_public);
144
40.2k
  }
145
146
  // Marking a DecompositionDecl as invalid implies all the child BindingDecl's
147
  // are invalid too.
148
43.4k
  if (auto *DD = dyn_cast<DecompositionDecl>(this)) {
149
110
    for (auto *Binding : DD->bindings()) {
150
110
      Binding->setInvalidDecl();
151
110
    }
152
78
  }
153
43.4k
}
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
45.2M
bool Decl::isTemplateParameterPack() const {
202
45.2M
  if (const auto *TTP = dyn_cast<TemplateTypeParmDecl>(this))
203
26.8M
    return TTP->isParameterPack();
204
18.4M
  if (const auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(this))
205
5.94M
    return NTTP->isParameterPack();
206
12.4M
  if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(this))
207
97.4k
    return TTP->isParameterPack();
208
12.3M
  return false;
209
12.4M
}
210
211
26.3M
bool Decl::isParameterPack() const {
212
26.3M
  if (const auto *Var = dyn_cast<VarDecl>(this))
213
17.9M
    return Var->isParameterPack();
214
215
8.44M
  return isTemplateParameterPack();
216
26.3M
}
217
218
68.5M
FunctionDecl *Decl::getAsFunction() {
219
68.5M
  if (auto *FD = dyn_cast<FunctionDecl>(this))
220
63.6M
    return FD;
221
4.94M
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
222
3.55M
    return FTD->getTemplatedDecl();
223
1.38M
  return nullptr;
224
4.94M
}
225
226
4.18M
bool Decl::isTemplateDecl() const {
227
4.18M
  return isa<TemplateDecl>(this);
228
4.18M
}
229
230
17.6M
TemplateDecl *Decl::getDescribedTemplate() const {
231
17.6M
  if (auto *FD = dyn_cast<FunctionDecl>(this))
232
3.30M
    return FD->getDescribedFunctionTemplate();
233
14.3M
  if (auto *RD = dyn_cast<CXXRecordDecl>(this))
234
770k
    return RD->getDescribedClassTemplate();
235
13.6M
  if (auto *VD = dyn_cast<VarDecl>(this))
236
1.80M
    return VD->getDescribedVarTemplate();
237
11.8M
  if (auto *AD = dyn_cast<TypeAliasDecl>(this))
238
2.09k
    return AD->getDescribedAliasTemplate();
239
240
11.8M
  return nullptr;
241
11.8M
}
242
243
4.01M
const TemplateParameterList *Decl::getDescribedTemplateParams() const {
244
4.01M
  if (auto *TD = getDescribedTemplate())
245
322k
    return TD->getTemplateParameters();
246
3.68M
  if (auto *CTPSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(this))
247
64.2k
    return CTPSD->getTemplateParameters();
248
3.62M
  if (auto *VTPSD = dyn_cast<VarTemplatePartialSpecializationDecl>(this))
249
13
    return VTPSD->getTemplateParameters();
250
3.62M
  return nullptr;
251
3.62M
}
252
253
29.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
29.3M
  if (auto *AsDC = dyn_cast<DeclContext>(this))
259
25.2M
    return AsDC->isDependentContext();
260
4.17M
  auto *DC = getFriendObjectKind() ? 
getLexicalDeclContext()0
: getDeclContext();
261
4.17M
  return DC->isDependentContext() || 
isTemplateDecl()4.10M
||
262
4.17M
         
getDescribedTemplateParams()3.60M
;
263
29.3M
}
264
265
26.1k
unsigned Decl::getTemplateDepth() const {
266
26.1k
  if (auto *DC = dyn_cast<DeclContext>(this))
267
26.1k
    if (DC->isFileContext())
268
118
      return 0;
269
270
26.0k
  if (auto *TPL = getDescribedTemplateParams())
271
25.8k
    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
1.78M
const DeclContext *Decl::getParentFunctionOrMethod() const {
287
1.78M
  for (const DeclContext *DC = getDeclContext();
288
1.82M
       DC && 
!DC->isTranslationUnit()1.81M
&&
!DC->isNamespace()1.71M
;
289
1.78M
       
DC = DC->getParent()41.6k
)
290
74.7k
    if (DC->isFunctionOrMethod())
291
33.1k
      return DC;
292
293
1.75M
  return nullptr;
294
1.78M
}
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.0k
Decl::~Decl() = default;
326
327
89.5M
void Decl::setDeclContext(DeclContext *DC) {
328
89.5M
  DeclCtx = DC;
329
89.5M
}
330
331
32.1M
void Decl::setLexicalDeclContext(DeclContext *DC) {
332
32.1M
  if (DC == getLexicalDeclContext())
333
31.5M
    return;
334
335
562k
  if (isInSemaDC()) {
336
548k
    setDeclContextsImpl(getDeclContext(), DC, getASTContext());
337
548k
  } else {
338
14.3k
    getMultipleDC()->LexicalDC = DC;
339
14.3k
  }
340
341
  // FIXME: We shouldn't be changing the lexical context of declarations
342
  // imported from AST files.
343
562k
  if (!isFromASTFile()) {
344
562k
    setModuleOwnershipKind(getModuleOwnershipKindForChildOf(DC));
345
562k
    if (hasOwningModule())
346
40.3k
      setLocalOwningModule(cast<Decl>(DC)->getOwningModule());
347
562k
  }
348
349
562k
  assert(
350
562k
      (getModuleOwnershipKind() != ModuleOwnershipKind::VisibleWhenImported ||
351
562k
       getOwningModule()) &&
352
562k
      "hidden declaration has no owning module");
353
562k
}
354
355
void Decl::setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
356
9.86M
                               ASTContext &Ctx) {
357
9.86M
  if (SemaDC == LexicalDC) {
358
8.96M
    DeclCtx = SemaDC;
359
8.96M
  } else {
360
902k
    auto *MDC = new (Ctx) Decl::MultipleDC();
361
902k
    MDC->SemanticDC = SemaDC;
362
902k
    MDC->LexicalDC = LexicalDC;
363
902k
    DeclCtx = MDC;
364
902k
  }
365
9.86M
}
366
367
138k
bool Decl::isInLocalScopeForInstantiation() const {
368
138k
  const DeclContext *LDC = getLexicalDeclContext();
369
138k
  if (!LDC->isDependentContext())
370
9.92k
    return false;
371
256k
  
while (128k
true) {
372
256k
    if (LDC->isFunctionOrMethod())
373
25
      return true;
374
256k
    if (!isa<TagDecl>(LDC))
375
128k
      return false;
376
128k
    if (const auto *CRD = dyn_cast<CXXRecordDecl>(LDC))
377
128k
      if (CRD->isLambda())
378
24
        return true;
379
128k
    LDC = LDC->getLexicalParent();
380
128k
  }
381
0
  return false;
382
128k
}
383
384
7.98M
bool Decl::isInAnonymousNamespace() const {
385
21.7M
  for (const DeclContext *DC = getDeclContext(); DC; 
DC = DC->getParent()13.7M
) {
386
13.7M
    if (const auto *ND = dyn_cast<NamespaceDecl>(DC))
387
4.20M
      if (ND->isAnonymousNamespace())
388
4.92k
        return true;
389
13.7M
  }
390
391
7.97M
  return false;
392
7.98M
}
393
394
2.83M
bool Decl::isInStdNamespace() const {
395
2.83M
  const DeclContext *DC = getDeclContext();
396
2.83M
  return DC && DC->isStdNamespace();
397
2.83M
}
398
399
2.89G
TranslationUnitDecl *Decl::getTranslationUnitDecl() {
400
2.89G
  if (auto *TUD = dyn_cast<TranslationUnitDecl>(this))
401
245M
    return TUD;
402
403
2.64G
  DeclContext *DC = getDeclContext();
404
2.64G
  assert(DC && "This decl is not contained in a translation unit!");
405
406
4.82G
  while (!DC->isTranslationUnit()) {
407
2.17G
    DC = DC->getParent();
408
2.17G
    assert(DC && "This decl is not contained in a translation unit!");
409
2.17G
  }
410
411
2.64G
  return cast<TranslationUnitDecl>(DC);
412
2.89G
}
413
414
2.89G
ASTContext &Decl::getASTContext() const {
415
2.89G
  return getTranslationUnitDecl()->getASTContext();
416
2.89G
}
417
418
/// Helper to get the language options from the ASTContext.
419
/// Defined out of line to avoid depending on ASTContext.h.
420
1.39M
const LangOptions &Decl::getLangOpts() const {
421
1.39M
  return getASTContext().getLangOpts();
422
1.39M
}
423
424
44.4M
ASTMutationListener *Decl::getASTMutationListener() const {
425
44.4M
  return getASTContext().getASTMutationListener();
426
44.4M
}
427
428
4.01M
unsigned Decl::getMaxAlignment() const {
429
4.01M
  if (!hasAttrs())
430
3.70M
    return 0;
431
432
311k
  unsigned Align = 0;
433
311k
  const AttrVec &V = getAttrs();
434
311k
  ASTContext &Ctx = getASTContext();
435
311k
  specific_attr_iterator<AlignedAttr> I(V.begin()), E(V.end());
436
325k
  for (; I != E; 
++I13.6k
) {
437
13.6k
    if (!I->isAlignmentErrorDependent())
438
13.6k
      Align = std::max(Align, I->getAlignment(Ctx));
439
13.6k
  }
440
311k
  return Align;
441
4.01M
}
442
443
97.0M
bool Decl::isUsed(bool CheckUsedAttr) const {
444
97.0M
  const Decl *CanonD = getCanonicalDecl();
445
97.0M
  if (CanonD->Used)
446
10.6M
    return true;
447
448
  // Check for used attribute.
449
  // Ask the most recent decl, since attributes accumulate in the redecl chain.
450
86.3M
  if (CheckUsedAttr && 
getMostRecentDecl()->hasAttr<UsedAttr>()48.2M
)
451
869
    return true;
452
453
  // The information may have not been deserialized yet. Force deserialization
454
  // to complete the needed information.
455
86.3M
  return getMostRecentDecl()->getCanonicalDecl()->Used;
456
86.3M
}
457
458
12.1M
void Decl::markUsed(ASTContext &C) {
459
12.1M
  if (isUsed(false))
460
3.63M
    return;
461
462
8.53M
  if (C.getASTMutationListener())
463
319k
    C.getASTMutationListener()->DeclarationMarkedUsed(this);
464
465
8.53M
  setIsUsed();
466
8.53M
}
467
468
112M
bool Decl::isReferenced() const {
469
112M
  if (Referenced)
470
23.6M
    return true;
471
472
  // Check redeclarations.
473
88.4M
  for (const auto *I : redecls())
474
103M
    if (I->Referenced)
475
6.54k
      return true;
476
477
88.4M
  return false;
478
88.4M
}
479
480
30.7k
ExternalSourceSymbolAttr *Decl::getExternalSourceSymbolAttr() const {
481
30.7k
  const Decl *Definition = nullptr;
482
30.7k
  if (auto *ID = dyn_cast<ObjCInterfaceDecl>(this)) {
483
1.51k
    Definition = ID->getDefinition();
484
29.2k
  } else if (auto *PD = dyn_cast<ObjCProtocolDecl>(this)) {
485
187
    Definition = PD->getDefinition();
486
29.0k
  } else if (auto *TD = dyn_cast<TagDecl>(this)) {
487
14.5k
    Definition = TD->getDefinition();
488
14.5k
  }
489
30.7k
  if (!Definition)
490
14.7k
    Definition = this;
491
492
30.7k
  if (auto *attr = Definition->getAttr<ExternalSourceSymbolAttr>())
493
71
    return attr;
494
30.6k
  if (auto *dcd = dyn_cast<Decl>(getDeclContext())) {
495
30.6k
    return dcd->getAttr<ExternalSourceSymbolAttr>();
496
30.6k
  }
497
498
0
  return nullptr;
499
30.6k
}
500
501
29.0M
bool Decl::hasDefiningAttr() const {
502
29.0M
  return hasAttr<AliasAttr>() || 
hasAttr<IFuncAttr>()29.0M
||
503
29.0M
         
hasAttr<LoaderUninitializedAttr>()29.0M
;
504
29.0M
}
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.31M
                                     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.31M
  StringRef RealizedPlatform = A->getPlatform()->getName();
521
4.31M
  if (!Context.getLangOpts().AppExt)
522
4.31M
    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.31M
                                            VersionTuple EnclosingVersion) {
542
4.31M
  if (EnclosingVersion.empty())
543
4.31M
    EnclosingVersion = Context.getTargetInfo().getPlatformMinVersion();
544
545
4.31M
  if (EnclosingVersion.empty())
546
35
    return AR_Available;
547
548
4.31M
  StringRef ActualPlatform = A->getPlatform()->getName();
549
4.31M
  StringRef TargetPlatform = Context.getTargetInfo().getPlatformName();
550
551
  // Match the platform name.
552
4.31M
  if (getRealizedPlatform(A, Context) != TargetPlatform)
553
2.82M
    return AR_Available;
554
555
1.49M
  StringRef PrettyPlatformName
556
1.49M
    = AvailabilityAttr::getPrettyPlatformName(ActualPlatform);
557
558
1.49M
  if (PrettyPlatformName.empty())
559
0
    PrettyPlatformName = ActualPlatform;
560
561
1.49M
  std::string HintMessage;
562
1.49M
  if (!A->getMessage().empty()) {
563
293k
    HintMessage = " - ";
564
293k
    HintMessage += A->getMessage();
565
293k
  }
566
567
  // Make sure that this declaration has not been marked 'unavailable'.
568
1.49M
  if (A->getUnavailable()) {
569
125k
    if (Message) {
570
373
      Message->clear();
571
373
      llvm::raw_string_ostream Out(*Message);
572
373
      Out << "not available on " << PrettyPlatformName
573
373
          << HintMessage;
574
373
    }
575
576
125k
    return AR_Unavailable;
577
125k
  }
578
579
  // Make sure that this declaration has already been introduced.
580
1.36M
  if (!A->getIntroduced().empty() &&
581
1.36M
      
EnclosingVersion < A->getIntroduced()1.36M
) {
582
1.23k
    if (Message) {
583
425
      Message->clear();
584
425
      llvm::raw_string_ostream Out(*Message);
585
425
      VersionTuple VTI(A->getIntroduced());
586
425
      Out << "introduced in " << PrettyPlatformName << ' '
587
425
          << VTI << HintMessage;
588
425
    }
589
590
1.23k
    return A->getStrict() ? 
AR_Unavailable8
:
AR_NotYetIntroduced1.22k
;
591
1.23k
  }
592
593
  // Make sure that this declaration hasn't been obsoleted.
594
1.36M
  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.36M
  if (!A->getDeprecated().empty() && 
EnclosingVersion >= A->getDeprecated()779k
) {
608
767k
    if (Message) {
609
265k
      Message->clear();
610
265k
      llvm::raw_string_ostream Out(*Message);
611
265k
      VersionTuple VTD(A->getDeprecated());
612
265k
      Out << "first deprecated in " << PrettyPlatformName << ' '
613
265k
          << VTD << HintMessage;
614
265k
    }
615
616
767k
    return AR_Deprecated;
617
767k
  }
618
619
600k
  return AR_Available;
620
1.36M
}
621
622
AvailabilityResult Decl::getAvailability(std::string *Message,
623
                                         VersionTuple EnclosingVersion,
624
125M
                                         StringRef *RealizedPlatform) const {
625
125M
  if (auto *FTD = dyn_cast<FunctionTemplateDecl>(this))
626
53.0k
    return FTD->getTemplatedDecl()->getAvailability(Message, EnclosingVersion,
627
53.0k
                                                    RealizedPlatform);
628
629
125M
  AvailabilityResult Result = AR_Available;
630
125M
  std::string ResultMessage;
631
632
125M
  for (const auto *A : attrs()) {
633
21.1M
    if (const auto *Deprecated = dyn_cast<DeprecatedAttr>(A)) {
634
3.35k
      if (Result >= AR_Deprecated)
635
62
        continue;
636
637
3.29k
      if (Message)
638
2.20k
        ResultMessage = std::string(Deprecated->getMessage());
639
640
3.29k
      Result = AR_Deprecated;
641
3.29k
      continue;
642
3.35k
    }
643
644
21.1M
    if (const auto *Unavailable = dyn_cast<UnavailableAttr>(A)) {
645
61.5k
      if (Message)
646
435
        *Message = std::string(Unavailable->getMessage());
647
61.5k
      return AR_Unavailable;
648
61.5k
    }
649
650
21.1M
    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
651
4.28M
      AvailabilityResult AR = CheckAvailability(getASTContext(), Availability,
652
4.28M
                                                Message, EnclosingVersion);
653
654
4.28M
      if (AR == AR_Unavailable) {
655
125k
        if (RealizedPlatform)
656
5
          *RealizedPlatform = Availability->getPlatform()->getName();
657
125k
        return AR_Unavailable;
658
125k
      }
659
660
4.16M
      if (AR > Result) {
661
768k
        Result = AR;
662
768k
        if (Message)
663
265k
          ResultMessage.swap(*Message);
664
768k
      }
665
4.16M
      continue;
666
4.28M
    }
667
21.1M
  }
668
669
125M
  if (Message)
670
122M
    Message->swap(ResultMessage);
671
125M
  return Result;
672
125M
}
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
18.1M
bool Decl::canBeWeakImported(bool &IsDefinition) const {
689
18.1M
  IsDefinition = false;
690
691
  // Variables, if they aren't definitions.
692
18.1M
  if (const auto *Var = dyn_cast<VarDecl>(this)) {
693
17.6M
    if (Var->isThisDeclarationADefinition()) {
694
13.4M
      IsDefinition = true;
695
13.4M
      return false;
696
13.4M
    }
697
4.23M
    return true;
698
17.6M
  }
699
  // Functions, if they aren't definitions.
700
456k
  if (const auto *FD = dyn_cast<FunctionDecl>(this)) {
701
426k
    if (FD->hasBody()) {
702
280k
      IsDefinition = true;
703
280k
      return false;
704
280k
    }
705
145k
    return true;
706
707
426k
  }
708
  // Objective-C classes, if this is the non-fragile runtime.
709
30.7k
  if (isa<ObjCInterfaceDecl>(this) &&
710
30.7k
             
getASTContext().getLangOpts().ObjCRuntime.hasWeakClassImport()22.9k
) {
711
22.7k
    return true;
712
22.7k
  }
713
  // Nothing else.
714
8.00k
  return false;
715
30.7k
}
716
717
18.1M
bool Decl::isWeakImported() const {
718
18.1M
  bool IsDefinition;
719
18.1M
  if (!canBeWeakImported(IsDefinition))
720
13.7M
    return false;
721
722
4.39M
  for (const auto *A : getMostRecentDecl()->attrs()) {
723
142k
    if (isa<WeakImportAttr>(A))
724
159
      return true;
725
726
142k
    if (const auto *Availability = dyn_cast<AvailabilityAttr>(A)) {
727
31.5k
      if (CheckAvailability(getASTContext(), Availability, nullptr,
728
31.5k
                            VersionTuple()) == AR_NotYetIntroduced)
729
43
        return true;
730
31.5k
    }
731
142k
  }
732
733
4.39M
  return false;
734
4.39M
}
735
736
143M
unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
737
143M
  switch (DeclKind) {
738
25.0M
    case Function:
739
25.0M
    case CXXDeductionGuide:
740
28.1M
    case CXXMethod:
741
29.2M
    case CXXConstructor:
742
29.2M
    case ConstructorUsingShadow:
743
29.4M
    case CXXDestructor:
744
29.5M
    case CXXConversion:
745
33.4M
    case EnumConstant:
746
37.6M
    case Var:
747
42.3M
    case ImplicitParam:
748
114M
    case ParmVar:
749
116M
    case ObjCMethod:
750
116M
    case ObjCProperty:
751
116M
    case MSProperty:
752
116M
      return IDNS_Ordinary;
753
2.62k
    case Label:
754
2.62k
      return IDNS_Label;
755
8.47k
    case IndirectField:
756
8.47k
      return IDNS_Ordinary | IDNS_Member;
757
758
949
    case Binding:
759
636k
    case NonTypeTemplateParm:
760
640k
    case VarTemplate:
761
640k
    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
640k
      return IDNS_Ordinary | IDNS_Tag;
765
766
246
    case ObjCCompatibleAlias:
767
287k
    case ObjCInterface:
768
287k
      return IDNS_Ordinary | IDNS_Type;
769
770
3.85M
    case Typedef:
771
4.16M
    case TypeAlias:
772
8.50M
    case TemplateTypeParm:
773
8.57M
    case ObjCTypeParam:
774
8.57M
      return IDNS_Ordinary | IDNS_Type;
775
776
1.24k
    case UnresolvedUsingTypename:
777
1.24k
      return IDNS_Ordinary | IDNS_Type | IDNS_Using;
778
779
415k
    case UsingShadow:
780
415k
      return 0; // we'll actually overwrite this later
781
782
1.05k
    case UnresolvedUsingValue:
783
1.05k
      return IDNS_Ordinary | IDNS_Using;
784
785
235k
    case Using:
786
235k
    case UsingPack:
787
235k
    case UsingEnum:
788
235k
      return IDNS_Using;
789
790
26.3k
    case ObjCProtocol:
791
26.3k
      return IDNS_ObjCProtocol;
792
793
4.18M
    case Field:
794
4.18M
    case ObjCAtDefsField:
795
4.32M
    case ObjCIvar:
796
4.32M
      return IDNS_Member;
797
798
553k
    case Record:
799
3.97M
    case CXXRecord:
800
4.53M
    case Enum:
801
4.53M
      return IDNS_Tag | IDNS_Type;
802
803
1.23M
    case Namespace:
804
1.23M
    case NamespaceAlias:
805
1.23M
      return IDNS_Namespace;
806
807
1.30M
    case FunctionTemplate:
808
1.30M
      return IDNS_Ordinary;
809
810
596k
    case ClassTemplate:
811
637k
    case TemplateTemplateParm:
812
739k
    case TypeAliasTemplate:
813
739k
      return IDNS_Ordinary | IDNS_Tag | IDNS_Type;
814
815
1.49k
    case UnresolvedUsingIfExists:
816
1.49k
      return IDNS_Type | IDNS_Ordinary;
817
818
906
    case OMPDeclareReduction:
819
906
      return IDNS_OMPReduction;
820
821
419
    case OMPDeclareMapper:
822
419
      return IDNS_OMPMapper;
823
824
    // Never have names.
825
145k
    case Friend:
826
145k
    case FriendTemplate:
827
601k
    case AccessSpec:
828
980k
    case LinkageSpec:
829
980k
    case Export:
830
981k
    case FileScopeAsm:
831
1.11M
    case StaticAssert:
832
1.12M
    case ObjCPropertyImpl:
833
1.12M
    case PragmaComment:
834
1.12M
    case PragmaDetectMismatch:
835
1.12M
    case Block:
836
1.72M
    case Captured:
837
1.82M
    case TranslationUnit:
838
1.89M
    case ExternCContext:
839
1.89M
    case Decomposition:
840
1.89M
    case MSGuid:
841
1.89M
    case UnnamedGlobalConstant:
842
1.89M
    case TemplateParamObject:
843
844
1.89M
    case UsingDirective:
845
1.89M
    case BuiltinTemplate:
846
3.96M
    case ClassTemplateSpecialization:
847
4.15M
    case ClassTemplatePartialSpecialization:
848
4.15M
    case ClassScopeFunctionSpecialization:
849
4.15M
    case VarTemplateSpecialization:
850
4.15M
    case VarTemplatePartialSpecialization:
851
4.16M
    case ObjCImplementation:
852
4.22M
    case ObjCCategory:
853
4.22M
    case ObjCCategoryImpl:
854
4.34M
    case Import:
855
4.34M
    case OMPThreadPrivate:
856
4.34M
    case OMPAllocate:
857
4.34M
    case OMPRequires:
858
4.41M
    case OMPCapturedExpr:
859
4.42M
    case Empty:
860
4.42M
    case LifetimeExtendedTemporary:
861
4.42M
    case RequiresExprBody:
862
      // Never looked up by name.
863
4.42M
      return 0;
864
143M
  }
865
866
0
  llvm_unreachable("Invalid DeclKind!");
867
0
}
868
869
31.2M
void Decl::setAttrsImpl(const AttrVec &attrs, ASTContext &Ctx) {
870
31.2M
  assert(!HasAttrs && "Decl already contains attrs.");
871
872
0
  AttrVec &AttrBlank = Ctx.getDeclAttrs(this);
873
31.2M
  assert(AttrBlank.empty() && "HasAttrs was wrong?");
874
875
0
  AttrBlank = attrs;
876
31.2M
  HasAttrs = true;
877
31.2M
}
878
879
4.57k
void Decl::dropAttrs() {
880
4.57k
  if (!HasAttrs) 
return0
;
881
882
4.57k
  HasAttrs = false;
883
4.57k
  getASTContext().eraseDeclAttrs(this);
884
4.57k
}
885
886
103M
void Decl::addAttr(Attr *A) {
887
103M
  if (!hasAttrs()) {
888
29.9M
    setAttrs(AttrVec(1, A));
889
29.9M
    return;
890
29.9M
  }
891
892
73.6M
  AttrVec &Attrs = getAttrs();
893
73.6M
  if (!A->isInherited()) {
894
73.3M
    Attrs.push_back(A);
895
73.3M
    return;
896
73.3M
  }
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
349k
  auto I = Attrs.begin(), E = Attrs.end();
902
549k
  for (; I != E; 
++I200k
) {
903
223k
    if (!(*I)->isInherited())
904
23.4k
      break;
905
223k
  }
906
349k
  Attrs.insert(I, A);
907
349k
}
908
909
1.84G
const AttrVec &Decl::getAttrs() const {
910
1.84G
  assert(HasAttrs && "No attrs to get!");
911
0
  return getASTContext().getDeclAttrs(this);
912
1.84G
}
913
914
3.78G
Decl *Decl::castFromDeclContext (const DeclContext *D) {
915
3.78G
  Decl::Kind DK = D->getDeclKind();
916
3.78G
  switch(DK) {
917
0
#define DECL(NAME, BASE)
918
0
#define DECL_CONTEXT(NAME) \
919
2.82G
    case Decl::NAME:       \
920
2.82G
      return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D));
921
0
#define DECL_CONTEXT_BASE(NAME)
922
0
#include "clang/AST/DeclNodes.inc"
923
962M
    default:
924
962M
#define DECL(NAME, BASE)
925
962M
#define DECL_CONTEXT_BASE(NAME)                  \
926
1.62G
      if (DK >= first##NAME && 
DK <= last962M
##NAME) \
927
1.62G
        
return static_cast<NAME##Decl *>(const_cast<DeclContext *>(D))962M
;
928
962M
#include "clang/AST/DeclNodes.inc"
929
18.4E
      llvm_unreachable("a decl that inherits DeclContext isn't handled");
930
3.78G
  }
931
3.78G
}
932
933
56.3M
DeclContext *Decl::castToDeclContext(const Decl *D) {
934
56.3M
  Decl::Kind DK = D->getKind();
935
56.3M
  switch(DK) {
936
0
#define DECL(NAME, BASE)
937
0
#define DECL_CONTEXT(NAME) \
938
7.27M
    case Decl::NAME:       \
939
7.27M
      return static_cast<NAME##Decl *>(const_cast<Decl *>(D));
940
0
#define DECL_CONTEXT_BASE(NAME)
941
0
#include "clang/AST/DeclNodes.inc"
942
49.1M
    default:
943
49.1M
#define DECL(NAME, BASE)
944
49.1M
#define DECL_CONTEXT_BASE(NAME)                                   \
945
65.9M
      if (DK >= first##NAME && 
DK <= last49.1M
##NAME) \
946
65.9M
        
return static_cast<NAME##Decl *>(const_cast<Decl *>(D))49.1M
;
947
49.1M
#include "clang/AST/DeclNodes.inc"
948
56.3M
      
llvm_unreachable0
("a decl that inherits DeclContext isn't handled");
949
56.3M
  }
950
56.3M
}
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.4k
  if (Stmt *Body = getBody())
963
26.4k
    return Body->getSourceRange().getEnd();
964
965
0
  return {};
966
26.4k
}
967
968
320M
bool Decl::AccessDeclContextCheck() const {
969
320M
#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
320M
  if (
isa<TranslationUnitDecl>(this)320M
|| isa<TemplateTypeParmDecl>(this) ||
980
320M
      
isa<NonTypeTemplateParmDecl>(this)312M
||
!getDeclContext()311M
||
981
320M
      
!isa<CXXRecordDecl>(getDeclContext())311M
||
isInvalidDecl()46.3M
||
982
320M
      
isa<StaticAssertDecl>(this)46.3M
||
isa<BlockDecl>(this)46.3M
||
983
      // FIXME: a ParmVarDecl can have ClassTemplateSpecialization
984
      // as DeclContext (?).
985
320M
      
isa<ParmVarDecl>(this)46.3M
||
986
      // FIXME: a ClassTemplateSpecialization or CXXRecordDecl can have
987
      // AS_none as access specifier.
988
320M
      
isa<CXXRecordDecl>(this)46.3M
||
989
320M
      
isa<ClassScopeFunctionSpecializationDecl>(this)42.2M
||
990
320M
      
isa<LifetimeExtendedTemporaryDecl>(this)42.2M
)
991
277M
    return true;
992
993
42.2M
  assert(Access != AS_none &&
994
42.2M
         "Access specifier is AS_none inside a record decl");
995
0
#endif
996
0
  return true;
997
320M
}
998
999
359k
bool Decl::isInExportDeclContext() const {
1000
359k
  const DeclContext *DC = getLexicalDeclContext();
1001
1002
968k
  while (DC && 
!isa<ExportDecl>(DC)608k
)
1003
608k
    DC = DC->getLexicalParent();
1004
1005
359k
  return DC && 
isa<ExportDecl>(DC)31
;
1006
359k
}
1007
1008
306k
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
19.9M
const FunctionType *Decl::getFunctionType(bool BlocksToo) const {
1016
19.9M
  QualType Ty;
1017
19.9M
  if (const auto *D = dyn_cast<ValueDecl>(this))
1018
19.9M
    Ty = D->getType();
1019
35.2k
  else if (const auto *D = dyn_cast<TypedefNameDecl>(this))
1020
1.91k
    Ty = D->getUnderlyingType();
1021
33.3k
  else
1022
33.3k
    return nullptr;
1023
1024
19.9M
  if (Ty->isFunctionPointerType())
1025
349
    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.10M
)
1029
1.89k
    Ty = Ty->castAs<BlockPointerType>()->getPointeeType();
1030
1031
19.9M
  return Ty->getAs<FunctionType>();
1032
19.9M
}
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
394k
template <class T> static Decl *getNonClosureContext(T *D) {
1037
394k
  if (getKind(D) == Decl::CXXMethod) {
1038
56.8k
    auto *MD = cast<CXXMethodDecl>(D);
1039
56.8k
    if (MD->getOverloadedOperator() == OO_Call &&
1040
56.8k
        
MD->getParent()->isLambda()5.08k
)
1041
3.11k
      return getNonClosureContext(MD->getParent()->getParent());
1042
53.6k
    return MD;
1043
56.8k
  }
1044
337k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
257k
    return FD;
1046
79.5k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1047
6.51k
    return MD;
1048
73.0k
  if (auto *BD = dyn_cast<BlockDecl>(D))
1049
1.61k
    return getNonClosureContext(BD->getParent());
1050
71.4k
  if (auto *CD = dyn_cast<CapturedDecl>(D))
1051
64.8k
    return getNonClosureContext(CD->getParent());
1052
6.57k
  return nullptr;
1053
71.4k
}
DeclBase.cpp:clang::Decl* getNonClosureContext<clang::Decl>(clang::Decl*)
Line
Count
Source
1036
306k
template <class T> static Decl *getNonClosureContext(T *D) {
1037
306k
  if (getKind(D) == Decl::CXXMethod) {
1038
52.0k
    auto *MD = cast<CXXMethodDecl>(D);
1039
52.0k
    if (MD->getOverloadedOperator() == OO_Call &&
1040
52.0k
        
MD->getParent()->isLambda()3.60k
)
1041
1.63k
      return getNonClosureContext(MD->getParent()->getParent());
1042
50.4k
    return MD;
1043
52.0k
  }
1044
254k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
218k
    return FD;
1046
35.4k
  if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
1047
2.58k
    return MD;
1048
32.8k
  if (auto *BD = dyn_cast<BlockDecl>(D))
1049
1.22k
    return getNonClosureContext(BD->getParent());
1050
31.6k
  if (auto *CD = dyn_cast<CapturedDecl>(D))
1051
25.2k
    return getNonClosureContext(CD->getParent());
1052
6.40k
  return nullptr;
1053
31.6k
}
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.2k
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1045
39.1k
    return FD;
1046
44.0k
  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.5k
    return getNonClosureContext(CD->getParent());
1052
171
  return nullptr;
1053
39.7k
}
1054
1055
306k
Decl *Decl::getNonClosureContext() {
1056
306k
  return ::getNonClosureContext(this);
1057
306k
}
1058
1059
18.4k
Decl *DeclContext::getNonClosureAncestor() {
1060
18.4k
  return ::getNonClosureContext(this);
1061
18.4k
}
1062
1063
//===----------------------------------------------------------------------===//
1064
// DeclContext Implementation
1065
//===----------------------------------------------------------------------===//
1066
1067
40.2M
DeclContext::DeclContext(Decl::Kind K) {
1068
40.2M
  DeclContextBits.DeclKind = K;
1069
40.2M
  setHasExternalLexicalStorage(false);
1070
40.2M
  setHasExternalVisibleStorage(false);
1071
40.2M
  setNeedToReconcileExternalVisibleStorage(false);
1072
40.2M
  setHasLazyLocalLexicalLookups(false);
1073
40.2M
  setHasLazyExternalLexicalLookups(false);
1074
40.2M
  setUseQualifiedLookup(false);
1075
40.2M
}
1076
1077
59.5M
bool DeclContext::classof(const Decl *D) {
1078
59.5M
  switch (D->getKind()) {
1079
0
#define DECL(NAME, BASE)
1080
30.9M
#define DECL_CONTEXT(NAME) case Decl::NAME:
1081
0
#define DECL_CONTEXT_BASE(NAME)
1082
5.61M
#include 
"clang/AST/DeclNodes.inc"0
1083
5.61M
      return true;
1084
53.9M
    default:
1085
53.9M
#define DECL(NAME, BASE)
1086
53.9M
#define DECL_CONTEXT_BASE(NAME)                 \
1087
98.8M
      if (D->getKind() >= Decl::first##NAME &&  \
1088
98.8M
          
D->getKind() <= Decl::last76.0M
##NAME) \
1089
98.8M
        
return true36.8M
;
1090
53.9M
#include "clang/AST/DeclNodes.inc"
1091
17.1M
      return false;
1092
59.5M
  }
1093
59.5M
}
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
67.3M
DeclContext *DeclContext::getLookupParent() {
1104
  // FIXME: Find a better way to identify friends.
1105
67.3M
  if (isa<FunctionDecl>(this))
1106
7.88M
    if (getParent()->getRedeclContext()->isFileContext() &&
1107
7.88M
        
getLexicalParent()->getRedeclContext()->isRecord()4.10M
)
1108
16.5k
      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
67.3M
  if (isLambdaCallOperator(this))
1114
21.1k
    return getParent()->getParent();
1115
1116
67.3M
  return getParent();
1117
67.3M
}
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
54.9M
bool DeclContext::isInlineNamespace() const {
1132
54.9M
  return isNamespace() &&
1133
54.9M
         
cast<NamespaceDecl>(this)->isInline()7.86M
;
1134
54.9M
}
1135
1136
3.50M
bool DeclContext::isStdNamespace() const {
1137
3.50M
  if (!isNamespace())
1138
2.13M
    return false;
1139
1140
1.36M
  const auto *ND = cast<NamespaceDecl>(this);
1141
1.36M
  if (ND->isInline()) {
1142
605k
    return ND->getParent()->isStdNamespace();
1143
605k
  }
1144
1145
762k
  if (!getParent()->getRedeclContext()->isTranslationUnit())
1146
36.3k
    return false;
1147
1148
726k
  const IdentifierInfo *II = ND->getIdentifier();
1149
726k
  return II && 
II->isStr("std")725k
;
1150
762k
}
1151
1152
385M
bool DeclContext::isDependentContext() const {
1153
385M
  if (isFileContext())
1154
198M
    return false;
1155
1156
186M
  if (isa<ClassTemplatePartialSpecializationDecl>(this))
1157
5.36M
    return true;
1158
1159
181M
  if (const auto *Record = dyn_cast<CXXRecordDecl>(this)) {
1160
64.0M
    if (Record->getDescribedClassTemplate())
1161
21.1M
      return true;
1162
1163
42.9M
    if (Record->isDependentLambda())
1164
24.1k
      return true;
1165
42.8M
    if (Record->isNeverDependentLambda())
1166
529
      return false;
1167
42.8M
  }
1168
1169
160M
  if (const auto *Function = dyn_cast<FunctionDecl>(this)) {
1170
62.0M
    if (Function->getDescribedFunctionTemplate())
1171
4.77M
      return true;
1172
1173
    // Friend function declarations are dependent if their *lexical*
1174
    // context is dependent.
1175
57.3M
    if (cast<Decl>(this)->getFriendObjectKind())
1176
83.5k
      return getLexicalParent()->isDependentContext();
1177
57.3M
  }
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
155M
  return getParent() && 
getParent()->isDependentContext()155M
;
1184
160M
}
1185
1186
1.41G
bool DeclContext::isTransparentContext() const {
1187
1.41G
  if (getDeclKind() == Decl::Enum)
1188
8.66M
    return !cast<EnumDecl>(this)->isScoped();
1189
1190
1.40G
  return getDeclKind() == Decl::LinkageSpec || 
getDeclKind() == Decl::Export1.09G
;
1191
1.41G
}
1192
1193
static bool isLinkageSpecContext(const DeclContext *DC,
1194
35.2M
                                 LinkageSpecDecl::LanguageIDs ID) {
1195
60.3M
  while (DC->getDeclKind() != Decl::TranslationUnit) {
1196
47.5M
    if (DC->getDeclKind() == Decl::LinkageSpec)
1197
22.4M
      return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
1198
25.0M
    DC = DC->getLexicalParent();
1199
25.0M
  }
1200
12.8M
  return false;
1201
35.2M
}
1202
1203
35.2M
bool DeclContext::isExternCContext() const {
1204
35.2M
  return isLinkageSpecContext(this, LinkageSpecDecl::lang_c);
1205
35.2M
}
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
21.5k
bool DeclContext::isExternCXXContext() const {
1219
21.5k
  return isLinkageSpecContext(this, LinkageSpecDecl::lang_cxx);
1220
21.5k
}
1221
1222
22.2M
bool DeclContext::Encloses(const DeclContext *DC) const {
1223
22.2M
  if (getPrimaryContext() != this)
1224
7.48M
    return getPrimaryContext()->Encloses(DC);
1225
1226
36.2M
  
for (; 14.7M
DC;
DC = DC->getParent()21.5M
)
1227
29.1M
    if (!isa<LinkageSpecDecl>(DC) && 
!isa<ExportDecl>(DC)29.1M
&&
1228
29.1M
        
DC->getPrimaryContext() == this29.1M
)
1229
7.59M
      return true;
1230
7.12M
  return false;
1231
14.7M
}
1232
1233
6.19M
DeclContext *DeclContext::getNonTransparentContext() {
1234
6.19M
  DeclContext *DC = this;
1235
6.61M
  while (DC->isTransparentContext()) {
1236
425k
    DC = DC->getParent();
1237
425k
    assert(DC && "All transparent contexts should have a parent!");
1238
425k
  }
1239
6.19M
  return DC;
1240
6.19M
}
1241
1242
1.37G
DeclContext *DeclContext::getPrimaryContext() {
1243
1.37G
  switch (getDeclKind()) {
1244
27.0M
  case Decl::ExternCContext:
1245
114M
  case Decl::LinkageSpec:
1246
114M
  case Decl::Export:
1247
115M
  case Decl::Block:
1248
124M
  case Decl::Captured:
1249
124M
  case Decl::OMPDeclareReduction:
1250
124M
  case Decl::OMPDeclareMapper:
1251
124M
  case Decl::RequiresExprBody:
1252
    // There is only one DeclContext for these entities.
1253
124M
    return this;
1254
1255
684M
  case Decl::TranslationUnit:
1256
684M
    return static_cast<TranslationUnitDecl *>(this)->getFirstDecl();
1257
264M
  case Decl::Namespace:
1258
    // The original namespace is our primary context.
1259
264M
    return static_cast<NamespaceDecl *>(this)->getOriginalNamespace();
1260
1261
403k
  case Decl::ObjCMethod:
1262
403k
    return this;
1263
1264
7.29M
  case Decl::ObjCInterface:
1265
7.29M
    if (auto *OID = dyn_cast<ObjCInterfaceDecl>(this))
1266
7.29M
      if (auto *Def = OID->getDefinition())
1267
7.29M
        return Def;
1268
1.08k
    return this;
1269
1270
2.70M
  case Decl::ObjCProtocol:
1271
2.70M
    if (auto *OPD = dyn_cast<ObjCProtocolDecl>(this))
1272
2.70M
      if (auto *Def = OPD->getDefinition())
1273
2.70M
        return Def;
1274
145
    return this;
1275
1276
9.42M
  case Decl::ObjCCategory:
1277
9.42M
    return this;
1278
1279
98.6k
  case Decl::ObjCImplementation:
1280
105k
  case Decl::ObjCCategoryImpl:
1281
105k
    return this;
1282
1283
283M
  default:
1284
283M
    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
242M
      auto *Tag = cast<TagDecl>(this);
1288
1289
242M
      if (TagDecl *Def = Tag->getDefinition())
1290
229M
        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
13.0M
          return PossiblePartialDef;
1297
13.5M
      } else {
1298
180k
        assert(isa<InjectedClassNameType>(Tag->getTypeForDecl()));
1299
180k
      }
1300
1301
696k
      return Tag;
1302
13.7M
    }
1303
1304
40.6M
    assert(getDeclKind() >= Decl::firstFunction &&
1305
40.6M
           getDeclKind() <= Decl::lastFunction &&
1306
40.6M
          "Unknown DeclContext kind");
1307
0
    return this;
1308
1.37G
  }
1309
1.37G
}
1310
1311
template <typename T>
1312
82.1k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
166k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()84.8k
)
1314
84.8k
    Contexts.push_back(D);
1315
1316
82.1k
  std::reverse(Contexts.begin(), Contexts.end());
1317
82.1k
}
void collectAllContextsImpl<clang::TranslationUnitDecl>(clang::TranslationUnitDecl*, llvm::SmallVectorImpl<clang::DeclContext*>&)
Line
Count
Source
1312
51.3k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
102k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()51.3k
)
1314
51.3k
    Contexts.push_back(D);
1315
1316
51.3k
  std::reverse(Contexts.begin(), Contexts.end());
1317
51.3k
}
void collectAllContextsImpl<clang::NamespaceDecl>(clang::NamespaceDecl*, llvm::SmallVectorImpl<clang::DeclContext*>&)
Line
Count
Source
1312
30.7k
void collectAllContextsImpl(T *Self, SmallVectorImpl<DeclContext *> &Contexts) {
1313
64.1k
  for (T *D = Self->getMostRecentDecl(); D; 
D = D->getPreviousDecl()33.4k
)
1314
33.4k
    Contexts.push_back(D);
1315
1316
30.7k
  std::reverse(Contexts.begin(), Contexts.end());
1317
30.7k
}
1318
1319
1.95M
void DeclContext::collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts) {
1320
1.95M
  Contexts.clear();
1321
1322
1.95M
  Decl::Kind Kind = getDeclKind();
1323
1324
1.95M
  if (Kind == Decl::TranslationUnit)
1325
51.3k
    collectAllContextsImpl(static_cast<TranslationUnitDecl *>(this), Contexts);
1326
1.90M
  else if (Kind == Decl::Namespace)
1327
30.7k
    collectAllContextsImpl(static_cast<NamespaceDecl *>(this), Contexts);
1328
1.87M
  else
1329
1.87M
    Contexts.push_back(this);
1330
1.95M
}
1331
1332
std::pair<Decl *, Decl *>
1333
DeclContext::BuildDeclChain(ArrayRef<Decl *> Decls,
1334
145k
                            bool FieldsAlreadyLoaded) {
1335
  // Build up a chain of declarations via the Decl::NextInContextAndBits field.
1336
145k
  Decl *FirstNewDecl = nullptr;
1337
145k
  Decl *PrevDecl = nullptr;
1338
1.32M
  for (auto *D : Decls) {
1339
1.32M
    if (FieldsAlreadyLoaded && 
isa<FieldDecl>(D)68.0k
)
1340
0
      continue;
1341
1342
1.32M
    if (PrevDecl)
1343
1.17M
      PrevDecl->NextInContextAndBits.setPointer(D);
1344
145k
    else
1345
145k
      FirstNewDecl = D;
1346
1347
1.32M
    PrevDecl = D;
1348
1.32M
  }
1349
1350
145k
  return std::make_pair(FirstNewDecl, PrevDecl);
1351
145k
}
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
28.4k
void DeclContext::reconcileExternalVisibleStorage() const {
1357
28.4k
  assert(hasNeedToReconcileExternalVisibleStorage() && LookupPtr);
1358
0
  setNeedToReconcileExternalVisibleStorage(false);
1359
1360
28.4k
  for (auto &Lookup : *LookupPtr)
1361
1.31M
    Lookup.second.setHasExternalDecls();
1362
28.4k
}
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
239k
DeclContext::LoadLexicalDeclsFromExternalStorage() const {
1369
239k
  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1370
239k
  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
239k
  SmallVector<Decl*, 64> Decls;
1377
239k
  setHasExternalLexicalStorage(false);
1378
239k
  Source->FindExternalLexicalDecls(this, Decls);
1379
1380
239k
  if (Decls.empty())
1381
104k
    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
135k
  bool FieldsAlreadyLoaded = false;
1386
135k
  if (const auto *RD = dyn_cast<RecordDecl>(this))
1387
129k
    FieldsAlreadyLoaded = RD->hasLoadedFieldsFromExternalStorage();
1388
1389
  // Splice the newly-read declarations into the beginning of the list
1390
  // of declarations.
1391
135k
  Decl *ExternalFirst, *ExternalLast;
1392
135k
  std::tie(ExternalFirst, ExternalLast) =
1393
135k
      BuildDeclChain(Decls, FieldsAlreadyLoaded);
1394
135k
  ExternalLast->NextInContextAndBits.setPointer(FirstDecl);
1395
135k
  FirstDecl = ExternalFirst;
1396
135k
  if (!LastDecl)
1397
133k
    LastDecl = ExternalLast;
1398
135k
  return true;
1399
239k
}
1400
1401
DeclContext::lookup_result
1402
ExternalASTSource::SetNoExternalVisibleDeclsForName(const DeclContext *DC,
1403
401k
                                                    DeclarationName Name) {
1404
401k
  ASTContext &Context = DC->getParentASTContext();
1405
401k
  StoredDeclsMap *Map;
1406
401k
  if (!(Map = DC->LookupPtr))
1407
0
    Map = DC->CreateStoredDeclsMap(Context);
1408
401k
  if (DC->hasNeedToReconcileExternalVisibleStorage())
1409
0
    DC->reconcileExternalVisibleStorage();
1410
1411
401k
  (*Map)[Name].removeExternalDecls();
1412
1413
401k
  return DeclContext::lookup_result();
1414
401k
}
1415
1416
DeclContext::lookup_result
1417
ExternalASTSource::SetExternalVisibleDeclsForName(const DeclContext *DC,
1418
                                                  DeclarationName Name,
1419
1.74M
                                                  ArrayRef<NamedDecl*> Decls) {
1420
1.74M
  ASTContext &Context = DC->getParentASTContext();
1421
1.74M
  StoredDeclsMap *Map;
1422
1.74M
  if (!(Map = DC->LookupPtr))
1423
19
    Map = DC->CreateStoredDeclsMap(Context);
1424
1.74M
  if (DC->hasNeedToReconcileExternalVisibleStorage())
1425
13.1k
    DC->reconcileExternalVisibleStorage();
1426
1427
1.74M
  StoredDeclsList &List = (*Map)[Name];
1428
1.74M
  List.replaceExternalDecls(Decls);
1429
1.74M
  return List.getLookupResult();
1430
1.74M
}
1431
1432
15.8M
DeclContext::decl_iterator DeclContext::decls_begin() const {
1433
15.8M
  if (hasExternalLexicalStorage())
1434
138k
    LoadLexicalDeclsFromExternalStorage();
1435
15.8M
  return decl_iterator(FirstDecl);
1436
15.8M
}
1437
1438
853k
bool DeclContext::decls_empty() const {
1439
853k
  if (hasExternalLexicalStorage())
1440
19
    LoadLexicalDeclsFromExternalStorage();
1441
1442
853k
  return !FirstDecl;
1443
853k
}
1444
1445
108k
bool DeclContext::containsDecl(Decl *D) const {
1446
108k
  return (D->getLexicalDeclContext() == this &&
1447
108k
          
(107k
D->NextInContextAndBits.getPointer()107k
||
D == LastDecl7.97k
));
1448
108k
}
1449
1450
7.60k
bool DeclContext::containsDeclAndLoad(Decl *D) const {
1451
7.60k
  if (hasExternalLexicalStorage())
1452
10
    LoadLexicalDeclsFromExternalStorage();
1453
7.60k
  return containsDecl(D);
1454
7.60k
}
1455
1456
/// shouldBeHidden - Determine whether a declaration which was declared
1457
/// within its semantic context should be invisible to qualified name lookup.
1458
56.3M
static bool shouldBeHidden(NamedDecl *D) {
1459
  // Skip unnamed declarations.
1460
56.3M
  if (!D->getDeclName())
1461
1.07M
    return true;
1462
1463
  // Skip entities that can't be found by name lookup into a particular
1464
  // context.
1465
55.2M
  if ((D->getIdentifierNamespace() == 0 && 
!isa<UsingDirectiveDecl>(D)326k
) ||
1466
55.2M
      
D->isTemplateParameter()54.9M
)
1467
323k
    return true;
1468
1469
  // Skip friends and local extern declarations unless they're the first
1470
  // declaration of the entity.
1471
54.9M
  if ((D->isLocalExternDecl() || 
D->getFriendObjectKind()54.9M
) &&
1472
54.9M
      
D != D->getCanonicalDecl()63.6k
)
1473
19.7k
    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
54.8M
  if (isa<ClassTemplateSpecializationDecl>(D))
1480
0
    return true;
1481
54.8M
  if (auto *FD = dyn_cast<FunctionDecl>(D))
1482
27.7M
    if (FD->isFunctionTemplateSpecialization())
1483
17.2k
      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
54.8M
  if (isa<CXXDestructorDecl>(D) && 
D->isInvalidDecl()168k
)
1490
35
    return true;
1491
1492
54.8M
  return false;
1493
54.8M
}
1494
1495
98.7k
void DeclContext::removeDecl(Decl *D) {
1496
98.7k
  assert(D->getLexicalDeclContext() == this &&
1497
98.7k
         "decl being removed from non-lexical context");
1498
0
  assert((D->NextInContextAndBits.getPointer() || D == LastDecl) &&
1499
98.7k
         "decl is not in decls list");
1500
1501
  // Remove D from the decl chain.  This is O(n) but hopefully rare.
1502
98.7k
  if (D == FirstDecl) {
1503
11.5k
    if (D == LastDecl)
1504
730
      FirstDecl = LastDecl = nullptr;
1505
10.8k
    else
1506
10.8k
      FirstDecl = D->NextInContextAndBits.getPointer();
1507
87.2k
  } else {
1508
3.50M
    for (Decl *I = FirstDecl; true; 
I = I->NextInContextAndBits.getPointer()3.41M
) {
1509
3.50M
      assert(I && "decl not found in linked list");
1510
3.50M
      if (I->NextInContextAndBits.getPointer() == D) {
1511
87.2k
        I->NextInContextAndBits.setPointer(D->NextInContextAndBits.getPointer());
1512
87.2k
        if (D == LastDecl) 
LastDecl = I2.00k
;
1513
87.2k
        break;
1514
87.2k
      }
1515
3.50M
    }
1516
87.2k
  }
1517
1518
  // Mark that D is no longer in the decl chain.
1519
98.7k
  D->NextInContextAndBits.setPointer(nullptr);
1520
1521
  // Remove D from the lookup table if necessary.
1522
98.7k
  if (isa<NamedDecl>(D)) {
1523
61.6k
    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
61.6k
    if (shouldBeHidden(ND))
1528
672
      return;
1529
1530
    // Remove only decls that have a name
1531
60.9k
    if (!ND->getDeclName())
1532
0
      return;
1533
1534
60.9k
    auto *DC = D->getDeclContext();
1535
60.9k
    do {
1536
60.9k
      StoredDeclsMap *Map = DC->getPrimaryContext()->LookupPtr;
1537
60.9k
      if (Map) {
1538
58.4k
        StoredDeclsMap::iterator Pos = Map->find(ND->getDeclName());
1539
58.4k
        assert(Pos != Map->end() && "no lookup entry for decl");
1540
0
        Pos->second.remove(ND);
1541
58.4k
      }
1542
60.9k
    } while (DC->isTransparentContext() && 
(DC = DC->getParent())0
);
1543
60.9k
  }
1544
98.7k
}
1545
1546
60.3M
void DeclContext::addHiddenDecl(Decl *D) {
1547
60.3M
  assert(D->getLexicalDeclContext() == this &&
1548
60.3M
         "Decl inserted into wrong lexical context");
1549
0
  assert(!D->getNextDeclInContext() && D != LastDecl &&
1550
60.3M
         "Decl already inserted into a DeclContext");
1551
1552
60.3M
  if (FirstDecl) {
1553
52.2M
    LastDecl->NextInContextAndBits.setPointer(D);
1554
52.2M
    LastDecl = D;
1555
52.2M
  } else {
1556
8.07M
    FirstDecl = LastDecl = D;
1557
8.07M
  }
1558
1559
  // Notify a C++ record declaration that we've added a member, so it can
1560
  // update its class-specific state.
1561
60.3M
  if (auto *Record = dyn_cast<CXXRecordDecl>(this))
1562
9.22M
    Record->addedMember(D);
1563
1564
  // If this is a newly-created (not de-serialized) import declaration, wire
1565
  // it in to the list of local import declarations.
1566
60.3M
  if (!D->isFromASTFile()) {
1567
60.3M
    if (auto *Import = dyn_cast<ImportDecl>(D))
1568
120k
      D->getASTContext().addedLocalImportDecl(Import);
1569
60.3M
  }
1570
60.3M
}
1571
1572
56.3M
void DeclContext::addDecl(Decl *D) {
1573
56.3M
  addHiddenDecl(D);
1574
1575
56.3M
  if (auto *ND = dyn_cast<NamedDecl>(D))
1576
55.0M
    ND->getDeclContext()->getPrimaryContext()->
1577
55.0M
        makeDeclVisibleInContextWithFlags(ND, false, true);
1578
56.3M
}
1579
1580
3.38M
void DeclContext::addDeclInternal(Decl *D) {
1581
3.38M
  addHiddenDecl(D);
1582
1583
3.38M
  if (auto *ND = dyn_cast<NamedDecl>(D))
1584
3.20M
    ND->getDeclContext()->getPrimaryContext()->
1585
3.20M
        makeDeclVisibleInContextWithFlags(ND, true, true);
1586
3.38M
}
1587
1588
/// buildLookup - Build the lookup data structure with all of the
1589
/// declarations in this DeclContext (and any other contexts linked
1590
/// to it or transparent contexts nested within it) and return it.
1591
///
1592
/// Note that the produced map may miss out declarations from an
1593
/// external source. If it does, those entries will be marked with
1594
/// the 'hasExternalDecls' flag.
1595
24.1M
StoredDeclsMap *DeclContext::buildLookup() {
1596
24.1M
  assert(this == getPrimaryContext() && "buildLookup called on non-primary DC");
1597
1598
24.1M
  if (!hasLazyLocalLexicalLookups() &&
1599
24.1M
      
!hasLazyExternalLexicalLookups()22.3M
)
1600
22.2M
    return LookupPtr;
1601
1602
1.86M
  SmallVector<DeclContext *, 2> Contexts;
1603
1.86M
  collectAllContexts(Contexts);
1604
1605
1.86M
  if (hasLazyExternalLexicalLookups()) {
1606
101k
    setHasLazyExternalLexicalLookups(false);
1607
101k
    for (auto *DC : Contexts) {
1608
101k
      if (DC->hasExternalLexicalStorage()) {
1609
100k
        bool LoadedDecls = DC->LoadLexicalDeclsFromExternalStorage();
1610
100k
        setHasLazyLocalLexicalLookups(
1611
100k
            hasLazyLocalLexicalLookups() | LoadedDecls );
1612
100k
      }
1613
101k
    }
1614
1615
101k
    if (!hasLazyLocalLexicalLookups())
1616
94.8k
      return LookupPtr;
1617
101k
  }
1618
1619
1.76M
  for (auto *DC : Contexts)
1620
1.77M
    buildLookupImpl(DC, hasExternalVisibleStorage());
1621
1622
  // We no longer have any lazy decls.
1623
1.76M
  setHasLazyLocalLexicalLookups(false);
1624
1.76M
  return LookupPtr;
1625
1.86M
}
1626
1627
/// buildLookupImpl - Build part of the lookup data structure for the
1628
/// declarations contained within DCtx, which will either be this
1629
/// DeclContext, a DeclContext linked to it, or a transparent context
1630
/// nested within it.
1631
1.88M
void DeclContext::buildLookupImpl(DeclContext *DCtx, bool Internal) {
1632
3.40M
  for (auto *D : DCtx->noload_decls()) {
1633
    // Insert this declaration into the lookup structure, but only if
1634
    // it's semantically within its decl context. Any other decls which
1635
    // should be found in this context are added eagerly.
1636
    //
1637
    // If it's from an AST file, don't add it now. It'll get handled by
1638
    // FindExternalVisibleDeclsByName if needed. Exception: if we're not
1639
    // in C++, we do not track external visible decls for the TU, so in
1640
    // that case we need to collect them all here.
1641
3.40M
    if (auto *ND = dyn_cast<NamedDecl>(D))
1642
3.17M
      if (ND->getDeclContext() == DCtx && 
!shouldBeHidden(ND)3.17M
&&
1643
3.17M
          
(3.14M
!ND->isFromASTFile()3.14M
||
1644
3.14M
           
(62.0k
isTranslationUnit()62.0k
&&
1645
62.0k
            
!getParentASTContext().getLangOpts().CPlusPlus5.24k
)))
1646
3.08M
        makeDeclVisibleInContextImpl(ND, Internal);
1647
1648
    // If this declaration is itself a transparent declaration context
1649
    // or inline namespace, add the members of this declaration of that
1650
    // context (recursively).
1651
3.40M
    if (auto *InnerCtx = dyn_cast<DeclContext>(D))
1652
1.68M
      if (InnerCtx->isTransparentContext() || 
InnerCtx->isInlineNamespace()1.67M
)
1653
16.0k
        buildLookupImpl(InnerCtx, Internal);
1654
3.40M
  }
1655
1.88M
}
1656
1657
DeclContext::lookup_result
1658
269M
DeclContext::lookup(DeclarationName Name) const {
1659
  // For transparent DeclContext, we should lookup in their enclosing context.
1660
269M
  if (getDeclKind() == Decl::LinkageSpec || 
getDeclKind() == Decl::Export269M
)
1661
4
    return getParent()->lookup(Name);
1662
1663
269M
  const DeclContext *PrimaryContext = getPrimaryContext();
1664
269M
  if (PrimaryContext != this)
1665
37.8M
    return PrimaryContext->lookup(Name);
1666
1667
  // If we have an external source, ensure that any later redeclarations of this
1668
  // context have been loaded, since they may add names to the result of this
1669
  // lookup (or add external visible storage).
1670
231M
  ExternalASTSource *Source = getParentASTContext().getExternalSource();
1671
231M
  if (Source)
1672
19.2M
    (void)cast<Decl>(this)->getMostRecentDecl();
1673
1674
231M
  if (hasExternalVisibleStorage()) {
1675
8.58M
    assert(Source && "external visible storage but no external source?");
1676
1677
8.58M
    if (hasNeedToReconcileExternalVisibleStorage())
1678
15.3k
      reconcileExternalVisibleStorage();
1679
1680
8.58M
    StoredDeclsMap *Map = LookupPtr;
1681
1682
8.58M
    if (hasLazyLocalLexicalLookups() ||
1683
8.58M
        
hasLazyExternalLexicalLookups()8.58M
)
1684
      // FIXME: Make buildLookup const?
1685
523
      Map = const_cast<DeclContext*>(this)->buildLookup();
1686
1687
8.58M
    if (!Map)
1688
41.7k
      Map = CreateStoredDeclsMap(getParentASTContext());
1689
1690
    // If we have a lookup result with no external decls, we are done.
1691
8.58M
    std::pair<StoredDeclsMap::iterator, bool> R =
1692
8.58M
        Map->insert(std::make_pair(Name, StoredDeclsList()));
1693
8.58M
    if (!R.second && 
!R.first->second.hasExternalDecls()7.49M
)
1694
6.60M
      return R.first->second.getLookupResult();
1695
1696
1.97M
    if (Source->FindExternalVisibleDeclsByName(this, Name) || 
!R.second1.06M
) {
1697
1.00M
      if (StoredDeclsMap *Map = LookupPtr) {
1698
1.00M
        StoredDeclsMap::iterator I = Map->find(Name);
1699
1.00M
        if (I != Map->end())
1700
1.00M
          return I->second.getLookupResult();
1701
1.00M
      }
1702
1.00M
    }
1703
1704
970k
    return {};
1705
1.97M
  }
1706
1707
222M
  StoredDeclsMap *Map = LookupPtr;
1708
222M
  if (hasLazyLocalLexicalLookups() ||
1709
222M
      
hasLazyExternalLexicalLookups()221M
)
1710
1.75M
    Map = const_cast<DeclContext*>(this)->buildLookup();
1711
1712
222M
  if (!Map)
1713
15.8M
    return {};
1714
1715
206M
  StoredDeclsMap::iterator I = Map->find(Name);
1716
206M
  if (I == Map->end())
1717
137M
    return {};
1718
1719
69.2M
  return I->second.getLookupResult();
1720
206M
}
1721
1722
DeclContext::lookup_result
1723
5.15M
DeclContext::noload_lookup(DeclarationName Name) {
1724
5.15M
  assert(getDeclKind() != Decl::LinkageSpec &&
1725
5.15M
         getDeclKind() != Decl::Export &&
1726
5.15M
         "should not perform lookups into transparent contexts");
1727
1728
0
  DeclContext *PrimaryContext = getPrimaryContext();
1729
5.15M
  if (PrimaryContext != this)
1730
124
    return PrimaryContext->noload_lookup(Name);
1731
1732
5.15M
  loadLazyLocalLexicalLookups();
1733
5.15M
  StoredDeclsMap *Map = LookupPtr;
1734
5.15M
  if (!Map)
1735
384k
    return {};
1736
1737
4.76M
  StoredDeclsMap::iterator I = Map->find(Name);
1738
4.76M
  return I != Map->end() ? 
I->second.getLookupResult()2.63M
1739
4.76M
                         : 
lookup_result()2.13M
;
1740
5.15M
}
1741
1742
// If we have any lazy lexical declarations not in our lookup map, add them
1743
// now. Don't import any external declarations, not even if we know we have
1744
// some missing from the external visible lookups.
1745
5.15M
void DeclContext::loadLazyLocalLexicalLookups() {
1746
5.15M
  if (hasLazyLocalLexicalLookups()) {
1747
93.3k
    SmallVector<DeclContext *, 2> Contexts;
1748
93.3k
    collectAllContexts(Contexts);
1749
93.3k
    for (auto *Context : Contexts)
1750
93.3k
      buildLookupImpl(Context, hasExternalVisibleStorage());
1751
93.3k
    setHasLazyLocalLexicalLookups(false);
1752
93.3k
  }
1753
5.15M
}
1754
1755
void DeclContext::localUncachedLookup(DeclarationName Name,
1756
1.31M
                                      SmallVectorImpl<NamedDecl *> &Results) {
1757
1.31M
  Results.clear();
1758
1759
  // If there's no external storage, just perform a normal lookup and copy
1760
  // the results.
1761
1.31M
  if (!hasExternalVisibleStorage() && 
!hasExternalLexicalStorage()1.07M
&&
Name864k
) {
1762
863k
    lookup_result LookupResults = lookup(Name);
1763
863k
    Results.insert(Results.end(), LookupResults.begin(), LookupResults.end());
1764
863k
    return;
1765
863k
  }
1766
1767
  // If we have a lookup table, check there first. Maybe we'll get lucky.
1768
  // FIXME: Should we be checking these flags on the primary context?
1769
448k
  if (Name && 
!hasLazyLocalLexicalLookups()447k
&&
1770
448k
      
!hasLazyExternalLexicalLookups()447k
) {
1771
253k
    if (StoredDeclsMap *Map = LookupPtr) {
1772
245k
      StoredDeclsMap::iterator Pos = Map->find(Name);
1773
245k
      if (Pos != Map->end()) {
1774
1.00k
        Results.insert(Results.end(),
1775
1.00k
                       Pos->second.getLookupResult().begin(),
1776
1.00k
                       Pos->second.getLookupResult().end());
1777
1.00k
        return;
1778
1.00k
      }
1779
245k
    }
1780
253k
  }
1781
1782
  // Slow case: grovel through the declarations in our chain looking for
1783
  // matches.
1784
  // FIXME: If we have lazy external declarations, this will not find them!
1785
  // FIXME: Should we CollectAllContexts and walk them all here?
1786
207M
  
for (Decl *D = FirstDecl; 447k
D;
D = D->getNextDeclInContext()207M
) {
1787
207M
    if (auto *ND = dyn_cast<NamedDecl>(D))
1788
206M
      if (ND->getDeclName() == Name)
1789
7.60k
        Results.push_back(ND);
1790
207M
  }
1791
447k
}
1792
1793
880M
DeclContext *DeclContext::getRedeclContext() {
1794
880M
  DeclContext *Ctx = this;
1795
1796
  // In C, a record type is the redeclaration context for its fields only. If
1797
  // we arrive at a record context after skipping anything else, we should skip
1798
  // the record as well. Currently, this means skipping enumerations because
1799
  // they're the only transparent context that can exist within a struct or
1800
  // union.
1801
880M
  bool SkipRecords = getDeclKind() == Decl::Kind::Enum &&
1802
880M
                     
!getParentASTContext().getLangOpts().CPlusPlus803k
;
1803
1804
  // Skip through contexts to get to the redeclaration context. Transparent
1805
  // contexts are always skipped.
1806
1.13G
  while ((SkipRecords && 
Ctx->isRecord()1.24M
) ||
Ctx->isTransparentContext()1.13G
)
1807
250M
    Ctx = Ctx->getParent();
1808
880M
  return Ctx;
1809
880M
}
1810
1811
73.3k
DeclContext *DeclContext::getEnclosingNamespaceContext() {
1812
73.3k
  DeclContext *Ctx = this;
1813
  // Skip through non-namespace, non-translation-unit contexts.
1814
119k
  while (!Ctx->isFileContext())
1815
46.6k
    Ctx = Ctx->getParent();
1816
73.3k
  return Ctx->getPrimaryContext();
1817
73.3k
}
1818
1819
18
RecordDecl *DeclContext::getOuterLexicalRecordContext() {
1820
  // Loop until we find a non-record context.
1821
18
  RecordDecl *OutermostRD = nullptr;
1822
18
  DeclContext *DC = this;
1823
45
  while (DC->isRecord()) {
1824
27
    OutermostRD = cast<RecordDecl>(DC);
1825
27
    DC = DC->getLexicalParent();
1826
27
  }
1827
18
  return OutermostRD;
1828
18
}
1829
1830
832k
bool DeclContext::InEnclosingNamespaceSetOf(const DeclContext *O) const {
1831
  // For non-file contexts, this is equivalent to Equals.
1832
832k
  if (!isFileContext())
1833
776k
    return O->Equals(this);
1834
1835
56.2k
  
do 56.1k
{
1836
56.2k
    if (O->Equals(this))
1837
56.1k
      return true;
1838
1839
124
    const auto *NS = dyn_cast<NamespaceDecl>(O);
1840
124
    if (!NS || 
!NS->isInline()109
)
1841
53
      break;
1842
71
    O = NS->getParent();
1843
71
  } while (O);
1844
1845
53
  return false;
1846
56.1k
}
1847
1848
1.31M
void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
1849
1.31M
  DeclContext *PrimaryDC = this->getPrimaryContext();
1850
1.31M
  DeclContext *DeclDC = D->getDeclContext()->getPrimaryContext();
1851
  // If the decl is being added outside of its semantic decl context, we
1852
  // need to ensure that we eagerly build the lookup information for it.
1853
1.31M
  PrimaryDC->makeDeclVisibleInContextWithFlags(D, false, PrimaryDC == DeclDC);
1854
1.31M
}
1855
1856
void DeclContext::makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
1857
74.5M
                                                    bool Recoverable) {
1858
74.5M
  assert(this == getPrimaryContext() && "expected a primary DC");
1859
1860
74.5M
  if (!isLookupContext()) {
1861
21.5M
    if (isTransparentContext())
1862
9.83M
      getParent()->getPrimaryContext()
1863
9.83M
        ->makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1864
21.5M
    return;
1865
21.5M
  }
1866
1867
  // Skip declarations which should be invisible to name lookup.
1868
53.0M
  if (shouldBeHidden(D))
1869
1.40M
    return;
1870
1871
  // If we already have a lookup data structure, perform the insertion into
1872
  // it. If we might have externally-stored decls with this name, look them
1873
  // up and perform the insertion. If this decl was declared outside its
1874
  // semantic context, buildLookup won't add it, so add it now.
1875
  //
1876
  // FIXME: As a performance hack, don't add such decls into the translation
1877
  // unit unless we're in C++, since qualified lookup into the TU is never
1878
  // performed.
1879
51.6M
  if (LookupPtr || 
hasExternalVisibleStorage()29.7M
||
1880
51.6M
      
(29.6M
(29.6M
!Recoverable29.6M
||
D->getDeclContext() != D->getLexicalDeclContext()29.6M
) &&
1881
29.6M
       
(23.5k
getParentASTContext().getLangOpts().CPlusPlus23.5k
||
1882
21.9M
        
!isTranslationUnit()4.16k
))) {
1883
    // If we have lazily omitted any decls, they might have the same name as
1884
    // the decl which we are adding, so build a full lookup table before adding
1885
    // this decl.
1886
21.9M
    buildLookup();
1887
21.9M
    makeDeclVisibleInContextImpl(D, Internal);
1888
29.6M
  } else {
1889
29.6M
    setHasLazyLocalLexicalLookups(true);
1890
29.6M
  }
1891
1892
  // If we are a transparent context or inline namespace, insert into our
1893
  // parent context, too. This operation is recursive.
1894
51.6M
  if (isTransparentContext() || 
isInlineNamespace()47.8M
)
1895
5.14M
    getParent()->getPrimaryContext()->
1896
5.14M
        makeDeclVisibleInContextWithFlags(D, Internal, Recoverable);
1897
1898
51.6M
  auto *DCAsDecl = cast<Decl>(this);
1899
  // Notify that a decl was made visible unless we are a Tag being defined.
1900
51.6M
  if (!(isa<TagDecl>(DCAsDecl) && 
cast<TagDecl>(DCAsDecl)->isBeingDefined()14.3M
))
1901
39.3M
    if (ASTMutationListener *L = DCAsDecl->getASTMutationListener())
1902
912k
      L->AddedVisibleDecl(this, D);
1903
51.6M
}
1904
1905
26.7M
void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal) {
1906
  // Find or create the stored declaration map.
1907
26.7M
  StoredDeclsMap *Map = LookupPtr;
1908
26.7M
  if (!Map) {
1909
2.05M
    ASTContext *C = &getParentASTContext();
1910
2.05M
    Map = CreateStoredDeclsMap(*C);
1911
2.05M
  }
1912
1913
  // If there is an external AST source, load any declarations it knows about
1914
  // with this declaration's name.
1915
  // If the lookup table contains an entry about this name it means that we
1916
  // have already checked the external source.
1917
26.7M
  if (!Internal)
1918
23.3M
    if (ExternalASTSource *Source = getParentASTContext().getExternalSource())
1919
2.32M
      if (hasExternalVisibleStorage() &&
1920
2.32M
          
Map->find(D->getDeclName()) == Map->end()706k
)
1921
163k
        Source->FindExternalVisibleDeclsByName(this, D->getDeclName());
1922
1923
  // Insert this declaration into the map.
1924
26.7M
  StoredDeclsList &DeclNameEntries = (*Map)[D->getDeclName()];
1925
1926
26.7M
  if (Internal) {
1927
    // If this is being added as part of loading an external declaration,
1928
    // this may not be the only external declaration with this name.
1929
    // In this case, we never try to replace an existing declaration; we'll
1930
    // handle that when we finalize the list of declarations for this name.
1931
3.37M
    DeclNameEntries.setHasExternalDecls();
1932
3.37M
    DeclNameEntries.prependDeclNoReplace(D);
1933
3.37M
    return;
1934
3.37M
  }
1935
1936
23.3M
  DeclNameEntries.addOrReplaceDecl(D);
1937
23.3M
}
1938
1939
14.0M
UsingDirectiveDecl *DeclContext::udir_iterator::operator*() const {
1940
14.0M
  return cast<UsingDirectiveDecl>(*I);
1941
14.0M
}
1942
1943
/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
1944
/// this context.
1945
88.8M
DeclContext::udir_range DeclContext::using_directives() const {
1946
  // FIXME: Use something more efficient than normal lookup for using
1947
  // directives. In C++, using directives are looked up more than anything else.
1948
88.8M
  lookup_result Result = lookup(UsingDirectiveDecl::getName());
1949
88.8M
  return udir_range(Result.begin(), Result.end());
1950
88.8M
}
1951
1952
//===----------------------------------------------------------------------===//
1953
// Creation and Destruction of StoredDeclsMaps.                               //
1954
//===----------------------------------------------------------------------===//
1955
1956
2.09M
StoredDeclsMap *DeclContext::CreateStoredDeclsMap(ASTContext &C) const {
1957
2.09M
  assert(!LookupPtr && "context already has a decls map");
1958
0
  assert(getPrimaryContext() == this &&
1959
2.09M
         "creating decls map on non-primary context");
1960
1961
0
  StoredDeclsMap *M;
1962
2.09M
  bool Dependent = isDependentContext();
1963
2.09M
  if (Dependent)
1964
466k
    M = new DependentStoredDeclsMap();
1965
1.63M
  else
1966
1.63M
    M = new StoredDeclsMap();
1967
2.09M
  M->Previous = C.LastSDM;
1968
2.09M
  C.LastSDM = llvm::PointerIntPair<StoredDeclsMap*,1>(M, Dependent);
1969
2.09M
  LookupPtr = M;
1970
2.09M
  return M;
1971
2.09M
}
1972
1973
94.2k
void ASTContext::ReleaseDeclContextMaps() {
1974
  // It's okay to delete DependentStoredDeclsMaps via a StoredDeclsMap
1975
  // pointer because the subclass doesn't add anything that needs to
1976
  // be deleted.
1977
94.2k
  StoredDeclsMap::DestroyAll(LastSDM.getPointer(), LastSDM.getInt());
1978
94.2k
  LastSDM.setPointer(nullptr);
1979
94.2k
}
1980
1981
94.2k
void StoredDeclsMap::DestroyAll(StoredDeclsMap *Map, bool Dependent) {
1982
2.19M
  while (Map) {
1983
    // Advance the iteration before we invalidate memory.
1984
2.09M
    llvm::PointerIntPair<StoredDeclsMap*,1> Next = Map->Previous;
1985
1986
2.09M
    if (Dependent)
1987
466k
      delete static_cast<DependentStoredDeclsMap*>(Map);
1988
1.63M
    else
1989
1.63M
      delete Map;
1990
1991
2.09M
    Map = Next.getPointer();
1992
2.09M
    Dependent = Next.getInt();
1993
2.09M
  }
1994
94.2k
}
1995
1996
DependentDiagnostic *DependentDiagnostic::Create(ASTContext &C,
1997
                                                 DeclContext *Parent,
1998
97
                                           const PartialDiagnostic &PDiag) {
1999
97
  assert(Parent->isDependentContext()
2000
97
         && "cannot iterate dependent diagnostics of non-dependent context");
2001
0
  Parent = Parent->getPrimaryContext();
2002
97
  if (!Parent->LookupPtr)
2003
87
    Parent->CreateStoredDeclsMap(C);
2004
2005
97
  auto *Map = static_cast<DependentStoredDeclsMap *>(Parent->LookupPtr);
2006
2007
  // Allocate the copy of the PartialDiagnostic via the ASTContext's
2008
  // BumpPtrAllocator, rather than the ASTContext itself.
2009
97
  DiagnosticStorage *DiagStorage = nullptr;
2010
97
  if (PDiag.hasStorage())
2011
2
    DiagStorage = new (C) DiagnosticStorage;
2012
2013
97
  auto *DD = new (C) DependentDiagnostic(PDiag, DiagStorage);
2014
2015
  // TODO: Maybe we shouldn't reverse the order during insertion.
2016
97
  DD->NextDiagnostic = Map->FirstDiagnostic;
2017
97
  Map->FirstDiagnostic = DD;
2018
2019
97
  return DD;
2020
97
}