IdentifierResolver.cpp revision 263508
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(0), 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 ExplicitInstantiationOrSpecialization) 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 ExplicitInstantiationOrSpecialization
135           ? Ctx->InEnclosingNamespaceSetOf(DCtx)
136           : Ctx->Equals(DCtx);
137}
138
139/// AddDecl - Link the decl to its shadowed decl chain.
140void IdentifierResolver::AddDecl(NamedDecl *D) {
141  DeclarationName Name = D->getDeclName();
142  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
143    updatingIdentifier(*II);
144
145  void *Ptr = Name.getFETokenInfo<void>();
146
147  if (!Ptr) {
148    Name.setFETokenInfo(D);
149    return;
150  }
151
152  IdDeclInfo *IDI;
153
154  if (isDeclPtr(Ptr)) {
155    Name.setFETokenInfo(NULL);
156    IDI = &(*IdDeclInfos)[Name];
157    NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
158    IDI->AddDecl(PrevD);
159  } else
160    IDI = toIdDeclInfo(Ptr);
161
162  IDI->AddDecl(D);
163}
164
165void IdentifierResolver::InsertDeclAfter(iterator Pos, NamedDecl *D) {
166  DeclarationName Name = D->getDeclName();
167  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
168    updatingIdentifier(*II);
169
170  void *Ptr = Name.getFETokenInfo<void>();
171
172  if (!Ptr) {
173    AddDecl(D);
174    return;
175  }
176
177  if (isDeclPtr(Ptr)) {
178    // We only have a single declaration: insert before or after it,
179    // as appropriate.
180    if (Pos == iterator()) {
181      // Add the new declaration before the existing declaration.
182      NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
183      RemoveDecl(PrevD);
184      AddDecl(D);
185      AddDecl(PrevD);
186    } else {
187      // Add new declaration after the existing declaration.
188      AddDecl(D);
189    }
190
191    return;
192  }
193
194  // General case: insert the declaration at the appropriate point in the
195  // list, which already has at least two elements.
196  IdDeclInfo *IDI = toIdDeclInfo(Ptr);
197  if (Pos.isIterator()) {
198    IDI->InsertDecl(Pos.getIterator() + 1, D);
199  } else
200    IDI->InsertDecl(IDI->decls_begin(), D);
201}
202
203/// RemoveDecl - Unlink the decl from its shadowed decl chain.
204/// The decl must already be part of the decl chain.
205void IdentifierResolver::RemoveDecl(NamedDecl *D) {
206  assert(D && "null param passed");
207  DeclarationName Name = D->getDeclName();
208  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
209    updatingIdentifier(*II);
210
211  void *Ptr = Name.getFETokenInfo<void>();
212
213  assert(Ptr && "Didn't find this decl on its identifier's chain!");
214
215  if (isDeclPtr(Ptr)) {
216    assert(D == Ptr && "Didn't find this decl on its identifier's chain!");
217    Name.setFETokenInfo(NULL);
218    return;
219  }
220
221  return toIdDeclInfo(Ptr)->RemoveDecl(D);
222}
223
224/// begin - Returns an iterator for decls with name 'Name'.
225IdentifierResolver::iterator
226IdentifierResolver::begin(DeclarationName Name) {
227  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
228    readingIdentifier(*II);
229
230  void *Ptr = Name.getFETokenInfo<void>();
231  if (!Ptr) return end();
232
233  if (isDeclPtr(Ptr))
234    return iterator(static_cast<NamedDecl*>(Ptr));
235
236  IdDeclInfo *IDI = toIdDeclInfo(Ptr);
237
238  IdDeclInfo::DeclsTy::iterator I = IDI->decls_end();
239  if (I != IDI->decls_begin())
240    return iterator(I-1);
241  // No decls found.
242  return end();
243}
244
245namespace {
246  enum DeclMatchKind {
247    DMK_Different,
248    DMK_Replace,
249    DMK_Ignore
250  };
251}
252
253/// \brief Compare two declarations to see whether they are different or,
254/// if they are the same, whether the new declaration should replace the
255/// existing declaration.
256static DeclMatchKind compareDeclarations(NamedDecl *Existing, NamedDecl *New) {
257  // If the declarations are identical, ignore the new one.
258  if (Existing == New)
259    return DMK_Ignore;
260
261  // If the declarations have different kinds, they're obviously different.
262  if (Existing->getKind() != New->getKind())
263    return DMK_Different;
264
265  // If the declarations are redeclarations of each other, keep the newest one.
266  if (Existing->getCanonicalDecl() == New->getCanonicalDecl()) {
267    // If either of these is the most recent declaration, use it.
268    Decl *MostRecent = Existing->getMostRecentDecl();
269    if (Existing == MostRecent)
270      return DMK_Ignore;
271
272    if (New == MostRecent)
273      return DMK_Replace;
274
275    // If the existing declaration is somewhere in the previous declaration
276    // chain of the new declaration, then prefer the new declaration.
277    for (Decl::redecl_iterator RD = New->redecls_begin(),
278                            RDEnd = New->redecls_end();
279         RD != RDEnd; ++RD) {
280      if (*RD == Existing)
281        return DMK_Replace;
282
283      if (RD->isCanonicalDecl())
284        break;
285    }
286
287    return DMK_Ignore;
288  }
289
290  return DMK_Different;
291}
292
293bool IdentifierResolver::tryAddTopLevelDecl(NamedDecl *D, DeclarationName Name){
294  if (IdentifierInfo *II = Name.getAsIdentifierInfo())
295    readingIdentifier(*II);
296
297  void *Ptr = Name.getFETokenInfo<void>();
298
299  if (!Ptr) {
300    Name.setFETokenInfo(D);
301    return true;
302  }
303
304  IdDeclInfo *IDI;
305
306  if (isDeclPtr(Ptr)) {
307    NamedDecl *PrevD = static_cast<NamedDecl*>(Ptr);
308
309    switch (compareDeclarations(PrevD, D)) {
310    case DMK_Different:
311      break;
312
313    case DMK_Ignore:
314      return false;
315
316    case DMK_Replace:
317      Name.setFETokenInfo(D);
318      return true;
319    }
320
321    Name.setFETokenInfo(NULL);
322    IDI = &(*IdDeclInfos)[Name];
323
324    // If the existing declaration is not visible in translation unit scope,
325    // then add the new top-level declaration first.
326    if (!PrevD->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
327      IDI->AddDecl(D);
328      IDI->AddDecl(PrevD);
329    } else {
330      IDI->AddDecl(PrevD);
331      IDI->AddDecl(D);
332    }
333    return true;
334  }
335
336  IDI = toIdDeclInfo(Ptr);
337
338  // See whether this declaration is identical to any existing declarations.
339  // If not, find the right place to insert it.
340  for (IdDeclInfo::DeclsTy::iterator I = IDI->decls_begin(),
341                                  IEnd = IDI->decls_end();
342       I != IEnd; ++I) {
343
344    switch (compareDeclarations(*I, D)) {
345    case DMK_Different:
346      break;
347
348    case DMK_Ignore:
349      return false;
350
351    case DMK_Replace:
352      *I = D;
353      return true;
354    }
355
356    if (!(*I)->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
357      // We've found a declaration that is not visible from the translation
358      // unit (it's in an inner scope). Insert our declaration here.
359      IDI->InsertDecl(I, D);
360      return true;
361    }
362  }
363
364  // Add the declaration to the end.
365  IDI->AddDecl(D);
366  return true;
367}
368
369void IdentifierResolver::readingIdentifier(IdentifierInfo &II) {
370  if (II.isOutOfDate())
371    PP.getExternalSource()->updateOutOfDateIdentifier(II);
372}
373
374void IdentifierResolver::updatingIdentifier(IdentifierInfo &II) {
375  if (II.isOutOfDate())
376    PP.getExternalSource()->updateOutOfDateIdentifier(II);
377
378  if (II.isFromAST())
379    II.setChangedSinceDeserialization();
380}
381
382//===----------------------------------------------------------------------===//
383// IdDeclInfoMap Implementation
384//===----------------------------------------------------------------------===//
385
386/// Returns the IdDeclInfo associated to the DeclarationName.
387/// It creates a new IdDeclInfo if one was not created before for this id.
388IdentifierResolver::IdDeclInfo &
389IdentifierResolver::IdDeclInfoMap::operator[](DeclarationName Name) {
390  void *Ptr = Name.getFETokenInfo<void>();
391
392  if (Ptr) return *toIdDeclInfo(Ptr);
393
394  if (CurIndex == POOL_SIZE) {
395    CurPool = new IdDeclInfoPool(CurPool);
396    CurIndex = 0;
397  }
398  IdDeclInfo *IDI = &CurPool->Pool[CurIndex];
399  Name.setFETokenInfo(reinterpret_cast<void*>(
400                              reinterpret_cast<uintptr_t>(IDI) | 0x1)
401                                                                     );
402  ++CurIndex;
403  return *IDI;
404}
405
406void IdentifierResolver::iterator::incrementSlowCase() {
407  NamedDecl *D = **this;
408  void *InfoPtr = D->getDeclName().getFETokenInfo<void>();
409  assert(!isDeclPtr(InfoPtr) && "Decl with wrong id ?");
410  IdDeclInfo *Info = toIdDeclInfo(InfoPtr);
411
412  BaseIter I = getIterator();
413  if (I != Info->decls_begin())
414    *this = iterator(I-1);
415  else // No more decls.
416    *this = iterator();
417}
418