Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Sema/IdentifierResolver.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- IdentifierResolver.cpp - Lexical Scope Name lookup -----------------===//
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 IdentifierResolver class, which is used for lexical
10
// scoped lookup, based on declaration names.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/Sema/IdentifierResolver.h"
15
#include "clang/AST/Decl.h"
16
#include "clang/AST/DeclBase.h"
17
#include "clang/AST/DeclarationName.h"
18
#include "clang/Basic/IdentifierTable.h"
19
#include "clang/Basic/LangOptions.h"
20
#include "clang/Lex/ExternalPreprocessorSource.h"
21
#include "clang/Lex/Preprocessor.h"
22
#include "clang/Sema/Scope.h"
23
#include "llvm/Support/ErrorHandling.h"
24
#include <cassert>
25
#include <cstdint>
26
27
using namespace clang;
28
29
//===----------------------------------------------------------------------===//
30
// IdDeclInfoMap class
31
//===----------------------------------------------------------------------===//
32
33
/// IdDeclInfoMap - Associates IdDeclInfos with declaration names.
34
/// Allocates 'pools' (vectors of IdDeclInfos) to avoid allocating each
35
/// individual IdDeclInfo to heap.
36
class IdentifierResolver::IdDeclInfoMap {
37
  static const unsigned int POOL_SIZE = 512;
38
39
  /// We use our own linked-list implementation because it is sadly
40
  /// impossible to add something to a pre-C++0x STL container without
41
  /// a completely unnecessary copy.
42
  struct IdDeclInfoPool {
43
    IdDeclInfoPool *Next;
44
    IdDeclInfo Pool[POOL_SIZE];
45
46
32
    IdDeclInfoPool(IdDeclInfoPool *Next) : Next(Next) {}
47
  };
48
49
  IdDeclInfoPool *CurPool = nullptr;
50
  unsigned int CurIndex = POOL_SIZE;
51
52
public:
53
46
  IdDeclInfoMap() = default;
54
55
46
  ~IdDeclInfoMap() {
56
46
    IdDeclInfoPool *Cur = CurPool;
57
78
    while (IdDeclInfoPool *P = Cur) {
58
32
      Cur = Cur->Next;
59
32
      delete P;
60
32
    }
61
46
  }
62
63
  IdDeclInfoMap(const IdDeclInfoMap &) = delete;
64
  IdDeclInfoMap &operator=(const IdDeclInfoMap &) = delete;
65
66
  /// Returns the IdDeclInfo associated to the DeclarationName.
67
  /// It creates a new IdDeclInfo if one was not created before for this id.
68
  IdDeclInfo &operator[](DeclarationName Name);
69
};
70
71
//===----------------------------------------------------------------------===//
72
// IdDeclInfo Implementation
73
//===----------------------------------------------------------------------===//
74
75
/// RemoveDecl - Remove the decl from the scope chain.
76
/// The decl must already be part of the decl chain.
77
95
void IdentifierResolver::IdDeclInfo::RemoveDecl(NamedDecl *D) {
78
233
  for (DeclsTy::iterator I = Decls.end(); I != Decls.begin(); --I) {
79
233
    if (D == *(I-1)) {
80
95
      Decls.erase(I-1);
81
95
      return;
82
95
    }
83
233
  }
84
85
0
  llvm_unreachable("Didn't find this decl on its identifier's chain!");
86
0
}
87
88
//===----------------------------------------------------------------------===//
89
// IdentifierResolver Implementation
90
//===----------------------------------------------------------------------===//
91
92
IdentifierResolver::IdentifierResolver(Preprocessor &PP)
93
46
    : LangOpt(PP.getLangOpts()), PP(PP), IdDeclInfos(new IdDeclInfoMap) {}
