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