blob: d85123c85369db2adec485f2fda06c29bd633ce6 [file] [log] [blame]
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001//===--------------------- SemaLookup.cpp - Name Lookup ------------------===//
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 name lookup for C, C++, Objective-C, and
11// Objective-C++.
12//
13//===----------------------------------------------------------------------===//
14#include "Sema.h"
Douglas Gregor7176fff2009-01-15 00:26:24 +000015#include "SemaInherit.h"
16#include "clang/AST/ASTContext.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000017#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000020#include "clang/AST/Expr.h"
Douglas Gregoreb11cd02009-01-14 22:20:51 +000021#include "clang/Parse/DeclSpec.h"
22#include "clang/Basic/LangOptions.h"
23#include "llvm/ADT/STLExtras.h"
Douglas Gregorfa047642009-02-04 00:32:51 +000024#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +000025#include <set>
Douglas Gregor2a3009a2009-02-03 19:21:40 +000026#include <vector>
27#include <iterator>
28#include <utility>
29#include <algorithm>
Douglas Gregoreb11cd02009-01-14 22:20:51 +000030
31using namespace clang;
32
Douglas Gregor2a3009a2009-02-03 19:21:40 +000033typedef llvm::SmallVector<UsingDirectiveDecl*, 4> UsingDirectivesTy;
34typedef llvm::DenseSet<NamespaceDecl*> NamespaceSet;
35typedef llvm::SmallVector<Sema::LookupResult, 3> LookupResultsTy;
36
37/// UsingDirAncestorCompare - Implements strict weak ordering of
38/// UsingDirectives. It orders them by address of its common ancestor.
39struct UsingDirAncestorCompare {
40
41 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
42 bool operator () (UsingDirectiveDecl *U, const DeclContext *Ctx) const {
43 return U->getCommonAncestor() < Ctx;
44 }
45
46 /// @brief Compares UsingDirectiveDecl common ancestor with DeclContext.
47 bool operator () (const DeclContext *Ctx, UsingDirectiveDecl *U) const {
48 return Ctx < U->getCommonAncestor();
49 }
50
51 /// @brief Compares UsingDirectiveDecl common ancestors.
52 bool operator () (UsingDirectiveDecl *U1, UsingDirectiveDecl *U2) const {
53 return U1->getCommonAncestor() < U2->getCommonAncestor();
54 }
55};
56
57/// AddNamespaceUsingDirectives - Adds all UsingDirectiveDecl's to heap UDirs
58/// (ordered by common ancestors), found in namespace NS,
59/// including all found (recursively) in their nominated namespaces.
60void AddNamespaceUsingDirectives(DeclContext *NS,
61 UsingDirectivesTy &UDirs,
62 NamespaceSet &Visited) {
63 DeclContext::udir_iterator I, End;
64
65 for (llvm::tie(I, End) = NS->getUsingDirectives(); I !=End; ++I) {
66 UDirs.push_back(*I);
67 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
68 NamespaceDecl *Nominated = (*I)->getNominatedNamespace();
69 if (Visited.insert(Nominated).second)
70 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ Visited);
71 }
72}
73
74/// AddScopeUsingDirectives - Adds all UsingDirectiveDecl's found in Scope S,
75/// including all found in the namespaces they nominate.
76static void AddScopeUsingDirectives(Scope *S, UsingDirectivesTy &UDirs) {
77 NamespaceSet VisitedNS;
78
79 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
80
81 if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(Ctx))
82 VisitedNS.insert(NS);
83
84 AddNamespaceUsingDirectives(Ctx, UDirs, /*ref*/ VisitedNS);
85
86 } else {
Chris Lattnerb28317a2009-03-28 19:18:32 +000087 Scope::udir_iterator I = S->using_directives_begin(),
88 End = S->using_directives_end();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000089
90 for (; I != End; ++I) {
Chris Lattnerb28317a2009-03-28 19:18:32 +000091 UsingDirectiveDecl *UD = I->getAs<UsingDirectiveDecl>();
Douglas Gregor2a3009a2009-02-03 19:21:40 +000092 UDirs.push_back(UD);
93 std::push_heap(UDirs.begin(), UDirs.end(), UsingDirAncestorCompare());
94
95 NamespaceDecl *Nominated = UD->getNominatedNamespace();
96 if (!VisitedNS.count(Nominated)) {
97 VisitedNS.insert(Nominated);
98 AddNamespaceUsingDirectives(Nominated, UDirs, /*ref*/ VisitedNS);
99 }
100 }
101 }
102}
103
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000104/// MaybeConstructOverloadSet - Name lookup has determined that the
105/// elements in [I, IEnd) have the name that we are looking for, and
106/// *I is a match for the namespace. This routine returns an
107/// appropriate Decl for name lookup, which may either be *I or an
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000108/// OverloadedFunctionDecl that represents the overloaded functions in
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000109/// [I, IEnd).
110///
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000111/// The existance of this routine is temporary; users of LookupResult
112/// should be able to handle multiple results, to deal with cases of
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000113/// ambiguity and overloaded functions without needing to create a
114/// Decl node.
115template<typename DeclIterator>
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000116static NamedDecl *
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000117MaybeConstructOverloadSet(ASTContext &Context,
118 DeclIterator I, DeclIterator IEnd) {
119 assert(I != IEnd && "Iterator range cannot be empty");
120 assert(!isa<OverloadedFunctionDecl>(*I) &&
121 "Cannot have an overloaded function");
122
123 if (isa<FunctionDecl>(*I)) {
124 // If we found a function, there might be more functions. If
125 // so, collect them into an overload set.
126 DeclIterator Last = I;
127 OverloadedFunctionDecl *Ovl = 0;
128 for (++Last; Last != IEnd && isa<FunctionDecl>(*Last); ++Last) {
129 if (!Ovl) {
130 // FIXME: We leak this overload set. Eventually, we want to
131 // stop building the declarations for these overload sets, so
132 // there will be nothing to leak.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000133 Ovl = OverloadedFunctionDecl::Create(Context, (*I)->getDeclContext(),
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000134 (*I)->getDeclName());
135 Ovl->addOverload(cast<FunctionDecl>(*I));
136 }
137 Ovl->addOverload(cast<FunctionDecl>(*Last));
138 }
139
140 // If we had more than one function, we built an overload
141 // set. Return it.
142 if (Ovl)
143 return Ovl;
144 }
145
146 return *I;
147}
148
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000149/// Merges together multiple LookupResults dealing with duplicated Decl's.
150static Sema::LookupResult
151MergeLookupResults(ASTContext &Context, LookupResultsTy &Results) {
152 typedef Sema::LookupResult LResult;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000153 typedef llvm::SmallPtrSet<NamedDecl*, 4> DeclsSetTy;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000154
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000155 // Remove duplicated Decl pointing at same Decl, by storing them in
156 // associative collection. This might be case for code like:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000157 //
158 // namespace A { int i; }
159 // namespace B { using namespace A; }
160 // namespace C { using namespace A; }
161 //
162 // void foo() {
163 // using namespace B;
164 // using namespace C;
165 // ++i; // finds A::i, from both namespace B and C at global scope
166 // }
167 //
168 // C++ [namespace.qual].p3:
169 // The same declaration found more than once is not an ambiguity
170 // (because it is still a unique declaration).
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000171 DeclsSetTy FoundDecls;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000172
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000173 // Counter of tag names, and functions for resolving ambiguity
174 // and name hiding.
175 std::size_t TagNames = 0, Functions = 0, OrdinaryNonFunc = 0;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000176
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000177 LookupResultsTy::iterator I = Results.begin(), End = Results.end();
178
179 // No name lookup results, return early.
180 if (I == End) return LResult::CreateLookupResult(Context, 0);
181
182 // Keep track of the tag declaration we found. We only use this if
183 // we find a single tag declaration.
184 TagDecl *TagFound = 0;
185
186 for (; I != End; ++I) {
187 switch (I->getKind()) {
188 case LResult::NotFound:
189 assert(false &&
190 "Should be always successful name lookup result here.");
191 break;
192
193 case LResult::AmbiguousReference:
194 case LResult::AmbiguousBaseSubobjectTypes:
195 case LResult::AmbiguousBaseSubobjects:
196 assert(false && "Shouldn't get ambiguous lookup here.");
197 break;
198
199 case LResult::Found: {
200 NamedDecl *ND = I->getAsDecl();
201 if (TagDecl *TD = dyn_cast<TagDecl>(ND)) {
202 TagFound = Context.getCanonicalDecl(TD);
203 TagNames += FoundDecls.insert(TagFound)? 1 : 0;
204 } else if (isa<FunctionDecl>(ND))
205 Functions += FoundDecls.insert(ND)? 1 : 0;
206 else
207 FoundDecls.insert(ND);
208 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000209 }
210
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000211 case LResult::FoundOverloaded:
212 for (LResult::iterator FI = I->begin(), FEnd = I->end(); FI != FEnd; ++FI)
213 Functions += FoundDecls.insert(*FI)? 1 : 0;
214 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000215 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000216 }
217 OrdinaryNonFunc = FoundDecls.size() - TagNames - Functions;
218 bool Ambiguous = false, NameHidesTags = false;
219
220 if (FoundDecls.size() == 1) {
221 // 1) Exactly one result.
222 } else if (TagNames > 1) {
223 // 2) Multiple tag names (even though they may be hidden by an
224 // object name).
225 Ambiguous = true;
226 } else if (FoundDecls.size() - TagNames == 1) {
227 // 3) Ordinary name hides (optional) tag.
228 NameHidesTags = TagFound;
229 } else if (Functions) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000230 // C++ [basic.lookup].p1:
231 // ... Name lookup may associate more than one declaration with
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000232 // a name if it finds the name to be a function name; the declarations
233 // are said to form a set of overloaded functions (13.1).
234 // Overload resolution (13.3) takes place after name lookup has succeeded.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000235 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000236 if (!OrdinaryNonFunc) {
237 // 4) Functions hide tag names.
238 NameHidesTags = TagFound;
239 } else {
240 // 5) Functions + ordinary names.
241 Ambiguous = true;
242 }
243 } else {
244 // 6) Multiple non-tag names
245 Ambiguous = true;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000246 }
247
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000248 if (Ambiguous)
249 return LResult::CreateLookupResult(Context,
250 FoundDecls.begin(), FoundDecls.size());
251 if (NameHidesTags) {
252 // There's only one tag, TagFound. Remove it.
253 assert(TagFound && FoundDecls.count(TagFound) && "No tag name found?");
254 FoundDecls.erase(TagFound);
255 }
256
257 // Return successful name lookup result.
258 return LResult::CreateLookupResult(Context,
259 MaybeConstructOverloadSet(Context,
260 FoundDecls.begin(),
261 FoundDecls.end()));
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000262}
263
264// Retrieve the set of identifier namespaces that correspond to a
265// specific kind of name lookup.
266inline unsigned
267getIdentifierNamespacesFromLookupNameKind(Sema::LookupNameKind NameKind,
268 bool CPlusPlus) {
269 unsigned IDNS = 0;
270 switch (NameKind) {
271 case Sema::LookupOrdinaryName:
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000272 case Sema::LookupOperatorName:
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000273 case Sema::LookupRedeclarationWithLinkage:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000274 IDNS = Decl::IDNS_Ordinary;
275 if (CPlusPlus)
276 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member;
277 break;
278
279 case Sema::LookupTagName:
280 IDNS = Decl::IDNS_Tag;
281 break;
282
283 case Sema::LookupMemberName:
284 IDNS = Decl::IDNS_Member;
285 if (CPlusPlus)
286 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
287 break;
288
289 case Sema::LookupNestedNameSpecifierName:
290 case Sema::LookupNamespaceName:
291 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member;
292 break;
293 }
294 return IDNS;
295}
296
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000297Sema::LookupResult
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000298Sema::LookupResult::CreateLookupResult(ASTContext &Context, NamedDecl *D) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000299 LookupResult Result;
300 Result.StoredKind = (D && isa<OverloadedFunctionDecl>(D))?
301 OverloadedDeclSingleDecl : SingleDecl;
302 Result.First = reinterpret_cast<uintptr_t>(D);
303 Result.Last = 0;
304 Result.Context = &Context;
305 return Result;
306}
307
Douglas Gregor4bb64e72009-01-15 02:19:31 +0000308/// @brief Moves the name-lookup results from Other to this LookupResult.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000309Sema::LookupResult
310Sema::LookupResult::CreateLookupResult(ASTContext &Context,
311 IdentifierResolver::iterator F,
312 IdentifierResolver::iterator L) {
313 LookupResult Result;
314 Result.Context = &Context;
315
Douglas Gregor7176fff2009-01-15 00:26:24 +0000316 if (F != L && isa<FunctionDecl>(*F)) {
317 IdentifierResolver::iterator Next = F;
318 ++Next;
319 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000320 Result.StoredKind = OverloadedDeclFromIdResolver;
321 Result.First = F.getAsOpaqueValue();
322 Result.Last = L.getAsOpaqueValue();
323 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000324 }
325 }
326
Douglas Gregor69d993a2009-01-17 01:13:24 +0000327 Result.StoredKind = SingleDecl;
328 Result.First = reinterpret_cast<uintptr_t>(*F);
329 Result.Last = 0;
330 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000331}
332
Douglas Gregor69d993a2009-01-17 01:13:24 +0000333Sema::LookupResult
334Sema::LookupResult::CreateLookupResult(ASTContext &Context,
335 DeclContext::lookup_iterator F,
336 DeclContext::lookup_iterator L) {
337 LookupResult Result;
338 Result.Context = &Context;
339
Douglas Gregor7176fff2009-01-15 00:26:24 +0000340 if (F != L && isa<FunctionDecl>(*F)) {
341 DeclContext::lookup_iterator Next = F;
342 ++Next;
343 if (Next != L && isa<FunctionDecl>(*Next)) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000344 Result.StoredKind = OverloadedDeclFromDeclContext;
345 Result.First = reinterpret_cast<uintptr_t>(F);
346 Result.Last = reinterpret_cast<uintptr_t>(L);
347 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000348 }
349 }
350
Douglas Gregor69d993a2009-01-17 01:13:24 +0000351 Result.StoredKind = SingleDecl;
352 Result.First = reinterpret_cast<uintptr_t>(*F);
353 Result.Last = 0;
354 return Result;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000355}
356
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000357/// @brief Determine the result of name lookup.
358Sema::LookupResult::LookupKind Sema::LookupResult::getKind() const {
359 switch (StoredKind) {
360 case SingleDecl:
361 return (reinterpret_cast<Decl *>(First) != 0)? Found : NotFound;
362
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000363 case OverloadedDeclSingleDecl:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000364 case OverloadedDeclFromIdResolver:
365 case OverloadedDeclFromDeclContext:
366 return FoundOverloaded;
367
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000368 case AmbiguousLookupStoresBasePaths:
Douglas Gregor7176fff2009-01-15 00:26:24 +0000369 return Last? AmbiguousBaseSubobjectTypes : AmbiguousBaseSubobjects;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000370
371 case AmbiguousLookupStoresDecls:
372 return AmbiguousReference;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000373 }
374
Douglas Gregor7176fff2009-01-15 00:26:24 +0000375 // We can't ever get here.
376 return NotFound;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000377}
378
379/// @brief Converts the result of name lookup into a single (possible
380/// NULL) pointer to a declaration.
381///
382/// The resulting declaration will either be the declaration we found
383/// (if only a single declaration was found), an
384/// OverloadedFunctionDecl (if an overloaded function was found), or
385/// NULL (if no declaration was found). This conversion must not be
386/// used anywhere where name lookup could result in an ambiguity.
387///
388/// The OverloadedFunctionDecl conversion is meant as a stop-gap
389/// solution, since it causes the OverloadedFunctionDecl to be
390/// leaked. FIXME: Eventually, there will be a better way to iterate
391/// over the set of overloaded functions returned by name lookup.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000392NamedDecl *Sema::LookupResult::getAsDecl() const {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000393 switch (StoredKind) {
394 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000395 return reinterpret_cast<NamedDecl *>(First);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000396
397 case OverloadedDeclFromIdResolver:
398 return MaybeConstructOverloadSet(*Context,
399 IdentifierResolver::iterator::getFromOpaqueValue(First),
400 IdentifierResolver::iterator::getFromOpaqueValue(Last));
401
402 case OverloadedDeclFromDeclContext:
403 return MaybeConstructOverloadSet(*Context,
404 reinterpret_cast<DeclContext::lookup_iterator>(First),
405 reinterpret_cast<DeclContext::lookup_iterator>(Last));
406
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000407 case OverloadedDeclSingleDecl:
408 return reinterpret_cast<OverloadedFunctionDecl*>(First);
409
410 case AmbiguousLookupStoresDecls:
411 case AmbiguousLookupStoresBasePaths:
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000412 assert(false &&
413 "Name lookup returned an ambiguity that could not be handled");
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregor7176fff2009-01-15 00:26:24 +0000420/// @brief Retrieves the BasePaths structure describing an ambiguous
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000421/// name lookup, or null.
Douglas Gregor7176fff2009-01-15 00:26:24 +0000422BasePaths *Sema::LookupResult::getBasePaths() const {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000423 if (StoredKind == AmbiguousLookupStoresBasePaths)
424 return reinterpret_cast<BasePaths *>(First);
425 return 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000426}
427
Douglas Gregord8635172009-02-02 21:35:47 +0000428Sema::LookupResult::iterator::reference
429Sema::LookupResult::iterator::operator*() const {
430 switch (Result->StoredKind) {
431 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000432 return reinterpret_cast<NamedDecl*>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000433
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000434 case OverloadedDeclSingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000435 return *reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000436
Douglas Gregord8635172009-02-02 21:35:47 +0000437 case OverloadedDeclFromIdResolver:
438 return *IdentifierResolver::iterator::getFromOpaqueValue(Current);
439
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000440 case AmbiguousLookupStoresBasePaths:
Douglas Gregor31a19b62009-04-01 21:51:26 +0000441 if (Result->Last)
442 return *reinterpret_cast<NamedDecl**>(Current);
443
444 // Fall through to handle the DeclContext::lookup_iterator we're
445 // storing.
446
447 case OverloadedDeclFromDeclContext:
448 case AmbiguousLookupStoresDecls:
449 return *reinterpret_cast<DeclContext::lookup_iterator>(Current);
Douglas Gregord8635172009-02-02 21:35:47 +0000450 }
451
452 return 0;
453}
454
455Sema::LookupResult::iterator& Sema::LookupResult::iterator::operator++() {
456 switch (Result->StoredKind) {
457 case SingleDecl:
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000458 Current = reinterpret_cast<uintptr_t>((NamedDecl*)0);
Douglas Gregord8635172009-02-02 21:35:47 +0000459 break;
460
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000461 case OverloadedDeclSingleDecl: {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000462 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000463 ++I;
464 Current = reinterpret_cast<uintptr_t>(I);
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000465 break;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000466 }
467
Douglas Gregord8635172009-02-02 21:35:47 +0000468 case OverloadedDeclFromIdResolver: {
469 IdentifierResolver::iterator I
470 = IdentifierResolver::iterator::getFromOpaqueValue(Current);
471 ++I;
472 Current = I.getAsOpaqueValue();
473 break;
474 }
475
Douglas Gregor31a19b62009-04-01 21:51:26 +0000476 case AmbiguousLookupStoresBasePaths:
477 if (Result->Last) {
478 NamedDecl ** I = reinterpret_cast<NamedDecl**>(Current);
479 ++I;
480 Current = reinterpret_cast<uintptr_t>(I);
481 break;
482 }
483 // Fall through to handle the DeclContext::lookup_iterator we're
484 // storing.
485
486 case OverloadedDeclFromDeclContext:
487 case AmbiguousLookupStoresDecls: {
Douglas Gregord8635172009-02-02 21:35:47 +0000488 DeclContext::lookup_iterator I
489 = reinterpret_cast<DeclContext::lookup_iterator>(Current);
490 ++I;
491 Current = reinterpret_cast<uintptr_t>(I);
492 break;
493 }
Douglas Gregord8635172009-02-02 21:35:47 +0000494 }
495
496 return *this;
497}
498
499Sema::LookupResult::iterator Sema::LookupResult::begin() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000500 switch (StoredKind) {
501 case SingleDecl:
502 case OverloadedDeclFromIdResolver:
503 case OverloadedDeclFromDeclContext:
504 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000505 return iterator(this, First);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000506
507 case OverloadedDeclSingleDecl: {
508 OverloadedFunctionDecl * Ovl =
509 reinterpret_cast<OverloadedFunctionDecl*>(First);
510 return iterator(this,
511 reinterpret_cast<uintptr_t>(&(*Ovl->function_begin())));
512 }
513
514 case AmbiguousLookupStoresBasePaths:
515 if (Last)
516 return iterator(this,
517 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_begin()));
518 else
519 return iterator(this,
520 reinterpret_cast<uintptr_t>(getBasePaths()->front().Decls.first));
521 }
522
523 // Required to suppress GCC warning.
524 return iterator();
Douglas Gregord8635172009-02-02 21:35:47 +0000525}
526
527Sema::LookupResult::iterator Sema::LookupResult::end() {
Douglas Gregor31a19b62009-04-01 21:51:26 +0000528 switch (StoredKind) {
529 case SingleDecl:
530 case OverloadedDeclFromIdResolver:
531 case OverloadedDeclFromDeclContext:
532 case AmbiguousLookupStoresDecls:
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000533 return iterator(this, Last);
Douglas Gregor31a19b62009-04-01 21:51:26 +0000534
535 case OverloadedDeclSingleDecl: {
536 OverloadedFunctionDecl * Ovl =
537 reinterpret_cast<OverloadedFunctionDecl*>(First);
538 return iterator(this,
539 reinterpret_cast<uintptr_t>(&(*Ovl->function_end())));
540 }
541
542 case AmbiguousLookupStoresBasePaths:
543 if (Last)
544 return iterator(this,
545 reinterpret_cast<uintptr_t>(getBasePaths()->found_decls_end()));
546 else
547 return iterator(this, reinterpret_cast<uintptr_t>(
548 getBasePaths()->front().Decls.second));
549 }
550
551 // Required to suppress GCC warning.
552 return iterator();
553}
554
555void Sema::LookupResult::Destroy() {
556 if (BasePaths *Paths = getBasePaths())
557 delete Paths;
558 else if (getKind() == AmbiguousReference)
559 delete[] reinterpret_cast<NamedDecl **>(First);
Douglas Gregord8635172009-02-02 21:35:47 +0000560}
561
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000562static void
563CppNamespaceLookup(ASTContext &Context, DeclContext *NS,
564 DeclarationName Name, Sema::LookupNameKind NameKind,
565 unsigned IDNS, LookupResultsTy &Results,
566 UsingDirectivesTy *UDirs = 0) {
567
568 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!");
569
570 // Perform qualified name lookup into the LookupCtx.
571 DeclContext::lookup_iterator I, E;
572 for (llvm::tie(I, E) = NS->lookup(Name); I != E; ++I)
573 if (Sema::isAcceptableLookupResult(*I, NameKind, IDNS)) {
574 Results.push_back(Sema::LookupResult::CreateLookupResult(Context, I, E));
575 break;
576 }
577
578 if (UDirs) {
579 // For each UsingDirectiveDecl, which common ancestor is equal
580 // to NS, we preform qualified name lookup into namespace nominated by it.
581 UsingDirectivesTy::const_iterator UI, UEnd;
582 llvm::tie(UI, UEnd) =
583 std::equal_range(UDirs->begin(), UDirs->end(), NS,
584 UsingDirAncestorCompare());
585
586 for (; UI != UEnd; ++UI)
587 CppNamespaceLookup(Context, (*UI)->getNominatedNamespace(),
588 Name, NameKind, IDNS, Results);
589 }
590}
591
592static bool isNamespaceOrTranslationUnitScope(Scope *S) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000593 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity()))
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000594 return Ctx->isFileContext();
595 return false;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000596}
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000597
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000598std::pair<bool, Sema::LookupResult>
599Sema::CppLookupName(Scope *S, DeclarationName Name,
600 LookupNameKind NameKind, bool RedeclarationOnly) {
601 assert(getLangOptions().CPlusPlus &&
602 "Can perform only C++ lookup");
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000603 unsigned IDNS
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000604 = getIdentifierNamespacesFromLookupNameKind(NameKind, /*CPlusPlus*/ true);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000605 Scope *Initial = S;
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000606 DeclContext *OutOfLineCtx = 0;
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000607 IdentifierResolver::iterator
608 I = IdResolver.begin(Name),
609 IEnd = IdResolver.end();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000610
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000611 // First we lookup local scope.
Douglas Gregoraaba5e32009-02-04 19:02:06 +0000612 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000613 // ...During unqualified name lookup (3.4.1), the names appear as if
614 // they were declared in the nearest enclosing namespace which contains
615 // both the using-directive and the nominated namespace.
616 // [Note: in this context, “contains” means “contains directly or
617 // indirectly”.
618 //
619 // For example:
620 // namespace A { int i; }
621 // void foo() {
622 // int i;
623 // {
624 // using namespace A;
625 // ++i; // finds local 'i', A::i appears at global scope
626 // }
627 // }
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000628 //
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000629 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000630 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000631 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000632 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
633 // We found something. Look for anything else in our scope
634 // with this same name and in an acceptable identifier
635 // namespace, so that we can construct an overload set if we
636 // need to.
637 IdentifierResolver::iterator LastI = I;
638 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000639 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000640 break;
641 }
642 LookupResult Result =
643 LookupResult::CreateLookupResult(Context, I, LastI);
644 return std::make_pair(true, Result);
645 }
646 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000647 if (DeclContext *Ctx = static_cast<DeclContext*>(S->getEntity())) {
648 LookupResult R;
649 // Perform member lookup into struct.
650 // FIXME: In some cases, we know that every name that could be
651 // found by this qualified name lookup will also be on the
652 // identifier chain. For example, inside a class without any
653 // base classes, we never need to perform qualified lookup
654 // because all of the members are on top of the identifier
655 // chain.
Douglas Gregor551f48c2009-03-27 04:21:56 +0000656 if (isa<RecordDecl>(Ctx)) {
657 R = LookupQualifiedName(Ctx, Name, NameKind, RedeclarationOnly);
658 if (R || RedeclarationOnly)
659 return std::make_pair(true, R);
660 }
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000661 if (Ctx->getParent() != Ctx->getLexicalParent()) {
662 // It is out of line defined C++ method or struct, we continue
663 // doing name lookup in parent context. Once we will find namespace
664 // or translation-unit we save it for possible checking
665 // using-directives later.
666 for (OutOfLineCtx = Ctx; OutOfLineCtx && !OutOfLineCtx->isFileContext();
667 OutOfLineCtx = OutOfLineCtx->getParent()) {
Douglas Gregor551f48c2009-03-27 04:21:56 +0000668 R = LookupQualifiedName(OutOfLineCtx, Name, NameKind, RedeclarationOnly);
669 if (R || RedeclarationOnly)
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000670 return std::make_pair(true, R);
671 }
672 }
673 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000674 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000675
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000676 // Collect UsingDirectiveDecls in all scopes, and recursively all
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000677 // nominated namespaces by those using-directives.
678 // UsingDirectives are pushed to heap, in common ancestor pointer
679 // value order.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000680 // FIXME: Cache this sorted list in Scope structure, and DeclContext,
681 // so we don't build it for each lookup!
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000682 UsingDirectivesTy UDirs;
683 for (Scope *SC = Initial; SC; SC = SC->getParent())
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000684 if (SC->getFlags() & Scope::DeclScope)
685 AddScopeUsingDirectives(SC, UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000686
687 // Sort heapified UsingDirectiveDecls.
688 std::sort_heap(UDirs.begin(), UDirs.end());
689
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000690 // Lookup namespace scope, and global scope.
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000691 // Unqualified name lookup in C++ requires looking into scopes
692 // that aren't strictly lexical, and therefore we walk through the
693 // context as well as walking through the scopes.
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000694
695 LookupResultsTy LookupResults;
Sebastian Redl22460502009-02-07 00:15:38 +0000696 assert((!OutOfLineCtx || OutOfLineCtx->isFileContext()) &&
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000697 "We should have been looking only at file context here already.");
698 bool LookedInCtx = false;
699 LookupResult Result;
700 while (OutOfLineCtx &&
701 OutOfLineCtx != S->getEntity() &&
702 OutOfLineCtx->isNamespace()) {
703 LookedInCtx = true;
704
705 // Look into context considering using-directives.
706 CppNamespaceLookup(Context, OutOfLineCtx, Name, NameKind, IDNS,
707 LookupResults, &UDirs);
708
709 if ((Result = MergeLookupResults(Context, LookupResults)) ||
710 (RedeclarationOnly && !OutOfLineCtx->isTransparentContext()))
711 return std::make_pair(true, Result);
712
713 OutOfLineCtx = OutOfLineCtx->getParent();
714 }
715
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000716 for (; S; S = S->getParent()) {
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000717 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
718 assert(Ctx && Ctx->isFileContext() &&
719 "We should have been looking only at file context here already.");
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000720
721 // Check whether the IdResolver has anything in this scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000722 for (; I != IEnd && S->isDeclScope(DeclPtrTy::make(*I)); ++I) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000723 if (isAcceptableLookupResult(*I, NameKind, IDNS)) {
724 // We found something. Look for anything else in our scope
725 // with this same name and in an acceptable identifier
726 // namespace, so that we can construct an overload set if we
727 // need to.
728 IdentifierResolver::iterator LastI = I;
729 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000730 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000731 break;
732 }
733
734 // We store name lookup result, and continue trying to look into
735 // associated context, and maybe namespaces nominated by
736 // using-directives.
737 LookupResults.push_back(
738 LookupResult::CreateLookupResult(Context, I, LastI));
739 break;
740 }
741 }
742
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000743 LookedInCtx = true;
744 // Look into context considering using-directives.
745 CppNamespaceLookup(Context, Ctx, Name, NameKind, IDNS,
746 LookupResults, &UDirs);
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000747
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000748 if ((Result = MergeLookupResults(Context, LookupResults)) ||
749 (RedeclarationOnly && !Ctx->isTransparentContext()))
750 return std::make_pair(true, Result);
751 }
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000752
Douglas Gregor7dda67d2009-02-05 19:25:20 +0000753 if (!(LookedInCtx || LookupResults.empty())) {
754 // We didn't Performed lookup in Scope entity, so we return
755 // result form IdentifierResolver.
756 assert((LookupResults.size() == 1) && "Wrong size!");
757 return std::make_pair(true, LookupResults.front());
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000758 }
759 return std::make_pair(false, LookupResult());
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000760}
761
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000762/// @brief Perform unqualified name lookup starting from a given
763/// scope.
764///
765/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
766/// used to find names within the current scope. For example, 'x' in
767/// @code
768/// int x;
769/// int f() {
770/// return x; // unqualified name look finds 'x' in the global scope
771/// }
772/// @endcode
773///
774/// Different lookup criteria can find different names. For example, a
775/// particular scope can have both a struct and a function of the same
776/// name, and each can be found by certain lookup criteria. For more
777/// information about lookup criteria, see the documentation for the
778/// class LookupCriteria.
779///
780/// @param S The scope from which unqualified name lookup will
781/// begin. If the lookup criteria permits, name lookup may also search
782/// in the parent scopes.
783///
784/// @param Name The name of the entity that we are searching for.
785///
Douglas Gregor3e41d602009-02-13 23:20:09 +0000786/// @param Loc If provided, the source location where we're performing
787/// name lookup. At present, this is only used to produce diagnostics when
788/// C library functions (like "malloc") are implicitly declared.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000789///
790/// @returns The result of name lookup, which includes zero or more
791/// declarations and possibly additional information used to diagnose
792/// ambiguities.
793Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000794Sema::LookupName(Scope *S, DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000795 bool RedeclarationOnly, bool AllowBuiltinCreation,
796 SourceLocation Loc) {
Douglas Gregor69d993a2009-01-17 01:13:24 +0000797 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000798
799 if (!getLangOptions().CPlusPlus) {
800 // Unqualified name lookup in C/Objective-C is purely lexical, so
801 // search in the declarations attached to the name.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000802 unsigned IDNS = 0;
803 switch (NameKind) {
804 case Sema::LookupOrdinaryName:
805 IDNS = Decl::IDNS_Ordinary;
806 break;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000807
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000808 case Sema::LookupTagName:
809 IDNS = Decl::IDNS_Tag;
810 break;
811
812 case Sema::LookupMemberName:
813 IDNS = Decl::IDNS_Member;
814 break;
815
Douglas Gregorf680a0f2009-02-04 16:44:47 +0000816 case Sema::LookupOperatorName:
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000817 case Sema::LookupNestedNameSpecifierName:
818 case Sema::LookupNamespaceName:
819 assert(false && "C does not perform these kinds of name lookup");
820 break;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000821
822 case Sema::LookupRedeclarationWithLinkage:
823 // Find the nearest non-transparent declaration scope.
824 while (!(S->getFlags() & Scope::DeclScope) ||
825 (S->getEntity() &&
826 static_cast<DeclContext *>(S->getEntity())
827 ->isTransparentContext()))
828 S = S->getParent();
829 IDNS = Decl::IDNS_Ordinary;
830 break;
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000831 }
832
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000833 // Scan up the scope chain looking for a decl that matches this
834 // identifier that is in the appropriate namespace. This search
835 // should not take long, as shadowing of names is uncommon, and
836 // deep shadowing is extremely uncommon.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000837 bool LeftStartingScope = false;
838
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000839 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
840 IEnd = IdResolver.end();
841 I != IEnd; ++I)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000842 if ((*I)->isInIdentifierNamespace(IDNS)) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000843 if (NameKind == LookupRedeclarationWithLinkage) {
844 // Determine whether this (or a previous) declaration is
845 // out-of-scope.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000846 if (!LeftStartingScope && !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000847 LeftStartingScope = true;
848
849 // If we found something outside of our starting scope that
850 // does not have linkage, skip it.
851 if (LeftStartingScope && !((*I)->hasLinkage()))
852 continue;
853 }
854
Douglas Gregorf9201e02009-02-11 23:02:49 +0000855 if ((*I)->getAttr<OverloadableAttr>()) {
856 // If this declaration has the "overloadable" attribute, we
857 // might have a set of overloaded functions.
858
859 // Figure out what scope the identifier is in.
Chris Lattnerb28317a2009-03-28 19:18:32 +0000860 while (!(S->getFlags() & Scope::DeclScope) ||
861 !S->isDeclScope(DeclPtrTy::make(*I)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000862 S = S->getParent();
863
864 // Find the last declaration in this scope (with the same
865 // name, naturally).
866 IdentifierResolver::iterator LastI = I;
867 for (++LastI; LastI != IEnd; ++LastI) {
Chris Lattnerb28317a2009-03-28 19:18:32 +0000868 if (!S->isDeclScope(DeclPtrTy::make(*LastI)))
Douglas Gregorf9201e02009-02-11 23:02:49 +0000869 break;
870 }
871
872 return LookupResult::CreateLookupResult(Context, I, LastI);
873 }
874
875 // We have a single lookup result.
Douglas Gregor69d993a2009-01-17 01:13:24 +0000876 return LookupResult::CreateLookupResult(Context, *I);
Douglas Gregorf9201e02009-02-11 23:02:49 +0000877 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000878 } else {
Douglas Gregor2a3009a2009-02-03 19:21:40 +0000879 // Perform C++ unqualified name lookup.
880 std::pair<bool, LookupResult> MaybeResult =
881 CppLookupName(S, Name, NameKind, RedeclarationOnly);
882 if (MaybeResult.first)
883 return MaybeResult.second;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000884 }
885
886 // If we didn't find a use of this identifier, and if the identifier
887 // corresponds to a compiler builtin, create the decl object for the builtin
888 // now, injecting it into translation unit scope, and return it.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +0000889 if (NameKind == LookupOrdinaryName ||
890 NameKind == LookupRedeclarationWithLinkage) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000891 IdentifierInfo *II = Name.getAsIdentifierInfo();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000892 if (II && AllowBuiltinCreation) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000893 // If this is a builtin on this (or all) targets, create the decl.
Douglas Gregor3e41d602009-02-13 23:20:09 +0000894 if (unsigned BuiltinID = II->getBuiltinID()) {
895 // In C++, we don't have any predefined library functions like
896 // 'malloc'. Instead, we'll just error.
897 if (getLangOptions().CPlusPlus &&
898 Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
899 return LookupResult::CreateLookupResult(Context, 0);
900
Douglas Gregor69d993a2009-01-17 01:13:24 +0000901 return LookupResult::CreateLookupResult(Context,
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000902 LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000903 S, RedeclarationOnly, Loc));
904 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000905 }
906 if (getLangOptions().ObjC1 && II) {
907 // @interface and @compatibility_alias introduce typedef-like names.
908 // Unlike typedef's, they can only be introduced at file-scope (and are
909 // therefore not scoped decls). They can, however, be shadowed by
910 // other names in IDNS_Ordinary.
911 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
912 if (IDI != ObjCInterfaceDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000913 return LookupResult::CreateLookupResult(Context, IDI->second);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000914 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
915 if (I != ObjCAliasDecls.end())
Douglas Gregor69d993a2009-01-17 01:13:24 +0000916 return LookupResult::CreateLookupResult(Context,
917 I->second->getClassInterface());
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000918 }
919 }
Douglas Gregor69d993a2009-01-17 01:13:24 +0000920 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000921}
922
923/// @brief Perform qualified name lookup into a given context.
924///
925/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
926/// names when the context of those names is explicit specified, e.g.,
927/// "std::vector" or "x->member".
928///
929/// Different lookup criteria can find different names. For example, a
930/// particular scope can have both a struct and a function of the same
931/// name, and each can be found by certain lookup criteria. For more
932/// information about lookup criteria, see the documentation for the
933/// class LookupCriteria.
934///
935/// @param LookupCtx The context in which qualified name lookup will
936/// search. If the lookup criteria permits, name lookup may also search
937/// in the parent contexts or (for C++ classes) base classes.
938///
939/// @param Name The name of the entity that we are searching for.
940///
941/// @param Criteria The criteria that this routine will use to
942/// determine which names are visible and which names will be
943/// found. Note that name lookup will find a name that is visible by
944/// the given criteria, but the entity itself may not be semantically
945/// correct or even the kind of entity expected based on the
946/// lookup. For example, searching for a nested-name-specifier name
947/// might result in an EnumDecl, which is visible but is not permitted
948/// as a nested-name-specifier in C++03.
949///
950/// @returns The result of name lookup, which includes zero or more
951/// declarations and possibly additional information used to diagnose
952/// ambiguities.
953Sema::LookupResult
954Sema::LookupQualifiedName(DeclContext *LookupCtx, DeclarationName Name,
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000955 LookupNameKind NameKind, bool RedeclarationOnly) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000956 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
957
Douglas Gregor69d993a2009-01-17 01:13:24 +0000958 if (!Name) return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000959
960 // If we're performing qualified name lookup (e.g., lookup into a
961 // struct), find fields as part of ordinary name lookup.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000962 unsigned IDNS
963 = getIdentifierNamespacesFromLookupNameKind(NameKind,
964 getLangOptions().CPlusPlus);
965 if (NameKind == LookupOrdinaryName)
966 IDNS |= Decl::IDNS_Member;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000967
968 // Perform qualified name lookup into the LookupCtx.
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000969 DeclContext::lookup_iterator I, E;
970 for (llvm::tie(I, E) = LookupCtx->lookup(Name); I != E; ++I)
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000971 if (isAcceptableLookupResult(*I, NameKind, IDNS))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000972 return LookupResult::CreateLookupResult(Context, I, E);
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000973
Douglas Gregor7176fff2009-01-15 00:26:24 +0000974 // If this isn't a C++ class or we aren't allowed to look into base
975 // classes, we're done.
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000976 if (RedeclarationOnly || !isa<CXXRecordDecl>(LookupCtx))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000977 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000978
979 // Perform lookup into our base classes.
980 BasePaths Paths;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +0000981 Paths.setOrigin(Context.getTypeDeclType(cast<RecordDecl>(LookupCtx)));
Douglas Gregor7176fff2009-01-15 00:26:24 +0000982
983 // Look for this member in our base classes
984 if (!LookupInBases(cast<CXXRecordDecl>(LookupCtx),
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000985 MemberLookupCriteria(Name, NameKind, IDNS), Paths))
Douglas Gregor69d993a2009-01-17 01:13:24 +0000986 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregor7176fff2009-01-15 00:26:24 +0000987
988 // C++ [class.member.lookup]p2:
989 // [...] If the resulting set of declarations are not all from
990 // sub-objects of the same type, or the set has a nonstatic member
991 // and includes members from distinct sub-objects, there is an
992 // ambiguity and the program is ill-formed. Otherwise that set is
993 // the result of the lookup.
994 // FIXME: support using declarations!
995 QualType SubobjectType;
Daniel Dunbarf1853192009-01-15 18:32:35 +0000996 int SubobjectNumber = 0;
Douglas Gregor7176fff2009-01-15 00:26:24 +0000997 for (BasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
998 Path != PathEnd; ++Path) {
999 const BasePathElement &PathElement = Path->back();
1000
1001 // Determine whether we're looking at a distinct sub-object or not.
1002 if (SubobjectType.isNull()) {
1003 // This is the first subobject we've looked at. Record it's type.
1004 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
1005 SubobjectNumber = PathElement.SubobjectNumber;
1006 } else if (SubobjectType
1007 != Context.getCanonicalType(PathElement.Base->getType())) {
1008 // We found members of the given name in two subobjects of
1009 // different types. This lookup is ambiguous.
1010 BasePaths *PathsOnHeap = new BasePaths;
1011 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001012 return LookupResult::CreateLookupResult(Context, PathsOnHeap, true);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001013 } else if (SubobjectNumber != PathElement.SubobjectNumber) {
1014 // We have a different subobject of the same type.
1015
1016 // C++ [class.member.lookup]p5:
1017 // A static member, a nested type or an enumerator defined in
1018 // a base class T can unambiguously be found even if an object
1019 // has more than one base class subobject of type T.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001020 Decl *FirstDecl = *Path->Decls.first;
Douglas Gregor7176fff2009-01-15 00:26:24 +00001021 if (isa<VarDecl>(FirstDecl) ||
1022 isa<TypeDecl>(FirstDecl) ||
1023 isa<EnumConstantDecl>(FirstDecl))
1024 continue;
1025
1026 if (isa<CXXMethodDecl>(FirstDecl)) {
1027 // Determine whether all of the methods are static.
1028 bool AllMethodsAreStatic = true;
1029 for (DeclContext::lookup_iterator Func = Path->Decls.first;
1030 Func != Path->Decls.second; ++Func) {
1031 if (!isa<CXXMethodDecl>(*Func)) {
1032 assert(isa<TagDecl>(*Func) && "Non-function must be a tag decl");
1033 break;
1034 }
1035
1036 if (!cast<CXXMethodDecl>(*Func)->isStatic()) {
1037 AllMethodsAreStatic = false;
1038 break;
1039 }
1040 }
1041
1042 if (AllMethodsAreStatic)
1043 continue;
1044 }
1045
1046 // We have found a nonstatic member name in multiple, distinct
1047 // subobjects. Name lookup is ambiguous.
1048 BasePaths *PathsOnHeap = new BasePaths;
1049 PathsOnHeap->swap(Paths);
Douglas Gregor69d993a2009-01-17 01:13:24 +00001050 return LookupResult::CreateLookupResult(Context, PathsOnHeap, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +00001051 }
1052 }
1053
1054 // Lookup in a base class succeeded; return these results.
1055
1056 // If we found a function declaration, return an overload set.
1057 if (isa<FunctionDecl>(*Paths.front().Decls.first))
Douglas Gregor69d993a2009-01-17 01:13:24 +00001058 return LookupResult::CreateLookupResult(Context,
Douglas Gregor7176fff2009-01-15 00:26:24 +00001059 Paths.front().Decls.first, Paths.front().Decls.second);
1060
1061 // We found a non-function declaration; return a single declaration.
Douglas Gregor69d993a2009-01-17 01:13:24 +00001062 return LookupResult::CreateLookupResult(Context, *Paths.front().Decls.first);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001063}
1064
1065/// @brief Performs name lookup for a name that was parsed in the
1066/// source code, and may contain a C++ scope specifier.
1067///
1068/// This routine is a convenience routine meant to be called from
1069/// contexts that receive a name and an optional C++ scope specifier
1070/// (e.g., "N::M::x"). It will then perform either qualified or
1071/// unqualified name lookup (with LookupQualifiedName or LookupName,
1072/// respectively) on the given name and return those results.
1073///
1074/// @param S The scope from which unqualified name lookup will
1075/// begin.
1076///
1077/// @param SS An optional C++ scope-specified, e.g., "::N::M".
1078///
1079/// @param Name The name of the entity that name lookup will
1080/// search for.
1081///
Douglas Gregor3e41d602009-02-13 23:20:09 +00001082/// @param Loc If provided, the source location where we're performing
1083/// name lookup. At present, this is only used to produce diagnostics when
1084/// C library functions (like "malloc") are implicitly declared.
1085///
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001086/// @returns The result of qualified or unqualified name lookup.
1087Sema::LookupResult
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001088Sema::LookupParsedName(Scope *S, const CXXScopeSpec *SS,
1089 DeclarationName Name, LookupNameKind NameKind,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001090 bool RedeclarationOnly, bool AllowBuiltinCreation,
1091 SourceLocation Loc) {
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001092 if (SS) {
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00001093 if (SS->isInvalid() || RequireCompleteDeclContext(*SS))
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001094 return LookupResult::CreateLookupResult(Context, 0);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001095
Douglas Gregore4e5b052009-03-19 00:18:19 +00001096 if (SS->isSet()) {
1097 return LookupQualifiedName(computeDeclContext(*SS),
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001098 Name, NameKind, RedeclarationOnly);
Douglas Gregore4e5b052009-03-19 00:18:19 +00001099 }
Douglas Gregor4c921ae2009-01-30 01:04:22 +00001100 }
1101
Douglas Gregor3e41d602009-02-13 23:20:09 +00001102 return LookupName(S, Name, NameKind, RedeclarationOnly,
1103 AllowBuiltinCreation, Loc);
Douglas Gregoreb11cd02009-01-14 22:20:51 +00001104}
1105
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001106
Douglas Gregor7176fff2009-01-15 00:26:24 +00001107/// @brief Produce a diagnostic describing the ambiguity that resulted
1108/// from name lookup.
1109///
1110/// @param Result The ambiguous name lookup result.
1111///
1112/// @param Name The name of the entity that name lookup was
1113/// searching for.
1114///
1115/// @param NameLoc The location of the name within the source code.
1116///
1117/// @param LookupRange A source range that provides more
1118/// source-location information concerning the lookup itself. For
1119/// example, this range might highlight a nested-name-specifier that
1120/// precedes the name.
1121///
1122/// @returns true
1123bool Sema::DiagnoseAmbiguousLookup(LookupResult &Result, DeclarationName Name,
1124 SourceLocation NameLoc,
1125 SourceRange LookupRange) {
1126 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
1127
Douglas Gregor31a19b62009-04-01 21:51:26 +00001128 if (BasePaths *Paths = Result.getBasePaths()) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001129 if (Result.getKind() == LookupResult::AmbiguousBaseSubobjects) {
1130 QualType SubobjectType = Paths->front().back().Base->getType();
1131 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
1132 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
1133 << LookupRange;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001134
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001135 DeclContext::lookup_iterator Found = Paths->front().Decls.first;
Douglas Gregor31a19b62009-04-01 21:51:26 +00001136 while (isa<CXXMethodDecl>(*Found) &&
1137 cast<CXXMethodDecl>(*Found)->isStatic())
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001138 ++Found;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001139
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001140 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
1141
Douglas Gregor31a19b62009-04-01 21:51:26 +00001142 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001143 return true;
1144 }
1145
1146 assert(Result.getKind() == LookupResult::AmbiguousBaseSubobjectTypes &&
1147 "Unhandled form of name lookup ambiguity");
1148
1149 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
1150 << Name << LookupRange;
1151
1152 std::set<Decl *> DeclsPrinted;
1153 for (BasePaths::paths_iterator Path = Paths->begin(), PathEnd = Paths->end();
1154 Path != PathEnd; ++Path) {
1155 Decl *D = *Path->Decls.first;
1156 if (DeclsPrinted.insert(D).second)
1157 Diag(D->getLocation(), diag::note_ambiguous_member_found);
1158 }
1159
Douglas Gregor31a19b62009-04-01 21:51:26 +00001160 Result.Destroy();
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001161 return true;
1162 } else if (Result.getKind() == LookupResult::AmbiguousReference) {
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001163 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
1164
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001165 NamedDecl **DI = reinterpret_cast<NamedDecl **>(Result.First),
Douglas Gregor31a19b62009-04-01 21:51:26 +00001166 **DEnd = reinterpret_cast<NamedDecl **>(Result.Last);
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001167
Chris Lattner48458d22009-02-03 21:29:32 +00001168 for (; DI != DEnd; ++DI)
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001169 Diag((*DI)->getLocation(), diag::note_ambiguous_candidate) << *DI;
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001170
Douglas Gregor31a19b62009-04-01 21:51:26 +00001171 Result.Destroy();
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001172 return true;
Douglas Gregor4dc6b1c2009-01-16 00:38:09 +00001173 }
1174
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001175 assert(false && "Unhandled form of name lookup ambiguity");
Douglas Gregor69d993a2009-01-17 01:13:24 +00001176
Douglas Gregor2a3009a2009-02-03 19:21:40 +00001177 // We can't reach here.
Douglas Gregor7176fff2009-01-15 00:26:24 +00001178 return true;
1179}
Douglas Gregorfa047642009-02-04 00:32:51 +00001180
1181// \brief Add the associated classes and namespaces for
1182// argument-dependent lookup with an argument of class type
1183// (C++ [basic.lookup.koenig]p2).
1184static void
1185addAssociatedClassesAndNamespaces(CXXRecordDecl *Class,
1186 ASTContext &Context,
1187 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1188 Sema::AssociatedClassSet &AssociatedClasses) {
1189 // C++ [basic.lookup.koenig]p2:
1190 // [...]
1191 // -- If T is a class type (including unions), its associated
1192 // classes are: the class itself; the class of which it is a
1193 // member, if any; and its direct and indirect base
1194 // classes. Its associated namespaces are the namespaces in
1195 // which its associated classes are defined.
1196
1197 // Add the class of which it is a member, if any.
1198 DeclContext *Ctx = Class->getDeclContext();
1199 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1200 AssociatedClasses.insert(EnclosingClass);
1201
1202 // Add the associated namespace for this class.
1203 while (Ctx->isRecord())
1204 Ctx = Ctx->getParent();
1205 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1206 AssociatedNamespaces.insert(EnclosingNamespace);
1207
1208 // Add the class itself. If we've already seen this class, we don't
1209 // need to visit base classes.
1210 if (!AssociatedClasses.insert(Class))
1211 return;
1212
1213 // FIXME: Handle class template specializations
1214
1215 // Add direct and indirect base classes along with their associated
1216 // namespaces.
1217 llvm::SmallVector<CXXRecordDecl *, 32> Bases;
1218 Bases.push_back(Class);
1219 while (!Bases.empty()) {
1220 // Pop this class off the stack.
1221 Class = Bases.back();
1222 Bases.pop_back();
1223
1224 // Visit the base classes.
1225 for (CXXRecordDecl::base_class_iterator Base = Class->bases_begin(),
1226 BaseEnd = Class->bases_end();
1227 Base != BaseEnd; ++Base) {
1228 const RecordType *BaseType = Base->getType()->getAsRecordType();
1229 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
1230 if (AssociatedClasses.insert(BaseDecl)) {
1231 // Find the associated namespace for this base class.
1232 DeclContext *BaseCtx = BaseDecl->getDeclContext();
1233 while (BaseCtx->isRecord())
1234 BaseCtx = BaseCtx->getParent();
1235 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(BaseCtx))
1236 AssociatedNamespaces.insert(EnclosingNamespace);
1237
1238 // Make sure we visit the bases of this base class.
1239 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
1240 Bases.push_back(BaseDecl);
1241 }
1242 }
1243 }
1244}
1245
1246// \brief Add the associated classes and namespaces for
1247// argument-dependent lookup with an argument of type T
1248// (C++ [basic.lookup.koenig]p2).
1249static void
1250addAssociatedClassesAndNamespaces(QualType T,
1251 ASTContext &Context,
1252 Sema::AssociatedNamespaceSet &AssociatedNamespaces,
1253 Sema::AssociatedClassSet &AssociatedClasses) {
1254 // C++ [basic.lookup.koenig]p2:
1255 //
1256 // For each argument type T in the function call, there is a set
1257 // of zero or more associated namespaces and a set of zero or more
1258 // associated classes to be considered. The sets of namespaces and
1259 // classes is determined entirely by the types of the function
1260 // arguments (and the namespace of any template template
1261 // argument). Typedef names and using-declarations used to specify
1262 // the types do not contribute to this set. The sets of namespaces
1263 // and classes are determined in the following way:
1264 T = Context.getCanonicalType(T).getUnqualifiedType();
1265
1266 // -- If T is a pointer to U or an array of U, its associated
1267 // namespaces and classes are those associated with U.
1268 //
1269 // We handle this by unwrapping pointer and array types immediately,
1270 // to avoid unnecessary recursion.
1271 while (true) {
1272 if (const PointerType *Ptr = T->getAsPointerType())
1273 T = Ptr->getPointeeType();
1274 else if (const ArrayType *Ptr = Context.getAsArrayType(T))
1275 T = Ptr->getElementType();
1276 else
1277 break;
1278 }
1279
1280 // -- If T is a fundamental type, its associated sets of
1281 // namespaces and classes are both empty.
1282 if (T->getAsBuiltinType())
1283 return;
1284
1285 // -- If T is a class type (including unions), its associated
1286 // classes are: the class itself; the class of which it is a
1287 // member, if any; and its direct and indirect base
1288 // classes. Its associated namespaces are the namespaces in
1289 // which its associated classes are defined.
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001290 if (const RecordType *ClassType = T->getAsRecordType())
1291 if (CXXRecordDecl *ClassDecl
1292 = dyn_cast<CXXRecordDecl>(ClassType->getDecl())) {
1293 addAssociatedClassesAndNamespaces(ClassDecl, Context,
1294 AssociatedNamespaces,
1295 AssociatedClasses);
1296 return;
1297 }
Douglas Gregorfa047642009-02-04 00:32:51 +00001298
1299 // -- If T is an enumeration type, its associated namespace is
1300 // the namespace in which it is defined. If it is class
1301 // member, its associated class is the member’s class; else
1302 // it has no associated class.
1303 if (const EnumType *EnumT = T->getAsEnumType()) {
1304 EnumDecl *Enum = EnumT->getDecl();
1305
1306 DeclContext *Ctx = Enum->getDeclContext();
1307 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
1308 AssociatedClasses.insert(EnclosingClass);
1309
1310 // Add the associated namespace for this class.
1311 while (Ctx->isRecord())
1312 Ctx = Ctx->getParent();
1313 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1314 AssociatedNamespaces.insert(EnclosingNamespace);
1315
1316 return;
1317 }
1318
1319 // -- If T is a function type, its associated namespaces and
1320 // classes are those associated with the function parameter
1321 // types and those associated with the return type.
1322 if (const FunctionType *FunctionType = T->getAsFunctionType()) {
1323 // Return type
1324 addAssociatedClassesAndNamespaces(FunctionType->getResultType(),
1325 Context,
1326 AssociatedNamespaces, AssociatedClasses);
1327
Douglas Gregor72564e72009-02-26 23:50:07 +00001328 const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(FunctionType);
Douglas Gregorfa047642009-02-04 00:32:51 +00001329 if (!Proto)
1330 return;
1331
1332 // Argument types
Douglas Gregor72564e72009-02-26 23:50:07 +00001333 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
Douglas Gregorfa047642009-02-04 00:32:51 +00001334 ArgEnd = Proto->arg_type_end();
1335 Arg != ArgEnd; ++Arg)
1336 addAssociatedClassesAndNamespaces(*Arg, Context,
1337 AssociatedNamespaces, AssociatedClasses);
1338
1339 return;
1340 }
1341
1342 // -- If T is a pointer to a member function of a class X, its
1343 // associated namespaces and classes are those associated
1344 // with the function parameter types and return type,
1345 // together with those associated with X.
1346 //
1347 // -- If T is a pointer to a data member of class X, its
1348 // associated namespaces and classes are those associated
1349 // with the member type together with those associated with
1350 // X.
1351 if (const MemberPointerType *MemberPtr = T->getAsMemberPointerType()) {
1352 // Handle the type that the pointer to member points to.
1353 addAssociatedClassesAndNamespaces(MemberPtr->getPointeeType(),
1354 Context,
1355 AssociatedNamespaces, AssociatedClasses);
1356
1357 // Handle the class type into which this points.
1358 if (const RecordType *Class = MemberPtr->getClass()->getAsRecordType())
1359 addAssociatedClassesAndNamespaces(cast<CXXRecordDecl>(Class->getDecl()),
1360 Context,
1361 AssociatedNamespaces, AssociatedClasses);
1362
1363 return;
1364 }
1365
1366 // FIXME: What about block pointers?
1367 // FIXME: What about Objective-C message sends?
1368}
1369
1370/// \brief Find the associated classes and namespaces for
1371/// argument-dependent lookup for a call with the given set of
1372/// arguments.
1373///
1374/// This routine computes the sets of associated classes and associated
1375/// namespaces searched by argument-dependent lookup
1376/// (C++ [basic.lookup.argdep]) for a given set of arguments.
1377void
1378Sema::FindAssociatedClassesAndNamespaces(Expr **Args, unsigned NumArgs,
1379 AssociatedNamespaceSet &AssociatedNamespaces,
1380 AssociatedClassSet &AssociatedClasses) {
1381 AssociatedNamespaces.clear();
1382 AssociatedClasses.clear();
1383
1384 // C++ [basic.lookup.koenig]p2:
1385 // For each argument type T in the function call, there is a set
1386 // of zero or more associated namespaces and a set of zero or more
1387 // associated classes to be considered. The sets of namespaces and
1388 // classes is determined entirely by the types of the function
1389 // arguments (and the namespace of any template template
1390 // argument).
1391 for (unsigned ArgIdx = 0; ArgIdx != NumArgs; ++ArgIdx) {
1392 Expr *Arg = Args[ArgIdx];
1393
1394 if (Arg->getType() != Context.OverloadTy) {
1395 addAssociatedClassesAndNamespaces(Arg->getType(), Context,
1396 AssociatedNamespaces, AssociatedClasses);
1397 continue;
1398 }
1399
1400 // [...] In addition, if the argument is the name or address of a
1401 // set of overloaded functions and/or function templates, its
1402 // associated classes and namespaces are the union of those
1403 // associated with each of the members of the set: the namespace
1404 // in which the function or function template is defined and the
1405 // classes and namespaces associated with its (non-dependent)
1406 // parameter types and return type.
1407 DeclRefExpr *DRE = 0;
1408 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg)) {
1409 if (unaryOp->getOpcode() == UnaryOperator::AddrOf)
1410 DRE = dyn_cast<DeclRefExpr>(unaryOp->getSubExpr());
1411 } else
1412 DRE = dyn_cast<DeclRefExpr>(Arg);
1413 if (!DRE)
1414 continue;
1415
1416 OverloadedFunctionDecl *Ovl
1417 = dyn_cast<OverloadedFunctionDecl>(DRE->getDecl());
1418 if (!Ovl)
1419 continue;
1420
1421 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
1422 FuncEnd = Ovl->function_end();
1423 Func != FuncEnd; ++Func) {
1424 FunctionDecl *FDecl = cast<FunctionDecl>(*Func);
1425
1426 // Add the namespace in which this function was defined. Note
1427 // that, if this is a member function, we do *not* consider the
1428 // enclosing namespace of its class.
1429 DeclContext *Ctx = FDecl->getDeclContext();
1430 if (NamespaceDecl *EnclosingNamespace = dyn_cast<NamespaceDecl>(Ctx))
1431 AssociatedNamespaces.insert(EnclosingNamespace);
1432
1433 // Add the classes and namespaces associated with the parameter
1434 // types and return type of this function.
1435 addAssociatedClassesAndNamespaces(FDecl->getType(), Context,
1436 AssociatedNamespaces, AssociatedClasses);
1437 }
1438 }
1439}
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001440
1441/// IsAcceptableNonMemberOperatorCandidate - Determine whether Fn is
1442/// an acceptable non-member overloaded operator for a call whose
1443/// arguments have types T1 (and, if non-empty, T2). This routine
1444/// implements the check in C++ [over.match.oper]p3b2 concerning
1445/// enumeration types.
1446static bool
1447IsAcceptableNonMemberOperatorCandidate(FunctionDecl *Fn,
1448 QualType T1, QualType T2,
1449 ASTContext &Context) {
Douglas Gregorba498172009-03-13 21:01:28 +00001450 if (T1->isDependentType() || (!T2.isNull() && T2->isDependentType()))
1451 return true;
1452
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001453 if (T1->isRecordType() || (!T2.isNull() && T2->isRecordType()))
1454 return true;
1455
1456 const FunctionProtoType *Proto = Fn->getType()->getAsFunctionProtoType();
1457 if (Proto->getNumArgs() < 1)
1458 return false;
1459
1460 if (T1->isEnumeralType()) {
1461 QualType ArgType = Proto->getArgType(0).getNonReferenceType();
1462 if (Context.getCanonicalType(T1).getUnqualifiedType()
1463 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1464 return true;
1465 }
1466
1467 if (Proto->getNumArgs() < 2)
1468 return false;
1469
1470 if (!T2.isNull() && T2->isEnumeralType()) {
1471 QualType ArgType = Proto->getArgType(1).getNonReferenceType();
1472 if (Context.getCanonicalType(T2).getUnqualifiedType()
1473 == Context.getCanonicalType(ArgType).getUnqualifiedType())
1474 return true;
1475 }
1476
1477 return false;
1478}
1479
1480void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
1481 QualType T1, QualType T2,
1482 FunctionSet &Functions) {
1483 // C++ [over.match.oper]p3:
1484 // -- The set of non-member candidates is the result of the
1485 // unqualified lookup of operator@ in the context of the
1486 // expression according to the usual rules for name lookup in
1487 // unqualified function calls (3.4.2) except that all member
1488 // functions are ignored. However, if no operand has a class
1489 // type, only those non-member functions in the lookup set
1490 // that have a first parameter of type T1 or “reference to
1491 // (possibly cv-qualified) T1”, when T1 is an enumeration
1492 // type, or (if there is a right operand) a second parameter
1493 // of type T2 or “reference to (possibly cv-qualified) T2”,
1494 // when T2 is an enumeration type, are candidate functions.
1495 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
1496 LookupResult Operators = LookupName(S, OpName, LookupOperatorName);
1497
1498 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
1499
1500 if (!Operators)
1501 return;
1502
1503 for (LookupResult::iterator Op = Operators.begin(), OpEnd = Operators.end();
1504 Op != OpEnd; ++Op) {
1505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Op))
1506 if (IsAcceptableNonMemberOperatorCandidate(FD, T1, T2, Context))
1507 Functions.insert(FD); // FIXME: canonical FD
1508 }
1509}
1510
1511void Sema::ArgumentDependentLookup(DeclarationName Name,
1512 Expr **Args, unsigned NumArgs,
1513 FunctionSet &Functions) {
1514 // Find all of the associated namespaces and classes based on the
1515 // arguments we have.
1516 AssociatedNamespaceSet AssociatedNamespaces;
1517 AssociatedClassSet AssociatedClasses;
1518 FindAssociatedClassesAndNamespaces(Args, NumArgs,
1519 AssociatedNamespaces, AssociatedClasses);
1520
1521 // C++ [basic.lookup.argdep]p3:
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00001522 // Let X be the lookup set produced by unqualified lookup (3.4.1)
1523 // and let Y be the lookup set produced by argument dependent
1524 // lookup (defined as follows). If X contains [...] then Y is
1525 // empty. Otherwise Y is the set of declarations found in the
1526 // namespaces associated with the argument types as described
1527 // below. The set of declarations found by the lookup of the name
1528 // is the union of X and Y.
1529 //
1530 // Here, we compute Y and add its members to the overloaded
1531 // candidate set.
1532 for (AssociatedNamespaceSet::iterator NS = AssociatedNamespaces.begin(),
1533 NSEnd = AssociatedNamespaces.end();
1534 NS != NSEnd; ++NS) {
1535 // When considering an associated namespace, the lookup is the
1536 // same as the lookup performed when the associated namespace is
1537 // used as a qualifier (3.4.3.2) except that:
1538 //
1539 // -- Any using-directives in the associated namespace are
1540 // ignored.
1541 //
1542 // -- FIXME: Any namespace-scope friend functions declared in
1543 // associated classes are visible within their respective
1544 // namespaces even if they are not visible during an ordinary
1545 // lookup (11.4).
1546 DeclContext::lookup_iterator I, E;
1547 for (llvm::tie(I, E) = (*NS)->lookup(Name); I != E; ++I) {
1548 FunctionDecl *Func = dyn_cast<FunctionDecl>(*I);
1549 if (!Func)
1550 break;
1551
1552 Functions.insert(Func);
1553 }
1554 }
1555}
1556