94
95
46
IdentifierResolver::~IdentifierResolver() {
96
46
  delete IdDeclInfos;
97
46
}
98
99
/// isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true
100
/// if 'D' is in Scope 'S', otherwise 'S' is ignored and isDeclInScope returns
101
/// true if 'D' belongs to the given declaration context.
102
bool IdentifierResolver::isDeclInScope(Decl *D, DeclContext *Ctx, Scope *S,
103
2.19k
                                       bool AllowInlineNamespace) const {
104
2.19k
  Ctx = Ctx->getRedeclContext();
105
  // The names for HLSL cbuffer/tbuffers only used by the CPU-side
106
  // reflection API which supports querying bindings. It will not have name
107
  // conflict with other Decls.
108
2.19k
  if (LangOpt.HLSL && isa<HLSLBufferDecl>(D))
109
0
    return false;
110
2.19k
  if (Ctx->isFunctionOrMethod() || (S && S->isFunctionPrototypeScope())) {
111
    // Ignore the scopes associated within transparent declaration contexts.
112
0
    while (S->getEntity() &&
113
0
           (S->getEntity()->isTransparentContext() ||
114
0
            (!LangOpt.CPlusPlus && isa<RecordDecl>(S->getEntity()))))
115
0
      S = S->getParent();
116
117
0
    if (S->isDeclScope(D))
118
0
      return true;
119
0
    if (LangOpt.CPlusPlus) {
120
      // C++ 3.3.2p3:
121
      // The name declared in a catch exception-declaration is local to the
122
      // handler and shall not be redeclared in the outermost block of the
123
      // handler.
124
      // C++ 3.3.2p4:
125
      // Names declared in the for-init-statement, and in the condition of if,
126
      // while, for, and switch statements are local to the if, while, for, or
127
      // switch statement (including the controlled statement), and shall not be
128
      // redeclared in a subsequent condition of that statement nor in the
129
      // outermost block (or, for the if statement, any of the outermost blocks)
130
      // of the controlled statement.
131
      //
132
0
      assert(S->getParent() && "No TUScope?");
133
      // If the current decl is in a lambda, we shouldn't consider this is a
134
      // redefinition as lambda has its own scope.
135
0
      if (S->getParent()->isControlScope() && !S->isFunctionScope()) {
136
0
        S = S->getParent();
137
0
        if (S->isDeclScope(D))
138
0
          return true;
139
0
      }
140
0
      if (S->isFnTryCatchScope())
141
0
        return S->getParent()->isDeclScope(D);
142
0
    }
143
0
    return false;
144
0
  }
145
146
  // FIXME: If D is a local extern declaration, this check doesn't make sense;
147
  // we should be checking its lexical context instead in that case, because
148
  // that is its scope.
149
2.19k
  DeclContext *DCtx = D->getDeclContext()->getRedeclContext();
150
2.19k
  return AllowInlineNamespace ? Ctx->InEnclosingNamespaceSetOf(DCtx)
151
2.19k
                              : Ctx->Equals(DCtx);
152
2.19k
}
153
154
/// AddDecl - Link the decl to its shadowed decl chain.
155
5.43k
void IdentifierResolver::AddDecl(NamedDecl *D) {
156
5.43k
  DeclarationName Name = D->getDeclName();
157
5.43k
  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
158
5.43k
    updatingIdentifier(*II);
159
160
5.43k
  void *Ptr = Name.getFETokenInfo();
161
162
5.43k
  if (!Ptr) {
163
3.32k
    Name.setFETokenInfo(D);
164
3.32k
    return;
165
3.32k
  }
166
167
2.10k
  IdDeclInfo *IDI;
168
169
2.10k
  if (isDeclPtr(Ptr)) {
170
837
    Name.setFETokenInfo(nullptr);
171
837
    IDI = &(*IdDeclInfos)[Name];
172
837
    NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
173
837
    IDI->AddDecl(PrevD);
174
837
  } else
175
1.27k
    IDI = toIdDeclInfo(Ptr);
176
177
2.10k
  IDI->AddDecl(D);
178
2.10k
}
179
180
0
void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) {
181
0
  DeclarationName Name = D->getDeclName();
182
0
  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
183
0
    updatingIdentifier(*II);
184
185
0
  void *Ptr = Name.getFETokenInfo();
186
187
0
  if (!Ptr) {
188
0
    AddDecl(D);
189
0
    return;
190
0
  }
191
192
0
  if (isDeclPtr(Ptr)) {
193
    // We only have a single declaration: insert before or after it,
194
    // as appropriate.
195
0
    if (Pos == iterator()) {
196
      // Add the new declaration before the existing declaration.
197
0
      NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
198
0
      RemoveDecl(PrevD);
199
0
      AddDecl(D);
200
0
      AddDecl(PrevD);
201
0
    } else {
202
      // Add new declaration after the existing declaration.
203
0
      AddDecl(D);
204
0
    }
205
206
0
    return;
207
0
  }
208
209
  // General case: insert the declaration at the appropriate point in the
210
  // list, which already has at least two elements.
211
0
  IdDeclInfo *IDI = toIdDeclInfo(Ptr);
212
0
  if (Pos.isIterator()) {
213
0
    IDI->InsertDecl(Pos.getIterator() + 1, D);
214
0
  } else
215
0
    IDI->InsertDecl(IDI->decls_begin(), D);
216
0
}
217
218
/// RemoveDecl - Unlink the decl from its shadowed decl chain.
219
/// The decl must already be part of the decl chain.
220
204
void IdentifierResolver::RemoveDecl(NamedDecl *D) {
221
204
  assert(D && "null param passed");
222
0
  DeclarationName Name = D->getDeclName();
223
204
  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
224
204
    updatingIdentifier(*II);
225
226
204
  void *Ptr = Name.getFETokenInfo();
227
228
204
  assert(Ptr && "Didn't find this decl on its identifier's chain!");
229
230
204
  if (isDeclPtr(Ptr)) {
231
109
    assert(D == Ptr && "Didn't find this decl on its identifier's chain!");
232
0
    Name.setFETokenInfo(nullptr);
233
109
    return;
234
109
  }
235
236
95
  return toIdDeclInfo(Ptr)->RemoveDecl(D);
237
204
}
238
239
llvm::iterator_range<IdentifierResolver::iterator>
240
0
IdentifierResolver::decls(DeclarationName Name) {
241
0
  return {begin(Name), end()};
242
0
}
243
244
43.2k
IdentifierResolver::iterator IdentifierResolver::begin(DeclarationName Name) {
245
43.2k
  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
246
43.1k
    readingIdentifier(*II);
247
248
43.2k
  void *Ptr = Name.getFETokenInfo();
249
43.2k
  if (!Ptr) return end();
250
251
15.4k
  if (isDeclPtr(Ptr))
252
7.10k
    return iterator(static_cast<NamedDecl*>(Ptr));
253
254
8.30k
  IdDeclInfo *IDI = toIdDeclInfo(Ptr);
255
256
8.30k
  IdDeclInfo::DeclsTy::iterator I = IDI->decls_end();
257
8.30k
  if (I != IDI->decls_begin())
258
8.30k
    return iterator(I-1);
259
  // No decls found.
260
0
  return end();
261
8.30k
}
262
263
namespace {
264
265
enum DeclMatchKind {
266
  DMK_Different,
267
  DMK_Replace,
268
  DMK_Ignore
269
};
270
271
} // namespace
272
273
/// Compare two declarations to see whether they are different or,
274
/// if they are the same, whether the new declaration should replace the
275
/// existing declaration.
276
0
static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) {
277
  // If the declarations are identical, ignore the new one.
278
0
  if (Existing == New)
279
0
    return DMK_Ignore;
280
281
  // If the declarations have different kinds, they're obviously different.
282
0
  if (Existing->getKind() != New->getKind())
283
0
    return DMK_Different;
284
285
  // If the declarations are redeclarations of each other, keep the newest one.
286
0
  if (Existing->getCanonicalDecl() == New->getCanonicalDecl()) {
287
    // If we're adding an imported declaration, don't replace another imported
288
    // declaration.
289
0
    if (Existing->isFromASTFile() && New->isFromASTFile())
290
0
      return DMK_Different;
291
292
    // If either of these is the most recent declaration, use it.
293
0
    Decl *MostRecent = Existing->getMostRecentDecl();
294
0
    if (Existing == MostRecent)
295
0
      return DMK_Ignore;
296
297
0
    if (New == MostRecent)
298
0
      return DMK_Replace;
299
300
    // If the existing declaration is somewhere in the previous declaration
301
    // chain of the new declaration, then prefer the new declaration.
302
0
    for (auto *RD : New->redecls()) {
303
0
      if (RD == Existing)
304
0
        return DMK_Replace;
305
306
0
      if (RD->isCanonicalDecl())
307
0
        break;
308
0
    }
309
310
0
    return DMK_Ignore;
311
0
  }
312
313
0
  return DMK_Different;
314
0
}
315
316
0
bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){
317
0
  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
318
0
    readingIdentifier(*II);
319
320
0
  void *Ptr = Name.getFETokenInfo();
321
322
0
  if (!Ptr) {
323
0
    Name.setFETokenInfo(D);
324
0
    return true;
325
0
  }
326
327
0
  IdDeclInfo *IDI;
328
329
0
  if (isDeclPtr(Ptr)) {
330
0
    NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
331
332
0
    switch (compareDeclarations(PrevD, D)) {
333
0
    case DMK_Different:
334
0
      break;
335
336
0
    case DMK_Ignore:
337
0
      return false;
338
339
0
    case DMK_Replace:
340
0
      Name.setFETokenInfo(D);
341
0
      return true;
342
0
    }
343
344
0
    Name.setFETokenInfo(nullptr);
345
0
    IDI = &(*IdDeclInfos)[Name];
346
347
    // If the existing declaration is not visible in translation unit scope,
348
    // then add the new top-level declaration first.
349
0
    if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
350
0
      IDI->AddDecl(D);
351
0
      IDI->AddDecl(PrevD);
352
0
    } else {
353
0
      IDI->AddDecl(PrevD);
354
0
      IDI->AddDecl(D);
355
0
    }
356
0
    return true;
357
0
  }
