blob: 812c362acd37f1dd082839a2c1223f8d7b408c49 [file] [log] [blame]
Eli Friedmana8a09ac2008-06-07 16:52:53 +00001//===--- DeclBase.cpp - Declaration AST Node Implementation ---------------===//
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 Decl and DeclContext classes.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/DeclBase.h"
Douglas Gregor469fc9a2009-02-02 23:39:07 +000015#include "clang/AST/Decl.h"
Argiris Kirtzidis6df1fc02008-06-09 21:05:31 +000016#include "clang/AST/DeclCXX.h"
Douglas Gregor279272e2009-02-04 19:02:06 +000017#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor8acb7272008-12-11 16:49:14 +000020#include "clang/AST/Type.h"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000021#include "llvm/ADT/DenseMap.h"
Chris Lattnerc309ade2009-03-05 08:00:35 +000022#include "llvm/Support/raw_ostream.h"
Douglas Gregor6e71edc2008-12-23 21:05:05 +000023#include <algorithm>
Chris Lattner7d6220c2009-03-02 22:20:04 +000024#include <cstdio>
Douglas Gregor6e71edc2008-12-23 21:05:05 +000025#include <functional>
Douglas Gregorddfd9d52008-12-23 00:26:44 +000026#include <vector>
Eli Friedmana8a09ac2008-06-07 16:52:53 +000027using namespace clang;
28
29//===----------------------------------------------------------------------===//
30// Statistics
31//===----------------------------------------------------------------------===//
32
Douglas Gregor469fc9a2009-02-02 23:39:07 +000033#define DECL(Derived, Base) static int n##Derived##s = 0;
34#include "clang/AST/DeclNodes.def"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000035
36static bool StatSwitch = false;
37
38// This keeps track of all decl attributes. Since so few decls have attrs, we
39// keep them in a hash map instead of wasting space in the Decl class.
40typedef llvm::DenseMap<const Decl*, Attr*> DeclAttrMapTy;
41
42static DeclAttrMapTy *DeclAttrs = 0;
43
44const char *Decl::getDeclKindName() const {
45 switch (DeclKind) {
Douglas Gregor469fc9a2009-02-02 23:39:07 +000046 default: assert(0 && "Declaration not in DeclNodes.def!");
47#define DECL(Derived, Base) case Derived: return #Derived;
48#include "clang/AST/DeclNodes.def"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000049 }
50}
51
Steve Naroffe5f128a2009-01-20 19:53:53 +000052const char *DeclContext::getDeclKindName() const {
53 switch (DeclKind) {
Douglas Gregor469fc9a2009-02-02 23:39:07 +000054 default: assert(0 && "Declaration context not in DeclNodes.def!");
Argiris Kirtzidis2d9b7612009-02-16 14:28:33 +000055#define DECL(Derived, Base) case Decl::Derived: return #Derived;
Douglas Gregor469fc9a2009-02-02 23:39:07 +000056#include "clang/AST/DeclNodes.def"
Steve Naroffe5f128a2009-01-20 19:53:53 +000057 }
58}
59
Eli Friedmana8a09ac2008-06-07 16:52:53 +000060bool Decl::CollectingStats(bool Enable) {
61 if (Enable)
62 StatSwitch = true;
63 return StatSwitch;
64}
65
66void Decl::PrintStats() {
67 fprintf(stderr, "*** Decl Stats:\n");
Eli Friedmana8a09ac2008-06-07 16:52:53 +000068
Douglas Gregor469fc9a2009-02-02 23:39:07 +000069 int totalDecls = 0;
70#define DECL(Derived, Base) totalDecls += n##Derived##s;
71#include "clang/AST/DeclNodes.def"
72 fprintf(stderr, " %d decls total.\n", totalDecls);
73
74 int totalBytes = 0;
75#define DECL(Derived, Base) \
76 if (n##Derived##s > 0) { \
77 totalBytes += (int)(n##Derived##s * sizeof(Derived##Decl)); \
78 fprintf(stderr, " %d " #Derived " decls, %d each (%d bytes)\n", \
79 n##Derived##s, (int)sizeof(Derived##Decl), \
80 (int)(n##Derived##s * sizeof(Derived##Decl))); \
81 }
82#include "clang/AST/DeclNodes.def"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000083
Douglas Gregor469fc9a2009-02-02 23:39:07 +000084 fprintf(stderr, "Total bytes = %d\n", totalBytes);
Eli Friedmana8a09ac2008-06-07 16:52:53 +000085}
86
87void Decl::addDeclKind(Kind k) {
88 switch (k) {
Douglas Gregor469fc9a2009-02-02 23:39:07 +000089 default: assert(0 && "Declaration not in DeclNodes.def!");
90#define DECL(Derived, Base) case Derived: ++n##Derived##s; break;
91#include "clang/AST/DeclNodes.def"
Eli Friedmana8a09ac2008-06-07 16:52:53 +000092 }
93}
94
95//===----------------------------------------------------------------------===//
Chris Lattnerc309ade2009-03-05 08:00:35 +000096// PrettyStackTraceDecl Implementation
97//===----------------------------------------------------------------------===//
98
99void PrettyStackTraceDecl::print(llvm::raw_ostream &OS) const {
100 SourceLocation TheLoc = Loc;
101 if (TheLoc.isInvalid() && TheDecl)
102 TheLoc = TheDecl->getLocation();
103
104 if (TheLoc.isValid()) {
105 TheLoc.print(OS, SM);
106 OS << ": ";
107 }
108
109 OS << Message;
110
111 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(TheDecl))
112 OS << " '" << DN->getQualifiedNameAsString() << '\'';
113 OS << '\n';
114}
115
116//===----------------------------------------------------------------------===//
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000117// Decl Implementation
118//===----------------------------------------------------------------------===//
119
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000120void Decl::setDeclContext(DeclContext *DC) {
121 if (isOutOfSemaDC())
122 delete getMultipleDC();
123
124 DeclCtx = reinterpret_cast<uintptr_t>(DC);
125}
126
127void Decl::setLexicalDeclContext(DeclContext *DC) {
128 if (DC == getLexicalDeclContext())
129 return;
130
131 if (isInSemaDC()) {
132 MultipleDC *MDC = new MultipleDC();
133 MDC->SemanticDC = getDeclContext();
134 MDC->LexicalDC = DC;
135 DeclCtx = reinterpret_cast<uintptr_t>(MDC) | 0x1;
136 } else {
137 getMultipleDC()->LexicalDC = DC;
138 }
139}
140
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000141// Out-of-line virtual method providing a home for Decl.
142Decl::~Decl() {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000143 if (isOutOfSemaDC())
144 delete getMultipleDC();
145
Chris Lattner0fc6d642009-03-04 06:05:19 +0000146 assert(!HasAttrs && "attributes should have been freed by Destroy");
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000147}
148
149void Decl::addAttr(Attr *NewAttr) {
150 if (!DeclAttrs)
151 DeclAttrs = new DeclAttrMapTy();
152
153 Attr *&ExistingAttr = (*DeclAttrs)[this];
154
155 NewAttr->setNext(ExistingAttr);
156 ExistingAttr = NewAttr;
157
158 HasAttrs = true;
159}
160
161void Decl::invalidateAttrs() {
162 if (!HasAttrs) return;
163
164 HasAttrs = false;
165 (*DeclAttrs)[this] = 0;
166 DeclAttrs->erase(this);
167
168 if (DeclAttrs->empty()) {
169 delete DeclAttrs;
170 DeclAttrs = 0;
171 }
172}
173
Chris Lattner004a9bb2009-03-21 06:27:31 +0000174const Attr *Decl::getAttrsImpl() const {
175 assert(HasAttrs && "getAttrs() should verify this!");
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000176 return (*DeclAttrs)[this];
177}
178
179void Decl::swapAttrs(Decl *RHS) {
180 bool HasLHSAttr = this->HasAttrs;
181 bool HasRHSAttr = RHS->HasAttrs;
182
183 // Usually, neither decl has attrs, nothing to do.
184 if (!HasLHSAttr && !HasRHSAttr) return;
185
186 // If 'this' has no attrs, swap the other way.
187 if (!HasLHSAttr)
188 return RHS->swapAttrs(this);
189
190 // Handle the case when both decls have attrs.
191 if (HasRHSAttr) {
192 std::swap((*DeclAttrs)[this], (*DeclAttrs)[RHS]);
193 return;
194 }
195
196 // Otherwise, LHS has an attr and RHS doesn't.
197 (*DeclAttrs)[RHS] = (*DeclAttrs)[this];
198 (*DeclAttrs).erase(this);
199 this->HasAttrs = false;
200 RHS->HasAttrs = true;
201}
202
203
Chris Lattner0fc6d642009-03-04 06:05:19 +0000204void Decl::Destroy(ASTContext &C) {
205 // Free attributes for this decl.
206 if (HasAttrs) {
207 DeclAttrMapTy::iterator it = DeclAttrs->find(this);
208 assert(it != DeclAttrs->end() && "No attrs found but HasAttrs is true!");
209
210 // release attributes.
211 it->second->Destroy(C);
212 invalidateAttrs();
213 HasAttrs = false;
214 }
215
Douglas Gregor8314d742009-01-13 19:47:12 +0000216#if 0
Douglas Gregorf4006be2009-01-20 04:25:11 +0000217 // FIXME: Once ownership is fully understood, we can enable this code
218 if (DeclContext *DC = dyn_cast<DeclContext>(this))
219 DC->decls_begin()->Destroy(C);
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000220
Douglas Gregorf4006be2009-01-20 04:25:11 +0000221 // Observe the unrolled recursion. By setting N->NextDeclInScope = 0x0
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000222 // within the loop, only the Destroy method for the first Decl
223 // will deallocate all of the Decls in a chain.
224
Douglas Gregorf4006be2009-01-20 04:25:11 +0000225 Decl* N = NextDeclInScope;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000226
227 while (N) {
Douglas Gregorf4006be2009-01-20 04:25:11 +0000228 Decl* Tmp = N->NextDeclInScope;
229 N->NextDeclInScope = 0;
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000230 N->Destroy(C);
231 N = Tmp;
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000232 }
Douglas Gregor8314d742009-01-13 19:47:12 +0000233
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000234 this->~Decl();
Steve Naroff5abb0282009-01-27 21:25:57 +0000235 C.Deallocate((void *)this);
Douglas Gregorf4006be2009-01-20 04:25:11 +0000236#endif
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000237}
238
Argiris Kirtzidis4b662ea2008-10-12 16:14:48 +0000239Decl *Decl::castFromDeclContext (const DeclContext *D) {
Argiris Kirtzidis981aa132009-02-16 14:29:28 +0000240 Decl::Kind DK = D->getDeclKind();
241 switch(DK) {
242#define DECL_CONTEXT(Name) \
243 case Decl::Name: \
244 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
245#define DECL_CONTEXT_BASE(Name)
246#include "clang/AST/DeclNodes.def"
247 default:
248#define DECL_CONTEXT_BASE(Name) \
249 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
250 return static_cast<Name##Decl*>(const_cast<DeclContext*>(D));
251#include "clang/AST/DeclNodes.def"
252 assert(false && "a decl that inherits DeclContext isn't handled");
253 return 0;
254 }
Argiris Kirtzidis4b662ea2008-10-12 16:14:48 +0000255}
256
257DeclContext *Decl::castToDeclContext(const Decl *D) {
Argiris Kirtzidis981aa132009-02-16 14:29:28 +0000258 Decl::Kind DK = D->getKind();
259 switch(DK) {
260#define DECL_CONTEXT(Name) \
261 case Decl::Name: \
262 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
263#define DECL_CONTEXT_BASE(Name)
264#include "clang/AST/DeclNodes.def"
265 default:
266#define DECL_CONTEXT_BASE(Name) \
267 if (DK >= Decl::Name##First && DK <= Decl::Name##Last) \
268 return static_cast<Name##Decl*>(const_cast<Decl*>(D));
269#include "clang/AST/DeclNodes.def"
270 assert(false && "a decl that inherits DeclContext isn't handled");
271 return 0;
272 }
Argiris Kirtzidis4b662ea2008-10-12 16:14:48 +0000273}
274
Eli Friedmana8a09ac2008-06-07 16:52:53 +0000275//===----------------------------------------------------------------------===//
276// DeclContext Implementation
277//===----------------------------------------------------------------------===//
278
Argiris Kirtzidis981aa132009-02-16 14:29:28 +0000279bool DeclContext::classof(const Decl *D) {
280 switch (D->getKind()) {
281#define DECL_CONTEXT(Name) case Decl::Name:
282#define DECL_CONTEXT_BASE(Name)
283#include "clang/AST/DeclNodes.def"
284 return true;
285 default:
286#define DECL_CONTEXT_BASE(Name) \
287 if (D->getKind() >= Decl::Name##First && \
288 D->getKind() <= Decl::Name##Last) \
289 return true;
290#include "clang/AST/DeclNodes.def"
291 return false;
292 }
293}
294
Chris Lattner77820d52009-02-20 01:44:05 +0000295/// StoredDeclsList - This is an array of decls optimized a common case of only
296/// containing one entry.
297struct StoredDeclsList {
298 /// Data - If the integer is 0, then the pointer is a NamedDecl*. If the
299 /// integer is 1, then it is a VectorTy;
300 llvm::PointerIntPair<void*, 1, bool> Data;
301
302 /// VectorTy - When in vector form, this is what the Data pointer points to.
303 typedef llvm::SmallVector<NamedDecl*, 4> VectorTy;
304public:
305 StoredDeclsList() {}
306 StoredDeclsList(const StoredDeclsList &RHS) : Data(RHS.Data) {
307 if (isVector())
308 Data.setPointer(new VectorTy(getVector()));
309 }
310
311 ~StoredDeclsList() {
312 // If this is a vector-form, free the vector.
313 if (isVector())
314 delete &getVector();
315 }
316
Chris Lattner51e57e62009-02-23 18:17:44 +0000317 StoredDeclsList &operator=(const StoredDeclsList &RHS) {
318 if (isVector())
319 delete &getVector();
320 Data = RHS.Data;
321 if (isVector())
322 Data.setPointer(new VectorTy(getVector()));
323 return *this;
324 }
325
Chris Lattner77820d52009-02-20 01:44:05 +0000326 bool isVector() const { return Data.getInt() != 0; }
327 bool isInline() const { return Data.getInt() == 0; }
328 bool isNull() const { return Data.getPointer() == 0; }
329
330 void setOnlyValue(NamedDecl *ND) {
331 assert(isInline() && "Not inline");
332 Data.setPointer(ND);
333 }
334
335 /// getLookupResult - Return an array of all the decls that this list
336 /// represents.
337 DeclContext::lookup_result getLookupResult() {
338 // If we have a single inline unit, return it.
339 if (isInline()) {
340 assert(!isNull() && "Empty list isn't allowed");
341
342 // Data is a raw pointer to a NamedDecl*, return it.
343 void *Ptr = &Data;
344 return DeclContext::lookup_result((NamedDecl**)Ptr, (NamedDecl**)Ptr+1);
345 }
346
347 // Otherwise, we have a range result.
348 VectorTy &V = getVector();
349 return DeclContext::lookup_result(&V[0], &V[0]+V.size());
350 }
351
352 /// HandleRedeclaration - If this is a redeclaration of an existing decl,
353 /// replace the old one with D and return true. Otherwise return false.
354 bool HandleRedeclaration(NamedDecl *D) {
355 // Most decls only have one entry in their list, special case it.
356 if (isInline()) {
357 if (!D->declarationReplaces(getInlineValue()))
358 return false;
359 setOnlyValue(D);
360 return true;
361 }
362
363 // Determine if this declaration is actually a redeclaration.
364 VectorTy &Vec = getVector();
365 VectorTy::iterator RDI
366 = std::find_if(Vec.begin(), Vec.end(),
367 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
368 D));
369 if (RDI == Vec.end())
370 return false;
371 *RDI = D;
372 return true;
373 }
374
375 /// AddSubsequentDecl - This is called on the second and later decl when it is
376 /// not a redeclaration to merge it into the appropriate place in our list.
377 ///
378 void AddSubsequentDecl(NamedDecl *D) {
379 // If this is the second decl added to the list, convert this to vector
380 // form.
381 if (isInline()) {
382 NamedDecl *OldD = getInlineValue();
383 Data.setInt(1);
384 VectorTy *VT = new VectorTy();
385 VT->push_back(OldD);
386 Data.setPointer(VT);
387 }
388
389 VectorTy &Vec = getVector();
390 if (isa<UsingDirectiveDecl>(D) ||
391 D->getIdentifierNamespace() == Decl::IDNS_Tag)
392 Vec.push_back(D);
393 else if (Vec.back()->getIdentifierNamespace() == Decl::IDNS_Tag) {
394 NamedDecl *TagD = Vec.back();
395 Vec.back() = D;
396 Vec.push_back(TagD);
397 } else
398 Vec.push_back(D);
399 }
400
401
402private:
403 VectorTy &getVector() const {
404 assert(isVector() && "Not in vector form");
405 return *static_cast<VectorTy*>(Data.getPointer());
406 }
407
408 NamedDecl *getInlineValue() const {
409 assert(isInline() && "Not in inline form");
410 return (NamedDecl*)Data.getPointer();
411 }
412};
413
414
415
416typedef llvm::DenseMap<DeclarationName, StoredDeclsList> StoredDeclsMap;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000417
418DeclContext::~DeclContext() {
419 unsigned Size = LookupPtr.getInt();
Chris Lattner265f01d2009-02-20 00:55:03 +0000420 if (Size == LookupIsMap)
421 delete static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
422 else
423 delete [] static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000424}
425
426void DeclContext::DestroyDecls(ASTContext &C) {
Douglas Gregorf4006be2009-01-20 04:25:11 +0000427 for (decl_iterator D = decls_begin(); D != decls_end(); )
428 (*D++)->Destroy(C);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000429}
430
Douglas Gregord8028382009-01-05 19:45:36 +0000431bool DeclContext::isTransparentContext() const {
432 if (DeclKind == Decl::Enum)
433 return true; // FIXME: Check for C++0x scoped enums
434 else if (DeclKind == Decl::LinkageSpec)
435 return true;
Douglas Gregor1db12932009-02-26 00:02:51 +0000436 else if (DeclKind >= Decl::RecordFirst && DeclKind <= Decl::RecordLast)
Douglas Gregor723d3332009-01-07 00:43:41 +0000437 return cast<RecordDecl>(this)->isAnonymousStructOrUnion();
Douglas Gregord8028382009-01-05 19:45:36 +0000438 else if (DeclKind == Decl::Namespace)
439 return false; // FIXME: Check for C++0x inline namespaces
440
441 return false;
442}
443
Steve Naroffab63fd62009-01-08 17:28:14 +0000444DeclContext *DeclContext::getPrimaryContext() {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000445 switch (DeclKind) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000446 case Decl::TranslationUnit:
Douglas Gregord8028382009-01-05 19:45:36 +0000447 case Decl::LinkageSpec:
448 case Decl::Block:
Douglas Gregor8acb7272008-12-11 16:49:14 +0000449 // There is only one DeclContext for these entities.
450 return this;
451
452 case Decl::Namespace:
453 // The original namespace is our primary context.
454 return static_cast<NamespaceDecl*>(this)->getOriginalNamespace();
455
Douglas Gregor8acb7272008-12-11 16:49:14 +0000456 case Decl::ObjCMethod:
457 return this;
458
459 case Decl::ObjCInterface:
Steve Naroffab63fd62009-01-08 17:28:14 +0000460 case Decl::ObjCProtocol:
461 case Decl::ObjCCategory:
Douglas Gregor8acb7272008-12-11 16:49:14 +0000462 // FIXME: Can Objective-C interfaces be forward-declared?
463 return this;
464
Steve Naroffab63fd62009-01-08 17:28:14 +0000465 case Decl::ObjCImplementation:
466 case Decl::ObjCCategoryImpl:
467 return this;
468
Douglas Gregor8acb7272008-12-11 16:49:14 +0000469 default:
Douglas Gregora08b6c72009-02-17 23:15:12 +0000470 if (DeclKind >= Decl::TagFirst && DeclKind <= Decl::TagLast) {
471 // If this is a tag type that has a definition or is currently
472 // being defined, that definition is our primary context.
Douglas Gregor9c7825b2009-02-26 22:19:44 +0000473 if (const TagType *TagT = cast<TagDecl>(this)->TypeForDecl->getAsTagType())
Douglas Gregora08b6c72009-02-17 23:15:12 +0000474 if (TagT->isBeingDefined() ||
475 (TagT->getDecl() && TagT->getDecl()->isDefinition()))
476 return TagT->getDecl();
477 return this;
478 }
479
Douglas Gregor8acb7272008-12-11 16:49:14 +0000480 assert(DeclKind >= Decl::FunctionFirst && DeclKind <= Decl::FunctionLast &&
481 "Unknown DeclContext kind");
482 return this;
483 }
484}
485
486DeclContext *DeclContext::getNextContext() {
487 switch (DeclKind) {
Douglas Gregor8acb7272008-12-11 16:49:14 +0000488 case Decl::Namespace:
489 // Return the next namespace
490 return static_cast<NamespaceDecl*>(this)->getNextNamespace();
491
492 default:
Douglas Gregor8acb7272008-12-11 16:49:14 +0000493 return 0;
494 }
495}
496
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000497void DeclContext::addDecl(Decl *D) {
Chris Lattner53602072009-02-20 00:56:18 +0000498 assert(D->getLexicalDeclContext() == this &&
499 "Decl inserted into wrong lexical context");
Douglas Gregord1675382009-01-09 19:42:16 +0000500 assert(!D->NextDeclInScope && D != LastDecl &&
501 "Decl already inserted into a DeclContext");
502
503 if (FirstDecl) {
504 LastDecl->NextDeclInScope = D;
505 LastDecl = D;
506 } else {
507 FirstDecl = LastDecl = D;
508 }
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000509
510 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000511 ND->getDeclContext()->makeDeclVisibleInContext(ND);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000512}
513
Douglas Gregord8028382009-01-05 19:45:36 +0000514/// buildLookup - Build the lookup data structure with all of the
515/// declarations in DCtx (and any other contexts linked to it or
516/// transparent contexts nested within it).
Steve Naroffab63fd62009-01-08 17:28:14 +0000517void DeclContext::buildLookup(DeclContext *DCtx) {
Douglas Gregord8028382009-01-05 19:45:36 +0000518 for (; DCtx; DCtx = DCtx->getNextContext()) {
Douglas Gregorf0464ec2009-01-06 07:17:58 +0000519 for (decl_iterator D = DCtx->decls_begin(), DEnd = DCtx->decls_end();
520 D != DEnd; ++D) {
Douglas Gregord8028382009-01-05 19:45:36 +0000521 // Insert this declaration into the lookup structure
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000522 if (NamedDecl *ND = dyn_cast<NamedDecl>(*D))
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000523 makeDeclVisibleInContextImpl(ND);
Douglas Gregord8028382009-01-05 19:45:36 +0000524
525 // If this declaration is itself a transparent declaration context,
526 // add its members (recursively).
527 if (DeclContext *InnerCtx = dyn_cast<DeclContext>(*D))
528 if (InnerCtx->isTransparentContext())
Steve Naroffab63fd62009-01-08 17:28:14 +0000529 buildLookup(InnerCtx->getPrimaryContext());
Douglas Gregord8028382009-01-05 19:45:36 +0000530 }
531 }
532}
533
Douglas Gregor8acb7272008-12-11 16:49:14 +0000534DeclContext::lookup_result
Steve Naroffab63fd62009-01-08 17:28:14 +0000535DeclContext::lookup(DeclarationName Name) {
536 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000537 if (PrimaryContext != this)
Steve Naroffab63fd62009-01-08 17:28:14 +0000538 return PrimaryContext->lookup(Name);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000539
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000540 /// If there is no lookup data structure, build one now by walking
Douglas Gregor8acb7272008-12-11 16:49:14 +0000541 /// all of the linked DeclContexts (in declaration order!) and
542 /// inserting their values.
Douglas Gregord8028382009-01-05 19:45:36 +0000543 if (LookupPtr.getPointer() == 0)
Steve Naroffab63fd62009-01-08 17:28:14 +0000544 buildLookup(this);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000545
Douglas Gregor8acb7272008-12-11 16:49:14 +0000546 if (isLookupMap()) {
547 StoredDeclsMap *Map = static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
548 StoredDeclsMap::iterator Pos = Map->find(Name);
Chris Lattner265f01d2009-02-20 00:55:03 +0000549 if (Pos == Map->end())
550 return lookup_result(0, 0);
Chris Lattner77820d52009-02-20 01:44:05 +0000551 return Pos->second.getLookupResult();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000552 }
553
554 // We have a small array. Look into it.
555 unsigned Size = LookupPtr.getInt();
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000556 NamedDecl **Array = static_cast<NamedDecl**>(LookupPtr.getPointer());
Douglas Gregor39677622008-12-11 20:41:00 +0000557 for (unsigned Idx = 0; Idx != Size; ++Idx)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000558 if (Array[Idx]->getDeclName() == Name) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000559 unsigned Last = Idx + 1;
560 while (Last != Size && Array[Last]->getDeclName() == Name)
561 ++Last;
562 return lookup_result(&Array[Idx], &Array[Last]);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000563 }
564
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000565 return lookup_result(0, 0);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000566}
567
568DeclContext::lookup_const_result
Steve Naroffab63fd62009-01-08 17:28:14 +0000569DeclContext::lookup(DeclarationName Name) const {
570 return const_cast<DeclContext*>(this)->lookup(Name);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000571}
572
Douglas Gregor38d38a02009-01-07 02:48:43 +0000573const DeclContext *DeclContext::getLookupContext() const {
574 const DeclContext *Ctx = this;
Douglas Gregordb568cf2009-01-08 20:45:30 +0000575 // Skip through transparent contexts.
Douglas Gregor69e781f2009-01-06 23:51:29 +0000576 while (Ctx->isTransparentContext())
577 Ctx = Ctx->getParent();
578 return Ctx;
579}
580
Douglas Gregor0d93f692009-02-25 22:02:03 +0000581DeclContext *DeclContext::getEnclosingNamespaceContext() {
582 DeclContext *Ctx = this;
583 // Skip through non-namespace, non-translation-unit contexts.
584 while (!Ctx->isFileContext() || Ctx->isTransparentContext())
585 Ctx = Ctx->getParent();
586 return Ctx->getPrimaryContext();
587}
588
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000589void DeclContext::makeDeclVisibleInContext(NamedDecl *D) {
Douglas Gregora08b6c72009-02-17 23:15:12 +0000590 // FIXME: This feels like a hack. Should DeclarationName support
591 // template-ids, or is there a better way to keep specializations
592 // from being visible?
593 if (isa<ClassTemplateSpecializationDecl>(D))
594 return;
595
Steve Naroffab63fd62009-01-08 17:28:14 +0000596 DeclContext *PrimaryContext = getPrimaryContext();
Douglas Gregor8acb7272008-12-11 16:49:14 +0000597 if (PrimaryContext != this) {
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000598 PrimaryContext->makeDeclVisibleInContext(D);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000599 return;
600 }
601
602 // If we already have a lookup data structure, perform the insertion
603 // into it. Otherwise, be lazy and don't build that structure until
604 // someone asks for it.
605 if (LookupPtr.getPointer())
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000606 makeDeclVisibleInContextImpl(D);
Douglas Gregord8028382009-01-05 19:45:36 +0000607
Douglas Gregord8028382009-01-05 19:45:36 +0000608 // If we are a transparent context, insert into our parent context,
609 // too. This operation is recursive.
610 if (isTransparentContext())
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000611 getParent()->makeDeclVisibleInContext(D);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000612}
613
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000614void DeclContext::makeDeclVisibleInContextImpl(NamedDecl *D) {
Douglas Gregord8028382009-01-05 19:45:36 +0000615 // Skip unnamed declarations.
616 if (!D->getDeclName())
617 return;
618
Douglas Gregora08b6c72009-02-17 23:15:12 +0000619 // FIXME: This feels like a hack. Should DeclarationName support
620 // template-ids, or is there a better way to keep specializations
621 // from being visible?
622 if (isa<ClassTemplateSpecializationDecl>(D))
623 return;
624
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000625 bool MayBeRedeclaration = true;
626
Douglas Gregor8acb7272008-12-11 16:49:14 +0000627 if (!isLookupMap()) {
628 unsigned Size = LookupPtr.getInt();
629
630 // The lookup data is stored as an array. Search through the array
631 // to find the insertion location.
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000632 NamedDecl **Array;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000633 if (Size == 0) {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000634 Array = new NamedDecl*[LookupIsMap - 1];
Douglas Gregor8acb7272008-12-11 16:49:14 +0000635 LookupPtr.setPointer(Array);
636 } else {
Douglas Gregoraf8ad2b2009-01-20 01:17:11 +0000637 Array = static_cast<NamedDecl **>(LookupPtr.getPointer());
Douglas Gregor8acb7272008-12-11 16:49:14 +0000638 }
639
640 // We always keep declarations of the same name next to each other
641 // in the array, so that it is easy to return multiple results
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000642 // from lookup().
643 unsigned FirstMatch;
644 for (FirstMatch = 0; FirstMatch != Size; ++FirstMatch)
645 if (Array[FirstMatch]->getDeclName() == D->getDeclName())
Douglas Gregor39677622008-12-11 20:41:00 +0000646 break;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000647
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000648 unsigned InsertPos = FirstMatch;
649 if (FirstMatch != Size) {
650 // We found another declaration with the same name. First
651 // determine whether this is a redeclaration of an existing
652 // declaration in this scope, in which case we will replace the
653 // existing declaration.
654 unsigned LastMatch = FirstMatch;
655 for (; LastMatch != Size; ++LastMatch) {
656 if (Array[LastMatch]->getDeclName() != D->getDeclName())
657 break;
658
Douglas Gregor6e71edc2008-12-23 21:05:05 +0000659 if (D->declarationReplaces(Array[LastMatch])) {
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000660 // D is a redeclaration of an existing element in the
661 // array. Replace that element with D.
662 Array[LastMatch] = D;
663 return;
664 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000665 }
666
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000667 // [FirstMatch, LastMatch) contains the set of declarations that
668 // have the same name as this declaration. Determine where the
Douglas Gregor7a7be652009-02-03 19:21:40 +0000669 // declaration D will be inserted into this range.
670 if (D->getKind() == Decl::UsingDirective ||
671 D->getIdentifierNamespace() == Decl::IDNS_Tag)
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000672 InsertPos = LastMatch;
673 else if (Array[LastMatch-1]->getIdentifierNamespace() == Decl::IDNS_Tag)
674 InsertPos = LastMatch - 1;
675 else
676 InsertPos = LastMatch;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000677 }
678
679 if (Size < LookupIsMap - 1) {
680 // The new declaration will fit in the array. Insert the new
681 // declaration at the position Match in the array.
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000682 for (unsigned Idx = Size; Idx > InsertPos; --Idx)
Douglas Gregor8acb7272008-12-11 16:49:14 +0000683 Array[Idx] = Array[Idx-1];
684
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000685 Array[InsertPos] = D;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000686 LookupPtr.setInt(Size + 1);
687 return;
688 }
689
690 // We've reached capacity in this array. Create a map and copy in
691 // all of the declarations that were stored in the array.
692 StoredDeclsMap *Map = new StoredDeclsMap(16);
693 LookupPtr.setPointer(Map);
694 LookupPtr.setInt(LookupIsMap);
Douglas Gregor39677622008-12-11 20:41:00 +0000695 for (unsigned Idx = 0; Idx != LookupIsMap - 1; ++Idx)
Douglas Gregor9ac66d22009-01-20 16:54:50 +0000696 makeDeclVisibleInContextImpl(Array[Idx]);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000697 delete [] Array;
698
699 // Fall through to perform insertion into the map.
Douglas Gregorddfd9d52008-12-23 00:26:44 +0000700 MayBeRedeclaration = false;
701 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000702
703 // Insert this declaration into the map.
Chris Lattner77820d52009-02-20 01:44:05 +0000704 StoredDeclsMap &Map = *static_cast<StoredDeclsMap*>(LookupPtr.getPointer());
705 StoredDeclsList &DeclNameEntries = Map[D->getDeclName()];
706 if (DeclNameEntries.isNull()) {
707 DeclNameEntries.setOnlyValue(D);
Chris Lattner6719b1f2009-02-19 07:00:44 +0000708 return;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000709 }
Chris Lattner265f01d2009-02-20 00:55:03 +0000710
Chris Lattnerba589d42009-02-20 01:10:07 +0000711 // If it is possible that this is a redeclaration, check to see if there is
712 // already a decl for which declarationReplaces returns true. If there is
713 // one, just replace it and return.
Chris Lattner77820d52009-02-20 01:44:05 +0000714 if (MayBeRedeclaration && DeclNameEntries.HandleRedeclaration(D))
715 return;
Chris Lattner265f01d2009-02-20 00:55:03 +0000716
Chris Lattner6719b1f2009-02-19 07:00:44 +0000717 // Put this declaration into the appropriate slot.
Chris Lattner77820d52009-02-20 01:44:05 +0000718 DeclNameEntries.AddSubsequentDecl(D);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000719}
Douglas Gregor7a7be652009-02-03 19:21:40 +0000720
721/// Returns iterator range [First, Last) of UsingDirectiveDecls stored within
722/// this context.
723DeclContext::udir_iterator_range DeclContext::getUsingDirectives() const {
724 lookup_const_result Result = lookup(UsingDirectiveDecl::getName());
725 return udir_iterator_range(reinterpret_cast<udir_iterator>(Result.first),
726 reinterpret_cast<udir_iterator>(Result.second));
727}
728