1 //===- IdentifierResolver.cpp - Lexical Scope Name lookup -----------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements the IdentifierResolver class, which is used for lexical
10 // scoped lookup, based on declaration names.
12 //===----------------------------------------------------------------------===//
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"
27 using namespace clang
;
29 //===----------------------------------------------------------------------===//
30 // IdDeclInfoMap class
31 //===----------------------------------------------------------------------===//
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;
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
{
44 IdDeclInfo Pool
[POOL_SIZE
];
46 IdDeclInfoPool(IdDeclInfoPool
*Next
) : Next(Next
) {}
49 IdDeclInfoPool
*CurPool
= nullptr;
50 unsigned int CurIndex
= POOL_SIZE
;
53 IdDeclInfoMap() = default;
56 IdDeclInfoPool
*Cur
= CurPool
;
57 while (IdDeclInfoPool
*P
= Cur
) {
63 IdDeclInfoMap(const IdDeclInfoMap
&) = delete;
64 IdDeclInfoMap
&operator=(const IdDeclInfoMap
&) = delete;
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
);
71 //===----------------------------------------------------------------------===//
72 // IdDeclInfo Implementation
73 //===----------------------------------------------------------------------===//
75 /// RemoveDecl - Remove the decl from the scope chain.
76 /// The decl must already be part of the decl chain.
77 void IdentifierResolver::IdDeclInfo::RemoveDecl(NamedDecl
*D
) {
78 for (DeclsTy::iterator I
= Decls
.end(); I
!= Decls
.begin(); --I
) {
85 llvm_unreachable("Didn't find this decl on its identifier's chain!");
88 //===----------------------------------------------------------------------===//
89 // IdentifierResolver Implementation
90 //===----------------------------------------------------------------------===//
92 IdentifierResolver::IdentifierResolver(Preprocessor
&PP
)
93 : LangOpt(PP
.getLangOpts()), PP(PP
), IdDeclInfos(new IdDeclInfoMap
) {}
95 IdentifierResolver::~IdentifierResolver() {
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 bool AllowInlineNamespace
) const {
104 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 if (LangOpt
.HLSL
&& isa
<HLSLBufferDecl
>(D
))
110 if (Ctx
->isFunctionOrMethod() || (S
&& S
->isFunctionPrototypeScope())) {
111 // Ignore the scopes associated within transparent declaration contexts.
112 while (S
->getEntity() && S
->getEntity()->isTransparentContext())
115 if (S
->isDeclScope(D
))
117 if (LangOpt
.CPlusPlus
) {
119 // The name declared in a catch exception-declaration is local to the
120 // handler and shall not be redeclared in the outermost block of the
123 // Names declared in the for-init-statement, and in the condition of if,
124 // while, for, and switch statements are local to the if, while, for, or
125 // switch statement (including the controlled statement), and shall not be
126 // redeclared in a subsequent condition of that statement nor in the
127 // outermost block (or, for the if statement, any of the outermost blocks)
128 // of the controlled statement.
130 assert(S
->getParent() && "No TUScope?");
131 // If the current decl is in a lambda, we shouldn't consider this is a
132 // redefinition as lambda has its own scope.
133 if (S
->getParent()->isControlScope() && !S
->isFunctionScope()) {
135 if (S
->isDeclScope(D
))
138 if (S
->isFnTryCatchScope())
139 return S
->getParent()->isDeclScope(D
);
144 // FIXME: If D is a local extern declaration, this check doesn't make sense;
145 // we should be checking its lexical context instead in that case, because
146 // that is its scope.
147 DeclContext
*DCtx
= D
->getDeclContext()->getRedeclContext();
148 return AllowInlineNamespace
? Ctx
->InEnclosingNamespaceSetOf(DCtx
)
152 /// AddDecl - Link the decl to its shadowed decl chain.
153 void IdentifierResolver::AddDecl(NamedDecl
*D
) {
154 DeclarationName Name
= D
->getDeclName();
155 if (IdentifierInfo
*II
= Name
.getAsIdentifierInfo())
156 updatingIdentifier(*II
);
158 void *Ptr
= Name
.getFETokenInfo();
161 Name
.setFETokenInfo(D
);
167 if (isDeclPtr(Ptr
)) {
168 Name
.setFETokenInfo(nullptr);
169 IDI
= &(*IdDeclInfos
)[Name
];
170 NamedDecl
*PrevD
= static_cast<NamedDecl
*>(Ptr
);
173 IDI
= toIdDeclInfo(Ptr
);
178 void IdentifierResolver::InsertDeclAfter(iterator Pos
, NamedDecl
*D
) {
179 DeclarationName Name
= D
->getDeclName();
180 if (IdentifierInfo
*II
= Name
.getAsIdentifierInfo())
181 updatingIdentifier(*II
);
183 void *Ptr
= Name
.getFETokenInfo();
190 if (isDeclPtr(Ptr
)) {
191 // We only have a single declaration: insert before or after it,
193 if (Pos
== iterator()) {
194 // Add the new declaration before the existing declaration.
195 NamedDecl
*PrevD
= static_cast<NamedDecl
*>(Ptr
);
200 // Add new declaration after the existing declaration.
207 // General case: insert the declaration at the appropriate point in the
208 // list, which already has at least two elements.
209 IdDeclInfo
*IDI
= toIdDeclInfo(Ptr
);
210 if (Pos
.isIterator()) {
211 IDI
->InsertDecl(Pos
.getIterator() + 1, D
);
213 IDI
->InsertDecl(IDI
->decls_begin(), D
);
216 /// RemoveDecl - Unlink the decl from its shadowed decl chain.
217 /// The decl must already be part of the decl chain.
218 void IdentifierResolver::RemoveDecl(NamedDecl
*D
) {
219 assert(D
&& "null param passed");
220 DeclarationName Name
= D
->getDeclName();
221 if (IdentifierInfo
*II
= Name
.getAsIdentifierInfo())
222 updatingIdentifier(*II
);
224 void *Ptr
= Name
.getFETokenInfo();
226 assert(Ptr
&& "Didn't find this decl on its identifier's chain!");
228 if (isDeclPtr(Ptr
)) {
229 assert(D
== Ptr
&& "Didn't find this decl on its identifier's chain!");
230 Name
.setFETokenInfo(nullptr);
234 return toIdDeclInfo(Ptr
)->RemoveDecl(D
);
237 llvm::iterator_range
<IdentifierResolver::iterator
>
238 IdentifierResolver::decls(DeclarationName Name
) {
239 return {begin(Name
), end()};
242 IdentifierResolver::iterator
IdentifierResolver::begin(DeclarationName Name
) {
243 if (IdentifierInfo
*II
= Name
.getAsIdentifierInfo())
244 readingIdentifier(*II
);
246 void *Ptr
= Name
.getFETokenInfo();
247 if (!Ptr
) return end();
250 return iterator(static_cast<NamedDecl
*>(Ptr
));
252 IdDeclInfo
*IDI
= toIdDeclInfo(Ptr
);
254 IdDeclInfo::DeclsTy::iterator I
= IDI
->decls_end();
255 if (I
!= IDI
->decls_begin())
256 return iterator(I
-1);
271 /// Compare two declarations to see whether they are different or,
272 /// if they are the same, whether the new declaration should replace the
273 /// existing declaration.
274 static DeclMatchKind
compareDeclarations(NamedDecl
*Existing
, NamedDecl
*New
) {
275 // If the declarations are identical, ignore the new one.
279 // If the declarations have different kinds, they're obviously different.
280 if (Existing
->getKind() != New
->getKind())
281 return DMK_Different
;
283 // If the declarations are redeclarations of each other, keep the newest one.
284 if (Existing
->getCanonicalDecl() == New
->getCanonicalDecl()) {
285 // If we're adding an imported declaration, don't replace another imported
287 if (Existing
->isFromASTFile() && New
->isFromASTFile())
288 return DMK_Different
;
290 // If either of these is the most recent declaration, use it.
291 Decl
*MostRecent
= Existing
->getMostRecentDecl();
292 if (Existing
== MostRecent
)
295 if (New
== MostRecent
)
298 // If the existing declaration is somewhere in the previous declaration
299 // chain of the new declaration, then prefer the new declaration.
300 for (auto *RD
: New
->redecls()) {
304 if (RD
->isCanonicalDecl())
311 return DMK_Different
;
314 bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl
*D
, DeclarationName Name
){
315 if (IdentifierInfo
*II
= Name
.getAsIdentifierInfo())
316 readingIdentifier(*II
);
318 void *Ptr
= Name
.getFETokenInfo();
321 Name
.setFETokenInfo(D
);
327 if (isDeclPtr(Ptr
)) {
328 NamedDecl
*PrevD
= static_cast<NamedDecl
*>(Ptr
);
330 switch (compareDeclarations(PrevD
, D
)) {
338 Name
.setFETokenInfo(D
);
342 Name
.setFETokenInfo(nullptr);
343 IDI
= &(*IdDeclInfos
)[Name
];
345 // If the existing declaration is not visible in translation unit scope,
346 // then add the new top-level declaration first.
347 if (!PrevD
->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
357 IDI
= toIdDeclInfo(Ptr
);
359 // See whether this declaration is identical to any existing declarations.
360 // If not, find the right place to insert it.
361 for (IdDeclInfo::DeclsTy::iterator I
= IDI
->decls_begin(),
362 IEnd
= IDI
->decls_end();
365 switch (compareDeclarations(*I
, D
)) {
377 if (!(*I
)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
378 // We've found a declaration that is not visible from the translation
379 // unit (it's in an inner scope). Insert our declaration here.
380 IDI
->InsertDecl(I
, D
);
385 // Add the declaration to the end.
390 void IdentifierResolver::readingIdentifier(IdentifierInfo
&II
) {
391 if (II
.isOutOfDate())
392 PP
.getExternalSource()->updateOutOfDateIdentifier(II
);
395 void IdentifierResolver::updatingIdentifier(IdentifierInfo
&II
) {
396 if (II
.isOutOfDate())
397 PP
.getExternalSource()->updateOutOfDateIdentifier(II
);
400 II
.setFETokenInfoChangedSinceDeserialization();
403 //===----------------------------------------------------------------------===//
404 // IdDeclInfoMap Implementation
405 //===----------------------------------------------------------------------===//
407 /// Returns the IdDeclInfo associated to the DeclarationName.
408 /// It creates a new IdDeclInfo if one was not created before for this id.
409 IdentifierResolver::IdDeclInfo
&
410 IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name
) {
411 void *Ptr
= Name
.getFETokenInfo();
413 if (Ptr
) return *toIdDeclInfo(Ptr
);
415 if (CurIndex
== POOL_SIZE
) {
416 CurPool
= new IdDeclInfoPool(CurPool
);
419 IdDeclInfo
*IDI
= &CurPool
->Pool
[CurIndex
];
420 Name
.setFETokenInfo(reinterpret_cast<void*>(
421 reinterpret_cast<uintptr_t>(IDI
) | 0x1)
427 void IdentifierResolver::iterator::incrementSlowCase() {
428 NamedDecl
*D
= **this;
429 void *InfoPtr
= D
->getDeclName().getFETokenInfo();
430 assert(!isDeclPtr(InfoPtr
) && "Decl with wrong id ?");
431 IdDeclInfo
*Info
= toIdDeclInfo(InfoPtr
);
433 BaseIter I
= getIterator();
434 if (I
!= Info
->decls_begin())
435 *this = iterator(I
-1);
436 else // No more decls.