358
359
0
  IDI = toIdDeclInfo(Ptr);
360
361
  // See whether this declaration is identical to any existing declarations.
362
  // If not, find the right place to insert it.
363
0
  for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(),
364
0
                                  IEnd = IDI->decls_end();
365
0
       I != IEnd; ++I) {
366
367
0
    switch (compareDeclarations(*I, D)) {
368
0
    case DMK_Different:
369
0
      break;
370
371
0
    case DMK_Ignore:
372
0
      return false;
373
374
0
    case DMK_Replace:
375
0
      *I = D;
376
0
      return true;
377
0
    }
378
379
0
    if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
380
      // We've found a declaration that is not visible from the translation
381
      // unit (it's in an inner scope). Insert our declaration here.
382
0
      IDI->InsertDecl(I, D);
383
0
      return true;
384
0
    }
385
0
  }
386
387
  // Add the declaration to the end.
388
0
  IDI->AddDecl(D);
389
0
  return true;
390
0
}
391
392
43.1k
void IdentifierResolver::readingIdentifier(IdentifierInfo &II) {
393
43.1k
  if (II.isOutOfDate())
394
0
    PP.getExternalSource()->updateOutOfDateIdentifier(II);
395
43.1k
}
396
397
5.63k
void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
398
5.63k
  if (II.isOutOfDate())
399
0
    PP.getExternalSource()->updateOutOfDateIdentifier(II);
400
401
5.63k
  if (II.isFromAST())
402
0
    II.setFETokenInfoChangedSinceDeserialization();
403
5.63k
}
404
405
//===----------------------------------------------------------------------===//
406
// IdDeclInfoMap Implementation
407
//===----------------------------------------------------------------------===//
408
409
/// Returns the IdDeclInfo associated to the DeclarationName.
410
/// It creates a new IdDeclInfo if one was not created before for this id.
411
IdentifierResolver::IdDeclInfo &
412
837
IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name) {
413
837
  void *Ptr = Name.getFETokenInfo();
414
415
837
  if (Ptr) return *toIdDeclInfo(Ptr);
416
417
837
  if (CurIndex == POOL_SIZE) {
418
32
    CurPool = new IdDeclInfoPool(CurPool);
419
32
    CurIndex = 0;
420
32
  }
421
837
  IdDeclInfo *IDI = &CurPool->Pool[CurIndex];
422
837
  Name.setFETokenInfo(reinterpret_cast<void*>(
423
837
                              reinterpret_cast<uintptr_t>(IDI) | 0x1)
424
837
                                                                     );
425
837
  ++CurIndex;
426
837
  return *IDI;
427
837
}
428
429
58.4k
void IdentifierResolver::iterator::incrementSlowCase() {
430
58.4k
  NamedDecl *D = **this;
431
58.4k
  void *InfoPtr = D->getDeclName().getFETokenInfo();
432
58.4k
  assert(!isDeclPtr(InfoPtr) && "Decl with wrong id ?");
433
0
  IdDeclInfo *Info = toIdDeclInfo(InfoPtr);
434
435
58.4k
  BaseIter I = getIterator();
436
58.4k
  if (I != Info->decls_begin())
437
50.2k
    *this = iterator(I-1);
438
8.21k
  else // No more decls.
439
8.21k
    *this = iterator();
440
58.4k
}