Bug Summary

File:tools/clang/lib/Sema/SemaLookup.cpp
Warning:line 3896, column 37
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp

1//===--------------------- 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
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclLookups.h"
20#include "clang/AST/DeclObjC.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/Basic/Builtins.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Lex/HeaderSearch.h"
27#include "clang/Lex/ModuleLoader.h"
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Sema/DeclSpec.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Overload.h"
32#include "clang/Sema/Scope.h"
33#include "clang/Sema/ScopeInfo.h"
34#include "clang/Sema/Sema.h"
35#include "clang/Sema/SemaInternal.h"
36#include "clang/Sema/TemplateDeduction.h"
37#include "clang/Sema/TypoCorrection.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallPtrSet.h"
40#include "llvm/ADT/TinyPtrVector.h"
41#include "llvm/ADT/edit_distance.h"
42#include "llvm/Support/ErrorHandling.h"
43#include <algorithm>
44#include <iterator>
45#include <list>
46#include <set>
47#include <utility>
48#include <vector>
49
50using namespace clang;
51using namespace sema;
52
53namespace {
54 class UnqualUsingEntry {
55 const DeclContext *Nominated;
56 const DeclContext *CommonAncestor;
57
58 public:
59 UnqualUsingEntry(const DeclContext *Nominated,
60 const DeclContext *CommonAncestor)
61 : Nominated(Nominated), CommonAncestor(CommonAncestor) {
62 }
63
64 const DeclContext *getCommonAncestor() const {
65 return CommonAncestor;
66 }
67
68 const DeclContext *getNominatedNamespace() const {
69 return Nominated;
70 }
71
72 // Sort by the pointer value of the common ancestor.
73 struct Comparator {
74 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
75 return L.getCommonAncestor() < R.getCommonAncestor();
76 }
77
78 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
79 return E.getCommonAncestor() < DC;
80 }
81
82 bool operator()(const DeclContext *DC, const UnqualUsingEntry &E) {
83 return DC < E.getCommonAncestor();
84 }
85 };
86 };
87
88 /// A collection of using directives, as used by C++ unqualified
89 /// lookup.
90 class UnqualUsingDirectiveSet {
91 Sema &SemaRef;
92
93 typedef SmallVector<UnqualUsingEntry, 8> ListTy;
94
95 ListTy list;
96 llvm::SmallPtrSet<DeclContext*, 8> visited;
97
98 public:
99 UnqualUsingDirectiveSet(Sema &SemaRef) : SemaRef(SemaRef) {}
100
101 void visitScopeChain(Scope *S, Scope *InnermostFileScope) {
102 // C++ [namespace.udir]p1:
103 // During unqualified name lookup, the names appear as if they
104 // were declared in the nearest enclosing namespace which contains
105 // both the using-directive and the nominated namespace.
106 DeclContext *InnermostFileDC = InnermostFileScope->getEntity();
107 assert(InnermostFileDC && InnermostFileDC->isFileContext())((InnermostFileDC && InnermostFileDC->isFileContext
()) ? static_cast<void> (0) : __assert_fail ("InnermostFileDC && InnermostFileDC->isFileContext()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 107, __PRETTY_FUNCTION__))
;
108
109 for (; S; S = S->getParent()) {
110 // C++ [namespace.udir]p1:
111 // A using-directive shall not appear in class scope, but may
112 // appear in namespace scope or in block scope.
113 DeclContext *Ctx = S->getEntity();
114 if (Ctx && Ctx->isFileContext()) {
115 visit(Ctx, Ctx);
116 } else if (!Ctx || Ctx->isFunctionOrMethod()) {
117 for (auto *I : S->using_directives())
118 if (SemaRef.isVisible(I))
119 visit(I, InnermostFileDC);
120 }
121 }
122 }
123
124 // Visits a context and collect all of its using directives
125 // recursively. Treats all using directives as if they were
126 // declared in the context.
127 //
128 // A given context is only every visited once, so it is important
129 // that contexts be visited from the inside out in order to get
130 // the effective DCs right.
131 void visit(DeclContext *DC, DeclContext *EffectiveDC) {
132 if (!visited.insert(DC).second)
133 return;
134
135 addUsingDirectives(DC, EffectiveDC);
136 }
137
138 // Visits a using directive and collects all of its using
139 // directives recursively. Treats all using directives as if they
140 // were declared in the effective DC.
141 void visit(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
142 DeclContext *NS = UD->getNominatedNamespace();
143 if (!visited.insert(NS).second)
144 return;
145
146 addUsingDirective(UD, EffectiveDC);
147 addUsingDirectives(NS, EffectiveDC);
148 }
149
150 // Adds all the using directives in a context (and those nominated
151 // by its using directives, transitively) as if they appeared in
152 // the given effective context.
153 void addUsingDirectives(DeclContext *DC, DeclContext *EffectiveDC) {
154 SmallVector<DeclContext*, 4> queue;
155 while (true) {
156 for (auto UD : DC->using_directives()) {
157 DeclContext *NS = UD->getNominatedNamespace();
158 if (SemaRef.isVisible(UD) && visited.insert(NS).second) {
159 addUsingDirective(UD, EffectiveDC);
160 queue.push_back(NS);
161 }
162 }
163
164 if (queue.empty())
165 return;
166
167 DC = queue.pop_back_val();
168 }
169 }
170
171 // Add a using directive as if it had been declared in the given
172 // context. This helps implement C++ [namespace.udir]p3:
173 // The using-directive is transitive: if a scope contains a
174 // using-directive that nominates a second namespace that itself
175 // contains using-directives, the effect is as if the
176 // using-directives from the second namespace also appeared in
177 // the first.
178 void addUsingDirective(UsingDirectiveDecl *UD, DeclContext *EffectiveDC) {
179 // Find the common ancestor between the effective context and
180 // the nominated namespace.
181 DeclContext *Common = UD->getNominatedNamespace();
182 while (!Common->Encloses(EffectiveDC))
183 Common = Common->getParent();
184 Common = Common->getPrimaryContext();
185
186 list.push_back(UnqualUsingEntry(UD->getNominatedNamespace(), Common));
187 }
188
189 void done() {
190 std::sort(list.begin(), list.end(), UnqualUsingEntry::Comparator());
191 }
192
193 typedef ListTy::const_iterator const_iterator;
194
195 const_iterator begin() const { return list.begin(); }
196 const_iterator end() const { return list.end(); }
197
198 llvm::iterator_range<const_iterator>
199 getNamespacesFor(DeclContext *DC) const {
200 return llvm::make_range(std::equal_range(begin(), end(),
201 DC->getPrimaryContext(),
202 UnqualUsingEntry::Comparator()));
203 }
204 };
205} // end anonymous namespace
206
207// Retrieve the set of identifier namespaces that correspond to a
208// specific kind of name lookup.
209static inline unsigned getIDNS(Sema::LookupNameKind NameKind,
210 bool CPlusPlus,
211 bool Redeclaration) {
212 unsigned IDNS = 0;
213 switch (NameKind) {
214 case Sema::LookupObjCImplicitSelfParam:
215 case Sema::LookupOrdinaryName:
216 case Sema::LookupRedeclarationWithLinkage:
217 case Sema::LookupLocalFriendName:
218 IDNS = Decl::IDNS_Ordinary;
219 if (CPlusPlus) {
220 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Member | Decl::IDNS_Namespace;
221 if (Redeclaration)
222 IDNS |= Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend;
223 }
224 if (Redeclaration)
225 IDNS |= Decl::IDNS_LocalExtern;
226 break;
227
228 case Sema::LookupOperatorName:
229 // Operator lookup is its own crazy thing; it is not the same
230 // as (e.g.) looking up an operator name for redeclaration.
231 assert(!Redeclaration && "cannot do redeclaration operator lookup")((!Redeclaration && "cannot do redeclaration operator lookup"
) ? static_cast<void> (0) : __assert_fail ("!Redeclaration && \"cannot do redeclaration operator lookup\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 231, __PRETTY_FUNCTION__))
;
232 IDNS = Decl::IDNS_NonMemberOperator;
233 break;
234
235 case Sema::LookupTagName:
236 if (CPlusPlus) {
237 IDNS = Decl::IDNS_Type;
238
239 // When looking for a redeclaration of a tag name, we add:
240 // 1) TagFriend to find undeclared friend decls
241 // 2) Namespace because they can't "overload" with tag decls.
242 // 3) Tag because it includes class templates, which can't
243 // "overload" with tag decls.
244 if (Redeclaration)
245 IDNS |= Decl::IDNS_Tag | Decl::IDNS_TagFriend | Decl::IDNS_Namespace;
246 } else {
247 IDNS = Decl::IDNS_Tag;
248 }
249 break;
250
251 case Sema::LookupLabel:
252 IDNS = Decl::IDNS_Label;
253 break;
254
255 case Sema::LookupMemberName:
256 IDNS = Decl::IDNS_Member;
257 if (CPlusPlus)
258 IDNS |= Decl::IDNS_Tag | Decl::IDNS_Ordinary;
259 break;
260
261 case Sema::LookupNestedNameSpecifierName:
262 IDNS = Decl::IDNS_Type | Decl::IDNS_Namespace;
263 break;
264
265 case Sema::LookupNamespaceName:
266 IDNS = Decl::IDNS_Namespace;
267 break;
268
269 case Sema::LookupUsingDeclName:
270 assert(Redeclaration && "should only be used for redecl lookup")((Redeclaration && "should only be used for redecl lookup"
) ? static_cast<void> (0) : __assert_fail ("Redeclaration && \"should only be used for redecl lookup\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 270, __PRETTY_FUNCTION__))
;
271 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member |
272 Decl::IDNS_Using | Decl::IDNS_TagFriend | Decl::IDNS_OrdinaryFriend |
273 Decl::IDNS_LocalExtern;
274 break;
275
276 case Sema::LookupObjCProtocolName:
277 IDNS = Decl::IDNS_ObjCProtocol;
278 break;
279
280 case Sema::LookupOMPReductionName:
281 IDNS = Decl::IDNS_OMPReduction;
282 break;
283
284 case Sema::LookupAnyName:
285 IDNS = Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Member
286 | Decl::IDNS_Using | Decl::IDNS_Namespace | Decl::IDNS_ObjCProtocol
287 | Decl::IDNS_Type;
288 break;
289 }
290 return IDNS;
291}
292
293void LookupResult::configure() {
294 IDNS = getIDNS(LookupKind, getSema().getLangOpts().CPlusPlus,
295 isForRedeclaration());
296
297 // If we're looking for one of the allocation or deallocation
298 // operators, make sure that the implicitly-declared new and delete
299 // operators can be found.
300 switch (NameInfo.getName().getCXXOverloadedOperator()) {
301 case OO_New:
302 case OO_Delete:
303 case OO_Array_New:
304 case OO_Array_Delete:
305 getSema().DeclareGlobalNewDelete();
306 break;
307
308 default:
309 break;
310 }
311
312 // Compiler builtins are always visible, regardless of where they end
313 // up being declared.
314 if (IdentifierInfo *Id = NameInfo.getName().getAsIdentifierInfo()) {
315 if (unsigned BuiltinID = Id->getBuiltinID()) {
316 if (!getSema().Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
317 AllowHidden = true;
318 }
319 }
320}
321
322bool LookupResult::sanity() const {
323 // This function is never called by NDEBUG builds.
324 assert(ResultKind != NotFound || Decls.size() == 0)((ResultKind != NotFound || Decls.size() == 0) ? static_cast<
void> (0) : __assert_fail ("ResultKind != NotFound || Decls.size() == 0"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 324, __PRETTY_FUNCTION__))
;
325 assert(ResultKind != Found || Decls.size() == 1)((ResultKind != Found || Decls.size() == 1) ? static_cast<
void> (0) : __assert_fail ("ResultKind != Found || Decls.size() == 1"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 325, __PRETTY_FUNCTION__))
;
326 assert(ResultKind != FoundOverloaded || Decls.size() > 1 ||((ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls
.size() == 1 && isa<FunctionTemplateDecl>((*begin
())->getUnderlyingDecl()))) ? static_cast<void> (0) :
__assert_fail ("ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls.size() == 1 && isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 328, __PRETTY_FUNCTION__))
327 (Decls.size() == 1 &&((ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls
.size() == 1 && isa<FunctionTemplateDecl>((*begin
())->getUnderlyingDecl()))) ? static_cast<void> (0) :
__assert_fail ("ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls.size() == 1 && isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 328, __PRETTY_FUNCTION__))
328 isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl())))((ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls
.size() == 1 && isa<FunctionTemplateDecl>((*begin
())->getUnderlyingDecl()))) ? static_cast<void> (0) :
__assert_fail ("ResultKind != FoundOverloaded || Decls.size() > 1 || (Decls.size() == 1 && isa<FunctionTemplateDecl>((*begin())->getUnderlyingDecl()))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 328, __PRETTY_FUNCTION__))
;
329 assert(ResultKind != FoundUnresolvedValue || sanityCheckUnresolved())((ResultKind != FoundUnresolvedValue || sanityCheckUnresolved
()) ? static_cast<void> (0) : __assert_fail ("ResultKind != FoundUnresolvedValue || sanityCheckUnresolved()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 329, __PRETTY_FUNCTION__))
;
330 assert(ResultKind != Ambiguous || Decls.size() > 1 ||((ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size
() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity
== AmbiguousBaseSubobjectTypes))) ? static_cast<void> (
0) : __assert_fail ("ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity == AmbiguousBaseSubobjectTypes))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 332, __PRETTY_FUNCTION__))
331 (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects ||((ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size
() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity
== AmbiguousBaseSubobjectTypes))) ? static_cast<void> (
0) : __assert_fail ("ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity == AmbiguousBaseSubobjectTypes))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 332, __PRETTY_FUNCTION__))
332 Ambiguity == AmbiguousBaseSubobjectTypes)))((ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size
() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity
== AmbiguousBaseSubobjectTypes))) ? static_cast<void> (
0) : __assert_fail ("ResultKind != Ambiguous || Decls.size() > 1 || (Decls.size() == 1 && (Ambiguity == AmbiguousBaseSubobjects || Ambiguity == AmbiguousBaseSubobjectTypes))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 332, __PRETTY_FUNCTION__))
;
333 assert((Paths != nullptr) == (ResultKind == Ambiguous &&(((Paths != nullptr) == (ResultKind == Ambiguous && (
Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects
))) ? static_cast<void> (0) : __assert_fail ("(Paths != nullptr) == (ResultKind == Ambiguous && (Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 335, __PRETTY_FUNCTION__))
334 (Ambiguity == AmbiguousBaseSubobjectTypes ||(((Paths != nullptr) == (ResultKind == Ambiguous && (
Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects
))) ? static_cast<void> (0) : __assert_fail ("(Paths != nullptr) == (ResultKind == Ambiguous && (Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 335, __PRETTY_FUNCTION__))
335 Ambiguity == AmbiguousBaseSubobjects)))(((Paths != nullptr) == (ResultKind == Ambiguous && (
Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects
))) ? static_cast<void> (0) : __assert_fail ("(Paths != nullptr) == (ResultKind == Ambiguous && (Ambiguity == AmbiguousBaseSubobjectTypes || Ambiguity == AmbiguousBaseSubobjects))"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 335, __PRETTY_FUNCTION__))
;
336 return true;
337}
338
339// Necessary because CXXBasePaths is not complete in Sema.h
340void LookupResult::deletePaths(CXXBasePaths *Paths) {
341 delete Paths;
342}
343
344/// Get a representative context for a declaration such that two declarations
345/// will have the same context if they were found within the same scope.
346static DeclContext *getContextForScopeMatching(Decl *D) {
347 // For function-local declarations, use that function as the context. This
348 // doesn't account for scopes within the function; the caller must deal with
349 // those.
350 DeclContext *DC = D->getLexicalDeclContext();
351 if (DC->isFunctionOrMethod())
352 return DC;
353
354 // Otherwise, look at the semantic context of the declaration. The
355 // declaration must have been found there.
356 return D->getDeclContext()->getRedeclContext();
357}
358
359/// \brief Determine whether \p D is a better lookup result than \p Existing,
360/// given that they declare the same entity.
361static bool isPreferredLookupResult(Sema &S, Sema::LookupNameKind Kind,
362 NamedDecl *D, NamedDecl *Existing) {
363 // When looking up redeclarations of a using declaration, prefer a using
364 // shadow declaration over any other declaration of the same entity.
365 if (Kind == Sema::LookupUsingDeclName && isa<UsingShadowDecl>(D) &&
366 !isa<UsingShadowDecl>(Existing))
367 return true;
368
369 auto *DUnderlying = D->getUnderlyingDecl();
370 auto *EUnderlying = Existing->getUnderlyingDecl();
371
372 // If they have different underlying declarations, prefer a typedef over the
373 // original type (this happens when two type declarations denote the same
374 // type), per a generous reading of C++ [dcl.typedef]p3 and p4. The typedef
375 // might carry additional semantic information, such as an alignment override.
376 // However, per C++ [dcl.typedef]p5, when looking up a tag name, prefer a tag
377 // declaration over a typedef.
378 if (DUnderlying->getCanonicalDecl() != EUnderlying->getCanonicalDecl()) {
379 assert(isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying))((isa<TypeDecl>(DUnderlying) && isa<TypeDecl
>(EUnderlying)) ? static_cast<void> (0) : __assert_fail
("isa<TypeDecl>(DUnderlying) && isa<TypeDecl>(EUnderlying)"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 379, __PRETTY_FUNCTION__))
;
380 bool HaveTag = isa<TagDecl>(EUnderlying);
381 bool WantTag = Kind == Sema::LookupTagName;
382 return HaveTag != WantTag;
383 }
384
385 // Pick the function with more default arguments.
386 // FIXME: In the presence of ambiguous default arguments, we should keep both,
387 // so we can diagnose the ambiguity if the default argument is needed.
388 // See C++ [over.match.best]p3.
389 if (auto *DFD = dyn_cast<FunctionDecl>(DUnderlying)) {
390 auto *EFD = cast<FunctionDecl>(EUnderlying);
391 unsigned DMin = DFD->getMinRequiredArguments();
392 unsigned EMin = EFD->getMinRequiredArguments();
393 // If D has more default arguments, it is preferred.
394 if (DMin != EMin)
395 return DMin < EMin;
396 // FIXME: When we track visibility for default function arguments, check
397 // that we pick the declaration with more visible default arguments.
398 }
399
400 // Pick the template with more default template arguments.
401 if (auto *DTD = dyn_cast<TemplateDecl>(DUnderlying)) {
402 auto *ETD = cast<TemplateDecl>(EUnderlying);
403 unsigned DMin = DTD->getTemplateParameters()->getMinRequiredArguments();
404 unsigned EMin = ETD->getTemplateParameters()->getMinRequiredArguments();
405 // If D has more default arguments, it is preferred. Note that default
406 // arguments (and their visibility) is monotonically increasing across the
407 // redeclaration chain, so this is a quick proxy for "is more recent".
408 if (DMin != EMin)
409 return DMin < EMin;
410 // If D has more *visible* default arguments, it is preferred. Note, an
411 // earlier default argument being visible does not imply that a later
412 // default argument is visible, so we can't just check the first one.
413 for (unsigned I = DMin, N = DTD->getTemplateParameters()->size();
414 I != N; ++I) {
415 if (!S.hasVisibleDefaultArgument(
416 ETD->getTemplateParameters()->getParam(I)) &&
417 S.hasVisibleDefaultArgument(
418 DTD->getTemplateParameters()->getParam(I)))
419 return true;
420 }
421 }
422
423 // VarDecl can have incomplete array types, prefer the one with more complete
424 // array type.
425 if (VarDecl *DVD = dyn_cast<VarDecl>(DUnderlying)) {
426 VarDecl *EVD = cast<VarDecl>(EUnderlying);
427 if (EVD->getType()->isIncompleteType() &&
428 !DVD->getType()->isIncompleteType()) {
429 // Prefer the decl with a more complete type if visible.
430 return S.isVisible(DVD);
431 }
432 return false; // Avoid picking up a newer decl, just because it was newer.
433 }
434
435 // For most kinds of declaration, it doesn't really matter which one we pick.
436 if (!isa<FunctionDecl>(DUnderlying) && !isa<VarDecl>(DUnderlying)) {
437 // If the existing declaration is hidden, prefer the new one. Otherwise,
438 // keep what we've got.
439 return !S.isVisible(Existing);
440 }
441
442 // Pick the newer declaration; it might have a more precise type.
443 for (Decl *Prev = DUnderlying->getPreviousDecl(); Prev;
444 Prev = Prev->getPreviousDecl())
445 if (Prev == EUnderlying)
446 return true;
447 return false;
448}
449
450/// Determine whether \p D can hide a tag declaration.
451static bool canHideTag(NamedDecl *D) {
452 // C++ [basic.scope.declarative]p4:
453 // Given a set of declarations in a single declarative region [...]
454 // exactly one declaration shall declare a class name or enumeration name
455 // that is not a typedef name and the other declarations shall all refer to
456 // the same variable, non-static data member, or enumerator, or all refer
457 // to functions and function templates; in this case the class name or
458 // enumeration name is hidden.
459 // C++ [basic.scope.hiding]p2:
460 // A class name or enumeration name can be hidden by the name of a
461 // variable, data member, function, or enumerator declared in the same
462 // scope.
463 // An UnresolvedUsingValueDecl always instantiates to one of these.
464 D = D->getUnderlyingDecl();
465 return isa<VarDecl>(D) || isa<EnumConstantDecl>(D) || isa<FunctionDecl>(D) ||
466 isa<FunctionTemplateDecl>(D) || isa<FieldDecl>(D) ||
467 isa<UnresolvedUsingValueDecl>(D);
468}
469
470/// Resolves the result kind of this lookup.
471void LookupResult::resolveKind() {
472 unsigned N = Decls.size();
473
474 // Fast case: no possible ambiguity.
475 if (N == 0) {
476 assert(ResultKind == NotFound ||((ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation
) ? static_cast<void> (0) : __assert_fail ("ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 477, __PRETTY_FUNCTION__))
477 ResultKind == NotFoundInCurrentInstantiation)((ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation
) ? static_cast<void> (0) : __assert_fail ("ResultKind == NotFound || ResultKind == NotFoundInCurrentInstantiation"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 477, __PRETTY_FUNCTION__))
;
478 return;
479 }
480
481 // If there's a single decl, we need to examine it to decide what
482 // kind of lookup this is.
483 if (N == 1) {
484 NamedDecl *D = (*Decls.begin())->getUnderlyingDecl();
485 if (isa<FunctionTemplateDecl>(D))
486 ResultKind = FoundOverloaded;
487 else if (isa<UnresolvedUsingValueDecl>(D))
488 ResultKind = FoundUnresolvedValue;
489 return;
490 }
491
492 // Don't do any extra resolution if we've already resolved as ambiguous.
493 if (ResultKind == Ambiguous) return;
494
495 llvm::SmallDenseMap<NamedDecl*, unsigned, 16> Unique;
496 llvm::SmallDenseMap<QualType, unsigned, 16> UniqueTypes;
497
498 bool Ambiguous = false;
499 bool HasTag = false, HasFunction = false;
500 bool HasFunctionTemplate = false, HasUnresolved = false;
501 NamedDecl *HasNonFunction = nullptr;
502
503 llvm::SmallVector<NamedDecl*, 4> EquivalentNonFunctions;
504
505 unsigned UniqueTagIndex = 0;
506
507 unsigned I = 0;
508 while (I < N) {
509 NamedDecl *D = Decls[I]->getUnderlyingDecl();
510 D = cast<NamedDecl>(D->getCanonicalDecl());
511
512 // Ignore an invalid declaration unless it's the only one left.
513 if (D->isInvalidDecl() && !(I == 0 && N == 1)) {
514 Decls[I] = Decls[--N];
515 continue;
516 }
517
518 llvm::Optional<unsigned> ExistingI;
519
520 // Redeclarations of types via typedef can occur both within a scope
521 // and, through using declarations and directives, across scopes. There is
522 // no ambiguity if they all refer to the same type, so unique based on the
523 // canonical type.
524 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
525 QualType T = getSema().Context.getTypeDeclType(TD);
526 auto UniqueResult = UniqueTypes.insert(
527 std::make_pair(getSema().Context.getCanonicalType(T), I));
528 if (!UniqueResult.second) {
529 // The type is not unique.
530 ExistingI = UniqueResult.first->second;
531 }
532 }
533
534 // For non-type declarations, check for a prior lookup result naming this
535 // canonical declaration.
536 if (!ExistingI) {
537 auto UniqueResult = Unique.insert(std::make_pair(D, I));
538 if (!UniqueResult.second) {
539 // We've seen this entity before.
540 ExistingI = UniqueResult.first->second;
541 }
542 }
543
544 if (ExistingI) {
545 // This is not a unique lookup result. Pick one of the results and
546 // discard the other.
547 if (isPreferredLookupResult(getSema(), getLookupKind(), Decls[I],
548 Decls[*ExistingI]))
549 Decls[*ExistingI] = Decls[I];
550 Decls[I] = Decls[--N];
551 continue;
552 }
553
554 // Otherwise, do some decl type analysis and then continue.
555
556 if (isa<UnresolvedUsingValueDecl>(D)) {
557 HasUnresolved = true;
558 } else if (isa<TagDecl>(D)) {
559 if (HasTag)
560 Ambiguous = true;
561 UniqueTagIndex = I;
562 HasTag = true;
563 } else if (isa<FunctionTemplateDecl>(D)) {
564 HasFunction = true;
565 HasFunctionTemplate = true;
566 } else if (isa<FunctionDecl>(D)) {
567 HasFunction = true;
568 } else {
569 if (HasNonFunction) {
570 // If we're about to create an ambiguity between two declarations that
571 // are equivalent, but one is an internal linkage declaration from one
572 // module and the other is an internal linkage declaration from another
573 // module, just skip it.
574 if (getSema().isEquivalentInternalLinkageDeclaration(HasNonFunction,
575 D)) {
576 EquivalentNonFunctions.push_back(D);
577 Decls[I] = Decls[--N];
578 continue;
579 }
580
581 Ambiguous = true;
582 }
583 HasNonFunction = D;
584 }
585 I++;
586 }
587
588 // C++ [basic.scope.hiding]p2:
589 // A class name or enumeration name can be hidden by the name of
590 // an object, function, or enumerator declared in the same
591 // scope. If a class or enumeration name and an object, function,
592 // or enumerator are declared in the same scope (in any order)
593 // with the same name, the class or enumeration name is hidden
594 // wherever the object, function, or enumerator name is visible.
595 // But it's still an error if there are distinct tag types found,
596 // even if they're not visible. (ref?)
597 if (N > 1 && HideTags && HasTag && !Ambiguous &&
598 (HasFunction || HasNonFunction || HasUnresolved)) {
599 NamedDecl *OtherDecl = Decls[UniqueTagIndex ? 0 : N - 1];
600 if (isa<TagDecl>(Decls[UniqueTagIndex]->getUnderlyingDecl()) &&
601 getContextForScopeMatching(Decls[UniqueTagIndex])->Equals(
602 getContextForScopeMatching(OtherDecl)) &&
603 canHideTag(OtherDecl))
604 Decls[UniqueTagIndex] = Decls[--N];
605 else
606 Ambiguous = true;
607 }
608
609 // FIXME: This diagnostic should really be delayed until we're done with
610 // the lookup result, in case the ambiguity is resolved by the caller.
611 if (!EquivalentNonFunctions.empty() && !Ambiguous)
612 getSema().diagnoseEquivalentInternalLinkageDeclarations(
613 getNameLoc(), HasNonFunction, EquivalentNonFunctions);
614
615 Decls.set_size(N);
616
617 if (HasNonFunction && (HasFunction || HasUnresolved))
618 Ambiguous = true;
619
620 if (Ambiguous)
621 setAmbiguous(LookupResult::AmbiguousReference);
622 else if (HasUnresolved)
623 ResultKind = LookupResult::FoundUnresolvedValue;
624 else if (N > 1 || HasFunctionTemplate)
625 ResultKind = LookupResult::FoundOverloaded;
626 else
627 ResultKind = LookupResult::Found;
628}
629
630void LookupResult::addDeclsFromBasePaths(const CXXBasePaths &P) {
631 CXXBasePaths::const_paths_iterator I, E;
632 for (I = P.begin(), E = P.end(); I != E; ++I)
633 for (DeclContext::lookup_iterator DI = I->Decls.begin(),
634 DE = I->Decls.end(); DI != DE; ++DI)
635 addDecl(*DI);
636}
637
638void LookupResult::setAmbiguousBaseSubobjects(CXXBasePaths &P) {
639 Paths = new CXXBasePaths;
640 Paths->swap(P);
641 addDeclsFromBasePaths(*Paths);
642 resolveKind();
643 setAmbiguous(AmbiguousBaseSubobjects);
644}
645
646void LookupResult::setAmbiguousBaseSubobjectTypes(CXXBasePaths &P) {
647 Paths = new CXXBasePaths;
648 Paths->swap(P);
649 addDeclsFromBasePaths(*Paths);
650 resolveKind();
651 setAmbiguous(AmbiguousBaseSubobjectTypes);
652}
653
654void LookupResult::print(raw_ostream &Out) {
655 Out << Decls.size() << " result(s)";
656 if (isAmbiguous()) Out << ", ambiguous";
657 if (Paths) Out << ", base paths present";
658
659 for (iterator I = begin(), E = end(); I != E; ++I) {
660 Out << "\n";
661 (*I)->print(Out, 2);
662 }
663}
664
665LLVM_DUMP_METHOD__attribute__((noinline)) __attribute__((__used__)) void LookupResult::dump() {
666 llvm::errs() << "lookup results for " << getLookupName().getAsString()
667 << ":\n";
668 for (NamedDecl *D : *this)
669 D->dump();
670}
671
672/// \brief Lookup a builtin function, when name lookup would otherwise
673/// fail.
674static bool LookupBuiltin(Sema &S, LookupResult &R) {
675 Sema::LookupNameKind NameKind = R.getLookupKind();
676
677 // If we didn't find a use of this identifier, and if the identifier
678 // corresponds to a compiler builtin, create the decl object for the builtin
679 // now, injecting it into translation unit scope, and return it.
680 if (NameKind == Sema::LookupOrdinaryName ||
681 NameKind == Sema::LookupRedeclarationWithLinkage) {
682 IdentifierInfo *II = R.getLookupName().getAsIdentifierInfo();
683 if (II) {
684 if (S.getLangOpts().CPlusPlus && NameKind == Sema::LookupOrdinaryName) {
685 if (II == S.getASTContext().getMakeIntegerSeqName()) {
686 R.addDecl(S.getASTContext().getMakeIntegerSeqDecl());
687 return true;
688 } else if (II == S.getASTContext().getTypePackElementName()) {
689 R.addDecl(S.getASTContext().getTypePackElementDecl());
690 return true;
691 }
692 }
693
694 // If this is a builtin on this (or all) targets, create the decl.
695 if (unsigned BuiltinID = II->getBuiltinID()) {
696 // In C++ and OpenCL (spec v1.2 s6.9.f), we don't have any predefined
697 // library functions like 'malloc'. Instead, we'll just error.
698 if ((S.getLangOpts().CPlusPlus || S.getLangOpts().OpenCL) &&
699 S.Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID))
700 return false;
701
702 if (NamedDecl *D = S.LazilyCreateBuiltin((IdentifierInfo *)II,
703 BuiltinID, S.TUScope,
704 R.isForRedeclaration(),
705 R.getNameLoc())) {
706 R.addDecl(D);
707 return true;
708 }
709 }
710 }
711 }
712
713 return false;
714}
715
716/// \brief Determine whether we can declare a special member function within
717/// the class at this point.
718static bool CanDeclareSpecialMemberFunction(const CXXRecordDecl *Class) {
719 // We need to have a definition for the class.
720 if (!Class->getDefinition() || Class->isDependentContext())
721 return false;
722
723 // We can't be in the middle of defining the class.
724 return !Class->isBeingDefined();
725}
726
727void Sema::ForceDeclarationOfImplicitMembers(CXXRecordDecl *Class) {
728 if (!CanDeclareSpecialMemberFunction(Class))
729 return;
730
731 // If the default constructor has not yet been declared, do so now.
732 if (Class->needsImplicitDefaultConstructor())
733 DeclareImplicitDefaultConstructor(Class);
734
735 // If the copy constructor has not yet been declared, do so now.
736 if (Class->needsImplicitCopyConstructor())
737 DeclareImplicitCopyConstructor(Class);
738
739 // If the copy assignment operator has not yet been declared, do so now.
740 if (Class->needsImplicitCopyAssignment())
741 DeclareImplicitCopyAssignment(Class);
742
743 if (getLangOpts().CPlusPlus11) {
744 // If the move constructor has not yet been declared, do so now.
745 if (Class->needsImplicitMoveConstructor())
746 DeclareImplicitMoveConstructor(Class);
747
748 // If the move assignment operator has not yet been declared, do so now.
749 if (Class->needsImplicitMoveAssignment())
750 DeclareImplicitMoveAssignment(Class);
751 }
752
753 // If the destructor has not yet been declared, do so now.
754 if (Class->needsImplicitDestructor())
755 DeclareImplicitDestructor(Class);
756}
757
758/// \brief Determine whether this is the name of an implicitly-declared
759/// special member function.
760static bool isImplicitlyDeclaredMemberFunctionName(DeclarationName Name) {
761 switch (Name.getNameKind()) {
762 case DeclarationName::CXXConstructorName:
763 case DeclarationName::CXXDestructorName:
764 return true;
765
766 case DeclarationName::CXXOperatorName:
767 return Name.getCXXOverloadedOperator() == OO_Equal;
768
769 default:
770 break;
771 }
772
773 return false;
774}
775
776/// \brief If there are any implicit member functions with the given name
777/// that need to be declared in the given declaration context, do so.
778static void DeclareImplicitMemberFunctionsWithName(Sema &S,
779 DeclarationName Name,
780 SourceLocation Loc,
781 const DeclContext *DC) {
782 if (!DC)
783 return;
784
785 switch (Name.getNameKind()) {
786 case DeclarationName::CXXConstructorName:
787 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
788 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
789 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
790 if (Record->needsImplicitDefaultConstructor())
791 S.DeclareImplicitDefaultConstructor(Class);
792 if (Record->needsImplicitCopyConstructor())
793 S.DeclareImplicitCopyConstructor(Class);
794 if (S.getLangOpts().CPlusPlus11 &&
795 Record->needsImplicitMoveConstructor())
796 S.DeclareImplicitMoveConstructor(Class);
797 }
798 break;
799
800 case DeclarationName::CXXDestructorName:
801 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC))
802 if (Record->getDefinition() && Record->needsImplicitDestructor() &&
803 CanDeclareSpecialMemberFunction(Record))
804 S.DeclareImplicitDestructor(const_cast<CXXRecordDecl *>(Record));
805 break;
806
807 case DeclarationName::CXXOperatorName:
808 if (Name.getCXXOverloadedOperator() != OO_Equal)
809 break;
810
811 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC)) {
812 if (Record->getDefinition() && CanDeclareSpecialMemberFunction(Record)) {
813 CXXRecordDecl *Class = const_cast<CXXRecordDecl *>(Record);
814 if (Record->needsImplicitCopyAssignment())
815 S.DeclareImplicitCopyAssignment(Class);
816 if (S.getLangOpts().CPlusPlus11 &&
817 Record->needsImplicitMoveAssignment())
818 S.DeclareImplicitMoveAssignment(Class);
819 }
820 }
821 break;
822
823 case DeclarationName::CXXDeductionGuideName:
824 S.DeclareImplicitDeductionGuides(Name.getCXXDeductionGuideTemplate(), Loc);
825 break;
826
827 default:
828 break;
829 }
830}
831
832// Adds all qualifying matches for a name within a decl context to the
833// given lookup result. Returns true if any matches were found.
834static bool LookupDirect(Sema &S, LookupResult &R, const DeclContext *DC) {
835 bool Found = false;
836
837 // Lazily declare C++ special member functions.
838 if (S.getLangOpts().CPlusPlus)
839 DeclareImplicitMemberFunctionsWithName(S, R.getLookupName(), R.getNameLoc(),
840 DC);
841
842 // Perform lookup into this declaration context.
843 DeclContext::lookup_result DR = DC->lookup(R.getLookupName());
844 for (NamedDecl *D : DR) {
845 if ((D = R.getAcceptableDecl(D))) {
846 R.addDecl(D);
847 Found = true;
848 }
849 }
850
851 if (!Found && DC->isTranslationUnit() && LookupBuiltin(S, R))
852 return true;
853
854 if (R.getLookupName().getNameKind()
855 != DeclarationName::CXXConversionFunctionName ||
856 R.getLookupName().getCXXNameType()->isDependentType() ||
857 !isa<CXXRecordDecl>(DC))
858 return Found;
859
860 // C++ [temp.mem]p6:
861 // A specialization of a conversion function template is not found by
862 // name lookup. Instead, any conversion function templates visible in the
863 // context of the use are considered. [...]
864 const CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
865 if (!Record->isCompleteDefinition())
866 return Found;
867
868 // For conversion operators, 'operator auto' should only match
869 // 'operator auto'. Since 'auto' is not a type, it shouldn't be considered
870 // as a candidate for template substitution.
871 auto *ContainedDeducedType =
872 R.getLookupName().getCXXNameType()->getContainedDeducedType();
873 if (R.getLookupName().getNameKind() ==
874 DeclarationName::CXXConversionFunctionName &&
875 ContainedDeducedType && ContainedDeducedType->isUndeducedType())
876 return Found;
877
878 for (CXXRecordDecl::conversion_iterator U = Record->conversion_begin(),
879 UEnd = Record->conversion_end(); U != UEnd; ++U) {
880 FunctionTemplateDecl *ConvTemplate = dyn_cast<FunctionTemplateDecl>(*U);
881 if (!ConvTemplate)
882 continue;
883
884 // When we're performing lookup for the purposes of redeclaration, just
885 // add the conversion function template. When we deduce template
886 // arguments for specializations, we'll end up unifying the return
887 // type of the new declaration with the type of the function template.
888 if (R.isForRedeclaration()) {
889 R.addDecl(ConvTemplate);
890 Found = true;
891 continue;
892 }
893
894 // C++ [temp.mem]p6:
895 // [...] For each such operator, if argument deduction succeeds
896 // (14.9.2.3), the resulting specialization is used as if found by
897 // name lookup.
898 //
899 // When referencing a conversion function for any purpose other than
900 // a redeclaration (such that we'll be building an expression with the
901 // result), perform template argument deduction and place the
902 // specialization into the result set. We do this to avoid forcing all
903 // callers to perform special deduction for conversion functions.
904 TemplateDeductionInfo Info(R.getNameLoc());
905 FunctionDecl *Specialization = nullptr;
906
907 const FunctionProtoType *ConvProto
908 = ConvTemplate->getTemplatedDecl()->getType()->getAs<FunctionProtoType>();
909 assert(ConvProto && "Nonsensical conversion function template type")((ConvProto && "Nonsensical conversion function template type"
) ? static_cast<void> (0) : __assert_fail ("ConvProto && \"Nonsensical conversion function template type\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 909, __PRETTY_FUNCTION__))
;
910
911 // Compute the type of the function that we would expect the conversion
912 // function to have, if it were to match the name given.
913 // FIXME: Calling convention!
914 FunctionProtoType::ExtProtoInfo EPI = ConvProto->getExtProtoInfo();
915 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(CC_C);
916 EPI.ExceptionSpec = EST_None;
917 QualType ExpectedType
918 = R.getSema().Context.getFunctionType(R.getLookupName().getCXXNameType(),
919 None, EPI);
920
921 // Perform template argument deduction against the type that we would
922 // expect the function to have.
923 if (R.getSema().DeduceTemplateArguments(ConvTemplate, nullptr, ExpectedType,
924 Specialization, Info)
925 == Sema::TDK_Success) {
926 R.addDecl(Specialization);
927 Found = true;
928 }
929 }
930
931 return Found;
932}
933
934// Performs C++ unqualified lookup into the given file context.
935static bool
936CppNamespaceLookup(Sema &S, LookupResult &R, ASTContext &Context,
937 DeclContext *NS, UnqualUsingDirectiveSet &UDirs) {
938
939 assert(NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!")((NS && NS->isFileContext() && "CppNamespaceLookup() requires namespace!"
) ? static_cast<void> (0) : __assert_fail ("NS && NS->isFileContext() && \"CppNamespaceLookup() requires namespace!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 939, __PRETTY_FUNCTION__))
;
940
941 // Perform direct name lookup into the LookupCtx.
942 bool Found = LookupDirect(S, R, NS);
943
944 // Perform direct name lookup into the namespaces nominated by the
945 // using directives whose common ancestor is this namespace.
946 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(NS))
947 if (LookupDirect(S, R, UUE.getNominatedNamespace()))
948 Found = true;
949
950 R.resolveKind();
951
952 return Found;
953}
954
955static bool isNamespaceOrTranslationUnitScope(Scope *S) {
956 if (DeclContext *Ctx = S->getEntity())
957 return Ctx->isFileContext();
958 return false;
959}
960
961// Find the next outer declaration context from this scope. This
962// routine actually returns the semantic outer context, which may
963// differ from the lexical context (encoded directly in the Scope
964// stack) when we are parsing a member of a class template. In this
965// case, the second element of the pair will be true, to indicate that
966// name lookup should continue searching in this semantic context when
967// it leaves the current template parameter scope.
968static std::pair<DeclContext *, bool> findOuterContext(Scope *S) {
969 DeclContext *DC = S->getEntity();
970 DeclContext *Lexical = nullptr;
971 for (Scope *OuterS = S->getParent(); OuterS;
972 OuterS = OuterS->getParent()) {
973 if (OuterS->getEntity()) {
974 Lexical = OuterS->getEntity();
975 break;
976 }
977 }
978
979 // C++ [temp.local]p8:
980 // In the definition of a member of a class template that appears
981 // outside of the namespace containing the class template
982 // definition, the name of a template-parameter hides the name of
983 // a member of this namespace.
984 //
985 // Example:
986 //
987 // namespace N {
988 // class C { };
989 //
990 // template<class T> class B {
991 // void f(T);
992 // };
993 // }
994 //
995 // template<class C> void N::B<C>::f(C) {
996 // C b; // C is the template parameter, not N::C
997 // }
998 //
999 // In this example, the lexical context we return is the
1000 // TranslationUnit, while the semantic context is the namespace N.
1001 if (!Lexical || !DC || !S->getParent() ||
1002 !S->getParent()->isTemplateParamScope())
1003 return std::make_pair(Lexical, false);
1004
1005 // Find the outermost template parameter scope.
1006 // For the example, this is the scope for the template parameters of
1007 // template<class C>.
1008 Scope *OutermostTemplateScope = S->getParent();
1009 while (OutermostTemplateScope->getParent() &&
1010 OutermostTemplateScope->getParent()->isTemplateParamScope())
1011 OutermostTemplateScope = OutermostTemplateScope->getParent();
1012
1013 // Find the namespace context in which the original scope occurs. In
1014 // the example, this is namespace N.
1015 DeclContext *Semantic = DC;
1016 while (!Semantic->isFileContext())
1017 Semantic = Semantic->getParent();
1018
1019 // Find the declaration context just outside of the template
1020 // parameter scope. This is the context in which the template is
1021 // being lexically declaration (a namespace context). In the
1022 // example, this is the global scope.
1023 if (Lexical->isFileContext() && !Lexical->Equals(Semantic) &&
1024 Lexical->Encloses(Semantic))
1025 return std::make_pair(Semantic, true);
1026
1027 return std::make_pair(Lexical, false);
1028}
1029
1030namespace {
1031/// An RAII object to specify that we want to find block scope extern
1032/// declarations.
1033struct FindLocalExternScope {
1034 FindLocalExternScope(LookupResult &R)
1035 : R(R), OldFindLocalExtern(R.getIdentifierNamespace() &
1036 Decl::IDNS_LocalExtern) {
1037 R.setFindLocalExtern(R.getIdentifierNamespace() &
1038 (Decl::IDNS_Ordinary | Decl::IDNS_NonMemberOperator));
1039 }
1040 void restore() {
1041 R.setFindLocalExtern(OldFindLocalExtern);
1042 }
1043 ~FindLocalExternScope() {
1044 restore();
1045 }
1046 LookupResult &R;
1047 bool OldFindLocalExtern;
1048};
1049} // end anonymous namespace
1050
1051bool Sema::CppLookupName(LookupResult &R, Scope *S) {
1052 assert(getLangOpts().CPlusPlus && "Can perform only C++ lookup")((getLangOpts().CPlusPlus && "Can perform only C++ lookup"
) ? static_cast<void> (0) : __assert_fail ("getLangOpts().CPlusPlus && \"Can perform only C++ lookup\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1052, __PRETTY_FUNCTION__))
;
1053
1054 DeclarationName Name = R.getLookupName();
1055 Sema::LookupNameKind NameKind = R.getLookupKind();
1056
1057 // If this is the name of an implicitly-declared special member function,
1058 // go through the scope stack to implicitly declare
1059 if (isImplicitlyDeclaredMemberFunctionName(Name)) {
1060 for (Scope *PreS = S; PreS; PreS = PreS->getParent())
1061 if (DeclContext *DC = PreS->getEntity())
1062 DeclareImplicitMemberFunctionsWithName(*this, Name, R.getNameLoc(), DC);
1063 }
1064
1065 // Implicitly declare member functions with the name we're looking for, if in
1066 // fact we are in a scope where it matters.
1067
1068 Scope *Initial = S;
1069 IdentifierResolver::iterator
1070 I = IdResolver.begin(Name),
1071 IEnd = IdResolver.end();
1072
1073 // First we lookup local scope.
1074 // We don't consider using-directives, as per 7.3.4.p1 [namespace.udir]
1075 // ...During unqualified name lookup (3.4.1), the names appear as if
1076 // they were declared in the nearest enclosing namespace which contains
1077 // both the using-directive and the nominated namespace.
1078 // [Note: in this context, "contains" means "contains directly or
1079 // indirectly".
1080 //
1081 // For example:
1082 // namespace A { int i; }
1083 // void foo() {
1084 // int i;
1085 // {
1086 // using namespace A;
1087 // ++i; // finds local 'i', A::i appears at global scope
1088 // }
1089 // }
1090 //
1091 UnqualUsingDirectiveSet UDirs(*this);
1092 bool VisitedUsingDirectives = false;
1093 bool LeftStartingScope = false;
1094 DeclContext *OutsideOfTemplateParamDC = nullptr;
1095
1096 // When performing a scope lookup, we want to find local extern decls.
1097 FindLocalExternScope FindLocals(R);
1098
1099 for (; S && !isNamespaceOrTranslationUnitScope(S); S = S->getParent()) {
1100 DeclContext *Ctx = S->getEntity();
1101 bool SearchNamespaceScope = true;
1102 // Check whether the IdResolver has anything in this scope.
1103 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1104 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1105 if (NameKind == LookupRedeclarationWithLinkage &&
1106 !(*I)->isTemplateParameter()) {
1107 // If it's a template parameter, we still find it, so we can diagnose
1108 // the invalid redeclaration.
1109
1110 // Determine whether this (or a previous) declaration is
1111 // out-of-scope.
1112 if (!LeftStartingScope && !Initial->isDeclScope(*I))
1113 LeftStartingScope = true;
1114
1115 // If we found something outside of our starting scope that
1116 // does not have linkage, skip it.
1117 if (LeftStartingScope && !((*I)->hasLinkage())) {
1118 R.setShadowed();
1119 continue;
1120 }
1121 } else {
1122 // We found something in this scope, we should not look at the
1123 // namespace scope
1124 SearchNamespaceScope = false;
1125 }
1126 R.addDecl(ND);
1127 }
1128 }
1129 if (!SearchNamespaceScope) {
1130 R.resolveKind();
1131 if (S->isClassScope())
1132 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Ctx))
1133 R.setNamingClass(Record);
1134 return true;
1135 }
1136
1137 if (NameKind == LookupLocalFriendName && !S->isClassScope()) {
1138 // C++11 [class.friend]p11:
1139 // If a friend declaration appears in a local class and the name
1140 // specified is an unqualified name, a prior declaration is
1141 // looked up without considering scopes that are outside the
1142 // innermost enclosing non-class scope.
1143 return false;
1144 }
1145
1146 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1147 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1148 // We've just searched the last template parameter scope and
1149 // found nothing, so look into the contexts between the
1150 // lexical and semantic declaration contexts returned by
1151 // findOuterContext(). This implements the name lookup behavior
1152 // of C++ [temp.local]p8.
1153 Ctx = OutsideOfTemplateParamDC;
1154 OutsideOfTemplateParamDC = nullptr;
1155 }
1156
1157 if (Ctx) {
1158 DeclContext *OuterCtx;
1159 bool SearchAfterTemplateScope;
1160 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1161 if (SearchAfterTemplateScope)
1162 OutsideOfTemplateParamDC = OuterCtx;
1163
1164 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1165 // We do not directly look into transparent contexts, since
1166 // those entities will be found in the nearest enclosing
1167 // non-transparent context.
1168 if (Ctx->isTransparentContext())
1169 continue;
1170
1171 // We do not look directly into function or method contexts,
1172 // since all of the local variables and parameters of the
1173 // function/method are present within the Scope.
1174 if (Ctx->isFunctionOrMethod()) {
1175 // If we have an Objective-C instance method, look for ivars
1176 // in the corresponding interface.
1177 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
1178 if (Method->isInstanceMethod() && Name.getAsIdentifierInfo())
1179 if (ObjCInterfaceDecl *Class = Method->getClassInterface()) {
1180 ObjCInterfaceDecl *ClassDeclared;
1181 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(
1182 Name.getAsIdentifierInfo(),
1183 ClassDeclared)) {
1184 if (NamedDecl *ND = R.getAcceptableDecl(Ivar)) {
1185 R.addDecl(ND);
1186 R.resolveKind();
1187 return true;
1188 }
1189 }
1190 }
1191 }
1192
1193 continue;
1194 }
1195
1196 // If this is a file context, we need to perform unqualified name
1197 // lookup considering using directives.
1198 if (Ctx->isFileContext()) {
1199 // If we haven't handled using directives yet, do so now.
1200 if (!VisitedUsingDirectives) {
1201 // Add using directives from this context up to the top level.
1202 for (DeclContext *UCtx = Ctx; UCtx; UCtx = UCtx->getParent()) {
1203 if (UCtx->isTransparentContext())
1204 continue;
1205
1206 UDirs.visit(UCtx, UCtx);
1207 }
1208
1209 // Find the innermost file scope, so we can add using directives
1210 // from local scopes.
1211 Scope *InnermostFileScope = S;
1212 while (InnermostFileScope &&
1213 !isNamespaceOrTranslationUnitScope(InnermostFileScope))
1214 InnermostFileScope = InnermostFileScope->getParent();
1215 UDirs.visitScopeChain(Initial, InnermostFileScope);
1216
1217 UDirs.done();
1218
1219 VisitedUsingDirectives = true;
1220 }
1221
1222 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs)) {
1223 R.resolveKind();
1224 return true;
1225 }
1226
1227 continue;
1228 }
1229
1230 // Perform qualified name lookup into this context.
1231 // FIXME: In some cases, we know that every name that could be found by
1232 // this qualified name lookup will also be on the identifier chain. For
1233 // example, inside a class without any base classes, we never need to
1234 // perform qualified lookup because all of the members are on top of the
1235 // identifier chain.
1236 if (LookupQualifiedName(R, Ctx, /*InUnqualifiedLookup=*/true))
1237 return true;
1238 }
1239 }
1240 }
1241
1242 // Stop if we ran out of scopes.
1243 // FIXME: This really, really shouldn't be happening.
1244 if (!S) return false;
1245
1246 // If we are looking for members, no need to look into global/namespace scope.
1247 if (NameKind == LookupMemberName)
1248 return false;
1249
1250 // Collect UsingDirectiveDecls in all scopes, and recursively all
1251 // nominated namespaces by those using-directives.
1252 //
1253 // FIXME: Cache this sorted list in Scope structure, and DeclContext, so we
1254 // don't build it for each lookup!
1255 if (!VisitedUsingDirectives) {
1256 UDirs.visitScopeChain(Initial, S);
1257 UDirs.done();
1258 }
1259
1260 // If we're not performing redeclaration lookup, do not look for local
1261 // extern declarations outside of a function scope.
1262 if (!R.isForRedeclaration())
1263 FindLocals.restore();
1264
1265 // Lookup namespace scope, and global scope.
1266 // Unqualified name lookup in C++ requires looking into scopes
1267 // that aren't strictly lexical, and therefore we walk through the
1268 // context as well as walking through the scopes.
1269 for (; S; S = S->getParent()) {
1270 // Check whether the IdResolver has anything in this scope.
1271 bool Found = false;
1272 for (; I != IEnd && S->isDeclScope(*I); ++I) {
1273 if (NamedDecl *ND = R.getAcceptableDecl(*I)) {
1274 // We found something. Look for anything else in our scope
1275 // with this same name and in an acceptable identifier
1276 // namespace, so that we can construct an overload set if we
1277 // need to.
1278 Found = true;
1279 R.addDecl(ND);
1280 }
1281 }
1282
1283 if (Found && S->isTemplateParamScope()) {
1284 R.resolveKind();
1285 return true;
1286 }
1287
1288 DeclContext *Ctx = S->getEntity();
1289 if (!Ctx && S->isTemplateParamScope() && OutsideOfTemplateParamDC &&
1290 S->getParent() && !S->getParent()->isTemplateParamScope()) {
1291 // We've just searched the last template parameter scope and
1292 // found nothing, so look into the contexts between the
1293 // lexical and semantic declaration contexts returned by
1294 // findOuterContext(). This implements the name lookup behavior
1295 // of C++ [temp.local]p8.
1296 Ctx = OutsideOfTemplateParamDC;
1297 OutsideOfTemplateParamDC = nullptr;
1298 }
1299
1300 if (Ctx) {
1301 DeclContext *OuterCtx;
1302 bool SearchAfterTemplateScope;
1303 std::tie(OuterCtx, SearchAfterTemplateScope) = findOuterContext(S);
1304 if (SearchAfterTemplateScope)
1305 OutsideOfTemplateParamDC = OuterCtx;
1306
1307 for (; Ctx && !Ctx->Equals(OuterCtx); Ctx = Ctx->getLookupParent()) {
1308 // We do not directly look into transparent contexts, since
1309 // those entities will be found in the nearest enclosing
1310 // non-transparent context.
1311 if (Ctx->isTransparentContext())
1312 continue;
1313
1314 // If we have a context, and it's not a context stashed in the
1315 // template parameter scope for an out-of-line definition, also
1316 // look into that context.
1317 if (!(Found && S->isTemplateParamScope())) {
1318 assert(Ctx->isFileContext() &&((Ctx->isFileContext() && "We should have been looking only at file context here already."
) ? static_cast<void> (0) : __assert_fail ("Ctx->isFileContext() && \"We should have been looking only at file context here already.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1319, __PRETTY_FUNCTION__))
1319 "We should have been looking only at file context here already.")((Ctx->isFileContext() && "We should have been looking only at file context here already."
) ? static_cast<void> (0) : __assert_fail ("Ctx->isFileContext() && \"We should have been looking only at file context here already.\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1319, __PRETTY_FUNCTION__))
;
1320
1321 // Look into context considering using-directives.
1322 if (CppNamespaceLookup(*this, R, Context, Ctx, UDirs))
1323 Found = true;
1324 }
1325
1326 if (Found) {
1327 R.resolveKind();
1328 return true;
1329 }
1330
1331 if (R.isForRedeclaration() && !Ctx->isTransparentContext())
1332 return false;
1333 }
1334 }
1335
1336 if (R.isForRedeclaration() && Ctx && !Ctx->isTransparentContext())
1337 return false;
1338 }
1339
1340 return !R.empty();
1341}
1342
1343void Sema::makeMergedDefinitionVisible(NamedDecl *ND) {
1344 if (auto *M = getCurrentModule())
1345 Context.mergeDefinitionIntoModule(ND, M);
1346 else
1347 // We're not building a module; just make the definition visible.
1348 ND->setVisibleDespiteOwningModule();
1349
1350 // If ND is a template declaration, make the template parameters
1351 // visible too. They're not (necessarily) within a mergeable DeclContext.
1352 if (auto *TD = dyn_cast<TemplateDecl>(ND))
1353 for (auto *Param : *TD->getTemplateParameters())
1354 makeMergedDefinitionVisible(Param);
1355}
1356
1357/// \brief Find the module in which the given declaration was defined.
1358static Module *getDefiningModule(Sema &S, Decl *Entity) {
1359 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Entity)) {
1360 // If this function was instantiated from a template, the defining module is
1361 // the module containing the pattern.
1362 if (FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
1363 Entity = Pattern;
1364 } else if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Entity)) {
1365 if (CXXRecordDecl *Pattern = RD->getTemplateInstantiationPattern())
1366 Entity = Pattern;
1367 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(Entity)) {
1368 if (auto *Pattern = ED->getTemplateInstantiationPattern())
1369 Entity = Pattern;
1370 } else if (VarDecl *VD = dyn_cast<VarDecl>(Entity)) {
1371 if (VarDecl *Pattern = VD->getTemplateInstantiationPattern())
1372 Entity = Pattern;
1373 }
1374
1375 // Walk up to the containing context. That might also have been instantiated
1376 // from a template.
1377 DeclContext *Context = Entity->getLexicalDeclContext();
1378 if (Context->isFileContext())
1379 return S.getOwningModule(Entity);
1380 return getDefiningModule(S, cast<Decl>(Context));
1381}
1382
1383llvm::DenseSet<Module*> &Sema::getLookupModules() {
1384 unsigned N = CodeSynthesisContexts.size();
1385 for (unsigned I = CodeSynthesisContextLookupModules.size();
1386 I != N; ++I) {
1387 Module *M = getDefiningModule(*this, CodeSynthesisContexts[I].Entity);
1388 if (M && !LookupModulesCache.insert(M).second)
1389 M = nullptr;
1390 CodeSynthesisContextLookupModules.push_back(M);
1391 }
1392 return LookupModulesCache;
1393}
1394
1395bool Sema::hasVisibleMergedDefinition(NamedDecl *Def) {
1396 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1397 if (isModuleVisible(Merged))
1398 return true;
1399 return false;
1400}
1401
1402bool Sema::hasMergedDefinitionInCurrentModule(NamedDecl *Def) {
1403 // FIXME: When not in local visibility mode, we can't tell the difference
1404 // between a declaration being visible because we merged a local copy of
1405 // the same declaration into it, and it being visible because its owning
1406 // module is visible.
1407 if (Def->getModuleOwnershipKind() == Decl::ModuleOwnershipKind::Visible &&
1408 getLangOpts().ModulesLocalVisibility)
1409 return true;
1410 for (Module *Merged : Context.getModulesWithMergedDefinition(Def))
1411 if (Merged->getTopLevelModuleName() == getLangOpts().CurrentModule)
1412 return true;
1413 return false;
1414}
1415
1416template<typename ParmDecl>
1417static bool
1418hasVisibleDefaultArgument(Sema &S, const ParmDecl *D,
1419 llvm::SmallVectorImpl<Module *> *Modules) {
1420 if (!D->hasDefaultArgument())
1421 return false;
1422
1423 while (D) {
1424 auto &DefaultArg = D->getDefaultArgStorage();
1425 if (!DefaultArg.isInherited() && S.isVisible(D))
1426 return true;
1427
1428 if (!DefaultArg.isInherited() && Modules) {
1429 auto *NonConstD = const_cast<ParmDecl*>(D);
1430 Modules->push_back(S.getOwningModule(NonConstD));
1431 const auto &Merged = S.Context.getModulesWithMergedDefinition(NonConstD);
1432 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1433 }
1434
1435 // If there was a previous default argument, maybe its parameter is visible.
1436 D = DefaultArg.getInheritedFrom();
1437 }
1438 return false;
1439}
1440
1441bool Sema::hasVisibleDefaultArgument(const NamedDecl *D,
1442 llvm::SmallVectorImpl<Module *> *Modules) {
1443 if (auto *P = dyn_cast<TemplateTypeParmDecl>(D))
1444 return ::hasVisibleDefaultArgument(*this, P, Modules);
1445 if (auto *P = dyn_cast<NonTypeTemplateParmDecl>(D))
1446 return ::hasVisibleDefaultArgument(*this, P, Modules);
1447 return ::hasVisibleDefaultArgument(*this, cast<TemplateTemplateParmDecl>(D),
1448 Modules);
1449}
1450
1451template<typename Filter>
1452static bool hasVisibleDeclarationImpl(Sema &S, const NamedDecl *D,
1453 llvm::SmallVectorImpl<Module *> *Modules,
1454 Filter F) {
1455 for (auto *Redecl : D->redecls()) {
1456 auto *R = cast<NamedDecl>(Redecl);
1457 if (!F(R))
1458 continue;
1459
1460 if (S.isVisible(R))
1461 return true;
1462
1463 if (Modules) {
1464 Modules->push_back(R->getOwningModule());
1465 const auto &Merged = S.Context.getModulesWithMergedDefinition(R);
1466 Modules->insert(Modules->end(), Merged.begin(), Merged.end());
1467 }
1468 }
1469
1470 return false;
1471}
1472
1473bool Sema::hasVisibleExplicitSpecialization(
1474 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1475 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1476 if (auto *RD = dyn_cast<CXXRecordDecl>(D))
1477 return RD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1478 if (auto *FD = dyn_cast<FunctionDecl>(D))
1479 return FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1480 if (auto *VD = dyn_cast<VarDecl>(D))
1481 return VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization;
1482 llvm_unreachable("unknown explicit specialization kind")::llvm::llvm_unreachable_internal("unknown explicit specialization kind"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1482)
;
1483 });
1484}
1485
1486bool Sema::hasVisibleMemberSpecialization(
1487 const NamedDecl *D, llvm::SmallVectorImpl<Module *> *Modules) {
1488 assert(isa<CXXRecordDecl>(D->getDeclContext()) &&((isa<CXXRecordDecl>(D->getDeclContext()) &&
"not a member specialization") ? static_cast<void> (0)
: __assert_fail ("isa<CXXRecordDecl>(D->getDeclContext()) && \"not a member specialization\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1489, __PRETTY_FUNCTION__))
1489 "not a member specialization")((isa<CXXRecordDecl>(D->getDeclContext()) &&
"not a member specialization") ? static_cast<void> (0)
: __assert_fail ("isa<CXXRecordDecl>(D->getDeclContext()) && \"not a member specialization\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1489, __PRETTY_FUNCTION__))
;
1490 return hasVisibleDeclarationImpl(*this, D, Modules, [](const NamedDecl *D) {
1491 // If the specialization is declared at namespace scope, then it's a member
1492 // specialization declaration. If it's lexically inside the class
1493 // definition then it was instantiated.
1494 //
1495 // FIXME: This is a hack. There should be a better way to determine this.
1496 // FIXME: What about MS-style explicit specializations declared within a
1497 // class definition?
1498 return D->getLexicalDeclContext()->isFileContext();
1499 });
1500
1501 return false;
1502}
1503
1504/// \brief Determine whether a declaration is visible to name lookup.
1505///
1506/// This routine determines whether the declaration D is visible in the current
1507/// lookup context, taking into account the current template instantiation
1508/// stack. During template instantiation, a declaration is visible if it is
1509/// visible from a module containing any entity on the template instantiation
1510/// path (by instantiating a template, you allow it to see the declarations that
1511/// your module can see, including those later on in your module).
1512bool LookupResult::isVisibleSlow(Sema &SemaRef, NamedDecl *D) {
1513 assert(D->isHidden() && "should not call this: not in slow case")((D->isHidden() && "should not call this: not in slow case"
) ? static_cast<void> (0) : __assert_fail ("D->isHidden() && \"should not call this: not in slow case\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1513, __PRETTY_FUNCTION__))
;
1514
1515 Module *DeclModule = SemaRef.getOwningModule(D);
1516 if (!DeclModule) {
1517 // A module-private declaration with no owning module means this is in the
1518 // global module in the C++ Modules TS. This is visible within the same
1519 // translation unit only.
1520 // FIXME: Don't assume that "same translation unit" means the same thing
1521 // as "not from an AST file".
1522 assert(D->isModulePrivate() && "hidden decl has no module")((D->isModulePrivate() && "hidden decl has no module"
) ? static_cast<void> (0) : __assert_fail ("D->isModulePrivate() && \"hidden decl has no module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1522, __PRETTY_FUNCTION__))
;
1523 if (!D->isFromASTFile() || SemaRef.hasMergedDefinitionInCurrentModule(D))
1524 return true;
1525 } else {
1526 // If the owning module is visible, and the decl is not module private,
1527 // then the decl is visible too. (Module private is ignored within the same
1528 // top-level module.)
1529 if (D->isModulePrivate()
1530 ? DeclModule->getTopLevelModuleName() ==
1531 SemaRef.getLangOpts().CurrentModule ||
1532 SemaRef.hasMergedDefinitionInCurrentModule(D)
1533 : SemaRef.isModuleVisible(DeclModule) ||
1534 SemaRef.hasVisibleMergedDefinition(D))
1535 return true;
1536 }
1537
1538 // Determine whether a decl context is a file context for the purpose of
1539 // visibility. This looks through some (export and linkage spec) transparent
1540 // contexts, but not others (enums).
1541 auto IsEffectivelyFileContext = [](const DeclContext *DC) {
1542 return DC->isFileContext() || isa<LinkageSpecDecl>(DC) ||
1543 isa<ExportDecl>(DC);
1544 };
1545
1546 // If this declaration is not at namespace scope
1547 // then it is visible if its lexical parent has a visible definition.
1548 DeclContext *DC = D->getLexicalDeclContext();
1549 if (DC && !IsEffectivelyFileContext(DC)) {
1550 // For a parameter, check whether our current template declaration's
1551 // lexical context is visible, not whether there's some other visible
1552 // definition of it, because parameters aren't "within" the definition.
1553 //
1554 // In C++ we need to check for a visible definition due to ODR merging,
1555 // and in C we must not because each declaration of a function gets its own
1556 // set of declarations for tags in prototype scope.
1557 bool VisibleWithinParent;
1558 if (D->isTemplateParameter() || isa<ParmVarDecl>(D) ||
1559 (isa<FunctionDecl>(DC) && !SemaRef.getLangOpts().CPlusPlus))
1560 VisibleWithinParent = isVisible(SemaRef, cast<NamedDecl>(DC));
1561 else if (D->isModulePrivate()) {
1562 // A module-private declaration is only visible if an enclosing lexical
1563 // parent was merged with another definition in the current module.
1564 VisibleWithinParent = false;
1565 do {
1566 if (SemaRef.hasMergedDefinitionInCurrentModule(cast<NamedDecl>(DC))) {
1567 VisibleWithinParent = true;
1568 break;
1569 }
1570 DC = DC->getLexicalParent();
1571 } while (!IsEffectivelyFileContext(DC));
1572 } else {
1573 VisibleWithinParent = SemaRef.hasVisibleDefinition(cast<NamedDecl>(DC));
1574 }
1575
1576 if (VisibleWithinParent && SemaRef.CodeSynthesisContexts.empty() &&
1577 // FIXME: Do something better in this case.
1578 !SemaRef.getLangOpts().ModulesLocalVisibility) {
1579 // Cache the fact that this declaration is implicitly visible because
1580 // its parent has a visible definition.
1581 D->setVisibleDespiteOwningModule();
1582 }
1583 return VisibleWithinParent;
1584 }
1585
1586 // FIXME: All uses of DeclModule below this point should also check merged
1587 // modules.
1588 if (!DeclModule)
1589 return false;
1590
1591 // Find the extra places where we need to look.
1592 llvm::DenseSet<Module*> &LookupModules = SemaRef.getLookupModules();
1593 if (LookupModules.empty())
1594 return false;
1595
1596 // If our lookup set contains the decl's module, it's visible.
1597 if (LookupModules.count(DeclModule))
1598 return true;
1599
1600 // If the declaration isn't exported, it's not visible in any other module.
1601 if (D->isModulePrivate())
1602 return false;
1603
1604 // Check whether DeclModule is transitively exported to an import of
1605 // the lookup set.
1606 return std::any_of(LookupModules.begin(), LookupModules.end(),
1607 [&](Module *M) { return M->isModuleVisible(DeclModule); });
1608}
1609
1610bool Sema::isVisibleSlow(const NamedDecl *D) {
1611 return LookupResult::isVisible(*this, const_cast<NamedDecl*>(D));
1612}
1613
1614bool Sema::shouldLinkPossiblyHiddenDecl(LookupResult &R, const NamedDecl *New) {
1615 // FIXME: If there are both visible and hidden declarations, we need to take
1616 // into account whether redeclaration is possible. Example:
1617 //
1618 // Non-imported module:
1619 // int f(T); // #1
1620 // Some TU:
1621 // static int f(U); // #2, not a redeclaration of #1
1622 // int f(T); // #3, finds both, should link with #1 if T != U, but
1623 // // with #2 if T == U; neither should be ambiguous.
1624 for (auto *D : R) {
1625 if (isVisible(D))
1626 return true;
1627 assert(D->isExternallyDeclarable() &&((D->isExternallyDeclarable() && "should not have hidden, non-externally-declarable result here"
) ? static_cast<void> (0) : __assert_fail ("D->isExternallyDeclarable() && \"should not have hidden, non-externally-declarable result here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1628, __PRETTY_FUNCTION__))
1628 "should not have hidden, non-externally-declarable result here")((D->isExternallyDeclarable() && "should not have hidden, non-externally-declarable result here"
) ? static_cast<void> (0) : __assert_fail ("D->isExternallyDeclarable() && \"should not have hidden, non-externally-declarable result here\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1628, __PRETTY_FUNCTION__))
;
1629 }
1630
1631 // This function is called once "New" is essentially complete, but before a
1632 // previous declaration is attached. We can't query the linkage of "New" in
1633 // general, because attaching the previous declaration can change the
1634 // linkage of New to match the previous declaration.
1635 //
1636 // However, because we've just determined that there is no *visible* prior
1637 // declaration, we can compute the linkage here. There are two possibilities:
1638 //
1639 // * This is not a redeclaration; it's safe to compute the linkage now.
1640 //
1641 // * This is a redeclaration of a prior declaration that is externally
1642 // redeclarable. In that case, the linkage of the declaration is not
1643 // changed by attaching the prior declaration, because both are externally
1644 // declarable (and thus ExternalLinkage or VisibleNoLinkage).
1645 //
1646 // FIXME: This is subtle and fragile.
1647 return New->isExternallyDeclarable();
1648}
1649
1650/// \brief Retrieve the visible declaration corresponding to D, if any.
1651///
1652/// This routine determines whether the declaration D is visible in the current
1653/// module, with the current imports. If not, it checks whether any
1654/// redeclaration of D is visible, and if so, returns that declaration.
1655///
1656/// \returns D, or a visible previous declaration of D, whichever is more recent
1657/// and visible. If no declaration of D is visible, returns null.
1658static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
1659 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case")((!LookupResult::isVisible(SemaRef, D) && "not in slow case"
) ? static_cast<void> (0) : __assert_fail ("!LookupResult::isVisible(SemaRef, D) && \"not in slow case\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1659, __PRETTY_FUNCTION__))
;
1660
1661 for (auto RD : D->redecls()) {
1662 // Don't bother with extra checks if we already know this one isn't visible.
1663 if (RD == D)
1664 continue;
1665
1666 auto ND = cast<NamedDecl>(RD);
1667 // FIXME: This is wrong in the case where the previous declaration is not
1668 // visible in the same scope as D. This needs to be done much more
1669 // carefully.
1670 if (LookupResult::isVisible(SemaRef, ND))
1671 return ND;
1672 }
1673
1674 return nullptr;
1675}
1676
1677bool Sema::hasVisibleDeclarationSlow(const NamedDecl *D,
1678 llvm::SmallVectorImpl<Module *> *Modules) {
1679 assert(!isVisible(D) && "not in slow case")((!isVisible(D) && "not in slow case") ? static_cast<
void> (0) : __assert_fail ("!isVisible(D) && \"not in slow case\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1679, __PRETTY_FUNCTION__))
;
1680 return hasVisibleDeclarationImpl(*this, D, Modules,
1681 [](const NamedDecl *) { return true; });
1682}
1683
1684NamedDecl *LookupResult::getAcceptableDeclSlow(NamedDecl *D) const {
1685 if (auto *ND = dyn_cast<NamespaceDecl>(D)) {
1686 // Namespaces are a bit of a special case: we expect there to be a lot of
1687 // redeclarations of some namespaces, all declarations of a namespace are
1688 // essentially interchangeable, all declarations are found by name lookup
1689 // if any is, and namespaces are never looked up during template
1690 // instantiation. So we benefit from caching the check in this case, and
1691 // it is correct to do so.
1692 auto *Key = ND->getCanonicalDecl();
1693 if (auto *Acceptable = getSema().VisibleNamespaceCache.lookup(Key))
1694 return Acceptable;
1695 auto *Acceptable =
1696 isVisible(getSema(), Key) ? Key : findAcceptableDecl(getSema(), Key);
1697 if (Acceptable)
1698 getSema().VisibleNamespaceCache.insert(std::make_pair(Key, Acceptable));
1699 return Acceptable;
1700 }
1701
1702 return findAcceptableDecl(getSema(), D);
1703}
1704
1705/// @brief Perform unqualified name lookup starting from a given
1706/// scope.
1707///
1708/// Unqualified name lookup (C++ [basic.lookup.unqual], C99 6.2.1) is
1709/// used to find names within the current scope. For example, 'x' in
1710/// @code
1711/// int x;
1712/// int f() {
1713/// return x; // unqualified name look finds 'x' in the global scope
1714/// }
1715/// @endcode
1716///
1717/// Different lookup criteria can find different names. For example, a
1718/// particular scope can have both a struct and a function of the same
1719/// name, and each can be found by certain lookup criteria. For more
1720/// information about lookup criteria, see the documentation for the
1721/// class LookupCriteria.
1722///
1723/// @param S The scope from which unqualified name lookup will
1724/// begin. If the lookup criteria permits, name lookup may also search
1725/// in the parent scopes.
1726///
1727/// @param [in,out] R Specifies the lookup to perform (e.g., the name to
1728/// look up and the lookup kind), and is updated with the results of lookup
1729/// including zero or more declarations and possibly additional information
1730/// used to diagnose ambiguities.
1731///
1732/// @returns \c true if lookup succeeded and false otherwise.
1733bool Sema::LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation) {
1734 DeclarationName Name = R.getLookupName();
1735 if (!Name) return false;
1736
1737 LookupNameKind NameKind = R.getLookupKind();
1738
1739 if (!getLangOpts().CPlusPlus) {
1740 // Unqualified name lookup in C/Objective-C is purely lexical, so
1741 // search in the declarations attached to the name.
1742 if (NameKind == Sema::LookupRedeclarationWithLinkage) {
1743 // Find the nearest non-transparent declaration scope.
1744 while (!(S->getFlags() & Scope::DeclScope) ||
1745 (S->getEntity() && S->getEntity()->isTransparentContext()))
1746 S = S->getParent();
1747 }
1748
1749 // When performing a scope lookup, we want to find local extern decls.
1750 FindLocalExternScope FindLocals(R);
1751
1752 // Scan up the scope chain looking for a decl that matches this
1753 // identifier that is in the appropriate namespace. This search
1754 // should not take long, as shadowing of names is uncommon, and
1755 // deep shadowing is extremely uncommon.
1756 bool LeftStartingScope = false;
1757
1758 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1759 IEnd = IdResolver.end();
1760 I != IEnd; ++I)
1761 if (NamedDecl *D = R.getAcceptableDecl(*I)) {
1762 if (NameKind == LookupRedeclarationWithLinkage) {
1763 // Determine whether this (or a previous) declaration is
1764 // out-of-scope.
1765 if (!LeftStartingScope && !S->isDeclScope(*I))
1766 LeftStartingScope = true;
1767
1768 // If we found something outside of our starting scope that
1769 // does not have linkage, skip it.
1770 if (LeftStartingScope && !((*I)->hasLinkage())) {
1771 R.setShadowed();
1772 continue;
1773 }
1774 }
1775 else if (NameKind == LookupObjCImplicitSelfParam &&
1776 !isa<ImplicitParamDecl>(*I))
1777 continue;
1778
1779 R.addDecl(D);
1780
1781 // Check whether there are any other declarations with the same name
1782 // and in the same scope.
1783 if (I != IEnd) {
1784 // Find the scope in which this declaration was declared (if it
1785 // actually exists in a Scope).
1786 while (S && !S->isDeclScope(D))
1787 S = S->getParent();
1788
1789 // If the scope containing the declaration is the translation unit,
1790 // then we'll need to perform our checks based on the matching
1791 // DeclContexts rather than matching scopes.
1792 if (S && isNamespaceOrTranslationUnitScope(S))
1793 S = nullptr;
1794
1795 // Compute the DeclContext, if we need it.
1796 DeclContext *DC = nullptr;
1797 if (!S)
1798 DC = (*I)->getDeclContext()->getRedeclContext();
1799
1800 IdentifierResolver::iterator LastI = I;
1801 for (++LastI; LastI != IEnd; ++LastI) {
1802 if (S) {
1803 // Match based on scope.
1804 if (!S->isDeclScope(*LastI))
1805 break;
1806 } else {
1807 // Match based on DeclContext.
1808 DeclContext *LastDC
1809 = (*LastI)->getDeclContext()->getRedeclContext();
1810 if (!LastDC->Equals(DC))
1811 break;
1812 }
1813
1814 // If the declaration is in the right namespace and visible, add it.
1815 if (NamedDecl *LastD = R.getAcceptableDecl(*LastI))
1816 R.addDecl(LastD);
1817 }
1818
1819 R.resolveKind();
1820 }
1821
1822 return true;
1823 }
1824 } else {
1825 // Perform C++ unqualified name lookup.
1826 if (CppLookupName(R, S))
1827 return true;
1828 }
1829
1830 // If we didn't find a use of this identifier, and if the identifier
1831 // corresponds to a compiler builtin, create the decl object for the builtin
1832 // now, injecting it into translation unit scope, and return it.
1833 if (AllowBuiltinCreation && LookupBuiltin(*this, R))
1834 return true;
1835
1836 // If we didn't find a use of this identifier, the ExternalSource
1837 // may be able to handle the situation.
1838 // Note: some lookup failures are expected!
1839 // See e.g. R.isForRedeclaration().
1840 return (ExternalSource && ExternalSource->LookupUnqualified(R, S));
1841}
1842
1843/// @brief Perform qualified name lookup in the namespaces nominated by
1844/// using directives by the given context.
1845///
1846/// C++98 [namespace.qual]p2:
1847/// Given X::m (where X is a user-declared namespace), or given \::m
1848/// (where X is the global namespace), let S be the set of all
1849/// declarations of m in X and in the transitive closure of all
1850/// namespaces nominated by using-directives in X and its used
1851/// namespaces, except that using-directives are ignored in any
1852/// namespace, including X, directly containing one or more
1853/// declarations of m. No namespace is searched more than once in
1854/// the lookup of a name. If S is the empty set, the program is
1855/// ill-formed. Otherwise, if S has exactly one member, or if the
1856/// context of the reference is a using-declaration
1857/// (namespace.udecl), S is the required set of declarations of
1858/// m. Otherwise if the use of m is not one that allows a unique
1859/// declaration to be chosen from S, the program is ill-formed.
1860///
1861/// C++98 [namespace.qual]p5:
1862/// During the lookup of a qualified namespace member name, if the
1863/// lookup finds more than one declaration of the member, and if one
1864/// declaration introduces a class name or enumeration name and the
1865/// other declarations either introduce the same object, the same
1866/// enumerator or a set of functions, the non-type name hides the
1867/// class or enumeration name if and only if the declarations are
1868/// from the same namespace; otherwise (the declarations are from
1869/// different namespaces), the program is ill-formed.
1870static bool LookupQualifiedNameInUsingDirectives(Sema &S, LookupResult &R,
1871 DeclContext *StartDC) {
1872 assert(StartDC->isFileContext() && "start context is not a file context")((StartDC->isFileContext() && "start context is not a file context"
) ? static_cast<void> (0) : __assert_fail ("StartDC->isFileContext() && \"start context is not a file context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1872, __PRETTY_FUNCTION__))
;
1873
1874 // We have not yet looked into these namespaces, much less added
1875 // their "using-children" to the queue.
1876 SmallVector<NamespaceDecl*, 8> Queue;
1877
1878 // We have at least added all these contexts to the queue.
1879 llvm::SmallPtrSet<DeclContext*, 8> Visited;
1880 Visited.insert(StartDC);
1881
1882 // We have already looked into the initial namespace; seed the queue
1883 // with its using-children.
1884 for (auto *I : StartDC->using_directives()) {
1885 NamespaceDecl *ND = I->getNominatedNamespace()->getOriginalNamespace();
1886 if (S.isVisible(I) && Visited.insert(ND).second)
1887 Queue.push_back(ND);
1888 }
1889
1890 // The easiest way to implement the restriction in [namespace.qual]p5
1891 // is to check whether any of the individual results found a tag
1892 // and, if so, to declare an ambiguity if the final result is not
1893 // a tag.
1894 bool FoundTag = false;
1895 bool FoundNonTag = false;
1896
1897 LookupResult LocalR(LookupResult::Temporary, R);
1898
1899 bool Found = false;
1900 while (!Queue.empty()) {
1901 NamespaceDecl *ND = Queue.pop_back_val();
1902
1903 // We go through some convolutions here to avoid copying results
1904 // between LookupResults.
1905 bool UseLocal = !R.empty();
1906 LookupResult &DirectR = UseLocal ? LocalR : R;
1907 bool FoundDirect = LookupDirect(S, DirectR, ND);
1908
1909 if (FoundDirect) {
1910 // First do any local hiding.
1911 DirectR.resolveKind();
1912
1913 // If the local result is a tag, remember that.
1914 if (DirectR.isSingleTagDecl())
1915 FoundTag = true;
1916 else
1917 FoundNonTag = true;
1918
1919 // Append the local results to the total results if necessary.
1920 if (UseLocal) {
1921 R.addAllDecls(LocalR);
1922 LocalR.clear();
1923 }
1924 }
1925
1926 // If we find names in this namespace, ignore its using directives.
1927 if (FoundDirect) {
1928 Found = true;
1929 continue;
1930 }
1931
1932 for (auto I : ND->using_directives()) {
1933 NamespaceDecl *Nom = I->getNominatedNamespace();
1934 if (S.isVisible(I) && Visited.insert(Nom).second)
1935 Queue.push_back(Nom);
1936 }
1937 }
1938
1939 if (Found) {
1940 if (FoundTag && FoundNonTag)
1941 R.setAmbiguousQualifiedTagHiding();
1942 else
1943 R.resolveKind();
1944 }
1945
1946 return Found;
1947}
1948
1949/// \brief Callback that looks for any member of a class with the given name.
1950static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
1951 CXXBasePath &Path, DeclarationName Name) {
1952 RecordDecl *BaseRecord = Specifier->getType()->getAs<RecordType>()->getDecl();
1953
1954 Path.Decls = BaseRecord->lookup(Name);
1955 return !Path.Decls.empty();
1956}
1957
1958/// \brief Determine whether the given set of member declarations contains only
1959/// static members, nested types, and enumerators.
1960template<typename InputIterator>
1961static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
1962 Decl *D = (*First)->getUnderlyingDecl();
1963 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
1964 return true;
1965
1966 if (isa<CXXMethodDecl>(D)) {
1967 // Determine whether all of the methods are static.
1968 bool AllMethodsAreStatic = true;
1969 for(; First != Last; ++First) {
1970 D = (*First)->getUnderlyingDecl();
1971
1972 if (!isa<CXXMethodDecl>(D)) {
1973 assert(isa<TagDecl>(D) && "Non-function must be a tag decl")((isa<TagDecl>(D) && "Non-function must be a tag decl"
) ? static_cast<void> (0) : __assert_fail ("isa<TagDecl>(D) && \"Non-function must be a tag decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 1973, __PRETTY_FUNCTION__))
;
1974 break;
1975 }
1976
1977 if (!cast<CXXMethodDecl>(D)->isStatic()) {
1978 AllMethodsAreStatic = false;
1979 break;
1980 }
1981 }
1982
1983 if (AllMethodsAreStatic)
1984 return true;
1985 }
1986
1987 return false;
1988}
1989
1990/// \brief Perform qualified name lookup into a given context.
1991///
1992/// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
1993/// names when the context of those names is explicit specified, e.g.,
1994/// "std::vector" or "x->member", or as part of unqualified name lookup.
1995///
1996/// Different lookup criteria can find different names. For example, a
1997/// particular scope can have both a struct and a function of the same
1998/// name, and each can be found by certain lookup criteria. For more
1999/// information about lookup criteria, see the documentation for the
2000/// class LookupCriteria.
2001///
2002/// \param R captures both the lookup criteria and any lookup results found.
2003///
2004/// \param LookupCtx The context in which qualified name lookup will
2005/// search. If the lookup criteria permits, name lookup may also search
2006/// in the parent contexts or (for C++ classes) base classes.
2007///
2008/// \param InUnqualifiedLookup true if this is qualified name lookup that
2009/// occurs as part of unqualified name lookup.
2010///
2011/// \returns true if lookup succeeded, false if it failed.
2012bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2013 bool InUnqualifiedLookup) {
2014 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context")((LookupCtx && "Sema::LookupQualifiedName requires a lookup context"
) ? static_cast<void> (0) : __assert_fail ("LookupCtx && \"Sema::LookupQualifiedName requires a lookup context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2014, __PRETTY_FUNCTION__))
;
2015
2016 if (!R.getLookupName())
2017 return false;
2018
2019 // Make sure that the declaration context is complete.
2020 assert((!isa<TagDecl>(LookupCtx) ||(((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext
() || cast<TagDecl>(LookupCtx)->isCompleteDefinition
() || cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
"Declaration context must already be complete!") ? static_cast
<void> (0) : __assert_fail ("(!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && \"Declaration context must already be complete!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2024, __PRETTY_FUNCTION__))
2021 LookupCtx->isDependentContext() ||(((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext
() || cast<TagDecl>(LookupCtx)->isCompleteDefinition
() || cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
"Declaration context must already be complete!") ? static_cast
<void> (0) : __assert_fail ("(!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && \"Declaration context must already be complete!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2024, __PRETTY_FUNCTION__))
2022 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||(((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext
() || cast<TagDecl>(LookupCtx)->isCompleteDefinition
() || cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
"Declaration context must already be complete!") ? static_cast
<void> (0) : __assert_fail ("(!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && \"Declaration context must already be complete!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2024, __PRETTY_FUNCTION__))
2023 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&(((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext
() || cast<TagDecl>(LookupCtx)->isCompleteDefinition
() || cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
"Declaration context must already be complete!") ? static_cast
<void> (0) : __assert_fail ("(!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && \"Declaration context must already be complete!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2024, __PRETTY_FUNCTION__))
2024 "Declaration context must already be complete!")(((!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext
() || cast<TagDecl>(LookupCtx)->isCompleteDefinition
() || cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
"Declaration context must already be complete!") ? static_cast
<void> (0) : __assert_fail ("(!isa<TagDecl>(LookupCtx) || LookupCtx->isDependentContext() || cast<TagDecl>(LookupCtx)->isCompleteDefinition() || cast<TagDecl>(LookupCtx)->isBeingDefined()) && \"Declaration context must already be complete!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2024, __PRETTY_FUNCTION__))
;
2025
2026 struct QualifiedLookupInScope {
2027 bool oldVal;
2028 DeclContext *Context;
2029 // Set flag in DeclContext informing debugger that we're looking for qualified name
2030 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2031 oldVal = ctx->setUseQualifiedLookup();
2032 }
2033 ~QualifiedLookupInScope() {
2034 Context->setUseQualifiedLookup(oldVal);
2035 }
2036 } QL(LookupCtx);
2037
2038 if (LookupDirect(*this, R, LookupCtx)) {
2039 R.resolveKind();
2040 if (isa<CXXRecordDecl>(LookupCtx))
2041 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2042 return true;
2043 }
2044
2045 // Don't descend into implied contexts for redeclarations.
2046 // C++98 [namespace.qual]p6:
2047 // In a declaration for a namespace member in which the
2048 // declarator-id is a qualified-id, given that the qualified-id
2049 // for the namespace member has the form
2050 // nested-name-specifier unqualified-id
2051 // the unqualified-id shall name a member of the namespace
2052 // designated by the nested-name-specifier.
2053 // See also [class.mfct]p5 and [class.static.data]p2.
2054 if (R.isForRedeclaration())
2055 return false;
2056
2057 // If this is a namespace, look it up in the implied namespaces.
2058 if (LookupCtx->isFileContext())
2059 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2060
2061 // If this isn't a C++ class, we aren't allowed to look into base
2062 // classes, we're done.
2063 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2064 if (!LookupRec || !LookupRec->getDefinition())
2065 return false;
2066
2067 // If we're performing qualified name lookup into a dependent class,
2068 // then we are actually looking into a current instantiation. If we have any
2069 // dependent base classes, then we either have to delay lookup until
2070 // template instantiation time (at which point all bases will be available)
2071 // or we have to fail.
2072 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2073 LookupRec->hasAnyDependentBases()) {
2074 R.setNotFoundInCurrentInstantiation();
2075 return false;
2076 }
2077
2078 // Perform lookup into our base classes.
2079 CXXBasePaths Paths;
2080 Paths.setOrigin(LookupRec);
2081
2082 // Look for this member in our base classes
2083 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2084 DeclarationName Name) = nullptr;
2085 switch (R.getLookupKind()) {
2086 case LookupObjCImplicitSelfParam:
2087 case LookupOrdinaryName:
2088 case LookupMemberName:
2089 case LookupRedeclarationWithLinkage:
2090 case LookupLocalFriendName:
2091 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2092 break;
2093
2094 case LookupTagName:
2095 BaseCallback = &CXXRecordDecl::FindTagMember;
2096 break;
2097
2098 case LookupAnyName:
2099 BaseCallback = &LookupAnyMember;
2100 break;
2101
2102 case LookupOMPReductionName:
2103 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2104 break;
2105
2106 case LookupUsingDeclName:
2107 // This lookup is for redeclarations only.
2108
2109 case LookupOperatorName:
2110 case LookupNamespaceName:
2111 case LookupObjCProtocolName:
2112 case LookupLabel:
2113 // These lookups will never find a member in a C++ class (or base class).
2114 return false;
2115
2116 case LookupNestedNameSpecifierName:
2117 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2118 break;
2119 }
2120
2121 DeclarationName Name = R.getLookupName();
2122 if (!LookupRec->lookupInBases(
2123 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2124 return BaseCallback(Specifier, Path, Name);
2125 },
2126 Paths))
2127 return false;
2128
2129 R.setNamingClass(LookupRec);
2130
2131 // C++ [class.member.lookup]p2:
2132 // [...] If the resulting set of declarations are not all from
2133 // sub-objects of the same type, or the set has a nonstatic member
2134 // and includes members from distinct sub-objects, there is an
2135 // ambiguity and the program is ill-formed. Otherwise that set is
2136 // the result of the lookup.
2137 QualType SubobjectType;
2138 int SubobjectNumber = 0;
2139 AccessSpecifier SubobjectAccess = AS_none;
2140
2141 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2142 Path != PathEnd; ++Path) {
2143 const CXXBasePathElement &PathElement = Path->back();
2144
2145 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2146 // across all paths.
2147 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2148
2149 // Determine whether we're looking at a distinct sub-object or not.
2150 if (SubobjectType.isNull()) {
2151 // This is the first subobject we've looked at. Record its type.
2152 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2153 SubobjectNumber = PathElement.SubobjectNumber;
2154 continue;
2155 }
2156
2157 if (SubobjectType
2158 != Context.getCanonicalType(PathElement.Base->getType())) {
2159 // We found members of the given name in two subobjects of
2160 // different types. If the declaration sets aren't the same, this
2161 // lookup is ambiguous.
2162 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
2163 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
2164 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2165 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
2166
2167 while (FirstD != FirstPath->Decls.end() &&
2168 CurrentD != Path->Decls.end()) {
2169 if ((*FirstD)->getUnderlyingDecl()->getCanonicalDecl() !=
2170 (*CurrentD)->getUnderlyingDecl()->getCanonicalDecl())
2171 break;
2172
2173 ++FirstD;
2174 ++CurrentD;
2175 }
2176
2177 if (FirstD == FirstPath->Decls.end() &&
2178 CurrentD == Path->Decls.end())
2179 continue;
2180 }
2181
2182 R.setAmbiguousBaseSubobjectTypes(Paths);
2183 return true;
2184 }
2185
2186 if (SubobjectNumber != PathElement.SubobjectNumber) {
2187 // We have a different subobject of the same type.
2188
2189 // C++ [class.member.lookup]p5:
2190 // A static member, a nested type or an enumerator defined in
2191 // a base class T can unambiguously be found even if an object
2192 // has more than one base class subobject of type T.
2193 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
2194 continue;
2195
2196 // We have found a nonstatic member name in multiple, distinct
2197 // subobjects. Name lookup is ambiguous.
2198 R.setAmbiguousBaseSubobjects(Paths);
2199 return true;
2200 }
2201 }
2202
2203 // Lookup in a base class succeeded; return these results.
2204
2205 for (auto *D : Paths.front().Decls) {
2206 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2207 D->getAccess());
2208 R.addDecl(D, AS);
2209 }
2210 R.resolveKind();
2211 return true;
2212}
2213
2214/// \brief Performs qualified name lookup or special type of lookup for
2215/// "__super::" scope specifier.
2216///
2217/// This routine is a convenience overload meant to be called from contexts
2218/// that need to perform a qualified name lookup with an optional C++ scope
2219/// specifier that might require special kind of lookup.
2220///
2221/// \param R captures both the lookup criteria and any lookup results found.
2222///
2223/// \param LookupCtx The context in which qualified name lookup will
2224/// search.
2225///
2226/// \param SS An optional C++ scope-specifier.
2227///
2228/// \returns true if lookup succeeded, false if it failed.
2229bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2230 CXXScopeSpec &SS) {
2231 auto *NNS = SS.getScopeRep();
2232 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2233 return LookupInSuper(R, NNS->getAsRecordDecl());
2234 else
2235
2236 return LookupQualifiedName(R, LookupCtx);
2237}
2238
2239/// @brief Performs name lookup for a name that was parsed in the
2240/// source code, and may contain a C++ scope specifier.
2241///
2242/// This routine is a convenience routine meant to be called from
2243/// contexts that receive a name and an optional C++ scope specifier
2244/// (e.g., "N::M::x"). It will then perform either qualified or
2245/// unqualified name lookup (with LookupQualifiedName or LookupName,
2246/// respectively) on the given name and return those results. It will
2247/// perform a special type of lookup for "__super::" scope specifier.
2248///
2249/// @param S The scope from which unqualified name lookup will
2250/// begin.
2251///
2252/// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2253///
2254/// @param EnteringContext Indicates whether we are going to enter the
2255/// context of the scope-specifier SS (if present).
2256///
2257/// @returns True if any decls were found (but possibly ambiguous)
2258bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2259 bool AllowBuiltinCreation, bool EnteringContext) {
2260 if (SS && SS->isInvalid()) {
2261 // When the scope specifier is invalid, don't even look for
2262 // anything.
2263 return false;
2264 }
2265
2266 if (SS && SS->isSet()) {
2267 NestedNameSpecifier *NNS = SS->getScopeRep();
2268 if (NNS->getKind() == NestedNameSpecifier::Super)
2269 return LookupInSuper(R, NNS->getAsRecordDecl());
2270
2271 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2272 // We have resolved the scope specifier to a particular declaration
2273 // contex, and will perform name lookup in that context.
2274 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2275 return false;
2276
2277 R.setContextRange(SS->getRange());
2278 return LookupQualifiedName(R, DC);
2279 }
2280
2281 // We could not resolve the scope specified to a specific declaration
2282 // context, which means that SS refers to an unknown specialization.
2283 // Name lookup can't find anything in this case.
2284 R.setNotFoundInCurrentInstantiation();
2285 R.setContextRange(SS->getRange());
2286 return false;
2287 }
2288
2289 // Perform unqualified name lookup starting in the given scope.
2290 return LookupName(R, S, AllowBuiltinCreation);
2291}
2292
2293/// \brief Perform qualified name lookup into all base classes of the given
2294/// class.
2295///
2296/// \param R captures both the lookup criteria and any lookup results found.
2297///
2298/// \param Class The context in which qualified name lookup will
2299/// search. Name lookup will search in all base classes merging the results.
2300///
2301/// @returns True if any decls were found (but possibly ambiguous)
2302bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2303 // The access-control rules we use here are essentially the rules for
2304 // doing a lookup in Class that just magically skipped the direct
2305 // members of Class itself. That is, the naming class is Class, and the
2306 // access includes the access of the base.
2307 for (const auto &BaseSpec : Class->bases()) {
2308 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2309 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2310 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2311 Result.setBaseObjectType(Context.getRecordType(Class));
2312 LookupQualifiedName(Result, RD);
2313
2314 // Copy the lookup results into the target, merging the base's access into
2315 // the path access.
2316 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2317 R.addDecl(I.getDecl(),
2318 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2319 I.getAccess()));
2320 }
2321
2322 Result.suppressDiagnostics();
2323 }
2324
2325 R.resolveKind();
2326 R.setNamingClass(Class);
2327
2328 return !R.empty();
2329}
2330
2331/// \brief Produce a diagnostic describing the ambiguity that resulted
2332/// from name lookup.
2333///
2334/// \param Result The result of the ambiguous lookup to be diagnosed.
2335void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2336 assert(Result.isAmbiguous() && "Lookup result must be ambiguous")((Result.isAmbiguous() && "Lookup result must be ambiguous"
) ? static_cast<void> (0) : __assert_fail ("Result.isAmbiguous() && \"Lookup result must be ambiguous\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2336, __PRETTY_FUNCTION__))
;
2337
2338 DeclarationName Name = Result.getLookupName();
2339 SourceLocation NameLoc = Result.getNameLoc();
2340 SourceRange LookupRange = Result.getContextRange();
2341
2342 switch (Result.getAmbiguityKind()) {
2343 case LookupResult::AmbiguousBaseSubobjects: {
2344 CXXBasePaths *Paths = Result.getBasePaths();
2345 QualType SubobjectType = Paths->front().back().Base->getType();
2346 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2347 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2348 << LookupRange;
2349
2350 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
2351 while (isa<CXXMethodDecl>(*Found) &&
2352 cast<CXXMethodDecl>(*Found)->isStatic())
2353 ++Found;
2354
2355 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2356 break;
2357 }
2358
2359 case LookupResult::AmbiguousBaseSubobjectTypes: {
2360 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2361 << Name << LookupRange;
2362
2363 CXXBasePaths *Paths = Result.getBasePaths();
2364 std::set<Decl *> DeclsPrinted;
2365 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2366 PathEnd = Paths->end();
2367 Path != PathEnd; ++Path) {
2368 Decl *D = Path->Decls.front();
2369 if (DeclsPrinted.insert(D).second)
2370 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2371 }
2372 break;
2373 }
2374
2375 case LookupResult::AmbiguousTagHiding: {
2376 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2377
2378 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2379
2380 for (auto *D : Result)
2381 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2382 TagDecls.insert(TD);
2383 Diag(TD->getLocation(), diag::note_hidden_tag);
2384 }
2385
2386 for (auto *D : Result)
2387 if (!isa<TagDecl>(D))
2388 Diag(D->getLocation(), diag::note_hiding_object);
2389
2390 // For recovery purposes, go ahead and implement the hiding.
2391 LookupResult::Filter F = Result.makeFilter();
2392 while (F.hasNext()) {
2393 if (TagDecls.count(F.next()))
2394 F.erase();
2395 }
2396 F.done();
2397 break;
2398 }
2399
2400 case LookupResult::AmbiguousReference: {
2401 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2402
2403 for (auto *D : Result)
2404 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2405 break;
2406 }
2407 }
2408}
2409
2410namespace {
2411 struct AssociatedLookup {
2412 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2413 Sema::AssociatedNamespaceSet &Namespaces,
2414 Sema::AssociatedClassSet &Classes)
2415 : S(S), Namespaces(Namespaces), Classes(Classes),
2416 InstantiationLoc(InstantiationLoc) {
2417 }
2418
2419 Sema &S;
2420 Sema::AssociatedNamespaceSet &Namespaces;
2421 Sema::AssociatedClassSet &Classes;
2422 SourceLocation InstantiationLoc;
2423 };
2424} // end anonymous namespace
2425
2426static void
2427addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2428
2429static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2430 DeclContext *Ctx) {
2431 // Add the associated namespace for this class.
2432
2433 // We don't use DeclContext::getEnclosingNamespaceContext() as this may
2434 // be a locally scoped record.
2435
2436 // We skip out of inline namespaces. The innermost non-inline namespace
2437 // contains all names of all its nested inline namespaces anyway, so we can
2438 // replace the entire inline namespace tree with its root.
2439 while (Ctx->isRecord() || Ctx->isTransparentContext() ||
2440 Ctx->isInlineNamespace())
2441 Ctx = Ctx->getParent();
2442
2443 if (Ctx->isFileContext())
2444 Namespaces.insert(Ctx->getPrimaryContext());
2445}
2446
2447// \brief Add the associated classes and namespaces for argument-dependent
2448// lookup that involves a template argument (C++ [basic.lookup.koenig]p2).
2449static void
2450addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2451 const TemplateArgument &Arg) {
2452 // C++ [basic.lookup.koenig]p2, last bullet:
2453 // -- [...] ;
2454 switch (Arg.getKind()) {
2455 case TemplateArgument::Null:
2456 break;
2457
2458 case TemplateArgument::Type:
2459 // [...] the namespaces and classes associated with the types of the
2460 // template arguments provided for template type parameters (excluding
2461 // template template parameters)
2462 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2463 break;
2464
2465 case TemplateArgument::Template:
2466 case TemplateArgument::TemplateExpansion: {
2467 // [...] the namespaces in which any template template arguments are
2468 // defined; and the classes in which any member templates used as
2469 // template template arguments are defined.
2470 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2471 if (ClassTemplateDecl *ClassTemplate
2472 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2473 DeclContext *Ctx = ClassTemplate->getDeclContext();
2474 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2475 Result.Classes.insert(EnclosingClass);
2476 // Add the associated namespace for this class.
2477 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2478 }
2479 break;
2480 }
2481
2482 case TemplateArgument::Declaration:
2483 case TemplateArgument::Integral:
2484 case TemplateArgument::Expression:
2485 case TemplateArgument::NullPtr:
2486 // [Note: non-type template arguments do not contribute to the set of
2487 // associated namespaces. ]
2488 break;
2489
2490 case TemplateArgument::Pack:
2491 for (const auto &P : Arg.pack_elements())
2492 addAssociatedClassesAndNamespaces(Result, P);
2493 break;
2494 }
2495}
2496
2497// \brief Add the associated classes and namespaces for
2498// argument-dependent lookup with an argument of class type
2499// (C++ [basic.lookup.koenig]p2).
2500static void
2501addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2502 CXXRecordDecl *Class) {
2503
2504 // Just silently ignore anything whose name is __va_list_tag.
2505 if (Class->getDeclName() == Result.S.VAListTagName)
2506 return;
2507
2508 // C++ [basic.lookup.koenig]p2:
2509 // [...]
2510 // -- If T is a class type (including unions), its associated
2511 // classes are: the class itself; the class of which it is a
2512 // member, if any; and its direct and indirect base
2513 // classes. Its associated namespaces are the namespaces in
2514 // which its associated classes are defined.
2515
2516 // Add the class of which it is a member, if any.
2517 DeclContext *Ctx = Class->getDeclContext();
2518 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2519 Result.Classes.insert(EnclosingClass);
2520 // Add the associated namespace for this class.
2521 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2522
2523 // Add the class itself. If we've already seen this class, we don't
2524 // need to visit base classes.
2525 //
2526 // FIXME: That's not correct, we may have added this class only because it
2527 // was the enclosing class of another class, and in that case we won't have
2528 // added its base classes yet.
2529 if (!Result.Classes.insert(Class))
2530 return;
2531
2532 // -- If T is a template-id, its associated namespaces and classes are
2533 // the namespace in which the template is defined; for member
2534 // templates, the member template's class; the namespaces and classes
2535 // associated with the types of the template arguments provided for
2536 // template type parameters (excluding template template parameters); the
2537 // namespaces in which any template template arguments are defined; and
2538 // the classes in which any member templates used as template template
2539 // arguments are defined. [Note: non-type template arguments do not
2540 // contribute to the set of associated namespaces. ]
2541 if (ClassTemplateSpecializationDecl *Spec
2542 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2543 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2544 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2545 Result.Classes.insert(EnclosingClass);
2546 // Add the associated namespace for this class.
2547 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2548
2549 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2550 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2551 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2552 }
2553
2554 // Only recurse into base classes for complete types.
2555 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2556 Result.S.Context.getRecordType(Class)))
2557 return;
2558
2559 // Add direct and indirect base classes along with their associated
2560 // namespaces.
2561 SmallVector<CXXRecordDecl *, 32> Bases;
2562 Bases.push_back(Class);
2563 while (!Bases.empty()) {
2564 // Pop this class off the stack.
2565 Class = Bases.pop_back_val();
2566
2567 // Visit the base classes.
2568 for (const auto &Base : Class->bases()) {
2569 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2570 // In dependent contexts, we do ADL twice, and the first time around,
2571 // the base type might be a dependent TemplateSpecializationType, or a
2572 // TemplateTypeParmType. If that happens, simply ignore it.
2573 // FIXME: If we want to support export, we probably need to add the
2574 // namespace of the template in a TemplateSpecializationType, or even
2575 // the classes and namespaces of known non-dependent arguments.
2576 if (!BaseType)
2577 continue;
2578 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2579 if (Result.Classes.insert(BaseDecl)) {
2580 // Find the associated namespace for this base class.
2581 DeclContext *BaseCtx = BaseDecl->getDeclContext();
2582 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2583
2584 // Make sure we visit the bases of this base class.
2585 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2586 Bases.push_back(BaseDecl);
2587 }
2588 }
2589 }
2590}
2591
2592// \brief Add the associated classes and namespaces for
2593// argument-dependent lookup with an argument of type T
2594// (C++ [basic.lookup.koenig]p2).
2595static void
2596addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2597 // C++ [basic.lookup.koenig]p2:
2598 //
2599 // For each argument type T in the function call, there is a set
2600 // of zero or more associated namespaces and a set of zero or more
2601 // associated classes to be considered. The sets of namespaces and
2602 // classes is determined entirely by the types of the function
2603 // arguments (and the namespace of any template template
2604 // argument). Typedef names and using-declarations used to specify
2605 // the types do not contribute to this set. The sets of namespaces
2606 // and classes are determined in the following way:
2607
2608 SmallVector<const Type *, 16> Queue;
2609 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2610
2611 while (true) {
2612 switch (T->getTypeClass()) {
2613
2614#define TYPE(Class, Base)
2615#define DEPENDENT_TYPE(Class, Base) case Type::Class:
2616#define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2617#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2618#define ABSTRACT_TYPE(Class, Base)
2619#include "clang/AST/TypeNodes.def"
2620 // T is canonical. We can also ignore dependent types because
2621 // we don't need to do ADL at the definition point, but if we
2622 // wanted to implement template export (or if we find some other
2623 // use for associated classes and namespaces...) this would be
2624 // wrong.
2625 break;
2626
2627 // -- If T is a pointer to U or an array of U, its associated
2628 // namespaces and classes are those associated with U.
2629 case Type::Pointer:
2630 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2631 continue;
2632 case Type::ConstantArray:
2633 case Type::IncompleteArray:
2634 case Type::VariableArray:
2635 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2636 continue;
2637
2638 // -- If T is a fundamental type, its associated sets of
2639 // namespaces and classes are both empty.
2640 case Type::Builtin:
2641 break;
2642
2643 // -- If T is a class type (including unions), its associated
2644 // classes are: the class itself; the class of which it is a
2645 // member, if any; and its direct and indirect base
2646 // classes. Its associated namespaces are the namespaces in
2647 // which its associated classes are defined.
2648 case Type::Record: {
2649 CXXRecordDecl *Class =
2650 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2651 addAssociatedClassesAndNamespaces(Result, Class);
2652 break;
2653 }
2654
2655 // -- If T is an enumeration type, its associated namespace is
2656 // the namespace in which it is defined. If it is class
2657 // member, its associated class is the member's class; else
2658 // it has no associated class.
2659 case Type::Enum: {
2660 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2661
2662 DeclContext *Ctx = Enum->getDeclContext();
2663 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2664 Result.Classes.insert(EnclosingClass);
2665
2666 // Add the associated namespace for this class.
2667 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2668
2669 break;
2670 }
2671
2672 // -- If T is a function type, its associated namespaces and
2673 // classes are those associated with the function parameter
2674 // types and those associated with the return type.
2675 case Type::FunctionProto: {
2676 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2677 for (const auto &Arg : Proto->param_types())
2678 Queue.push_back(Arg.getTypePtr());
2679 // fallthrough
2680 LLVM_FALLTHROUGH[[clang::fallthrough]];
2681 }
2682 case Type::FunctionNoProto: {
2683 const FunctionType *FnType = cast<FunctionType>(T);
2684 T = FnType->getReturnType().getTypePtr();
2685 continue;
2686 }
2687
2688 // -- If T is a pointer to a member function of a class X, its
2689 // associated namespaces and classes are those associated
2690 // with the function parameter types and return type,
2691 // together with those associated with X.
2692 //
2693 // -- If T is a pointer to a data member of class X, its
2694 // associated namespaces and classes are those associated
2695 // with the member type together with those associated with
2696 // X.
2697 case Type::MemberPointer: {
2698 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2699
2700 // Queue up the class type into which this points.
2701 Queue.push_back(MemberPtr->getClass());
2702
2703 // And directly continue with the pointee type.
2704 T = MemberPtr->getPointeeType().getTypePtr();
2705 continue;
2706 }
2707
2708 // As an extension, treat this like a normal pointer.
2709 case Type::BlockPointer:
2710 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2711 continue;
2712
2713 // References aren't covered by the standard, but that's such an
2714 // obvious defect that we cover them anyway.
2715 case Type::LValueReference:
2716 case Type::RValueReference:
2717 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2718 continue;
2719
2720 // These are fundamental types.
2721 case Type::Vector:
2722 case Type::ExtVector:
2723 case Type::Complex:
2724 break;
2725
2726 // Non-deduced auto types only get here for error cases.
2727 case Type::Auto:
2728 case Type::DeducedTemplateSpecialization:
2729 break;
2730
2731 // If T is an Objective-C object or interface type, or a pointer to an
2732 // object or interface type, the associated namespace is the global
2733 // namespace.
2734 case Type::ObjCObject:
2735 case Type::ObjCInterface:
2736 case Type::ObjCObjectPointer:
2737 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2738 break;
2739
2740 // Atomic types are just wrappers; use the associations of the
2741 // contained type.
2742 case Type::Atomic:
2743 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2744 continue;
2745 case Type::Pipe:
2746 T = cast<PipeType>(T)->getElementType().getTypePtr();
2747 continue;
2748 }
2749
2750 if (Queue.empty())
2751 break;
2752 T = Queue.pop_back_val();
2753 }
2754}
2755
2756/// \brief Find the associated classes and namespaces for
2757/// argument-dependent lookup for a call with the given set of
2758/// arguments.
2759///
2760/// This routine computes the sets of associated classes and associated
2761/// namespaces searched by argument-dependent lookup
2762/// (C++ [basic.lookup.argdep]) for a given set of arguments.
2763void Sema::FindAssociatedClassesAndNamespaces(
2764 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2765 AssociatedNamespaceSet &AssociatedNamespaces,
2766 AssociatedClassSet &AssociatedClasses) {
2767 AssociatedNamespaces.clear();
2768 AssociatedClasses.clear();
2769
2770 AssociatedLookup Result(*this, InstantiationLoc,
2771 AssociatedNamespaces, AssociatedClasses);
2772
2773 // C++ [basic.lookup.koenig]p2:
2774 // For each argument type T in the function call, there is a set
2775 // of zero or more associated namespaces and a set of zero or more
2776 // associated classes to be considered. The sets of namespaces and
2777 // classes is determined entirely by the types of the function
2778 // arguments (and the namespace of any template template
2779 // argument).
2780 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2781 Expr *Arg = Args[ArgIdx];
2782
2783 if (Arg->getType() != Context.OverloadTy) {
2784 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2785 continue;
2786 }
2787
2788 // [...] In addition, if the argument is the name or address of a
2789 // set of overloaded functions and/or function templates, its
2790 // associated classes and namespaces are the union of those
2791 // associated with each of the members of the set: the namespace
2792 // in which the function or function template is defined and the
2793 // classes and namespaces associated with its (non-dependent)
2794 // parameter types and return type.
2795 Arg = Arg->IgnoreParens();
2796 if (UnaryOperator *unaryOp = dyn_cast<UnaryOperator>(Arg))
2797 if (unaryOp->getOpcode() == UO_AddrOf)
2798 Arg = unaryOp->getSubExpr();
2799
2800 UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Arg);
2801 if (!ULE) continue;
2802
2803 for (const auto *D : ULE->decls()) {
2804 // Look through any using declarations to find the underlying function.
2805 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2806
2807 // Add the classes and namespaces associated with the parameter
2808 // types and return type of this function.
2809 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2810 }
2811 }
2812}
2813
2814NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2815 SourceLocation Loc,
2816 LookupNameKind NameKind,
2817 RedeclarationKind Redecl) {
2818 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2819 LookupName(R, S);
2820 return R.getAsSingle<NamedDecl>();
2821}
2822
2823/// \brief Find the protocol with the given name, if any.
2824ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2825 SourceLocation IdLoc,
2826 RedeclarationKind Redecl) {
2827 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2828 LookupObjCProtocolName, Redecl);
2829 return cast_or_null<ObjCProtocolDecl>(D);
2830}
2831
2832void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
2833 QualType T1, QualType T2,
2834 UnresolvedSetImpl &Functions) {
2835 // C++ [over.match.oper]p3:
2836 // -- The set of non-member candidates is the result of the
2837 // unqualified lookup of operator@ in the context of the
2838 // expression according to the usual rules for name lookup in
2839 // unqualified function calls (3.4.2) except that all member
2840 // functions are ignored.
2841 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2842 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
2843 LookupName(Operators, S);
2844
2845 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous")((!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous"
) ? static_cast<void> (0) : __assert_fail ("!Operators.isAmbiguous() && \"Operator lookup cannot be ambiguous\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2845, __PRETTY_FUNCTION__))
;
2846 Functions.append(Operators.begin(), Operators.end());
2847}
2848
2849Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
2850 CXXSpecialMember SM,
2851 bool ConstArg,
2852 bool VolatileArg,
2853 bool RValueThis,
2854 bool ConstThis,
2855 bool VolatileThis) {
2856 assert(CanDeclareSpecialMemberFunction(RD) &&((CanDeclareSpecialMemberFunction(RD) && "doing special member lookup into record that isn't fully complete"
) ? static_cast<void> (0) : __assert_fail ("CanDeclareSpecialMemberFunction(RD) && \"doing special member lookup into record that isn't fully complete\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2857, __PRETTY_FUNCTION__))
2857 "doing special member lookup into record that isn't fully complete")((CanDeclareSpecialMemberFunction(RD) && "doing special member lookup into record that isn't fully complete"
) ? static_cast<void> (0) : __assert_fail ("CanDeclareSpecialMemberFunction(RD) && \"doing special member lookup into record that isn't fully complete\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2857, __PRETTY_FUNCTION__))
;
2858 RD = RD->getDefinition();
2859 if (RValueThis || ConstThis || VolatileThis)
2860 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&(((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
"constructors and destructors always have unqualified lvalue this"
) ? static_cast<void> (0) : __assert_fail ("(SM == CXXCopyAssignment || SM == CXXMoveAssignment) && \"constructors and destructors always have unqualified lvalue this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2861, __PRETTY_FUNCTION__))
2861 "constructors and destructors always have unqualified lvalue this")(((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
"constructors and destructors always have unqualified lvalue this"
) ? static_cast<void> (0) : __assert_fail ("(SM == CXXCopyAssignment || SM == CXXMoveAssignment) && \"constructors and destructors always have unqualified lvalue this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2861, __PRETTY_FUNCTION__))
;
2862 if (ConstArg || VolatileArg)
2863 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&(((SM != CXXDefaultConstructor && SM != CXXDestructor
) && "parameter-less special members can't have qualified arguments"
) ? static_cast<void> (0) : __assert_fail ("(SM != CXXDefaultConstructor && SM != CXXDestructor) && \"parameter-less special members can't have qualified arguments\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2864, __PRETTY_FUNCTION__))
2864 "parameter-less special members can't have qualified arguments")(((SM != CXXDefaultConstructor && SM != CXXDestructor
) && "parameter-less special members can't have qualified arguments"
) ? static_cast<void> (0) : __assert_fail ("(SM != CXXDefaultConstructor && SM != CXXDestructor) && \"parameter-less special members can't have qualified arguments\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2864, __PRETTY_FUNCTION__))
;
2865
2866 // FIXME: Get the caller to pass in a location for the lookup.
2867 SourceLocation LookupLoc = RD->getLocation();
2868
2869 llvm::FoldingSetNodeID ID;
2870 ID.AddPointer(RD);
2871 ID.AddInteger(SM);
2872 ID.AddInteger(ConstArg);
2873 ID.AddInteger(VolatileArg);
2874 ID.AddInteger(RValueThis);
2875 ID.AddInteger(ConstThis);
2876 ID.AddInteger(VolatileThis);
2877
2878 void *InsertPoint;
2879 SpecialMemberOverloadResultEntry *Result =
2880 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
2881
2882 // This was already cached
2883 if (Result)
2884 return *Result;
2885
2886 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
2887 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
2888 SpecialMemberCache.InsertNode(Result, InsertPoint);
2889
2890 if (SM == CXXDestructor) {
2891 if (RD->needsImplicitDestructor())
2892 DeclareImplicitDestructor(RD);
2893 CXXDestructorDecl *DD = RD->getDestructor();
2894 assert(DD && "record without a destructor")((DD && "record without a destructor") ? static_cast<
void> (0) : __assert_fail ("DD && \"record without a destructor\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2894, __PRETTY_FUNCTION__))
;
2895 Result->setMethod(DD);
2896 Result->setKind(DD->isDeleted() ?
2897 SpecialMemberOverloadResult::NoMemberOrDeleted :
2898 SpecialMemberOverloadResult::Success);
2899 return *Result;
2900 }
2901
2902 // Prepare for overload resolution. Here we construct a synthetic argument
2903 // if necessary and make sure that implicit functions are declared.
2904 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
2905 DeclarationName Name;
2906 Expr *Arg = nullptr;
2907 unsigned NumArgs;
2908
2909 QualType ArgType = CanTy;
2910 ExprValueKind VK = VK_LValue;
2911
2912 if (SM == CXXDefaultConstructor) {
2913 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2914 NumArgs = 0;
2915 if (RD->needsImplicitDefaultConstructor())
2916 DeclareImplicitDefaultConstructor(RD);
2917 } else {
2918 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
2919 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
2920 if (RD->needsImplicitCopyConstructor())
2921 DeclareImplicitCopyConstructor(RD);
2922 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor())
2923 DeclareImplicitMoveConstructor(RD);
2924 } else {
2925 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
2926 if (RD->needsImplicitCopyAssignment())
2927 DeclareImplicitCopyAssignment(RD);
2928 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment())
2929 DeclareImplicitMoveAssignment(RD);
2930 }
2931
2932 if (ConstArg)
2933 ArgType.addConst();
2934 if (VolatileArg)
2935 ArgType.addVolatile();
2936
2937 // This isn't /really/ specified by the standard, but it's implied
2938 // we should be working from an RValue in the case of move to ensure
2939 // that we prefer to bind to rvalue references, and an LValue in the
2940 // case of copy to ensure we don't bind to rvalue references.
2941 // Possibly an XValue is actually correct in the case of move, but
2942 // there is no semantic difference for class types in this restricted
2943 // case.
2944 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
2945 VK = VK_LValue;
2946 else
2947 VK = VK_RValue;
2948 }
2949
2950 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
2951
2952 if (SM != CXXDefaultConstructor) {
2953 NumArgs = 1;
2954 Arg = &FakeArg;
2955 }
2956
2957 // Create the object argument
2958 QualType ThisTy = CanTy;
2959 if (ConstThis)
2960 ThisTy.addConst();
2961 if (VolatileThis)
2962 ThisTy.addVolatile();
2963 Expr::Classification Classification =
2964 OpaqueValueExpr(LookupLoc, ThisTy,
2965 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
2966
2967 // Now we perform lookup on the name we computed earlier and do overload
2968 // resolution. Lookup is only performed directly into the class since there
2969 // will always be a (possibly implicit) declaration to shadow any others.
2970 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
2971 DeclContext::lookup_result R = RD->lookup(Name);
2972
2973 if (R.empty()) {
2974 // We might have no default constructor because we have a lambda's closure
2975 // type, rather than because there's some other declared constructor.
2976 // Every class has a copy/move constructor, copy/move assignment, and
2977 // destructor.
2978 assert(SM == CXXDefaultConstructor &&((SM == CXXDefaultConstructor && "lookup for a constructor or assignment operator was empty"
) ? static_cast<void> (0) : __assert_fail ("SM == CXXDefaultConstructor && \"lookup for a constructor or assignment operator was empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2979, __PRETTY_FUNCTION__))
2979 "lookup for a constructor or assignment operator was empty")((SM == CXXDefaultConstructor && "lookup for a constructor or assignment operator was empty"
) ? static_cast<void> (0) : __assert_fail ("SM == CXXDefaultConstructor && \"lookup for a constructor or assignment operator was empty\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 2979, __PRETTY_FUNCTION__))
;
2980 Result->setMethod(nullptr);
2981 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
2982 return *Result;
2983 }
2984
2985 // Copy the candidates as our processing of them may load new declarations
2986 // from an external source and invalidate lookup_result.
2987 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
2988
2989 for (NamedDecl *CandDecl : Candidates) {
2990 if (CandDecl->isInvalidDecl())
2991 continue;
2992
2993 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
2994 auto CtorInfo = getConstructorInfo(Cand);
2995 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
2996 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
2997 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
2998 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
2999 else if (CtorInfo)
3000 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3001 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3002 else
3003 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3004 true);
3005 } else if (FunctionTemplateDecl *Tmpl =
3006 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3007 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3008 AddMethodTemplateCandidate(
3009 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3010 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3011 else if (CtorInfo)
3012 AddTemplateOverloadCandidate(
3013 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3014 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3015 else
3016 AddTemplateOverloadCandidate(
3017 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3018 } else {
3019 assert(isa<UsingDecl>(Cand.getDecl()) &&((isa<UsingDecl>(Cand.getDecl()) && "illegal Kind of operator = Decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UsingDecl>(Cand.getDecl()) && \"illegal Kind of operator = Decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3020, __PRETTY_FUNCTION__))
3020 "illegal Kind of operator = Decl")((isa<UsingDecl>(Cand.getDecl()) && "illegal Kind of operator = Decl"
) ? static_cast<void> (0) : __assert_fail ("isa<UsingDecl>(Cand.getDecl()) && \"illegal Kind of operator = Decl\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3020, __PRETTY_FUNCTION__))
;
3021 }
3022 }
3023
3024 OverloadCandidateSet::iterator Best;
3025 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3026 case OR_Success:
3027 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3028 Result->setKind(SpecialMemberOverloadResult::Success);
3029 break;
3030
3031 case OR_Deleted:
3032 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3033 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3034 break;
3035
3036 case OR_Ambiguous:
3037 Result->setMethod(nullptr);
3038 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3039 break;
3040
3041 case OR_No_Viable_Function:
3042 Result->setMethod(nullptr);
3043 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3044 break;
3045 }
3046
3047 return *Result;
3048}
3049
3050/// \brief Look up the default constructor for the given class.
3051CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3052 SpecialMemberOverloadResult Result =
3053 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3054 false, false);
3055
3056 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3057}
3058
3059/// \brief Look up the copying constructor for the given class.
3060CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3061 unsigned Quals) {
3062 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&((!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
"non-const, non-volatile qualifiers for copy ctor arg") ? static_cast
<void> (0) : __assert_fail ("!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy ctor arg\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3063, __PRETTY_FUNCTION__))
3063 "non-const, non-volatile qualifiers for copy ctor arg")((!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
"non-const, non-volatile qualifiers for copy ctor arg") ? static_cast
<void> (0) : __assert_fail ("!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy ctor arg\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3063, __PRETTY_FUNCTION__))
;
3064 SpecialMemberOverloadResult Result =
3065 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3066 Quals & Qualifiers::Volatile, false, false, false);
3067
3068 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3069}
3070
3071/// \brief Look up the moving constructor for the given class.
3072CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3073 unsigned Quals) {
3074 SpecialMemberOverloadResult Result =
3075 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3076 Quals & Qualifiers::Volatile, false, false, false);
3077
3078 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3079}
3080
3081/// \brief Look up the constructors for the given class.
3082DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3083 // If the implicit constructors have not yet been declared, do so now.
3084 if (CanDeclareSpecialMemberFunction(Class)) {
3085 if (Class->needsImplicitDefaultConstructor())
3086 DeclareImplicitDefaultConstructor(Class);
3087 if (Class->needsImplicitCopyConstructor())
3088 DeclareImplicitCopyConstructor(Class);
3089 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3090 DeclareImplicitMoveConstructor(Class);
3091 }
3092
3093 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3094 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3095 return Class->lookup(Name);
3096}
3097
3098/// \brief Look up the copying assignment operator for the given class.
3099CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3100 unsigned Quals, bool RValueThis,
3101 unsigned ThisQuals) {
3102 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&((!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
"non-const, non-volatile qualifiers for copy assignment arg"
) ? static_cast<void> (0) : __assert_fail ("!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment arg\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3103, __PRETTY_FUNCTION__))
3103 "non-const, non-volatile qualifiers for copy assignment arg")((!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
"non-const, non-volatile qualifiers for copy assignment arg"
) ? static_cast<void> (0) : __assert_fail ("!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment arg\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3103, __PRETTY_FUNCTION__))
;
3104 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&((!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile
)) && "non-const, non-volatile qualifiers for copy assignment this"
) ? static_cast<void> (0) : __assert_fail ("!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3105, __PRETTY_FUNCTION__))
3105 "non-const, non-volatile qualifiers for copy assignment this")((!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile
)) && "non-const, non-volatile qualifiers for copy assignment this"
) ? static_cast<void> (0) : __assert_fail ("!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3105, __PRETTY_FUNCTION__))
;
3106 SpecialMemberOverloadResult Result =
3107 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3108 Quals & Qualifiers::Volatile, RValueThis,
3109 ThisQuals & Qualifiers::Const,
3110 ThisQuals & Qualifiers::Volatile);
3111
3112 return Result.getMethod();
3113}
3114
3115/// \brief Look up the moving assignment operator for the given class.
3116CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3117 unsigned Quals,
3118 bool RValueThis,
3119 unsigned ThisQuals) {
3120 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&((!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile
)) && "non-const, non-volatile qualifiers for copy assignment this"
) ? static_cast<void> (0) : __assert_fail ("!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3121, __PRETTY_FUNCTION__))
3121 "non-const, non-volatile qualifiers for copy assignment this")((!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile
)) && "non-const, non-volatile qualifiers for copy assignment this"
) ? static_cast<void> (0) : __assert_fail ("!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) && \"non-const, non-volatile qualifiers for copy assignment this\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3121, __PRETTY_FUNCTION__))
;
3122 SpecialMemberOverloadResult Result =
3123 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3124 Quals & Qualifiers::Volatile, RValueThis,
3125 ThisQuals & Qualifiers::Const,
3126 ThisQuals & Qualifiers::Volatile);
3127
3128 return Result.getMethod();
3129}
3130
3131/// \brief Look for the destructor of the given class.
3132///
3133/// During semantic analysis, this routine should be used in lieu of
3134/// CXXRecordDecl::getDestructor().
3135///
3136/// \returns The destructor for this class.
3137CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3138 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3139 false, false, false,
3140 false, false).getMethod());
3141}
3142
3143/// LookupLiteralOperator - Determine which literal operator should be used for
3144/// a user-defined literal, per C++11 [lex.ext].
3145///
3146/// Normal overload resolution is not used to select which literal operator to
3147/// call for a user-defined literal. Look up the provided literal operator name,
3148/// and filter the results to the appropriate set for the given argument types.
3149Sema::LiteralOperatorLookupResult
3150Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3151 ArrayRef<QualType> ArgTys,
3152 bool AllowRaw, bool AllowTemplate,
3153 bool AllowStringTemplate, bool DiagnoseMissing) {
3154 LookupName(R, S);
3155 assert(R.getResultKind() != LookupResult::Ambiguous &&((R.getResultKind() != LookupResult::Ambiguous && "literal operator lookup can't be ambiguous"
) ? static_cast<void> (0) : __assert_fail ("R.getResultKind() != LookupResult::Ambiguous && \"literal operator lookup can't be ambiguous\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3156, __PRETTY_FUNCTION__))
3156 "literal operator lookup can't be ambiguous")((R.getResultKind() != LookupResult::Ambiguous && "literal operator lookup can't be ambiguous"
) ? static_cast<void> (0) : __assert_fail ("R.getResultKind() != LookupResult::Ambiguous && \"literal operator lookup can't be ambiguous\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3156, __PRETTY_FUNCTION__))
;
3157
3158 // Filter the lookup results appropriately.
3159 LookupResult::Filter F = R.makeFilter();
3160
3161 bool FoundRaw = false;
3162 bool FoundTemplate = false;
3163 bool FoundStringTemplate = false;
3164 bool FoundExactMatch = false;
3165
3166 while (F.hasNext()) {
3167 Decl *D = F.next();
3168 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3169 D = USD->getTargetDecl();
3170
3171 // If the declaration we found is invalid, skip it.
3172 if (D->isInvalidDecl()) {
3173 F.erase();
3174 continue;
3175 }
3176
3177 bool IsRaw = false;
3178 bool IsTemplate = false;
3179 bool IsStringTemplate = false;
3180 bool IsExactMatch = false;
3181
3182 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3183 if (FD->getNumParams() == 1 &&
3184 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3185 IsRaw = true;
3186 else if (FD->getNumParams() == ArgTys.size()) {
3187 IsExactMatch = true;
3188 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3189 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3190 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3191 IsExactMatch = false;
3192 break;
3193 }
3194 }
3195 }
3196 }
3197 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3198 TemplateParameterList *Params = FD->getTemplateParameters();
3199 if (Params->size() == 1)
3200 IsTemplate = true;
3201 else
3202 IsStringTemplate = true;
3203 }
3204
3205 if (IsExactMatch) {
3206 FoundExactMatch = true;
3207 AllowRaw = false;
3208 AllowTemplate = false;
3209 AllowStringTemplate = false;
3210 if (FoundRaw || FoundTemplate || FoundStringTemplate) {
3211 // Go through again and remove the raw and template decls we've
3212 // already found.
3213 F.restart();
3214 FoundRaw = FoundTemplate = FoundStringTemplate = false;
3215 }
3216 } else if (AllowRaw && IsRaw) {
3217 FoundRaw = true;
3218 } else if (AllowTemplate && IsTemplate) {
3219 FoundTemplate = true;
3220 } else if (AllowStringTemplate && IsStringTemplate) {
3221 FoundStringTemplate = true;
3222 } else {
3223 F.erase();
3224 }
3225 }
3226
3227 F.done();
3228
3229 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3230 // parameter type, that is used in preference to a raw literal operator
3231 // or literal operator template.
3232 if (FoundExactMatch)
3233 return LOLR_Cooked;
3234
3235 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3236 // operator template, but not both.
3237 if (FoundRaw && FoundTemplate) {
3238 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3239 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3240 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3241 return LOLR_Error;
3242 }
3243
3244 if (FoundRaw)
3245 return LOLR_Raw;
3246
3247 if (FoundTemplate)
3248 return LOLR_Template;
3249
3250 if (FoundStringTemplate)
3251 return LOLR_StringTemplate;
3252
3253 // Didn't find anything we could use.
3254 if (DiagnoseMissing) {
3255 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3256 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3257 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3258 << (AllowTemplate || AllowStringTemplate);
3259 return LOLR_Error;
3260 }
3261
3262 return LOLR_ErrorNoDiagnostic;
3263}
3264
3265void ADLResult::insert(NamedDecl *New) {
3266 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3267
3268 // If we haven't yet seen a decl for this key, or the last decl
3269 // was exactly this one, we're done.
3270 if (Old == nullptr || Old == New) {
3271 Old = New;
3272 return;
3273 }
3274
3275 // Otherwise, decide which is a more recent redeclaration.
3276 FunctionDecl *OldFD = Old->getAsFunction();
3277 FunctionDecl *NewFD = New->getAsFunction();
3278
3279 FunctionDecl *Cursor = NewFD;
3280 while (true) {
3281 Cursor = Cursor->getPreviousDecl();
3282
3283 // If we got to the end without finding OldFD, OldFD is the newer
3284 // declaration; leave things as they are.
3285 if (!Cursor) return;
3286
3287 // If we do find OldFD, then NewFD is newer.
3288 if (Cursor == OldFD) break;
3289
3290 // Otherwise, keep looking.
3291 }
3292
3293 Old = New;
3294}
3295
3296void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3297 ArrayRef<Expr *> Args, ADLResult &Result) {
3298 // Find all of the associated namespaces and classes based on the
3299 // arguments we have.
3300 AssociatedNamespaceSet AssociatedNamespaces;
3301 AssociatedClassSet AssociatedClasses;
3302 FindAssociatedClassesAndNamespaces(Loc, Args,
3303 AssociatedNamespaces,
3304 AssociatedClasses);
3305
3306 // C++ [basic.lookup.argdep]p3:
3307 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3308 // and let Y be the lookup set produced by argument dependent
3309 // lookup (defined as follows). If X contains [...] then Y is
3310 // empty. Otherwise Y is the set of declarations found in the
3311 // namespaces associated with the argument types as described
3312 // below. The set of declarations found by the lookup of the name
3313 // is the union of X and Y.
3314 //
3315 // Here, we compute Y and add its members to the overloaded
3316 // candidate set.
3317 for (auto *NS : AssociatedNamespaces) {
3318 // When considering an associated namespace, the lookup is the
3319 // same as the lookup performed when the associated namespace is
3320 // used as a qualifier (3.4.3.2) except that:
3321 //
3322 // -- Any using-directives in the associated namespace are
3323 // ignored.
3324 //
3325 // -- Any namespace-scope friend functions declared in
3326 // associated classes are visible within their respective
3327 // namespaces even if they are not visible during an ordinary
3328 // lookup (11.4).
3329 DeclContext::lookup_result R = NS->lookup(Name);
3330 for (auto *D : R) {
3331 // If the only declaration here is an ordinary friend, consider
3332 // it only if it was declared in an associated classes.
3333 if ((D->getIdentifierNamespace() & Decl::IDNS_Ordinary) == 0) {
3334 // If it's neither ordinarily visible nor a friend, we can't find it.
3335 if ((D->getIdentifierNamespace() & Decl::IDNS_OrdinaryFriend) == 0)
3336 continue;
3337
3338 bool DeclaredInAssociatedClass = false;
3339 for (Decl *DI = D; DI; DI = DI->getPreviousDecl()) {
3340 DeclContext *LexDC = DI->getLexicalDeclContext();
3341 if (isa<CXXRecordDecl>(LexDC) &&
3342 AssociatedClasses.count(cast<CXXRecordDecl>(LexDC)) &&
3343 isVisible(cast<NamedDecl>(DI))) {
3344 DeclaredInAssociatedClass = true;
3345 break;
3346 }
3347 }
3348 if (!DeclaredInAssociatedClass)
3349 continue;
3350 }
3351
3352 auto *Underlying = D;
3353 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3354 Underlying = USD->getTargetDecl();
3355
3356 if (!isa<FunctionDecl>(Underlying) &&
3357 !isa<FunctionTemplateDecl>(Underlying))
3358 continue;
3359
3360 if (!isVisible(D)) {
3361 D = findAcceptableDecl(*this, D);
3362 if (!D)
3363 continue;
3364 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3365 Underlying = USD->getTargetDecl();
3366 }
3367
3368 // FIXME: Preserve D as the FoundDecl.
3369 Result.insert(Underlying);
3370 }
3371 }
3372}
3373
3374//----------------------------------------------------------------------------
3375// Search for all visible declarations.
3376//----------------------------------------------------------------------------
3377VisibleDeclConsumer::~VisibleDeclConsumer() { }
3378
3379bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3380
3381namespace {
3382
3383class ShadowContextRAII;
3384
3385class VisibleDeclsRecord {
3386public:
3387 /// \brief An entry in the shadow map, which is optimized to store a
3388 /// single declaration (the common case) but can also store a list
3389 /// of declarations.
3390 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3391
3392private:
3393 /// \brief A mapping from declaration names to the declarations that have
3394 /// this name within a particular scope.
3395 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3396
3397 /// \brief A list of shadow maps, which is used to model name hiding.
3398 std::list<ShadowMap> ShadowMaps;
3399
3400 /// \brief The declaration contexts we have already visited.
3401 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3402
3403 friend class ShadowContextRAII;
3404
3405public:
3406 /// \brief Determine whether we have already visited this context
3407 /// (and, if not, note that we are going to visit that context now).
3408 bool visitedContext(DeclContext *Ctx) {
3409 return !VisitedContexts.insert(Ctx).second;
3410 }
3411
3412 bool alreadyVisitedContext(DeclContext *Ctx) {
3413 return VisitedContexts.count(Ctx);
3414 }
3415
3416 /// \brief Determine whether the given declaration is hidden in the
3417 /// current scope.
3418 ///
3419 /// \returns the declaration that hides the given declaration, or
3420 /// NULL if no such declaration exists.
3421 NamedDecl *checkHidden(NamedDecl *ND);
3422
3423 /// \brief Add a declaration to the current shadow map.
3424 void add(NamedDecl *ND) {
3425 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3426 }
3427};
3428
3429/// \brief RAII object that records when we've entered a shadow context.
3430class ShadowContextRAII {
3431 VisibleDeclsRecord &Visible;
3432
3433 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3434
3435public:
3436 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3437 Visible.ShadowMaps.emplace_back();
3438 }
3439
3440 ~ShadowContextRAII() {
3441 Visible.ShadowMaps.pop_back();
3442 }
3443};
3444
3445} // end anonymous namespace
3446
3447NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3448 unsigned IDNS = ND->getIdentifierNamespace();
3449 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3450 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3451 SM != SMEnd; ++SM) {
3452 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3453 if (Pos == SM->end())
3454 continue;
3455
3456 for (auto *D : Pos->second) {
3457 // A tag declaration does not hide a non-tag declaration.
3458 if (D->hasTagIdentifierNamespace() &&
3459 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3460 Decl::IDNS_ObjCProtocol)))
3461 continue;
3462
3463 // Protocols are in distinct namespaces from everything else.
3464 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3465 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3466 D->getIdentifierNamespace() != IDNS)
3467 continue;
3468
3469 // Functions and function templates in the same scope overload
3470 // rather than hide. FIXME: Look for hiding based on function
3471 // signatures!
3472 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3473 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3474 SM == ShadowMaps.rbegin())
3475 continue;
3476
3477 // A shadow declaration that's created by a resolved using declaration
3478 // is not hidden by the same using declaration.
3479 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3480 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3481 continue;
3482
3483 // We've found a declaration that hides this one.
3484 return D;
3485 }
3486 }
3487
3488 return nullptr;
3489}
3490
3491static void LookupVisibleDecls(DeclContext *Ctx, LookupResult &Result,
3492 bool QualifiedNameLookup,
3493 bool InBaseClass,
3494 VisibleDeclConsumer &Consumer,
3495 VisibleDeclsRecord &Visited,
3496 bool IncludeDependentBases = false) {
3497 if (!Ctx)
3498 return;
3499
3500 // Make sure we don't visit the same context twice.
3501 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3502 return;
3503
3504 // Outside C++, lookup results for the TU live on identifiers.
3505 if (isa<TranslationUnitDecl>(Ctx) &&
3506 !Result.getSema().getLangOpts().CPlusPlus) {
3507 auto &S = Result.getSema();
3508 auto &Idents = S.Context.Idents;
3509
3510 // Ensure all external identifiers are in the identifier table.
3511 if (IdentifierInfoLookup *External = Idents.getExternalIdentifierLookup()) {
3512 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3513 for (StringRef Name = Iter->Next(); !Name.empty(); Name = Iter->Next())
3514 Idents.get(Name);
3515 }
3516
3517 // Walk all lookup results in the TU for each identifier.
3518 for (const auto &Ident : Idents) {
3519 for (auto I = S.IdResolver.begin(Ident.getValue()),
3520 E = S.IdResolver.end();
3521 I != E; ++I) {
3522 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3523 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3524 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3525 Visited.add(ND);
3526 }
3527 }
3528 }
3529 }
3530
3531 return;
3532 }
3533
3534 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3535 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3536
3537 // Enumerate all of the results in this context.
3538 for (DeclContextLookupResult R : Ctx->lookups()) {
3539 for (auto *D : R) {
3540 if (auto *ND = Result.getAcceptableDecl(D)) {
3541 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3542 Visited.add(ND);
3543 }
3544 }
3545 }
3546
3547 // Traverse using directives for qualified name lookup.
3548 if (QualifiedNameLookup) {
3549 ShadowContextRAII Shadow(Visited);
3550 for (auto I : Ctx->using_directives()) {
3551 if (!Result.getSema().isVisible(I))
3552 continue;
3553 LookupVisibleDecls(I->getNominatedNamespace(), Result,
3554 QualifiedNameLookup, InBaseClass, Consumer, Visited,
3555 IncludeDependentBases);
3556 }
3557 }
3558
3559 // Traverse the contexts of inherited C++ classes.
3560 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3561 if (!Record->hasDefinition())
3562 return;
3563
3564 for (const auto &B : Record->bases()) {
3565 QualType BaseType = B.getType();
3566
3567 RecordDecl *RD;
3568 if (BaseType->isDependentType()) {
3569 if (!IncludeDependentBases) {
3570 // Don't look into dependent bases, because name lookup can't look
3571 // there anyway.
3572 continue;
3573 }
3574 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3575 if (!TST)
3576 continue;
3577 TemplateName TN = TST->getTemplateName();
3578 const auto *TD =
3579 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3580 if (!TD)
3581 continue;
3582 RD = TD->getTemplatedDecl();
3583 } else {
3584 const auto *Record = BaseType->getAs<RecordType>();
3585 if (!Record)
3586 continue;
3587 RD = Record->getDecl();
3588 }
3589
3590 // FIXME: It would be nice to be able to determine whether referencing
3591 // a particular member would be ambiguous. For example, given
3592 //
3593 // struct A { int member; };
3594 // struct B { int member; };
3595 // struct C : A, B { };
3596 //
3597 // void f(C *c) { c->### }
3598 //
3599 // accessing 'member' would result in an ambiguity. However, we
3600 // could be smart enough to qualify the member with the base
3601 // class, e.g.,
3602 //
3603 // c->B::member
3604 //
3605 // or
3606 //
3607 // c->A::member
3608
3609 // Find results in this base class (and its bases).
3610 ShadowContextRAII Shadow(Visited);
3611 LookupVisibleDecls(RD, Result, QualifiedNameLookup, true, Consumer,
3612 Visited, IncludeDependentBases);
3613 }
3614 }
3615
3616 // Traverse the contexts of Objective-C classes.
3617 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3618 // Traverse categories.
3619 for (auto *Cat : IFace->visible_categories()) {
3620 ShadowContextRAII Shadow(Visited);
3621 LookupVisibleDecls(Cat, Result, QualifiedNameLookup, false,
3622 Consumer, Visited);
3623 }
3624
3625 // Traverse protocols.
3626 for (auto *I : IFace->all_referenced_protocols()) {
3627 ShadowContextRAII Shadow(Visited);
3628 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3629 Visited);
3630 }
3631
3632 // Traverse the superclass.
3633 if (IFace->getSuperClass()) {
3634 ShadowContextRAII Shadow(Visited);
3635 LookupVisibleDecls(IFace->getSuperClass(), Result, QualifiedNameLookup,
3636 true, Consumer, Visited);
3637 }
3638
3639 // If there is an implementation, traverse it. We do this to find
3640 // synthesized ivars.
3641 if (IFace->getImplementation()) {
3642 ShadowContextRAII Shadow(Visited);
3643 LookupVisibleDecls(IFace->getImplementation(), Result,
3644 QualifiedNameLookup, InBaseClass, Consumer, Visited);
3645 }
3646 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3647 for (auto *I : Protocol->protocols()) {
3648 ShadowContextRAII Shadow(Visited);
3649 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3650 Visited);
3651 }
3652 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3653 for (auto *I : Category->protocols()) {
3654 ShadowContextRAII Shadow(Visited);
3655 LookupVisibleDecls(I, Result, QualifiedNameLookup, false, Consumer,
3656 Visited);
3657 }
3658
3659 // If there is an implementation, traverse it.
3660 if (Category->getImplementation()) {
3661 ShadowContextRAII Shadow(Visited);
3662 LookupVisibleDecls(Category->getImplementation(), Result,
3663 QualifiedNameLookup, true, Consumer, Visited);
3664 }
3665 }
3666}
3667
3668static void LookupVisibleDecls(Scope *S, LookupResult &Result,
3669 UnqualUsingDirectiveSet &UDirs,
3670 VisibleDeclConsumer &Consumer,
3671 VisibleDeclsRecord &Visited) {
3672 if (!S)
3673 return;
3674
3675 if (!S->getEntity() ||
3676 (!S->getParent() &&
3677 !Visited.alreadyVisitedContext(S->getEntity())) ||
3678 (S->getEntity())->isFunctionOrMethod()) {
3679 FindLocalExternScope FindLocals(Result);
3680 // Walk through the declarations in this Scope. The consumer might add new
3681 // decls to the scope as part of deserialization, so make a copy first.
3682 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3683 for (Decl *D : ScopeDecls) {
3684 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3685 if ((ND = Result.getAcceptableDecl(ND))) {
3686 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3687 Visited.add(ND);
3688 }
3689 }
3690 }
3691
3692 // FIXME: C++ [temp.local]p8
3693 DeclContext *Entity = nullptr;
3694 if (S->getEntity()) {
3695 // Look into this scope's declaration context, along with any of its
3696 // parent lookup contexts (e.g., enclosing classes), up to the point
3697 // where we hit the context stored in the next outer scope.
3698 Entity = S->getEntity();
3699 DeclContext *OuterCtx = findOuterContext(S).first; // FIXME
3700
3701 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3702 Ctx = Ctx->getLookupParent()) {
3703 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3704 if (Method->isInstanceMethod()) {
3705 // For instance methods, look for ivars in the method's interface.
3706 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3707 Result.getNameLoc(), Sema::LookupMemberName);
3708 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3709 LookupVisibleDecls(IFace, IvarResult, /*QualifiedNameLookup=*/false,
3710 /*InBaseClass=*/false, Consumer, Visited);
3711 }
3712 }
3713
3714 // We've already performed all of the name lookup that we need
3715 // to for Objective-C methods; the next context will be the
3716 // outer scope.
3717 break;
3718 }
3719
3720 if (Ctx->isFunctionOrMethod())
3721 continue;
3722
3723 LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/false,
3724 /*InBaseClass=*/false, Consumer, Visited);
3725 }
3726 } else if (!S->getParent()) {
3727 // Look into the translation unit scope. We walk through the translation
3728 // unit's declaration context, because the Scope itself won't have all of
3729 // the declarations if we loaded a precompiled header.
3730 // FIXME: We would like the translation unit's Scope object to point to the
3731 // translation unit, so we don't need this special "if" branch. However,
3732 // doing so would force the normal C++ name-lookup code to look into the
3733 // translation unit decl when the IdentifierInfo chains would suffice.
3734 // Once we fix that problem (which is part of a more general "don't look
3735 // in DeclContexts unless we have to" optimization), we can eliminate this.
3736 Entity = Result.getSema().Context.getTranslationUnitDecl();
3737 LookupVisibleDecls(Entity, Result, /*QualifiedNameLookup=*/false,
3738 /*InBaseClass=*/false, Consumer, Visited);
3739 }
3740
3741 if (Entity) {
3742 // Lookup visible declarations in any namespaces found by using
3743 // directives.
3744 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
3745 LookupVisibleDecls(const_cast<DeclContext *>(UUE.getNominatedNamespace()),
3746 Result, /*QualifiedNameLookup=*/false,
3747 /*InBaseClass=*/false, Consumer, Visited);
3748 }
3749
3750 // Lookup names in the parent scope.
3751 ShadowContextRAII Shadow(Visited);
3752 LookupVisibleDecls(S->getParent(), Result, UDirs, Consumer, Visited);
3753}
3754
3755void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
3756 VisibleDeclConsumer &Consumer,
3757 bool IncludeGlobalScope) {
3758 // Determine the set of using directives available during
3759 // unqualified name lookup.
3760 Scope *Initial = S;
3761 UnqualUsingDirectiveSet UDirs(*this);
3762 if (getLangOpts().CPlusPlus) {
3763 // Find the first namespace or translation-unit scope.
3764 while (S && !isNamespaceOrTranslationUnitScope(S))
3765 S = S->getParent();
3766
3767 UDirs.visitScopeChain(Initial, S);
3768 }
3769 UDirs.done();
3770
3771 // Look for visible declarations.
3772 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3773 Result.setAllowHidden(Consumer.includeHiddenDecls());
3774 VisibleDeclsRecord Visited;
3775 if (!IncludeGlobalScope)
3776 Visited.visitedContext(Context.getTranslationUnitDecl());
3777 ShadowContextRAII Shadow(Visited);
3778 ::LookupVisibleDecls(Initial, Result, UDirs, Consumer, Visited);
3779}
3780
3781void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
3782 VisibleDeclConsumer &Consumer,
3783 bool IncludeGlobalScope,
3784 bool IncludeDependentBases) {
3785 LookupResult Result(*this, DeclarationName(), SourceLocation(), Kind);
3786 Result.setAllowHidden(Consumer.includeHiddenDecls());
3787 VisibleDeclsRecord Visited;
3788 if (!IncludeGlobalScope)
3789 Visited.visitedContext(Context.getTranslationUnitDecl());
3790 ShadowContextRAII Shadow(Visited);
3791 ::LookupVisibleDecls(Ctx, Result, /*QualifiedNameLookup=*/true,
3792 /*InBaseClass=*/false, Consumer, Visited,
3793 IncludeDependentBases);
3794}
3795
3796/// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
3797/// If GnuLabelLoc is a valid source location, then this is a definition
3798/// of an __label__ label name, otherwise it is a normal label definition
3799/// or use.
3800LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
3801 SourceLocation GnuLabelLoc) {
3802 // Do a lookup to see if we have a label with this name already.
3803 NamedDecl *Res = nullptr;
3804
3805 if (GnuLabelLoc.isValid()) {
3806 // Local label definitions always shadow existing labels.
3807 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
3808 Scope *S = CurScope;
3809 PushOnScopeChains(Res, S, true);
3810 return cast<LabelDecl>(Res);
3811 }
3812
3813 // Not a GNU local label.
3814 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
3815 // If we found a label, check to see if it is in the same context as us.
3816 // When in a Block, we don't want to reuse a label in an enclosing function.
3817 if (Res && Res->getDeclContext() != CurContext)
3818 Res = nullptr;
3819 if (!Res) {
3820 // If not forward referenced or defined already, create the backing decl.
3821 Res = LabelDecl::Create(Context, CurContext, Loc, II);
3822 Scope *S = CurScope->getFnParent();
3823 assert(S && "Not in a function?")((S && "Not in a function?") ? static_cast<void>
(0) : __assert_fail ("S && \"Not in a function?\"", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 3823, __PRETTY_FUNCTION__))
;
3824 PushOnScopeChains(Res, S, true);
3825 }
3826 return cast<LabelDecl>(Res);
3827}
3828
3829//===----------------------------------------------------------------------===//
3830// Typo correction
3831//===----------------------------------------------------------------------===//
3832
3833static bool isCandidateViable(CorrectionCandidateCallback &CCC,
3834 TypoCorrection &Candidate) {
3835 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
3836 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
3837}
3838
3839static void LookupPotentialTypoResult(Sema &SemaRef,
3840 LookupResult &Res,
3841 IdentifierInfo *Name,
3842 Scope *S, CXXScopeSpec *SS,
3843 DeclContext *MemberContext,
3844 bool EnteringContext,
3845 bool isObjCIvarLookup,
3846 bool FindHidden);
3847
3848/// \brief Check whether the declarations found for a typo correction are
3849/// visible. Set the correction's RequiresImport flag to true if none of the
3850/// declarations are visible, false otherwise.
3851static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
3852 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
3853
3854 for (/**/; DI != DE; ++DI)
3855 if (!LookupResult::isVisible(SemaRef, *DI))
3856 break;
3857 // No filtering needed if all decls are visible.
3858 if (DI == DE) {
3859 TC.setRequiresImport(false);
3860 return;
3861 }
3862
3863 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
3864 bool AnyVisibleDecls = !NewDecls.empty();
3865
3866 for (/**/; DI != DE; ++DI) {
3867 NamedDecl *VisibleDecl = *DI;
3868 if (!LookupResult::isVisible(SemaRef, *DI))
3869 VisibleDecl = findAcceptableDecl(SemaRef, *DI);
3870
3871 if (VisibleDecl) {
3872 if (!AnyVisibleDecls) {
3873 // Found a visible decl, discard all hidden ones.
3874 AnyVisibleDecls = true;
3875 NewDecls.clear();
3876 }
3877 NewDecls.push_back(VisibleDecl);
3878 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
3879 NewDecls.push_back(*DI);
3880 }
3881
3882 if (NewDecls.empty())
3883 TC = TypoCorrection();
3884 else {
3885 TC.setCorrectionDecls(NewDecls);
3886 TC.setRequiresImport(!AnyVisibleDecls);
3887 }
3888}
3889
3890// Fill the supplied vector with the IdentifierInfo pointers for each piece of
3891// the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
3892// fill the vector with the IdentifierInfo pointers for "foo" and "bar").
3893static void getNestedNameSpecifierIdentifiers(
3894 NestedNameSpecifier *NNS,
3895 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
3896 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
69
Called C++ object pointer is null
3897 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
3898 else
3899 Identifiers.clear();
3900
3901 const IdentifierInfo *II = nullptr;
3902
3903 switch (NNS->getKind()) {
3904 case NestedNameSpecifier::Identifier:
3905 II = NNS->getAsIdentifier();
3906 break;
3907
3908 case NestedNameSpecifier::Namespace:
3909 if (NNS->getAsNamespace()->isAnonymousNamespace())
3910 return;
3911 II = NNS->getAsNamespace()->getIdentifier();
3912 break;
3913
3914 case NestedNameSpecifier::NamespaceAlias:
3915 II = NNS->getAsNamespaceAlias()->getIdentifier();
3916 break;
3917
3918 case NestedNameSpecifier::TypeSpecWithTemplate:
3919 case NestedNameSpecifier::TypeSpec:
3920 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
3921 break;
3922
3923 case NestedNameSpecifier::Global:
3924 case NestedNameSpecifier::Super:
3925 return;
3926 }
3927
3928 if (II)
3929 Identifiers.push_back(II);
3930}
3931
3932void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
3933 DeclContext *Ctx, bool InBaseClass) {
3934 // Don't consider hidden names for typo correction.
3935 if (Hiding)
3936 return;
3937
3938 // Only consider entities with identifiers for names, ignoring
3939 // special names (constructors, overloaded operators, selectors,
3940 // etc.).
3941 IdentifierInfo *Name = ND->getIdentifier();
3942 if (!Name)
3943 return;
3944
3945 // Only consider visible declarations and declarations from modules with
3946 // names that exactly match.
3947 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo &&
3948 !findAcceptableDecl(SemaRef, ND))
3949 return;
3950
3951 FoundName(Name->getName());
3952}
3953
3954void TypoCorrectionConsumer::FoundName(StringRef Name) {
3955 // Compute the edit distance between the typo and the name of this
3956 // entity, and add the identifier to the list of results.
3957 addName(Name, nullptr);
3958}
3959
3960void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
3961 // Compute the edit distance between the typo and this keyword,
3962 // and add the keyword to the list of results.
3963 addName(Keyword, nullptr, nullptr, true);
3964}
3965
3966void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
3967 NestedNameSpecifier *NNS, bool isKeyword) {
3968 // Use a simple length-based heuristic to determine the minimum possible
3969 // edit distance. If the minimum isn't good enough, bail out early.
3970 StringRef TypoStr = Typo->getName();
3971 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
3972 if (MinED && TypoStr.size() / MinED < 3)
3973 return;
3974
3975 // Compute an upper bound on the allowable edit distance, so that the
3976 // edit-distance algorithm can short-circuit.
3977 unsigned UpperBound = (TypoStr.size() + 2) / 3 + 1;
3978 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
3979 if (ED >= UpperBound) return;
3980
3981 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
3982 if (isKeyword) TC.makeKeyword();
3983 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
3984 addCorrection(TC);
3985}
3986
3987static const unsigned MaxTypoDistanceResultSets = 5;
3988
3989void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
3990 StringRef TypoStr = Typo->getName();
3991 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
3992
3993 // For very short typos, ignore potential corrections that have a different
3994 // base identifier from the typo or which have a normalized edit distance
3995 // longer than the typo itself.
3996 if (TypoStr.size() < 3 &&
3997 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
3998 return;
3999
4000 // If the correction is resolved but is not viable, ignore it.
4001 if (Correction.isResolved()) {
4002 checkCorrectionVisibility(SemaRef, Correction);
4003 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4004 return;
4005 }
4006
4007 TypoResultList &CList =
4008 CorrectionResults[Correction.getEditDistance(false)][Name];
4009
4010 if (!CList.empty() && !CList.back().isResolved())
4011 CList.pop_back();
4012 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4013 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4014 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4015 RI != RIEnd; ++RI) {
4016 // If the Correction refers to a decl already in the result list,
4017 // replace the existing result if the string representation of Correction
4018 // comes before the current result alphabetically, then stop as there is
4019 // nothing more to be done to add Correction to the candidate set.
4020 if (RI->getCorrectionDecl() == NewND) {
4021 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4022 *RI = Correction;
4023 return;
4024 }
4025 }
4026 }
4027 if (CList.empty() || Correction.isResolved())
4028 CList.push_back(Correction);
4029
4030 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4031 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4032}
4033
4034void TypoCorrectionConsumer::addNamespaces(
4035 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4036 SearchNamespaces = true;
4037
4038 for (auto KNPair : KnownNamespaces)
4039 Namespaces.addNameSpecifier(KNPair.first);
4040
4041 bool SSIsTemplate = false;
4042 if (NestedNameSpecifier *NNS =
2
Taking false branch
4043 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
1
'?' condition is false
4044 if (const Type *T = NNS->getAsType())
4045 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4046 }
4047 // Do not transform this into an iterator-based loop. The loop body can
4048 // trigger the creation of further types (through lazy deserialization) and
4049 // invalide iterators into this list.
4050 auto &Types = SemaRef.getASTContext().getTypes();
4051 for (unsigned I = 0; I != Types.size(); ++I) {
3
Assuming the condition is true
4
Loop condition is true. Entering loop body
7
Assuming the condition is true
8
Loop condition is true. Entering loop body
11
Assuming the condition is true
12
Loop condition is true. Entering loop body
15
Assuming the condition is true
16
Loop condition is true. Entering loop body
4052 const auto *TI = Types[I];
4053 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
5
Assuming 'CD' is null
6
Taking false branch
9
Assuming 'CD' is null
10
Taking false branch
13
Assuming 'CD' is null
14
Taking false branch
17
Assuming 'CD' is non-null
18
Taking true branch
4054 CD = CD->getCanonicalDecl();
4055 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
19
Assuming the condition is true
20
Assuming the condition is true
23
Taking true branch
4056 !CD->isUnion() && CD->getIdentifier() &&
4057 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4058 (CD->isBeingDefined() || CD->isCompleteDefinition()))
21
Assuming the condition is false
22
Assuming the condition is true
4059 Namespaces.addNameSpecifier(CD);
24
Calling 'NamespaceSpecifierSet::addNameSpecifier'
4060 }
4061 }
4062}
4063
4064const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4065 if (++CurrentTCIndex < ValidatedCorrections.size())
4066 return ValidatedCorrections[CurrentTCIndex];
4067
4068 CurrentTCIndex = ValidatedCorrections.size();
4069 while (!CorrectionResults.empty()) {
4070 auto DI = CorrectionResults.begin();
4071 if (DI->second.empty()) {
4072 CorrectionResults.erase(DI);
4073 continue;
4074 }
4075
4076 auto RI = DI->second.begin();
4077 if (RI->second.empty()) {
4078 DI->second.erase(RI);
4079 performQualifiedLookups();
4080 continue;
4081 }
4082
4083 TypoCorrection TC = RI->second.pop_back_val();
4084 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4085 ValidatedCorrections.push_back(TC);
4086 return ValidatedCorrections[CurrentTCIndex];
4087 }
4088 }
4089 return ValidatedCorrections[0]; // The empty correction.
4090}
4091
4092bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4093 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4094 DeclContext *TempMemberContext = MemberContext;
4095 CXXScopeSpec *TempSS = SS.get();
4096retry_lookup:
4097 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4098 EnteringContext,
4099 CorrectionValidator->IsObjCIvarLookup,
4100 Name == Typo && !Candidate.WillReplaceSpecifier());
4101 switch (Result.getResultKind()) {
4102 case LookupResult::NotFound:
4103 case LookupResult::NotFoundInCurrentInstantiation:
4104 case LookupResult::FoundUnresolvedValue:
4105 if (TempSS) {
4106 // Immediately retry the lookup without the given CXXScopeSpec
4107 TempSS = nullptr;
4108 Candidate.WillReplaceSpecifier(true);
4109 goto retry_lookup;
4110 }
4111 if (TempMemberContext) {
4112 if (SS && !TempSS)
4113 TempSS = SS.get();
4114 TempMemberContext = nullptr;
4115 goto retry_lookup;
4116 }
4117 if (SearchNamespaces)
4118 QualifiedResults.push_back(Candidate);
4119 break;
4120
4121 case LookupResult::Ambiguous:
4122 // We don't deal with ambiguities.
4123 break;
4124
4125 case LookupResult::Found:
4126 case LookupResult::FoundOverloaded:
4127 // Store all of the Decls for overloaded symbols
4128 for (auto *TRD : Result)
4129 Candidate.addCorrectionDecl(TRD);
4130 checkCorrectionVisibility(SemaRef, Candidate);
4131 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4132 if (SearchNamespaces)
4133 QualifiedResults.push_back(Candidate);
4134 break;
4135 }
4136 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4137 return true;
4138 }
4139 return false;
4140}
4141
4142void TypoCorrectionConsumer::performQualifiedLookups() {
4143 unsigned TypoLen = Typo->getName().size();
4144 for (const TypoCorrection &QR : QualifiedResults) {
4145 for (const auto &NSI : Namespaces) {
4146 DeclContext *Ctx = NSI.DeclCtx;
4147 const Type *NSType = NSI.NameSpecifier->getAsType();
4148
4149 // If the current NestedNameSpecifier refers to a class and the
4150 // current correction candidate is the name of that class, then skip
4151 // it as it is unlikely a qualified version of the class' constructor
4152 // is an appropriate correction.
4153 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4154 nullptr) {
4155 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4156 continue;
4157 }
4158
4159 TypoCorrection TC(QR);
4160 TC.ClearCorrectionDecls();
4161 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4162 TC.setQualifierDistance(NSI.EditDistance);
4163 TC.setCallbackDistance(0); // Reset the callback distance
4164
4165 // If the current correction candidate and namespace combination are
4166 // too far away from the original typo based on the normalized edit
4167 // distance, then skip performing a qualified name lookup.
4168 unsigned TmpED = TC.getEditDistance(true);
4169 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4170 TypoLen / TmpED < 3)
4171 continue;
4172
4173 Result.clear();
4174 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4175 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4176 continue;
4177
4178 // Any corrections added below will be validated in subsequent
4179 // iterations of the main while() loop over the Consumer's contents.
4180 switch (Result.getResultKind()) {
4181 case LookupResult::Found:
4182 case LookupResult::FoundOverloaded: {
4183 if (SS && SS->isValid()) {
4184 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4185 std::string OldQualified;
4186 llvm::raw_string_ostream OldOStream(OldQualified);
4187 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4188 OldOStream << Typo->getName();
4189 // If correction candidate would be an identical written qualified
4190 // identifer, then the existing CXXScopeSpec probably included a
4191 // typedef that didn't get accounted for properly.
4192 if (OldOStream.str() == NewQualified)
4193 break;
4194 }
4195 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4196 TRD != TRDEnd; ++TRD) {
4197 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4198 NSType ? NSType->getAsCXXRecordDecl()
4199 : nullptr,
4200 TRD.getPair()) == Sema::AR_accessible)
4201 TC.addCorrectionDecl(*TRD);
4202 }
4203 if (TC.isResolved()) {
4204 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4205 addCorrection(TC);
4206 }
4207 break;
4208 }
4209 case LookupResult::NotFound:
4210 case LookupResult::NotFoundInCurrentInstantiation:
4211 case LookupResult::Ambiguous:
4212 case LookupResult::FoundUnresolvedValue:
4213 break;
4214 }
4215 }
4216 }
4217 QualifiedResults.clear();
4218}
4219
4220TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4221 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4222 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4223 if (NestedNameSpecifier *NNS =
4224 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4225 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4226 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4227
4228 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4229 }
4230 // Build the list of identifiers that would be used for an absolute
4231 // (from the global context) NestedNameSpecifier referring to the current
4232 // context.
4233 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4234 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4235 CurContextIdentifiers.push_back(ND->getIdentifier());
4236 }
4237
4238 // Add the global context as a NestedNameSpecifier
4239 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4240 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4241 DistanceMap[1].push_back(SI);
4242}
4243
4244auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4245 DeclContext *Start) -> DeclContextList {
4246 assert(Start && "Building a context chain from a null context")((Start && "Building a context chain from a null context"
) ? static_cast<void> (0) : __assert_fail ("Start && \"Building a context chain from a null context\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 4246, __PRETTY_FUNCTION__))
;
4247 DeclContextList Chain;
4248 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4249 DC = DC->getLookupParent()) {
4250 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4251 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4252 !(ND && ND->isAnonymousNamespace()))
4253 Chain.push_back(DC->getPrimaryContext());
4254 }
4255 return Chain;
4256}
4257
4258unsigned
4259TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4260 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4261 unsigned NumSpecifiers = 0;
4262 for (DeclContext *C : llvm::reverse(DeclChain)) {
36
Calling 'reverse'
43
Returning from 'reverse'
44
Calling 'operator!='
48
Returning from 'operator!='
56
Calling 'operator!='
60
Returning from 'operator!='
4263 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
49
Calling 'dyn_cast_or_null'
51
Returning from 'dyn_cast_or_null'
52
Taking false branch
4264 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4265 ++NumSpecifiers;
4266 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
53
Calling 'dyn_cast_or_null'
54
Returning from 'dyn_cast_or_null'
55
Taking false branch
4267 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4268 RD->getTypeForDecl());
4269 ++NumSpecifiers;
4270 }
4271 }
4272 return NumSpecifiers;
4273}
4274
4275void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4276 DeclContext *Ctx) {
4277 NestedNameSpecifier *NNS = nullptr;
25
'NNS' initialized to a null pointer value
4278 unsigned NumSpecifiers = 0;
4279 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4280 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4281
4282 // Eliminate common elements from the two DeclContext chains.
4283 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4284 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
26
Assuming the condition is false
27
Taking false branch
28
Assuming the condition is false
29
Taking false branch
30
Assuming the condition is false
31
Taking false branch
32
Assuming the condition is true
33
Taking true branch
4285 break;
34
Execution continues on line 4290
4286 NamespaceDeclChain.pop_back();
4287 }
4288
4289 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4290 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
35
Calling 'NamespaceSpecifierSet::buildNestedNameSpecifier'
61
Returning from 'NamespaceSpecifierSet::buildNestedNameSpecifier'
4291
4292 // Add an explicit leading '::' specifier if needed.
4293 if (NamespaceDeclChain.empty()) {
62
Taking false branch
4294 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4295 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4296 NumSpecifiers =
4297 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4298 } else if (NamedDecl *ND =
63
Assuming 'ND' is non-null
64
Taking true branch
4299 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4300 IdentifierInfo *Name = ND->getIdentifier();
4301 bool SameNameSpecifier = false;
4302 if (std::find(CurNameSpecifierIdentifiers.begin(),
65
Assuming the condition is true
66
Taking true branch
4303 CurNameSpecifierIdentifiers.end(),
4304 Name) != CurNameSpecifierIdentifiers.end()) {
4305 std::string NewNameSpecifier;
4306 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4307 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4308 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
67
Passing null pointer value via 1st parameter 'NNS'
68
Calling 'getNestedNameSpecifierIdentifiers'
4309 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4310 SpecifierOStream.flush();
4311 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4312 }
4313 if (SameNameSpecifier ||
4314 std::find(CurContextIdentifiers.begin(), CurContextIdentifiers.end(),
4315 Name) != CurContextIdentifiers.end()) {
4316 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4317 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4318 NumSpecifiers =
4319 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4320 }
4321 }
4322
4323 // If the built NestedNameSpecifier would be replacing an existing
4324 // NestedNameSpecifier, use the number of component identifiers that
4325 // would need to be changed as the edit distance instead of the number
4326 // of components in the built NestedNameSpecifier.
4327 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4328 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4329 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4330 NumSpecifiers = llvm::ComputeEditDistance(
4331 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4332 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4333 }
4334
4335 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4336 DistanceMap[NumSpecifiers].push_back(SI);
4337}
4338
4339/// \brief Perform name lookup for a possible result for typo correction.
4340static void LookupPotentialTypoResult(Sema &SemaRef,
4341 LookupResult &Res,
4342 IdentifierInfo *Name,
4343 Scope *S, CXXScopeSpec *SS,
4344 DeclContext *MemberContext,
4345 bool EnteringContext,
4346 bool isObjCIvarLookup,
4347 bool FindHidden) {
4348 Res.suppressDiagnostics();
4349 Res.clear();
4350 Res.setLookupName(Name);
4351 Res.setAllowHidden(FindHidden);
4352 if (MemberContext) {
4353 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4354 if (isObjCIvarLookup) {
4355 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4356 Res.addDecl(Ivar);
4357 Res.resolveKind();
4358 return;
4359 }
4360 }
4361
4362 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4363 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4364 Res.addDecl(Prop);
4365 Res.resolveKind();
4366 return;
4367 }
4368 }
4369
4370 SemaRef.LookupQualifiedName(Res, MemberContext);
4371 return;
4372 }
4373
4374 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4375 EnteringContext);
4376
4377 // Fake ivar lookup; this should really be part of
4378 // LookupParsedName.
4379 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4380 if (Method->isInstanceMethod() && Method->getClassInterface() &&
4381 (Res.empty() ||
4382 (Res.isSingleResult() &&
4383 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4384 if (ObjCIvarDecl *IV
4385 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4386 Res.addDecl(IV);
4387 Res.resolveKind();
4388 }
4389 }
4390 }
4391}
4392
4393/// \brief Add keywords to the consumer as possible typo corrections.
4394static void AddKeywordsToConsumer(Sema &SemaRef,
4395 TypoCorrectionConsumer &Consumer,
4396 Scope *S, CorrectionCandidateCallback &CCC,
4397 bool AfterNestedNameSpecifier) {
4398 if (AfterNestedNameSpecifier) {
4399 // For 'X::', we know exactly which keywords can appear next.
4400 Consumer.addKeywordResult("template");
4401 if (CCC.WantExpressionKeywords)
4402 Consumer.addKeywordResult("operator");
4403 return;
4404 }
4405
4406 if (CCC.WantObjCSuper)
4407 Consumer.addKeywordResult("super");
4408
4409 if (CCC.WantTypeSpecifiers) {
4410 // Add type-specifier keywords to the set of results.
4411 static const char *const CTypeSpecs[] = {
4412 "char", "const", "double", "enum", "float", "int", "long", "short",
4413 "signed", "struct", "union", "unsigned", "void", "volatile",
4414 "_Complex", "_Imaginary",
4415 // storage-specifiers as well
4416 "extern", "inline", "static", "typedef"
4417 };
4418
4419 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4420 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4421 Consumer.addKeywordResult(CTypeSpecs[I]);
4422
4423 if (SemaRef.getLangOpts().C99)
4424 Consumer.addKeywordResult("restrict");
4425 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4426 Consumer.addKeywordResult("bool");
4427 else if (SemaRef.getLangOpts().C99)
4428 Consumer.addKeywordResult("_Bool");
4429
4430 if (SemaRef.getLangOpts().CPlusPlus) {
4431 Consumer.addKeywordResult("class");
4432 Consumer.addKeywordResult("typename");
4433 Consumer.addKeywordResult("wchar_t");
4434
4435 if (SemaRef.getLangOpts().CPlusPlus11) {
4436 Consumer.addKeywordResult("char16_t");
4437 Consumer.addKeywordResult("char32_t");
4438 Consumer.addKeywordResult("constexpr");
4439 Consumer.addKeywordResult("decltype");
4440 Consumer.addKeywordResult("thread_local");
4441 }
4442 }
4443
4444 if (SemaRef.getLangOpts().GNUMode)
4445 Consumer.addKeywordResult("typeof");
4446 } else if (CCC.WantFunctionLikeCasts) {
4447 static const char *const CastableTypeSpecs[] = {
4448 "char", "double", "float", "int", "long", "short",
4449 "signed", "unsigned", "void"
4450 };
4451 for (auto *kw : CastableTypeSpecs)
4452 Consumer.addKeywordResult(kw);
4453 }
4454
4455 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4456 Consumer.addKeywordResult("const_cast");
4457 Consumer.addKeywordResult("dynamic_cast");
4458 Consumer.addKeywordResult("reinterpret_cast");
4459 Consumer.addKeywordResult("static_cast");
4460 }
4461
4462 if (CCC.WantExpressionKeywords) {
4463 Consumer.addKeywordResult("sizeof");
4464 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4465 Consumer.addKeywordResult("false");
4466 Consumer.addKeywordResult("true");
4467 }
4468
4469 if (SemaRef.getLangOpts().CPlusPlus) {
4470 static const char *const CXXExprs[] = {
4471 "delete", "new", "operator", "throw", "typeid"
4472 };
4473 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4474 for (unsigned I = 0; I != NumCXXExprs; ++I)
4475 Consumer.addKeywordResult(CXXExprs[I]);
4476
4477 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4478 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4479 Consumer.addKeywordResult("this");
4480
4481 if (SemaRef.getLangOpts().CPlusPlus11) {
4482 Consumer.addKeywordResult("alignof");
4483 Consumer.addKeywordResult("nullptr");
4484 }
4485 }
4486
4487 if (SemaRef.getLangOpts().C11) {
4488 // FIXME: We should not suggest _Alignof if the alignof macro
4489 // is present.
4490 Consumer.addKeywordResult("_Alignof");
4491 }
4492 }
4493
4494 if (CCC.WantRemainingKeywords) {
4495 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4496 // Statements.
4497 static const char *const CStmts[] = {
4498 "do", "else", "for", "goto", "if", "return", "switch", "while" };
4499 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4500 for (unsigned I = 0; I != NumCStmts; ++I)
4501 Consumer.addKeywordResult(CStmts[I]);
4502
4503 if (SemaRef.getLangOpts().CPlusPlus) {
4504 Consumer.addKeywordResult("catch");
4505 Consumer.addKeywordResult("try");
4506 }
4507
4508 if (S && S->getBreakParent())
4509 Consumer.addKeywordResult("break");
4510
4511 if (S && S->getContinueParent())
4512 Consumer.addKeywordResult("continue");
4513
4514 if (!SemaRef.getCurFunction()->SwitchStack.empty()) {
4515 Consumer.addKeywordResult("case");
4516 Consumer.addKeywordResult("default");
4517 }
4518 } else {
4519 if (SemaRef.getLangOpts().CPlusPlus) {
4520 Consumer.addKeywordResult("namespace");
4521 Consumer.addKeywordResult("template");
4522 }
4523
4524 if (S && S->isClassScope()) {
4525 Consumer.addKeywordResult("explicit");
4526 Consumer.addKeywordResult("friend");
4527 Consumer.addKeywordResult("mutable");
4528 Consumer.addKeywordResult("private");
4529 Consumer.addKeywordResult("protected");
4530 Consumer.addKeywordResult("public");
4531 Consumer.addKeywordResult("virtual");
4532 }
4533 }
4534
4535 if (SemaRef.getLangOpts().CPlusPlus) {
4536 Consumer.addKeywordResult("using");
4537
4538 if (SemaRef.getLangOpts().CPlusPlus11)
4539 Consumer.addKeywordResult("static_assert");
4540 }
4541 }
4542}
4543
4544std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4545 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4546 Scope *S, CXXScopeSpec *SS,
4547 std::unique_ptr<CorrectionCandidateCallback> CCC,
4548 DeclContext *MemberContext, bool EnteringContext,
4549 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4550
4551 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4552 DisableTypoCorrection)
4553 return nullptr;
4554
4555 // In Microsoft mode, don't perform typo correction in a template member
4556 // function dependent context because it interferes with the "lookup into
4557 // dependent bases of class templates" feature.
4558 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4559 isa<CXXMethodDecl>(CurContext))
4560 return nullptr;
4561
4562 // We only attempt to correct typos for identifiers.
4563 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4564 if (!Typo)
4565 return nullptr;
4566
4567 // If the scope specifier itself was invalid, don't try to correct
4568 // typos.
4569 if (SS && SS->isInvalid())
4570 return nullptr;
4571
4572 // Never try to correct typos during any kind of code synthesis.
4573 if (!CodeSynthesisContexts.empty())
4574 return nullptr;
4575
4576 // Don't try to correct 'super'.
4577 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4578 return nullptr;
4579
4580 // Abort if typo correction already failed for this specific typo.
4581 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4582 if (locs != TypoCorrectionFailures.end() &&
4583 locs->second.count(TypoName.getLoc()))
4584 return nullptr;
4585
4586 // Don't try to correct the identifier "vector" when in AltiVec mode.
4587 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4588 // remove this workaround.
4589 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4590 return nullptr;
4591
4592 // Provide a stop gap for files that are just seriously broken. Trying
4593 // to correct all typos can turn into a HUGE performance penalty, causing
4594 // some files to take minutes to get rejected by the parser.
4595 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4596 if (Limit && TyposCorrected >= Limit)
4597 return nullptr;
4598 ++TyposCorrected;
4599
4600 // If we're handling a missing symbol error, using modules, and the
4601 // special search all modules option is used, look for a missing import.
4602 if (ErrorRecovery && getLangOpts().Modules &&
4603 getLangOpts().ModulesSearchAll) {
4604 // The following has the side effect of loading the missing module.
4605 getModuleLoader().lookupMissingImports(Typo->getName(),
4606 TypoName.getLocStart());
4607 }
4608
4609 CorrectionCandidateCallback &CCCRef = *CCC;
4610 auto Consumer = llvm::make_unique<TypoCorrectionConsumer>(
4611 *this, TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4612 EnteringContext);
4613
4614 // Perform name lookup to find visible, similarly-named entities.
4615 bool IsUnqualifiedLookup = false;
4616 DeclContext *QualifiedDC = MemberContext;
4617 if (MemberContext) {
4618 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4619
4620 // Look in qualified interfaces.
4621 if (OPT) {
4622 for (auto *I : OPT->quals())
4623 LookupVisibleDecls(I, LookupKind, *Consumer);
4624 }
4625 } else if (SS && SS->isSet()) {
4626 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4627 if (!QualifiedDC)
4628 return nullptr;
4629
4630 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4631 } else {
4632 IsUnqualifiedLookup = true;
4633 }
4634
4635 // Determine whether we are going to search in the various namespaces for
4636 // corrections.
4637 bool SearchNamespaces
4638 = getLangOpts().CPlusPlus &&
4639 (IsUnqualifiedLookup || (SS && SS->isSet()));
4640
4641 if (IsUnqualifiedLookup || SearchNamespaces) {
4642 // For unqualified lookup, look through all of the names that we have
4643 // seen in this translation unit.
4644 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4645 for (const auto &I : Context.Idents)
4646 Consumer->FoundName(I.getKey());
4647
4648 // Walk through identifiers in external identifier sources.
4649 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4650 if (IdentifierInfoLookup *External
4651 = Context.Idents.getExternalIdentifierLookup()) {
4652 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4653 do {
4654 StringRef Name = Iter->Next();
4655 if (Name.empty())
4656 break;
4657
4658 Consumer->FoundName(Name);
4659 } while (true);
4660 }
4661 }
4662
4663 AddKeywordsToConsumer(*this, *Consumer, S, CCCRef, SS && SS->isNotEmpty());
4664
4665 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4666 // to search those namespaces.
4667 if (SearchNamespaces) {
4668 // Load any externally-known namespaces.
4669 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4670 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4671 LoadedExternalKnownNamespaces = true;
4672 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4673 for (auto *N : ExternalKnownNamespaces)
4674 KnownNamespaces[N] = true;
4675 }
4676
4677 Consumer->addNamespaces(KnownNamespaces);
4678 }
4679
4680 return Consumer;
4681}
4682
4683/// \brief Try to "correct" a typo in the source code by finding
4684/// visible declarations whose names are similar to the name that was
4685/// present in the source code.
4686///
4687/// \param TypoName the \c DeclarationNameInfo structure that contains
4688/// the name that was present in the source code along with its location.
4689///
4690/// \param LookupKind the name-lookup criteria used to search for the name.
4691///
4692/// \param S the scope in which name lookup occurs.
4693///
4694/// \param SS the nested-name-specifier that precedes the name we're
4695/// looking for, if present.
4696///
4697/// \param CCC A CorrectionCandidateCallback object that provides further
4698/// validation of typo correction candidates. It also provides flags for
4699/// determining the set of keywords permitted.
4700///
4701/// \param MemberContext if non-NULL, the context in which to look for
4702/// a member access expression.
4703///
4704/// \param EnteringContext whether we're entering the context described by
4705/// the nested-name-specifier SS.
4706///
4707/// \param OPT when non-NULL, the search for visible declarations will
4708/// also walk the protocols in the qualified interfaces of \p OPT.
4709///
4710/// \returns a \c TypoCorrection containing the corrected name if the typo
4711/// along with information such as the \c NamedDecl where the corrected name
4712/// was declared, and any additional \c NestedNameSpecifier needed to access
4713/// it (C++ only). The \c TypoCorrection is empty if there is no correction.
4714TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4715 Sema::LookupNameKind LookupKind,
4716 Scope *S, CXXScopeSpec *SS,
4717 std::unique_ptr<CorrectionCandidateCallback> CCC,
4718 CorrectTypoKind Mode,
4719 DeclContext *MemberContext,
4720 bool EnteringContext,
4721 const ObjCObjectPointerType *OPT,
4722 bool RecordFailure) {
4723 assert(CCC && "CorrectTypo requires a CorrectionCandidateCallback")((CCC && "CorrectTypo requires a CorrectionCandidateCallback"
) ? static_cast<void> (0) : __assert_fail ("CCC && \"CorrectTypo requires a CorrectionCandidateCallback\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 4723, __PRETTY_FUNCTION__))
;
4724
4725 // Always let the ExternalSource have the first chance at correction, even
4726 // if we would otherwise have given up.
4727 if (ExternalSource) {
4728 if (TypoCorrection Correction = ExternalSource->CorrectTypo(
4729 TypoName, LookupKind, S, SS, *CCC, MemberContext, EnteringContext, OPT))
4730 return Correction;
4731 }
4732
4733 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4734 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4735 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4736 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4737 bool ObjCMessageReceiver = CCC->WantObjCSuper && !CCC->WantRemainingKeywords;
4738
4739 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4740 auto Consumer = makeTypoCorrectionConsumer(
4741 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4742 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4743
4744 if (!Consumer)
4745 return TypoCorrection();
4746
4747 // If we haven't found anything, we're done.
4748 if (Consumer->empty())
4749 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4750
4751 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4752 // is not more that about a third of the length of the typo's identifier.
4753 unsigned ED = Consumer->getBestEditDistance(true);
4754 unsigned TypoLen = Typo->getName().size();
4755 if (ED > 0 && TypoLen / ED < 3)
4756 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4757
4758 TypoCorrection BestTC = Consumer->getNextCorrection();
4759 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
4760 if (!BestTC)
4761 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4762
4763 ED = BestTC.getEditDistance();
4764
4765 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
4766 // If this was an unqualified lookup and we believe the callback
4767 // object wouldn't have filtered out possible corrections, note
4768 // that no correction was found.
4769 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4770 }
4771
4772 // If only a single name remains, return that result.
4773 if (!SecondBestTC ||
4774 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
4775 const TypoCorrection &Result = BestTC;
4776
4777 // Don't correct to a keyword that's the same as the typo; the keyword
4778 // wasn't actually in scope.
4779 if (ED == 0 && Result.isKeyword())
4780 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4781
4782 TypoCorrection TC = Result;
4783 TC.setCorrectionRange(SS, TypoName);
4784 checkCorrectionVisibility(*this, TC);
4785 return TC;
4786 } else if (SecondBestTC && ObjCMessageReceiver) {
4787 // Prefer 'super' when we're completing in a message-receiver
4788 // context.
4789
4790 if (BestTC.getCorrection().getAsString() != "super") {
4791 if (SecondBestTC.getCorrection().getAsString() == "super")
4792 BestTC = SecondBestTC;
4793 else if ((*Consumer)["super"].front().isKeyword())
4794 BestTC = (*Consumer)["super"].front();
4795 }
4796 // Don't correct to a keyword that's the same as the typo; the keyword
4797 // wasn't actually in scope.
4798 if (BestTC.getEditDistance() == 0 ||
4799 BestTC.getCorrection().getAsString() != "super")
4800 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4801
4802 BestTC.setCorrectionRange(SS, TypoName);
4803 return BestTC;
4804 }
4805
4806 // Record the failure's location if needed and return an empty correction. If
4807 // this was an unqualified lookup and we believe the callback object did not
4808 // filter out possible corrections, also cache the failure for the typo.
4809 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
4810}
4811
4812/// \brief Try to "correct" a typo in the source code by finding
4813/// visible declarations whose names are similar to the name that was
4814/// present in the source code.
4815///
4816/// \param TypoName the \c DeclarationNameInfo structure that contains
4817/// the name that was present in the source code along with its location.
4818///
4819/// \param LookupKind the name-lookup criteria used to search for the name.
4820///
4821/// \param S the scope in which name lookup occurs.
4822///
4823/// \param SS the nested-name-specifier that precedes the name we're
4824/// looking for, if present.
4825///
4826/// \param CCC A CorrectionCandidateCallback object that provides further
4827/// validation of typo correction candidates. It also provides flags for
4828/// determining the set of keywords permitted.
4829///
4830/// \param TDG A TypoDiagnosticGenerator functor that will be used to print
4831/// diagnostics when the actual typo correction is attempted.
4832///
4833/// \param TRC A TypoRecoveryCallback functor that will be used to build an
4834/// Expr from a typo correction candidate.
4835///
4836/// \param MemberContext if non-NULL, the context in which to look for
4837/// a member access expression.
4838///
4839/// \param EnteringContext whether we're entering the context described by
4840/// the nested-name-specifier SS.
4841///
4842/// \param OPT when non-NULL, the search for visible declarations will
4843/// also walk the protocols in the qualified interfaces of \p OPT.
4844///
4845/// \returns a new \c TypoExpr that will later be replaced in the AST with an
4846/// Expr representing the result of performing typo correction, or nullptr if
4847/// typo correction is not possible. If nullptr is returned, no diagnostics will
4848/// be emitted and it is the responsibility of the caller to emit any that are
4849/// needed.
4850TypoExpr *Sema::CorrectTypoDelayed(
4851 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4852 Scope *S, CXXScopeSpec *SS,
4853 std::unique_ptr<CorrectionCandidateCallback> CCC,
4854 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
4855 DeclContext *MemberContext, bool EnteringContext,
4856 const ObjCObjectPointerType *OPT) {
4857 assert(CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback")((CCC && "CorrectTypoDelayed requires a CorrectionCandidateCallback"
) ? static_cast<void> (0) : __assert_fail ("CCC && \"CorrectTypoDelayed requires a CorrectionCandidateCallback\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 4857, __PRETTY_FUNCTION__))
;
4858
4859 auto Consumer = makeTypoCorrectionConsumer(
4860 TypoName, LookupKind, S, SS, std::move(CCC), MemberContext,
4861 EnteringContext, OPT, Mode == CTK_ErrorRecovery);
4862
4863 // Give the external sema source a chance to correct the typo.
4864 TypoCorrection ExternalTypo;
4865 if (ExternalSource && Consumer) {
4866 ExternalTypo = ExternalSource->CorrectTypo(
4867 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
4868 MemberContext, EnteringContext, OPT);
4869 if (ExternalTypo)
4870 Consumer->addCorrection(ExternalTypo);
4871 }
4872
4873 if (!Consumer || Consumer->empty())
4874 return nullptr;
4875
4876 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4877 // is not more that about a third of the length of the typo's identifier.
4878 unsigned ED = Consumer->getBestEditDistance(true);
4879 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4880 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
4881 return nullptr;
4882
4883 ExprEvalContexts.back().NumTypos++;
4884 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC));
4885}
4886
4887void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
4888 if (!CDecl) return;
4889
4890 if (isKeyword())
4891 CorrectionDecls.clear();
4892
4893 CorrectionDecls.push_back(CDecl);
4894
4895 if (!CorrectionName)
4896 CorrectionName = CDecl->getDeclName();
4897}
4898
4899std::string TypoCorrection::getAsString(const LangOptions &LO) const {
4900 if (CorrectionNameSpec) {
4901 std::string tmpBuffer;
4902 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
4903 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
4904 PrefixOStream << CorrectionName;
4905 return PrefixOStream.str();
4906 }
4907
4908 return CorrectionName.getAsString();
4909}
4910
4911bool CorrectionCandidateCallback::ValidateCandidate(
4912 const TypoCorrection &candidate) {
4913 if (!candidate.isResolved())
4914 return true;
4915
4916 if (candidate.isKeyword())
4917 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
4918 WantRemainingKeywords || WantObjCSuper;
4919
4920 bool HasNonType = false;
4921 bool HasStaticMethod = false;
4922 bool HasNonStaticMethod = false;
4923 for (Decl *D : candidate) {
4924 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
4925 D = FTD->getTemplatedDecl();
4926 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4927 if (Method->isStatic())
4928 HasStaticMethod = true;
4929 else
4930 HasNonStaticMethod = true;
4931 }
4932 if (!isa<TypeDecl>(D))
4933 HasNonType = true;
4934 }
4935
4936 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
4937 !candidate.getCorrectionSpecifier())
4938 return false;
4939
4940 return WantTypeSpecifiers || HasNonType;
4941}
4942
4943FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
4944 bool HasExplicitTemplateArgs,
4945 MemberExpr *ME)
4946 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
4947 CurContext(SemaRef.CurContext), MemberFn(ME) {
4948 WantTypeSpecifiers = false;
4949 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus && NumArgs == 1;
4950 WantRemainingKeywords = false;
4951}
4952
4953bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
4954 if (!candidate.getCorrectionDecl())
4955 return candidate.isKeyword();
4956
4957 for (auto *C : candidate) {
4958 FunctionDecl *FD = nullptr;
4959 NamedDecl *ND = C->getUnderlyingDecl();
4960 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
4961 FD = FTD->getTemplatedDecl();
4962 if (!HasExplicitTemplateArgs && !FD) {
4963 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
4964 // If the Decl is neither a function nor a template function,
4965 // determine if it is a pointer or reference to a function. If so,
4966 // check against the number of arguments expected for the pointee.
4967 QualType ValType = cast<ValueDecl>(ND)->getType();
4968 if (ValType->isAnyPointerType() || ValType->isReferenceType())
4969 ValType = ValType->getPointeeType();
4970 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
4971 if (FPT->getNumParams() == NumArgs)
4972 return true;
4973 }
4974 }
4975
4976 // Skip the current candidate if it is not a FunctionDecl or does not accept
4977 // the current number of arguments.
4978 if (!FD || !(FD->getNumParams() >= NumArgs &&
4979 FD->getMinRequiredArguments() <= NumArgs))
4980 continue;
4981
4982 // If the current candidate is a non-static C++ method, skip the candidate
4983 // unless the method being corrected--or the current DeclContext, if the
4984 // function being corrected is not a method--is a method in the same class
4985 // or a descendent class of the candidate's parent class.
4986 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
4987 if (MemberFn || !MD->isStatic()) {
4988 CXXMethodDecl *CurMD =
4989 MemberFn
4990 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
4991 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
4992 CXXRecordDecl *CurRD =
4993 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
4994 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
4995 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
4996 continue;
4997 }
4998 }
4999 return true;
5000 }
5001 return false;
5002}
5003
5004void Sema::diagnoseTypo(const TypoCorrection &Correction,
5005 const PartialDiagnostic &TypoDiag,
5006 bool ErrorRecovery) {
5007 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5008 ErrorRecovery);
5009}
5010
5011/// Find which declaration we should import to provide the definition of
5012/// the given declaration.
5013static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5014 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5015 return VD->getDefinition();
5016 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5017 return FD->getDefinition();
5018 if (TagDecl *TD = dyn_cast<TagDecl>(D))
5019 return TD->getDefinition();
5020 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5021 return ID->getDefinition();
5022 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5023 return PD->getDefinition();
5024 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5025 return getDefinitionToImport(TD->getTemplatedDecl());
5026 return nullptr;
5027}
5028
5029void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5030 MissingImportKind MIK, bool Recover) {
5031 // Suggest importing a module providing the definition of this entity, if
5032 // possible.
5033 NamedDecl *Def = getDefinitionToImport(Decl);
5034 if (!Def)
5035 Def = Decl;
5036
5037 Module *Owner = getOwningModule(Decl);
5038 assert(Owner && "definition of hidden declaration is not in a module")((Owner && "definition of hidden declaration is not in a module"
) ? static_cast<void> (0) : __assert_fail ("Owner && \"definition of hidden declaration is not in a module\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5038, __PRETTY_FUNCTION__))
;
5039
5040 llvm::SmallVector<Module*, 8> OwningModules;
5041 OwningModules.push_back(Owner);
5042 auto Merged = Context.getModulesWithMergedDefinition(Decl);
5043 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5044
5045 diagnoseMissingImport(Loc, Decl, Decl->getLocation(), OwningModules, MIK,
5046 Recover);
5047}
5048
5049/// \brief Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5050/// suggesting the addition of a #include of the specified file.
5051static std::string getIncludeStringForHeader(Preprocessor &PP,
5052 const FileEntry *E) {
5053 bool IsSystem;
5054 auto Path =
5055 PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(E, &IsSystem);
5056 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5057}
5058
5059void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5060 SourceLocation DeclLoc,
5061 ArrayRef<Module *> Modules,
5062 MissingImportKind MIK, bool Recover) {
5063 assert(!Modules.empty())((!Modules.empty()) ? static_cast<void> (0) : __assert_fail
("!Modules.empty()", "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5063, __PRETTY_FUNCTION__))
;
5064
5065 // Weed out duplicates from module list.
5066 llvm::SmallVector<Module*, 8> UniqueModules;
5067 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5068 for (auto *M : Modules)
5069 if (UniqueModuleSet.insert(M).second)
5070 UniqueModules.push_back(M);
5071 Modules = UniqueModules;
5072
5073 if (Modules.size() > 1) {
5074 std::string ModuleList;
5075 unsigned N = 0;
5076 for (Module *M : Modules) {
5077 ModuleList += "\n ";
5078 if (++N == 5 && N != Modules.size()) {
5079 ModuleList += "[...]";
5080 break;
5081 }
5082 ModuleList += M->getFullModuleName();
5083 }
5084
5085 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5086 << (int)MIK << Decl << ModuleList;
5087 } else if (const FileEntry *E = PP.getModuleHeaderToIncludeForDiagnostics(
5088 UseLoc, Modules[0], DeclLoc)) {
5089 // The right way to make the declaration visible is to include a header;
5090 // suggest doing so.
5091 //
5092 // FIXME: Find a smart place to suggest inserting a #include, and add
5093 // a FixItHint there.
5094 Diag(UseLoc, diag::err_module_unimported_use_header)
5095 << (int)MIK << Decl << Modules[0]->getFullModuleName()
5096 << getIncludeStringForHeader(PP, E);
5097 } else {
5098 // FIXME: Add a FixItHint that imports the corresponding module.
5099 Diag(UseLoc, diag::err_module_unimported_use)
5100 << (int)MIK << Decl << Modules[0]->getFullModuleName();
5101 }
5102
5103 unsigned DiagID;
5104 switch (MIK) {
5105 case MissingImportKind::Declaration:
5106 DiagID = diag::note_previous_declaration;
5107 break;
5108 case MissingImportKind::Definition:
5109 DiagID = diag::note_previous_definition;
5110 break;
5111 case MissingImportKind::DefaultArgument:
5112 DiagID = diag::note_default_argument_declared_here;
5113 break;
5114 case MissingImportKind::ExplicitSpecialization:
5115 DiagID = diag::note_explicit_specialization_declared_here;
5116 break;
5117 case MissingImportKind::PartialSpecialization:
5118 DiagID = diag::note_partial_specialization_declared_here;
5119 break;
5120 }
5121 Diag(DeclLoc, DiagID);
5122
5123 // Try to recover by implicitly importing this module.
5124 if (Recover)
5125 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5126}
5127
5128/// \brief Diagnose a successfully-corrected typo. Separated from the correction
5129/// itself to allow external validation of the result, etc.
5130///
5131/// \param Correction The result of performing typo correction.
5132/// \param TypoDiag The diagnostic to produce. This will have the corrected
5133/// string added to it (and usually also a fixit).
5134/// \param PrevNote A note to use when indicating the location of the entity to
5135/// which we are correcting. Will have the correction string added to it.
5136/// \param ErrorRecovery If \c true (the default), the caller is going to
5137/// recover from the typo as if the corrected string had been typed.
5138/// In this case, \c PDiag must be an error, and we will attach a fixit
5139/// to it.
5140void Sema::diagnoseTypo(const TypoCorrection &Correction,
5141 const PartialDiagnostic &TypoDiag,
5142 const PartialDiagnostic &PrevNote,
5143 bool ErrorRecovery) {
5144 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5145 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5146 FixItHint FixTypo = FixItHint::CreateReplacement(
5147 Correction.getCorrectionRange(), CorrectedStr);
5148
5149 // Maybe we're just missing a module import.
5150 if (Correction.requiresImport()) {
5151 NamedDecl *Decl = Correction.getFoundDecl();
5152 assert(Decl && "import required but no declaration to import")((Decl && "import required but no declaration to import"
) ? static_cast<void> (0) : __assert_fail ("Decl && \"import required but no declaration to import\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5152, __PRETTY_FUNCTION__))
;
5153
5154 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5155 MissingImportKind::Declaration, ErrorRecovery);
5156 return;
5157 }
5158
5159 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5160 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5161
5162 NamedDecl *ChosenDecl =
5163 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5164 if (PrevNote.getDiagID() && ChosenDecl)
5165 Diag(ChosenDecl->getLocation(), PrevNote)
5166 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5167
5168 // Add any extra diagnostics.
5169 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5170 Diag(Correction.getCorrectionRange().getBegin(), PD);
5171}
5172
5173TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5174 TypoDiagnosticGenerator TDG,
5175 TypoRecoveryCallback TRC) {
5176 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer")((TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer"
) ? static_cast<void> (0) : __assert_fail ("TCC && \"createDelayedTypo requires a valid TypoCorrectionConsumer\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5176, __PRETTY_FUNCTION__))
;
5177 auto TE = new (Context) TypoExpr(Context.DependentTy);
5178 auto &State = DelayedTypos[TE];
5179 State.Consumer = std::move(TCC);
5180 State.DiagHandler = std::move(TDG);
5181 State.RecoveryHandler = std::move(TRC);
5182 return TE;
5183}
5184
5185const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5186 auto Entry = DelayedTypos.find(TE);
5187 assert(Entry != DelayedTypos.end() &&((Entry != DelayedTypos.end() && "Failed to get the state for a TypoExpr!"
) ? static_cast<void> (0) : __assert_fail ("Entry != DelayedTypos.end() && \"Failed to get the state for a TypoExpr!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5188, __PRETTY_FUNCTION__))
5188 "Failed to get the state for a TypoExpr!")((Entry != DelayedTypos.end() && "Failed to get the state for a TypoExpr!"
) ? static_cast<void> (0) : __assert_fail ("Entry != DelayedTypos.end() && \"Failed to get the state for a TypoExpr!\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/tools/clang/lib/Sema/SemaLookup.cpp"
, 5188, __PRETTY_FUNCTION__))
;
5189 return Entry->second;
5190}
5191
5192void Sema::clearDelayedTypo(TypoExpr *TE) {
5193 DelayedTypos.erase(TE);
5194}
5195
5196void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5197 DeclarationNameInfo Name(II, IILoc);
5198 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5199 R.suppressDiagnostics();
5200 R.setHideTags(false);
5201 LookupName(R, S);
5202 R.dump();
5203}

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h

1//===- llvm/ADT/STLExtras.h - Useful STL related functions ------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file contains some templates that are useful if you are working with the
11// STL at all.
12//
13// No library is required when using these functions.
14//
15//===----------------------------------------------------------------------===//
16
17#ifndef LLVM_ADT_STLEXTRAS_H
18#define LLVM_ADT_STLEXTRAS_H
19
20#include "llvm/ADT/Optional.h"
21#include "llvm/ADT/SmallVector.h"
22#include "llvm/ADT/iterator.h"
23#include "llvm/ADT/iterator_range.h"
24#include "llvm/Support/ErrorHandling.h"
25#include <algorithm>
26#include <cassert>
27#include <cstddef>
28#include <cstdint>
29#include <cstdlib>
30#include <functional>
31#include <initializer_list>
32#include <iterator>
33#include <limits>
34#include <memory>
35#include <tuple>
36#include <type_traits>
37#include <utility>
38
39namespace llvm {
40
41// Only used by compiler if both template types are the same. Useful when
42// using SFINAE to test for the existence of member functions.
43template <typename T, T> struct SameType;
44
45namespace detail {
46
47template <typename RangeT>
48using IterOfRange = decltype(std::begin(std::declval<RangeT &>()));
49
50template <typename RangeT>
51using ValueOfRange = typename std::remove_reference<decltype(
52 *std::begin(std::declval<RangeT &>()))>::type;
53
54} // end namespace detail
55
56//===----------------------------------------------------------------------===//
57// Extra additions to <functional>
58//===----------------------------------------------------------------------===//
59
60template <class Ty> struct identity {
61 using argument_type = Ty;
62
63 Ty &operator()(Ty &self) const {
64 return self;
65 }
66 const Ty &operator()(const Ty &self) const {
67 return self;
68 }
69};
70
71template <class Ty> struct less_ptr {
72 bool operator()(const Ty* left, const Ty* right) const {
73 return *left < *right;
74 }
75};
76
77template <class Ty> struct greater_ptr {
78 bool operator()(const Ty* left, const Ty* right) const {
79 return *right < *left;
80 }
81};
82
83/// An efficient, type-erasing, non-owning reference to a callable. This is
84/// intended for use as the type of a function parameter that is not used
85/// after the function in question returns.
86///
87/// This class does not own the callable, so it is not in general safe to store
88/// a function_ref.
89template<typename Fn> class function_ref;
90
91template<typename Ret, typename ...Params>
92class function_ref<Ret(Params...)> {
93 Ret (*callback)(intptr_t callable, Params ...params) = nullptr;
94 intptr_t callable;
95
96 template<typename Callable>
97 static Ret callback_fn(intptr_t callable, Params ...params) {
98 return (*reinterpret_cast<Callable*>(callable))(
99 std::forward<Params>(params)...);
100 }
101
102public:
103 function_ref() = default;
104
105 template <typename Callable>
106 function_ref(Callable &&callable,
107 typename std::enable_if<
108 !std::is_same<typename std::remove_reference<Callable>::type,
109 function_ref>::value>::type * = nullptr)
110 : callback(callback_fn<typename std::remove_reference<Callable>::type>),
111 callable(reinterpret_cast<intptr_t>(&callable)) {}
112
113 Ret operator()(Params ...params) const {
114 return callback(callable, std::forward<Params>(params)...);
115 }
116
117 operator bool() const { return callback; }
118};
119
120// deleter - Very very very simple method that is used to invoke operator
121// delete on something. It is used like this:
122//
123// for_each(V.begin(), B.end(), deleter<Interval>);
124template <class T>
125inline void deleter(T *Ptr) {
126 delete Ptr;
127}
128
129//===----------------------------------------------------------------------===//
130// Extra additions to <iterator>
131//===----------------------------------------------------------------------===//
132
133// mapped_iterator - This is a simple iterator adapter that causes a function to
134// be applied whenever operator* is invoked on the iterator.
135
136template <typename ItTy, typename FuncTy,
137 typename FuncReturnTy =
138 decltype(std::declval<FuncTy>()(*std::declval<ItTy>()))>
139class mapped_iterator
140 : public iterator_adaptor_base<
141 mapped_iterator<ItTy, FuncTy>, ItTy,
142 typename std::iterator_traits<ItTy>::iterator_category,
143 typename std::remove_reference<FuncReturnTy>::type> {
144public:
145 mapped_iterator(ItTy U, FuncTy F)
146 : mapped_iterator::iterator_adaptor_base(std::move(U)), F(std::move(F)) {}
147
148 ItTy getCurrent() { return this->I; }
149
150 FuncReturnTy operator*() { return F(*this->I); }
151
152private:
153 FuncTy F;
154};
155
156// map_iterator - Provide a convenient way to create mapped_iterators, just like
157// make_pair is useful for creating pairs...
158template <class ItTy, class FuncTy>
159inline mapped_iterator<ItTy, FuncTy> map_iterator(ItTy I, FuncTy F) {
160 return mapped_iterator<ItTy, FuncTy>(std::move(I), std::move(F));
161}
162
163/// Helper to determine if type T has a member called rbegin().
164template <typename Ty> class has_rbegin_impl {
165 using yes = char[1];
166 using no = char[2];
167
168 template <typename Inner>
169 static yes& test(Inner *I, decltype(I->rbegin()) * = nullptr);
170
171 template <typename>
172 static no& test(...);
173
174public:
175 static const bool value = sizeof(test<Ty>(nullptr)) == sizeof(yes);
176};
177
178/// Metafunction to determine if T& or T has a member called rbegin().
179template <typename Ty>
180struct has_rbegin : has_rbegin_impl<typename std::remove_reference<Ty>::type> {
181};
182
183// Returns an iterator_range over the given container which iterates in reverse.
184// Note that the container must have rbegin()/rend() methods for this to work.
185template <typename ContainerTy>
186auto reverse(ContainerTy &&C,
187 typename std::enable_if<has_rbegin<ContainerTy>::value>::type * =
188 nullptr) -> decltype(make_range(C.rbegin(), C.rend())) {
189 return make_range(C.rbegin(), C.rend());
37
Calling 'make_range'
42
Returning from 'make_range'
190}
191
192// Returns a std::reverse_iterator wrapped around the given iterator.
193template <typename IteratorTy>
194std::reverse_iterator<IteratorTy> make_reverse_iterator(IteratorTy It) {
195 return std::reverse_iterator<IteratorTy>(It);
196}
197
198// Returns an iterator_range over the given container which iterates in reverse.
199// Note that the container must have begin()/end() methods which return
200// bidirectional iterators for this to work.
201template <typename ContainerTy>
202auto reverse(
203 ContainerTy &&C,
204 typename std::enable_if<!has_rbegin<ContainerTy>::value>::type * = nullptr)
205 -> decltype(make_range(llvm::make_reverse_iterator(std::end(C)),
206 llvm::make_reverse_iterator(std::begin(C)))) {
207 return make_range(llvm::make_reverse_iterator(std::end(C)),
208 llvm::make_reverse_iterator(std::begin(C)));
209}
210
211/// An iterator adaptor that filters the elements of given inner iterators.
212///
213/// The predicate parameter should be a callable object that accepts the wrapped
214/// iterator's reference type and returns a bool. When incrementing or
215/// decrementing the iterator, it will call the predicate on each element and
216/// skip any where it returns false.
217///
218/// \code
219/// int A[] = { 1, 2, 3, 4 };
220/// auto R = make_filter_range(A, [](int N) { return N % 2 == 1; });
221/// // R contains { 1, 3 }.
222/// \endcode
223template <typename WrappedIteratorT, typename PredicateT>
224class filter_iterator
225 : public iterator_adaptor_base<
226 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
227 typename std::common_type<
228 std::forward_iterator_tag,
229 typename std::iterator_traits<
230 WrappedIteratorT>::iterator_category>::type> {
231 using BaseT = iterator_adaptor_base<
232 filter_iterator<WrappedIteratorT, PredicateT>, WrappedIteratorT,
233 typename std::common_type<
234 std::forward_iterator_tag,
235 typename std::iterator_traits<WrappedIteratorT>::iterator_category>::
236 type>;
237
238 struct PayloadType {
239 WrappedIteratorT End;
240 PredicateT Pred;
241 };
242
243 Optional<PayloadType> Payload;
244
245 void findNextValid() {
246 assert(Payload && "Payload should be engaged when findNextValid is called")((Payload && "Payload should be engaged when findNextValid is called"
) ? static_cast<void> (0) : __assert_fail ("Payload && \"Payload should be engaged when findNextValid is called\""
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 246, __PRETTY_FUNCTION__))
;
247 while (this->I != Payload->End && !Payload->Pred(*this->I))
248 BaseT::operator++();
249 }
250
251 // Construct the begin iterator. The begin iterator requires to know where end
252 // is, so that it can properly stop when it hits end.
253 filter_iterator(WrappedIteratorT Begin, WrappedIteratorT End, PredicateT Pred)
254 : BaseT(std::move(Begin)),
255 Payload(PayloadType{std::move(End), std::move(Pred)}) {
256 findNextValid();
257 }
258
259 // Construct the end iterator. It's not incrementable, so Payload doesn't
260 // have to be engaged.
261 filter_iterator(WrappedIteratorT End) : BaseT(End) {}
262
263public:
264 using BaseT::operator++;
265
266 filter_iterator &operator++() {
267 BaseT::operator++();
268 findNextValid();
269 return *this;
270 }
271
272 template <typename RT, typename PT>
273 friend iterator_range<filter_iterator<detail::IterOfRange<RT>, PT>>
274 make_filter_range(RT &&, PT);
275};
276
277/// Convenience function that takes a range of elements and a predicate,
278/// and return a new filter_iterator range.
279///
280/// FIXME: Currently if RangeT && is a rvalue reference to a temporary, the
281/// lifetime of that temporary is not kept by the returned range object, and the
282/// temporary is going to be dropped on the floor after the make_iterator_range
283/// full expression that contains this function call.
284template <typename RangeT, typename PredicateT>
285iterator_range<filter_iterator<detail::IterOfRange<RangeT>, PredicateT>>
286make_filter_range(RangeT &&Range, PredicateT Pred) {
287 using FilterIteratorT =
288 filter_iterator<detail::IterOfRange<RangeT>, PredicateT>;
289 return make_range(FilterIteratorT(std::begin(std::forward<RangeT>(Range)),
290 std::end(std::forward<RangeT>(Range)),
291 std::move(Pred)),
292 FilterIteratorT(std::end(std::forward<RangeT>(Range))));
293}
294
295// forward declarations required by zip_shortest/zip_first
296template <typename R, typename UnaryPredicate>
297bool all_of(R &&range, UnaryPredicate P);
298
299template <size_t... I> struct index_sequence;
300
301template <class... Ts> struct index_sequence_for;
302
303namespace detail {
304
305using std::declval;
306
307// We have to alias this since inlining the actual type at the usage site
308// in the parameter list of iterator_facade_base<> below ICEs MSVC 2017.
309template<typename... Iters> struct ZipTupleType {
310 using type = std::tuple<decltype(*declval<Iters>())...>;
311};
312
313template <typename ZipType, typename... Iters>
314using zip_traits = iterator_facade_base<
315 ZipType, typename std::common_type<std::bidirectional_iterator_tag,
316 typename std::iterator_traits<
317 Iters>::iterator_category...>::type,
318 // ^ TODO: Implement random access methods.
319 typename ZipTupleType<Iters...>::type,
320 typename std::iterator_traits<typename std::tuple_element<
321 0, std::tuple<Iters...>>::type>::difference_type,
322 // ^ FIXME: This follows boost::make_zip_iterator's assumption that all
323 // inner iterators have the same difference_type. It would fail if, for
324 // instance, the second field's difference_type were non-numeric while the
325 // first is.
326 typename ZipTupleType<Iters...>::type *,
327 typename ZipTupleType<Iters...>::type>;
328
329template <typename ZipType, typename... Iters>
330struct zip_common : public zip_traits<ZipType, Iters...> {
331 using Base = zip_traits<ZipType, Iters...>;
332 using value_type = typename Base::value_type;
333
334 std::tuple<Iters...> iterators;
335
336protected:
337 template <size_t... Ns> value_type deref(index_sequence<Ns...>) const {
338 return value_type(*std::get<Ns>(iterators)...);
339 }
340
341 template <size_t... Ns>
342 decltype(iterators) tup_inc(index_sequence<Ns...>) const {
343 return std::tuple<Iters...>(std::next(std::get<Ns>(iterators))...);
344 }
345
346 template <size_t... Ns>
347 decltype(iterators) tup_dec(index_sequence<Ns...>) const {
348 return std::tuple<Iters...>(std::prev(std::get<Ns>(iterators))...);
349 }
350
351public:
352 zip_common(Iters &&... ts) : iterators(std::forward<Iters>(ts)...) {}
353
354 value_type operator*() { return deref(index_sequence_for<Iters...>{}); }
355
356 const value_type operator*() const {
357 return deref(index_sequence_for<Iters...>{});
358 }
359
360 ZipType &operator++() {
361 iterators = tup_inc(index_sequence_for<Iters...>{});
362 return *reinterpret_cast<ZipType *>(this);
363 }
364
365 ZipType &operator--() {
366 static_assert(Base::IsBidirectional,
367 "All inner iterators must be at least bidirectional.");
368 iterators = tup_dec(index_sequence_for<Iters...>{});
369 return *reinterpret_cast<ZipType *>(this);
370 }
371};
372
373template <typename... Iters>
374struct zip_first : public zip_common<zip_first<Iters...>, Iters...> {
375 using Base = zip_common<zip_first<Iters...>, Iters...>;
376
377 bool operator==(const zip_first<Iters...> &other) const {
378 return std::get<0>(this->iterators) == std::get<0>(other.iterators);
379 }
380
381 zip_first(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
382};
383
384template <typename... Iters>
385class zip_shortest : public zip_common<zip_shortest<Iters...>, Iters...> {
386 template <size_t... Ns>
387 bool test(const zip_shortest<Iters...> &other, index_sequence<Ns...>) const {
388 return all_of(std::initializer_list<bool>{std::get<Ns>(this->iterators) !=
389 std::get<Ns>(other.iterators)...},
390 identity<bool>{});
391 }
392
393public:
394 using Base = zip_common<zip_shortest<Iters...>, Iters...>;
395
396 zip_shortest(Iters &&... ts) : Base(std::forward<Iters>(ts)...) {}
397
398 bool operator==(const zip_shortest<Iters...> &other) const {
399 return !test(other, index_sequence_for<Iters...>{});
400 }
401};
402
403template <template <typename...> class ItType, typename... Args> class zippy {
404public:
405 using iterator = ItType<decltype(std::begin(std::declval<Args>()))...>;
406 using iterator_category = typename iterator::iterator_category;
407 using value_type = typename iterator::value_type;
408 using difference_type = typename iterator::difference_type;
409 using pointer = typename iterator::pointer;
410 using reference = typename iterator::reference;
411
412private:
413 std::tuple<Args...> ts;
414
415 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) const {
416 return iterator(std::begin(std::get<Ns>(ts))...);
417 }
418 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) const {
419 return iterator(std::end(std::get<Ns>(ts))...);
420 }
421
422public:
423 zippy(Args &&... ts_) : ts(std::forward<Args>(ts_)...) {}
424
425 iterator begin() const { return begin_impl(index_sequence_for<Args...>{}); }
426 iterator end() const { return end_impl(index_sequence_for<Args...>{}); }
427};
428
429} // end namespace detail
430
431/// zip iterator for two or more iteratable types.
432template <typename T, typename U, typename... Args>
433detail::zippy<detail::zip_shortest, T, U, Args...> zip(T &&t, U &&u,
434 Args &&... args) {
435 return detail::zippy<detail::zip_shortest, T, U, Args...>(
436 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
437}
438
439/// zip iterator that, for the sake of efficiency, assumes the first iteratee to
440/// be the shortest.
441template <typename T, typename U, typename... Args>
442detail::zippy<detail::zip_first, T, U, Args...> zip_first(T &&t, U &&u,
443 Args &&... args) {
444 return detail::zippy<detail::zip_first, T, U, Args...>(
445 std::forward<T>(t), std::forward<U>(u), std::forward<Args>(args)...);
446}
447
448/// Iterator wrapper that concatenates sequences together.
449///
450/// This can concatenate different iterators, even with different types, into
451/// a single iterator provided the value types of all the concatenated
452/// iterators expose `reference` and `pointer` types that can be converted to
453/// `ValueT &` and `ValueT *` respectively. It doesn't support more
454/// interesting/customized pointer or reference types.
455///
456/// Currently this only supports forward or higher iterator categories as
457/// inputs and always exposes a forward iterator interface.
458template <typename ValueT, typename... IterTs>
459class concat_iterator
460 : public iterator_facade_base<concat_iterator<ValueT, IterTs...>,
461 std::forward_iterator_tag, ValueT> {
462 using BaseT = typename concat_iterator::iterator_facade_base;
463
464 /// We store both the current and end iterators for each concatenated
465 /// sequence in a tuple of pairs.
466 ///
467 /// Note that something like iterator_range seems nice at first here, but the
468 /// range properties are of little benefit and end up getting in the way
469 /// because we need to do mutation on the current iterators.
470 std::tuple<std::pair<IterTs, IterTs>...> IterPairs;
471
472 /// Attempts to increment a specific iterator.
473 ///
474 /// Returns true if it was able to increment the iterator. Returns false if
475 /// the iterator is already at the end iterator.
476 template <size_t Index> bool incrementHelper() {
477 auto &IterPair = std::get<Index>(IterPairs);
478 if (IterPair.first == IterPair.second)
479 return false;
480
481 ++IterPair.first;
482 return true;
483 }
484
485 /// Increments the first non-end iterator.
486 ///
487 /// It is an error to call this with all iterators at the end.
488 template <size_t... Ns> void increment(index_sequence<Ns...>) {
489 // Build a sequence of functions to increment each iterator if possible.
490 bool (concat_iterator::*IncrementHelperFns[])() = {
491 &concat_iterator::incrementHelper<Ns>...};
492
493 // Loop over them, and stop as soon as we succeed at incrementing one.
494 for (auto &IncrementHelperFn : IncrementHelperFns)
495 if ((this->*IncrementHelperFn)())
496 return;
497
498 llvm_unreachable("Attempted to increment an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to increment an end concat iterator!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 498)
;
499 }
500
501 /// Returns null if the specified iterator is at the end. Otherwise,
502 /// dereferences the iterator and returns the address of the resulting
503 /// reference.
504 template <size_t Index> ValueT *getHelper() const {
505 auto &IterPair = std::get<Index>(IterPairs);
506 if (IterPair.first == IterPair.second)
507 return nullptr;
508
509 return &*IterPair.first;
510 }
511
512 /// Finds the first non-end iterator, dereferences, and returns the resulting
513 /// reference.
514 ///
515 /// It is an error to call this with all iterators at the end.
516 template <size_t... Ns> ValueT &get(index_sequence<Ns...>) const {
517 // Build a sequence of functions to get from iterator if possible.
518 ValueT *(concat_iterator::*GetHelperFns[])() const = {
519 &concat_iterator::getHelper<Ns>...};
520
521 // Loop over them, and return the first result we find.
522 for (auto &GetHelperFn : GetHelperFns)
523 if (ValueT *P = (this->*GetHelperFn)())
524 return *P;
525
526 llvm_unreachable("Attempted to get a pointer from an end concat iterator!")::llvm::llvm_unreachable_internal("Attempted to get a pointer from an end concat iterator!"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 526)
;
527 }
528
529public:
530 /// Constructs an iterator from a squence of ranges.
531 ///
532 /// We need the full range to know how to switch between each of the
533 /// iterators.
534 template <typename... RangeTs>
535 explicit concat_iterator(RangeTs &&... Ranges)
536 : IterPairs({std::begin(Ranges), std::end(Ranges)}...) {}
537
538 using BaseT::operator++;
539
540 concat_iterator &operator++() {
541 increment(index_sequence_for<IterTs...>());
542 return *this;
543 }
544
545 ValueT &operator*() const { return get(index_sequence_for<IterTs...>()); }
546
547 bool operator==(const concat_iterator &RHS) const {
548 return IterPairs == RHS.IterPairs;
549 }
550};
551
552namespace detail {
553
554/// Helper to store a sequence of ranges being concatenated and access them.
555///
556/// This is designed to facilitate providing actual storage when temporaries
557/// are passed into the constructor such that we can use it as part of range
558/// based for loops.
559template <typename ValueT, typename... RangeTs> class concat_range {
560public:
561 using iterator =
562 concat_iterator<ValueT,
563 decltype(std::begin(std::declval<RangeTs &>()))...>;
564
565private:
566 std::tuple<RangeTs...> Ranges;
567
568 template <size_t... Ns> iterator begin_impl(index_sequence<Ns...>) {
569 return iterator(std::get<Ns>(Ranges)...);
570 }
571 template <size_t... Ns> iterator end_impl(index_sequence<Ns...>) {
572 return iterator(make_range(std::end(std::get<Ns>(Ranges)),
573 std::end(std::get<Ns>(Ranges)))...);
574 }
575
576public:
577 concat_range(RangeTs &&... Ranges)
578 : Ranges(std::forward<RangeTs>(Ranges)...) {}
579
580 iterator begin() { return begin_impl(index_sequence_for<RangeTs...>{}); }
581 iterator end() { return end_impl(index_sequence_for<RangeTs...>{}); }
582};
583
584} // end namespace detail
585
586/// Concatenated range across two or more ranges.
587///
588/// The desired value type must be explicitly specified.
589template <typename ValueT, typename... RangeTs>
590detail::concat_range<ValueT, RangeTs...> concat(RangeTs &&... Ranges) {
591 static_assert(sizeof...(RangeTs) > 1,
592 "Need more than one range to concatenate!");
593 return detail::concat_range<ValueT, RangeTs...>(
594 std::forward<RangeTs>(Ranges)...);
595}
596
597//===----------------------------------------------------------------------===//
598// Extra additions to <utility>
599//===----------------------------------------------------------------------===//
600
601/// \brief Function object to check whether the first component of a std::pair
602/// compares less than the first component of another std::pair.
603struct less_first {
604 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
605 return lhs.first < rhs.first;
606 }
607};
608
609/// \brief Function object to check whether the second component of a std::pair
610/// compares less than the second component of another std::pair.
611struct less_second {
612 template <typename T> bool operator()(const T &lhs, const T &rhs) const {
613 return lhs.second < rhs.second;
614 }
615};
616
617// A subset of N3658. More stuff can be added as-needed.
618
619/// \brief Represents a compile-time sequence of integers.
620template <class T, T... I> struct integer_sequence {
621 using value_type = T;
622
623 static constexpr size_t size() { return sizeof...(I); }
624};
625
626/// \brief Alias for the common case of a sequence of size_ts.
627template <size_t... I>
628struct index_sequence : integer_sequence<std::size_t, I...> {};
629
630template <std::size_t N, std::size_t... I>
631struct build_index_impl : build_index_impl<N - 1, N - 1, I...> {};
632template <std::size_t... I>
633struct build_index_impl<0, I...> : index_sequence<I...> {};
634
635/// \brief Creates a compile-time integer sequence for a parameter pack.
636template <class... Ts>
637struct index_sequence_for : build_index_impl<sizeof...(Ts)> {};
638
639/// Utility type to build an inheritance chain that makes it easy to rank
640/// overload candidates.
641template <int N> struct rank : rank<N - 1> {};
642template <> struct rank<0> {};
643
644/// \brief traits class for checking whether type T is one of any of the given
645/// types in the variadic list.
646template <typename T, typename... Ts> struct is_one_of {
647 static const bool value = false;
648};
649
650template <typename T, typename U, typename... Ts>
651struct is_one_of<T, U, Ts...> {
652 static const bool value =
653 std::is_same<T, U>::value || is_one_of<T, Ts...>::value;
654};
655
656/// \brief traits class for checking whether type T is a base class for all
657/// the given types in the variadic list.
658template <typename T, typename... Ts> struct are_base_of {
659 static const bool value = true;
660};
661
662template <typename T, typename U, typename... Ts>
663struct are_base_of<T, U, Ts...> {
664 static const bool value =
665 std::is_base_of<T, U>::value && are_base_of<T, Ts...>::value;
666};
667
668//===----------------------------------------------------------------------===//
669// Extra additions for arrays
670//===----------------------------------------------------------------------===//
671
672/// Find the length of an array.
673template <class T, std::size_t N>
674constexpr inline size_t array_lengthof(T (&)[N]) {
675 return N;
676}
677
678/// Adapt std::less<T> for array_pod_sort.
679template<typename T>
680inline int array_pod_sort_comparator(const void *P1, const void *P2) {
681 if (std::less<T>()(*reinterpret_cast<const T*>(P1),
682 *reinterpret_cast<const T*>(P2)))
683 return -1;
684 if (std::less<T>()(*reinterpret_cast<const T*>(P2),
685 *reinterpret_cast<const T*>(P1)))
686 return 1;
687 return 0;
688}
689
690/// get_array_pod_sort_comparator - This is an internal helper function used to
691/// get type deduction of T right.
692template<typename T>
693inline int (*get_array_pod_sort_comparator(const T &))
694 (const void*, const void*) {
695 return array_pod_sort_comparator<T>;
696}
697
698/// array_pod_sort - This sorts an array with the specified start and end
699/// extent. This is just like std::sort, except that it calls qsort instead of
700/// using an inlined template. qsort is slightly slower than std::sort, but
701/// most sorts are not performance critical in LLVM and std::sort has to be
702/// template instantiated for each type, leading to significant measured code
703/// bloat. This function should generally be used instead of std::sort where
704/// possible.
705///
706/// This function assumes that you have simple POD-like types that can be
707/// compared with std::less and can be moved with memcpy. If this isn't true,
708/// you should use std::sort.
709///
710/// NOTE: If qsort_r were portable, we could allow a custom comparator and
711/// default to std::less.
712template<class IteratorTy>
713inline void array_pod_sort(IteratorTy Start, IteratorTy End) {
714 // Don't inefficiently call qsort with one element or trigger undefined
715 // behavior with an empty sequence.
716 auto NElts = End - Start;
717 if (NElts <= 1) return;
718 qsort(&*Start, NElts, sizeof(*Start), get_array_pod_sort_comparator(*Start));
719}
720
721template <class IteratorTy>
722inline void array_pod_sort(
723 IteratorTy Start, IteratorTy End,
724 int (*Compare)(
725 const typename std::iterator_traits<IteratorTy>::value_type *,
726 const typename std::iterator_traits<IteratorTy>::value_type *)) {
727 // Don't inefficiently call qsort with one element or trigger undefined
728 // behavior with an empty sequence.
729 auto NElts = End - Start;
730 if (NElts <= 1) return;
731 qsort(&*Start, NElts, sizeof(*Start),
732 reinterpret_cast<int (*)(const void *, const void *)>(Compare));
733}
734
735//===----------------------------------------------------------------------===//
736// Extra additions to <algorithm>
737//===----------------------------------------------------------------------===//
738
739/// For a container of pointers, deletes the pointers and then clears the
740/// container.
741template<typename Container>
742void DeleteContainerPointers(Container &C) {
743 for (auto V : C)
744 delete V;
745 C.clear();
746}
747
748/// In a container of pairs (usually a map) whose second element is a pointer,
749/// deletes the second elements and then clears the container.
750template<typename Container>
751void DeleteContainerSeconds(Container &C) {
752 for (auto &V : C)
753 delete V.second;
754 C.clear();
755}
756
757/// Provide wrappers to std::for_each which take ranges instead of having to
758/// pass begin/end explicitly.
759template <typename R, typename UnaryPredicate>
760UnaryPredicate for_each(R &&Range, UnaryPredicate P) {
761 return std::for_each(std::begin(Range), std::end(Range), P);
762}
763
764/// Provide wrappers to std::all_of which take ranges instead of having to pass
765/// begin/end explicitly.
766template <typename R, typename UnaryPredicate>
767bool all_of(R &&Range, UnaryPredicate P) {
768 return std::all_of(std::begin(Range), std::end(Range), P);
769}
770
771/// Provide wrappers to std::any_of which take ranges instead of having to pass
772/// begin/end explicitly.
773template <typename R, typename UnaryPredicate>
774bool any_of(R &&Range, UnaryPredicate P) {
775 return std::any_of(std::begin(Range), std::end(Range), P);
776}
777
778/// Provide wrappers to std::none_of which take ranges instead of having to pass
779/// begin/end explicitly.
780template <typename R, typename UnaryPredicate>
781bool none_of(R &&Range, UnaryPredicate P) {
782 return std::none_of(std::begin(Range), std::end(Range), P);
783}
784
785/// Provide wrappers to std::find which take ranges instead of having to pass
786/// begin/end explicitly.
787template <typename R, typename T>
788auto find(R &&Range, const T &Val) -> decltype(std::begin(Range)) {
789 return std::find(std::begin(Range), std::end(Range), Val);
790}
791
792/// Provide wrappers to std::find_if which take ranges instead of having to pass
793/// begin/end explicitly.
794template <typename R, typename UnaryPredicate>
795auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
796 return std::find_if(std::begin(Range), std::end(Range), P);
797}
798
799template <typename R, typename UnaryPredicate>
800auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
801 return std::find_if_not(std::begin(Range), std::end(Range), P);
802}
803
804/// Provide wrappers to std::remove_if which take ranges instead of having to
805/// pass begin/end explicitly.
806template <typename R, typename UnaryPredicate>
807auto remove_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
808 return std::remove_if(std::begin(Range), std::end(Range), P);
809}
810
811/// Provide wrappers to std::copy_if which take ranges instead of having to
812/// pass begin/end explicitly.
813template <typename R, typename OutputIt, typename UnaryPredicate>
814OutputIt copy_if(R &&Range, OutputIt Out, UnaryPredicate P) {
815 return std::copy_if(std::begin(Range), std::end(Range), Out, P);
816}
817
818/// Wrapper function around std::find to detect if an element exists
819/// in a container.
820template <typename R, typename E>
821bool is_contained(R &&Range, const E &Element) {
822 return std::find(std::begin(Range), std::end(Range), Element) !=
823 std::end(Range);
824}
825
826/// Wrapper function around std::count to count the number of times an element
827/// \p Element occurs in the given range \p Range.
828template <typename R, typename E>
829auto count(R &&Range, const E &Element) -> typename std::iterator_traits<
830 decltype(std::begin(Range))>::difference_type {
831 return std::count(std::begin(Range), std::end(Range), Element);
832}
833
834/// Wrapper function around std::count_if to count the number of times an
835/// element satisfying a given predicate occurs in a range.
836template <typename R, typename UnaryPredicate>
837auto count_if(R &&Range, UnaryPredicate P) -> typename std::iterator_traits<
838 decltype(std::begin(Range))>::difference_type {
839 return std::count_if(std::begin(Range), std::end(Range), P);
840}
841
842/// Wrapper function around std::transform to apply a function to a range and
843/// store the result elsewhere.
844template <typename R, typename OutputIt, typename UnaryPredicate>
845OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P) {
846 return std::transform(std::begin(Range), std::end(Range), d_first, P);
847}
848
849/// Provide wrappers to std::partition which take ranges instead of having to
850/// pass begin/end explicitly.
851template <typename R, typename UnaryPredicate>
852auto partition(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range)) {
853 return std::partition(std::begin(Range), std::end(Range), P);
854}
855
856/// Provide wrappers to std::lower_bound which take ranges instead of having to
857/// pass begin/end explicitly.
858template <typename R, typename ForwardIt>
859auto lower_bound(R &&Range, ForwardIt I) -> decltype(std::begin(Range)) {
860 return std::lower_bound(std::begin(Range), std::end(Range), I);
861}
862
863/// \brief Given a range of type R, iterate the entire range and return a
864/// SmallVector with elements of the vector. This is useful, for example,
865/// when you want to iterate a range and then sort the results.
866template <unsigned Size, typename R>
867SmallVector<typename std::remove_const<detail::ValueOfRange<R>>::type, Size>
868to_vector(R &&Range) {
869 return {std::begin(Range), std::end(Range)};
870}
871
872/// Provide a container algorithm similar to C++ Library Fundamentals v2's
873/// `erase_if` which is equivalent to:
874///
875/// C.erase(remove_if(C, pred), C.end());
876///
877/// This version works for any container with an erase method call accepting
878/// two iterators.
879template <typename Container, typename UnaryPredicate>
880void erase_if(Container &C, UnaryPredicate P) {
881 C.erase(remove_if(C, P), C.end());
882}
883
884//===----------------------------------------------------------------------===//
885// Extra additions to <memory>
886//===----------------------------------------------------------------------===//
887
888// Implement make_unique according to N3656.
889
890/// \brief Constructs a `new T()` with the given args and returns a
891/// `unique_ptr<T>` which owns the object.
892///
893/// Example:
894///
895/// auto p = make_unique<int>();
896/// auto p = make_unique<std::tuple<int, int>>(0, 1);
897template <class T, class... Args>
898typename std::enable_if<!std::is_array<T>::value, std::unique_ptr<T>>::type
899make_unique(Args &&... args) {
900 return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
901}
902
903/// \brief Constructs a `new T[n]` with the given args and returns a
904/// `unique_ptr<T[]>` which owns the object.
905///
906/// \param n size of the new array.
907///
908/// Example:
909///
910/// auto p = make_unique<int[]>(2); // value-initializes the array with 0's.
911template <class T>
912typename std::enable_if<std::is_array<T>::value && std::extent<T>::value == 0,
913 std::unique_ptr<T>>::type
914make_unique(size_t n) {
915 return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
916}
917
918/// This function isn't used and is only here to provide better compile errors.
919template <class T, class... Args>
920typename std::enable_if<std::extent<T>::value != 0>::type
921make_unique(Args &&...) = delete;
922
923struct FreeDeleter {
924 void operator()(void* v) {
925 ::free(v);
926 }
927};
928
929template<typename First, typename Second>
930struct pair_hash {
931 size_t operator()(const std::pair<First, Second> &P) const {
932 return std::hash<First>()(P.first) * 31 + std::hash<Second>()(P.second);
933 }
934};
935
936/// A functor like C++14's std::less<void> in its absence.
937struct less {
938 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
939 return std::forward<A>(a) < std::forward<B>(b);
940 }
941};
942
943/// A functor like C++14's std::equal<void> in its absence.
944struct equal {
945 template <typename A, typename B> bool operator()(A &&a, B &&b) const {
946 return std::forward<A>(a) == std::forward<B>(b);
947 }
948};
949
950/// Binary functor that adapts to any other binary functor after dereferencing
951/// operands.
952template <typename T> struct deref {
953 T func;
954
955 // Could be further improved to cope with non-derivable functors and
956 // non-binary functors (should be a variadic template member function
957 // operator()).
958 template <typename A, typename B>
959 auto operator()(A &lhs, B &rhs) const -> decltype(func(*lhs, *rhs)) {
960 assert(lhs)((lhs) ? static_cast<void> (0) : __assert_fail ("lhs", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 960, __PRETTY_FUNCTION__))
;
961 assert(rhs)((rhs) ? static_cast<void> (0) : __assert_fail ("rhs", "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 961, __PRETTY_FUNCTION__))
;
962 return func(*lhs, *rhs);
963 }
964};
965
966namespace detail {
967
968template <typename R> class enumerator_iter;
969
970template <typename R> struct result_pair {
971 friend class enumerator_iter<R>;
972
973 result_pair() = default;
974 result_pair(std::size_t Index, IterOfRange<R> Iter)
975 : Index(Index), Iter(Iter) {}
976
977 result_pair<R> &operator=(const result_pair<R> &Other) {
978 Index = Other.Index;
979 Iter = Other.Iter;
980 return *this;
981 }
982
983 std::size_t index() const { return Index; }
984 const ValueOfRange<R> &value() const { return *Iter; }
985 ValueOfRange<R> &value() { return *Iter; }
986
987private:
988 std::size_t Index = std::numeric_limits<std::size_t>::max();
989 IterOfRange<R> Iter;
990};
991
992template <typename R>
993class enumerator_iter
994 : public iterator_facade_base<
995 enumerator_iter<R>, std::forward_iterator_tag, result_pair<R>,
996 typename std::iterator_traits<IterOfRange<R>>::difference_type,
997 typename std::iterator_traits<IterOfRange<R>>::pointer,
998 typename std::iterator_traits<IterOfRange<R>>::reference> {
999 using result_type = result_pair<R>;
1000
1001public:
1002 explicit enumerator_iter(IterOfRange<R> EndIter)
1003 : Result(std::numeric_limits<size_t>::max(), EndIter) {}
1004
1005 enumerator_iter(std::size_t Index, IterOfRange<R> Iter)
1006 : Result(Index, Iter) {}
1007
1008 result_type &operator*() { return Result; }
1009 const result_type &operator*() const { return Result; }
1010
1011 enumerator_iter<R> &operator++() {
1012 assert(Result.Index != std::numeric_limits<size_t>::max())((Result.Index != std::numeric_limits<size_t>::max()) ?
static_cast<void> (0) : __assert_fail ("Result.Index != std::numeric_limits<size_t>::max()"
, "/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/STLExtras.h"
, 1012, __PRETTY_FUNCTION__))
;
1013 ++Result.Iter;
1014 ++Result.Index;
1015 return *this;
1016 }
1017
1018 bool operator==(const enumerator_iter<R> &RHS) const {
1019 // Don't compare indices here, only iterators. It's possible for an end
1020 // iterator to have different indices depending on whether it was created
1021 // by calling std::end() versus incrementing a valid iterator.
1022 return Result.Iter == RHS.Result.Iter;
1023 }
1024
1025 enumerator_iter<R> &operator=(const enumerator_iter<R> &Other) {
1026 Result = Other.Result;
1027 return *this;
1028 }
1029
1030private:
1031 result_type Result;
1032};
1033
1034template <typename R> class enumerator {
1035public:
1036 explicit enumerator(R &&Range) : TheRange(std::forward<R>(Range)) {}
1037
1038 enumerator_iter<R> begin() {
1039 return enumerator_iter<R>(0, std::begin(TheRange));
1040 }
1041
1042 enumerator_iter<R> end() {
1043 return enumerator_iter<R>(std::end(TheRange));
1044 }
1045
1046private:
1047 R TheRange;
1048};
1049
1050} // end namespace detail
1051
1052/// Given an input range, returns a new range whose values are are pair (A,B)
1053/// such that A is the 0-based index of the item in the sequence, and B is
1054/// the value from the original sequence. Example:
1055///
1056/// std::vector<char> Items = {'A', 'B', 'C', 'D'};
1057/// for (auto X : enumerate(Items)) {
1058/// printf("Item %d - %c\n", X.index(), X.value());
1059/// }
1060///
1061/// Output:
1062/// Item 0 - A
1063/// Item 1 - B
1064/// Item 2 - C
1065/// Item 3 - D
1066///
1067template <typename R> detail::enumerator<R> enumerate(R &&TheRange) {
1068 return detail::enumerator<R>(std::forward<R>(TheRange));
1069}
1070
1071namespace detail {
1072
1073template <typename F, typename Tuple, std::size_t... I>
1074auto apply_tuple_impl(F &&f, Tuple &&t, index_sequence<I...>)
1075 -> decltype(std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...)) {
1076 return std::forward<F>(f)(std::get<I>(std::forward<Tuple>(t))...);
1077}
1078
1079} // end namespace detail
1080
1081/// Given an input tuple (a1, a2, ..., an), pass the arguments of the
1082/// tuple variadically to f as if by calling f(a1, a2, ..., an) and
1083/// return the result.
1084template <typename F, typename Tuple>
1085auto apply_tuple(F &&f, Tuple &&t) -> decltype(detail::apply_tuple_impl(
1086 std::forward<F>(f), std::forward<Tuple>(t),
1087 build_index_impl<
1088 std::tuple_size<typename std::decay<Tuple>::type>::value>{})) {
1089 using Indices = build_index_impl<
1090 std::tuple_size<typename std::decay<Tuple>::type>::value>;
1091
1092 return detail::apply_tuple_impl(std::forward<F>(f), std::forward<Tuple>(t),
1093 Indices{});
1094}
1095
1096} // end namespace llvm
1097
1098#endif // LLVM_ADT_STLEXTRAS_H

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/ADT/iterator_range.h

1//===- iterator_range.h - A range adaptor for iterators ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// This provides a very simple, boring adaptor for a begin and end iterator
11/// into a range type. This should be used to build range views that work well
12/// with range based for loops and range based constructors.
13///
14/// Note that code here follows more standards-based coding conventions as it
15/// is mirroring proposed interfaces for standardization.
16///
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_ADT_ITERATOR_RANGE_H
20#define LLVM_ADT_ITERATOR_RANGE_H
21
22#include <iterator>
23#include <utility>
24
25namespace llvm {
26
27/// \brief A range adaptor for a pair of iterators.
28///
29/// This just wraps two iterators into a range-compatible interface. Nothing
30/// fancy at all.
31template <typename IteratorT>
32class iterator_range {
33 IteratorT begin_iterator, end_iterator;
34
35public:
36 //TODO: Add SFINAE to test that the Container's iterators match the range's
37 // iterators.
38 template <typename Container>
39 iterator_range(Container &&c)
40 //TODO: Consider ADL/non-member begin/end calls.
41 : begin_iterator(c.begin()), end_iterator(c.end()) {}
42 iterator_range(IteratorT begin_iterator, IteratorT end_iterator)
43 : begin_iterator(std::move(begin_iterator)),
44 end_iterator(std::move(end_iterator)) {}
45
46 IteratorT begin() const { return begin_iterator; }
47 IteratorT end() const { return end_iterator; }
48};
49
50/// \brief Convenience function for iterating over sub-ranges.
51///
52/// This provides a bit of syntactic sugar to make using sub-ranges
53/// in for loops a bit easier. Analogous to std::make_pair().
54template <class T> iterator_range<T> make_range(T x, T y) {
55 return iterator_range<T>(std::move(x), std::move(y));
38
Calling 'move'
39
Returning from 'move'
40
Calling 'move'
41
Returning from 'move'
56}
57
58template <typename T> iterator_range<T> make_range(std::pair<T, T> p) {
59 return iterator_range<T>(std::move(p.first), std::move(p.second));
60}
61
62template<typename T>
63iterator_range<decltype(begin(std::declval<T>()))> drop_begin(T &&t, int n) {
64 return make_range(std::next(begin(t), n), end(t));
65}
66}
67
68#endif

/usr/lib/gcc/x86_64-linux-gnu/7.2.0/../../../../include/c++/7.2.0/bits/stl_iterator.h

1// Iterators -*- C++ -*-
2
3// Copyright (C) 2001-2017 Free Software Foundation, Inc.
4//
5// This file is part of the GNU ISO C++ Library. This library is free
6// software; you can redistribute it and/or modify it under the
7// terms of the GNU General Public License as published by the
8// Free Software Foundation; either version 3, or (at your option)
9// any later version.
10
11// This library is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// Under Section 7 of GPL version 3, you are granted additional
17// permissions described in the GCC Runtime Library Exception, version
18// 3.1, as published by the Free Software Foundation.
19
20// You should have received a copy of the GNU General Public License and
21// a copy of the GCC Runtime Library Exception along with this program;
22// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23// <http://www.gnu.org/licenses/>.
24
25/*
26 *
27 * Copyright (c) 1994
28 * Hewlett-Packard Company
29 *
30 * Permission to use, copy, modify, distribute and sell this software
31 * and its documentation for any purpose is hereby granted without fee,
32 * provided that the above copyright notice appear in all copies and
33 * that both that copyright notice and this permission notice appear
34 * in supporting documentation. Hewlett-Packard Company makes no
35 * representations about the suitability of this software for any
36 * purpose. It is provided "as is" without express or implied warranty.
37 *
38 *
39 * Copyright (c) 1996-1998
40 * Silicon Graphics Computer Systems, Inc.
41 *
42 * Permission to use, copy, modify, distribute and sell this software
43 * and its documentation for any purpose is hereby granted without fee,
44 * provided that the above copyright notice appear in all copies and
45 * that both that copyright notice and this permission notice appear
46 * in supporting documentation. Silicon Graphics makes no
47 * representations about the suitability of this software for any
48 * purpose. It is provided "as is" without express or implied warranty.
49 */
50
51/** @file bits/stl_iterator.h
52 * This is an internal header file, included by other library headers.
53 * Do not attempt to use it directly. @headername{iterator}
54 *
55 * This file implements reverse_iterator, back_insert_iterator,
56 * front_insert_iterator, insert_iterator, __normal_iterator, and their
57 * supporting functions and overloaded operators.
58 */
59
60#ifndef _STL_ITERATOR_H1
61#define _STL_ITERATOR_H1 1
62
63#include <bits/cpp_type_traits.h>
64#include <ext/type_traits.h>
65#include <bits/move.h>
66#include <bits/ptr_traits.h>
67
68#if __cplusplus201103L > 201402L
69# define __cpp_lib_array_constexpr 201603
70#endif
71
72namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
73{
74_GLIBCXX_BEGIN_NAMESPACE_VERSION
75
76 /**
77 * @addtogroup iterators
78 * @{
79 */
80
81 // 24.4.1 Reverse iterators
82 /**
83 * Bidirectional and random access iterators have corresponding reverse
84 * %iterator adaptors that iterate through the data structure in the
85 * opposite direction. They have the same signatures as the corresponding
86 * iterators. The fundamental relation between a reverse %iterator and its
87 * corresponding %iterator @c i is established by the identity:
88 * @code
89 * &*(reverse_iterator(i)) == &*(i - 1)
90 * @endcode
91 *
92 * <em>This mapping is dictated by the fact that while there is always a
93 * pointer past the end of an array, there might not be a valid pointer
94 * before the beginning of an array.</em> [24.4.1]/1,2
95 *
96 * Reverse iterators can be tricky and surprising at first. Their
97 * semantics make sense, however, and the trickiness is a side effect of
98 * the requirement that the iterators must be safe.
99 */
100 template<typename _Iterator>
101 class reverse_iterator
102 : public iterator<typename iterator_traits<_Iterator>::iterator_category,
103 typename iterator_traits<_Iterator>::value_type,
104 typename iterator_traits<_Iterator>::difference_type,
105 typename iterator_traits<_Iterator>::pointer,
106 typename iterator_traits<_Iterator>::reference>
107 {
108 protected:
109 _Iterator current;
110
111 typedef iterator_traits<_Iterator> __traits_type;
112
113 public:
114 typedef _Iterator iterator_type;
115 typedef typename __traits_type::difference_type difference_type;
116 typedef typename __traits_type::pointer pointer;
117 typedef typename __traits_type::reference reference;
118
119 /**
120 * The default constructor value-initializes member @p current.
121 * If it is a pointer, that means it is zero-initialized.
122 */
123 // _GLIBCXX_RESOLVE_LIB_DEFECTS
124 // 235 No specification of default ctor for reverse_iterator
125 _GLIBCXX17_CONSTEXPR
126 reverse_iterator() : current() { }
127
128 /**
129 * This %iterator will move in the opposite direction that @p x does.
130 */
131 explicit _GLIBCXX17_CONSTEXPR
132 reverse_iterator(iterator_type __x) : current(__x) { }
133
134 /**
135 * The copy constructor is normal.
136 */
137 _GLIBCXX17_CONSTEXPR
138 reverse_iterator(const reverse_iterator& __x)
139 : current(__x.current) { }
140
141 /**
142 * A %reverse_iterator across other types can be copied if the
143 * underlying %iterator can be converted to the type of @c current.
144 */
145 template<typename _Iter>
146 _GLIBCXX17_CONSTEXPR
147 reverse_iterator(const reverse_iterator<_Iter>& __x)
148 : current(__x.base()) { }
149
150 /**
151 * @return @c current, the %iterator used for underlying work.
152 */
153 _GLIBCXX17_CONSTEXPR iterator_type
154 base() const
155 { return current; }
156
157 /**
158 * @return A reference to the value at @c --current
159 *
160 * This requires that @c --current is dereferenceable.
161 *
162 * @warning This implementation requires that for an iterator of the
163 * underlying iterator type, @c x, a reference obtained by
164 * @c *x remains valid after @c x has been modified or
165 * destroyed. This is a bug: http://gcc.gnu.org/PR51823
166 */
167 _GLIBCXX17_CONSTEXPR reference
168 operator*() const
169 {
170 _Iterator __tmp = current;
171 return *--__tmp;
172 }
173
174 /**
175 * @return A pointer to the value at @c --current
176 *
177 * This requires that @c --current is dereferenceable.
178 */
179 _GLIBCXX17_CONSTEXPR pointer
180 operator->() const
181 { return &(operator*()); }
182
183 /**
184 * @return @c *this
185 *
186 * Decrements the underlying iterator.
187 */
188 _GLIBCXX17_CONSTEXPR reverse_iterator&
189 operator++()
190 {
191 --current;
192 return *this;
193 }
194
195 /**
196 * @return The original value of @c *this
197 *
198 * Decrements the underlying iterator.
199 */
200 _GLIBCXX17_CONSTEXPR reverse_iterator
201 operator++(int)
202 {
203 reverse_iterator __tmp = *this;
204 --current;
205 return __tmp;
206 }
207
208 /**
209 * @return @c *this
210 *
211 * Increments the underlying iterator.
212 */
213 _GLIBCXX17_CONSTEXPR reverse_iterator&
214 operator--()
215 {
216 ++current;
217 return *this;
218 }
219
220 /**
221 * @return A reverse_iterator with the previous value of @c *this
222 *
223 * Increments the underlying iterator.
224 */
225 _GLIBCXX17_CONSTEXPR reverse_iterator
226 operator--(int)
227 {
228 reverse_iterator __tmp = *this;
229 ++current;
230 return __tmp;
231 }
232
233 /**
234 * @return A reverse_iterator that refers to @c current - @a __n
235 *
236 * The underlying iterator must be a Random Access Iterator.
237 */
238 _GLIBCXX17_CONSTEXPR reverse_iterator
239 operator+(difference_type __n) const
240 { return reverse_iterator(current - __n); }
241
242 /**
243 * @return *this
244 *
245 * Moves the underlying iterator backwards @a __n steps.
246 * The underlying iterator must be a Random Access Iterator.
247 */
248 _GLIBCXX17_CONSTEXPR reverse_iterator&
249 operator+=(difference_type __n)
250 {
251 current -= __n;
252 return *this;
253 }
254
255 /**
256 * @return A reverse_iterator that refers to @c current - @a __n
257 *
258 * The underlying iterator must be a Random Access Iterator.
259 */
260 _GLIBCXX17_CONSTEXPR reverse_iterator
261 operator-(difference_type __n) const
262 { return reverse_iterator(current + __n); }
263
264 /**
265 * @return *this
266 *
267 * Moves the underlying iterator forwards @a __n steps.
268 * The underlying iterator must be a Random Access Iterator.
269 */
270 _GLIBCXX17_CONSTEXPR reverse_iterator&
271 operator-=(difference_type __n)
272 {
273 current += __n;
274 return *this;
275 }
276
277 /**
278 * @return The value at @c current - @a __n - 1
279 *
280 * The underlying iterator must be a Random Access Iterator.
281 */
282 _GLIBCXX17_CONSTEXPR reference
283 operator[](difference_type __n) const
284 { return *(*this + __n); }
285 };
286
287 //@{
288 /**
289 * @param __x A %reverse_iterator.
290 * @param __y A %reverse_iterator.
291 * @return A simple bool.
292 *
293 * Reverse iterators forward many operations to their underlying base()
294 * iterators. Others are implemented in terms of one another.
295 *
296 */
297 template<typename _Iterator>
298 inline _GLIBCXX17_CONSTEXPR bool
299 operator==(const reverse_iterator<_Iterator>& __x,
300 const reverse_iterator<_Iterator>& __y)
301 { return __x.base() == __y.base(); }
46
Assuming the condition is false
58
Assuming the condition is true
302
303 template<typename _Iterator>
304 inline _GLIBCXX17_CONSTEXPR bool
305 operator<(const reverse_iterator<_Iterator>& __x,
306 const reverse_iterator<_Iterator>& __y)
307 { return __y.base() < __x.base(); }
308
309 template<typename _Iterator>
310 inline _GLIBCXX17_CONSTEXPR bool
311 operator!=(const reverse_iterator<_Iterator>& __x,
312 const reverse_iterator<_Iterator>& __y)
313 { return !(__x == __y); }
45
Calling 'operator=='
47
Returning from 'operator=='
57
Calling 'operator=='
59
Returning from 'operator=='
314
315 template<typename _Iterator>
316 inline _GLIBCXX17_CONSTEXPR bool
317 operator>(const reverse_iterator<_Iterator>& __x,
318 const reverse_iterator<_Iterator>& __y)
319 { return __y < __x; }
320
321 template<typename _Iterator>
322 inline _GLIBCXX17_CONSTEXPR bool
323 operator<=(const reverse_iterator<_Iterator>& __x,
324 const reverse_iterator<_Iterator>& __y)
325 { return !(__y < __x); }
326
327 template<typename _Iterator>
328 inline _GLIBCXX17_CONSTEXPR bool
329 operator>=(const reverse_iterator<_Iterator>& __x,
330 const reverse_iterator<_Iterator>& __y)
331 { return !(__x < __y); }
332
333 // _GLIBCXX_RESOLVE_LIB_DEFECTS
334 // DR 280. Comparison of reverse_iterator to const reverse_iterator.
335 template<typename _IteratorL, typename _IteratorR>
336 inline _GLIBCXX17_CONSTEXPR bool
337 operator==(const reverse_iterator<_IteratorL>& __x,
338 const reverse_iterator<_IteratorR>& __y)
339 { return __x.base() == __y.base(); }
340
341 template<typename _IteratorL, typename _IteratorR>
342 inline _GLIBCXX17_CONSTEXPR bool
343 operator<(const reverse_iterator<_IteratorL>& __x,
344 const reverse_iterator<_IteratorR>& __y)
345 { return __y.base() < __x.base(); }
346
347 template<typename _IteratorL, typename _IteratorR>
348 inline _GLIBCXX17_CONSTEXPR bool
349 operator!=(const reverse_iterator<_IteratorL>& __x,
350 const reverse_iterator<_IteratorR>& __y)
351 { return !(__x == __y); }
352
353 template<typename _IteratorL, typename _IteratorR>
354 inline _GLIBCXX17_CONSTEXPR bool
355 operator>(const reverse_iterator<_IteratorL>& __x,
356 const reverse_iterator<_IteratorR>& __y)
357 { return __y < __x; }
358
359 template<typename _IteratorL, typename _IteratorR>
360 inline _GLIBCXX17_CONSTEXPR bool
361 operator<=(const reverse_iterator<_IteratorL>& __x,
362 const reverse_iterator<_IteratorR>& __y)
363 { return !(__y < __x); }
364
365 template<typename _IteratorL, typename _IteratorR>
366 inline _GLIBCXX17_CONSTEXPR bool
367 operator>=(const reverse_iterator<_IteratorL>& __x,
368 const reverse_iterator<_IteratorR>& __y)
369 { return !(__x < __y); }
370 //@}
371
372#if __cplusplus201103L < 201103L
373 template<typename _Iterator>
374 inline typename reverse_iterator<_Iterator>::difference_type
375 operator-(const reverse_iterator<_Iterator>& __x,
376 const reverse_iterator<_Iterator>& __y)
377 { return __y.base() - __x.base(); }
378
379 template<typename _IteratorL, typename _IteratorR>
380 inline typename reverse_iterator<_IteratorL>::difference_type
381 operator-(const reverse_iterator<_IteratorL>& __x,
382 const reverse_iterator<_IteratorR>& __y)
383 { return __y.base() - __x.base(); }
384#else
385 // _GLIBCXX_RESOLVE_LIB_DEFECTS
386 // DR 685. reverse_iterator/move_iterator difference has invalid signatures
387 template<typename _IteratorL, typename _IteratorR>
388 inline _GLIBCXX17_CONSTEXPR auto
389 operator-(const reverse_iterator<_IteratorL>& __x,
390 const reverse_iterator<_IteratorR>& __y)
391 -> decltype(__y.base() - __x.base())
392 { return __y.base() - __x.base(); }
393#endif
394
395 template<typename _Iterator>
396 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
397 operator+(typename reverse_iterator<_Iterator>::difference_type __n,
398 const reverse_iterator<_Iterator>& __x)
399 { return reverse_iterator<_Iterator>(__x.base() - __n); }
400
401#if __cplusplus201103L >= 201103L
402 // Same as C++14 make_reverse_iterator but used in C++03 mode too.
403 template<typename _Iterator>
404 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
405 __make_reverse_iterator(_Iterator __i)
406 { return reverse_iterator<_Iterator>(__i); }
407
408# if __cplusplus201103L > 201103L
409# define __cpp_lib_make_reverse_iterator 201402
410
411 // _GLIBCXX_RESOLVE_LIB_DEFECTS
412 // DR 2285. make_reverse_iterator
413 /// Generator function for reverse_iterator.
414 template<typename _Iterator>
415 inline _GLIBCXX17_CONSTEXPR reverse_iterator<_Iterator>
416 make_reverse_iterator(_Iterator __i)
417 { return reverse_iterator<_Iterator>(__i); }
418# endif
419#endif
420
421#if __cplusplus201103L >= 201103L
422 template<typename _Iterator>
423 auto
424 __niter_base(reverse_iterator<_Iterator> __it)
425 -> decltype(__make_reverse_iterator(__niter_base(__it.base())))
426 { return __make_reverse_iterator(__niter_base(__it.base())); }
427
428 template<typename _Iterator>
429 struct __is_move_iterator<reverse_iterator<_Iterator> >
430 : __is_move_iterator<_Iterator>
431 { };
432
433 template<typename _Iterator>
434 auto
435 __miter_base(reverse_iterator<_Iterator> __it)
436 -> decltype(__make_reverse_iterator(__miter_base(__it.base())))
437 { return __make_reverse_iterator(__miter_base(__it.base())); }
438#endif
439
440 // 24.4.2.2.1 back_insert_iterator
441 /**
442 * @brief Turns assignment into insertion.
443 *
444 * These are output iterators, constructed from a container-of-T.
445 * Assigning a T to the iterator appends it to the container using
446 * push_back.
447 *
448 * Tip: Using the back_inserter function to create these iterators can
449 * save typing.
450 */
451 template<typename _Container>
452 class back_insert_iterator
453 : public iterator<output_iterator_tag, void, void, void, void>
454 {
455 protected:
456 _Container* container;
457
458 public:
459 /// A nested typedef for the type of whatever container you used.
460 typedef _Container container_type;
461
462 /// The only way to create this %iterator is with a container.
463 explicit
464 back_insert_iterator(_Container& __x)
465 : container(std::__addressof(__x)) { }
466
467 /**
468 * @param __value An instance of whatever type
469 * container_type::const_reference is; presumably a
470 * reference-to-const T for container<T>.
471 * @return This %iterator, for chained operations.
472 *
473 * This kind of %iterator doesn't really have a @a position in the
474 * container (you can think of the position as being permanently at
475 * the end, if you like). Assigning a value to the %iterator will
476 * always append the value to the end of the container.
477 */
478#if __cplusplus201103L < 201103L
479 back_insert_iterator&
480 operator=(typename _Container::const_reference __value)
481 {
482 container->push_back(__value);
483 return *this;
484 }
485#else
486 back_insert_iterator&
487 operator=(const typename _Container::value_type& __value)
488 {
489 container->push_back(__value);
490 return *this;
491 }
492
493 back_insert_iterator&
494 operator=(typename _Container::value_type&& __value)
495 {
496 container->push_back(std::move(__value));
497 return *this;
498 }
499#endif
500
501 /// Simply returns *this.
502 back_insert_iterator&
503 operator*()
504 { return *this; }
505
506 /// Simply returns *this. (This %iterator does not @a move.)
507 back_insert_iterator&
508 operator++()
509 { return *this; }
510
511 /// Simply returns *this. (This %iterator does not @a move.)
512 back_insert_iterator
513 operator++(int)
514 { return *this; }
515 };
516
517 /**
518 * @param __x A container of arbitrary type.
519 * @return An instance of back_insert_iterator working on @p __x.
520 *
521 * This wrapper function helps in creating back_insert_iterator instances.
522 * Typing the name of the %iterator requires knowing the precise full
523 * type of the container, which can be tedious and impedes generic
524 * programming. Using this function lets you take advantage of automatic
525 * template parameter deduction, making the compiler match the correct
526 * types for you.
527 */
528 template<typename _Container>
529 inline back_insert_iterator<_Container>
530 back_inserter(_Container& __x)
531 { return back_insert_iterator<_Container>(__x); }
532
533 /**
534 * @brief Turns assignment into insertion.
535 *
536 * These are output iterators, constructed from a container-of-T.
537 * Assigning a T to the iterator prepends it to the container using
538 * push_front.
539 *
540 * Tip: Using the front_inserter function to create these iterators can
541 * save typing.
542 */
543 template<typename _Container>
544 class front_insert_iterator
545 : public iterator<output_iterator_tag, void, void, void, void>
546 {
547 protected:
548 _Container* container;
549
550 public:
551 /// A nested typedef for the type of whatever container you used.
552 typedef _Container container_type;
553
554 /// The only way to create this %iterator is with a container.
555 explicit front_insert_iterator(_Container& __x)
556 : container(std::__addressof(__x)) { }
557
558 /**
559 * @param __value An instance of whatever type
560 * container_type::const_reference is; presumably a
561 * reference-to-const T for container<T>.
562 * @return This %iterator, for chained operations.
563 *
564 * This kind of %iterator doesn't really have a @a position in the
565 * container (you can think of the position as being permanently at
566 * the front, if you like). Assigning a value to the %iterator will
567 * always prepend the value to the front of the container.
568 */
569#if __cplusplus201103L < 201103L
570 front_insert_iterator&
571 operator=(typename _Container::const_reference __value)
572 {
573 container->push_front(__value);
574 return *this;
575 }
576#else
577 front_insert_iterator&
578 operator=(const typename _Container::value_type& __value)
579 {
580 container->push_front(__value);
581 return *this;
582 }
583
584 front_insert_iterator&
585 operator=(typename _Container::value_type&& __value)
586 {
587 container->push_front(std::move(__value));
588 return *this;
589 }
590#endif
591
592 /// Simply returns *this.
593 front_insert_iterator&
594 operator*()
595 { return *this; }
596
597 /// Simply returns *this. (This %iterator does not @a move.)
598 front_insert_iterator&
599 operator++()
600 { return *this; }
601
602 /// Simply returns *this. (This %iterator does not @a move.)
603 front_insert_iterator
604 operator++(int)
605 { return *this; }
606 };
607
608 /**
609 * @param __x A container of arbitrary type.
610 * @return An instance of front_insert_iterator working on @p x.
611 *
612 * This wrapper function helps in creating front_insert_iterator instances.
613 * Typing the name of the %iterator requires knowing the precise full
614 * type of the container, which can be tedious and impedes generic
615 * programming. Using this function lets you take advantage of automatic
616 * template parameter deduction, making the compiler match the correct
617 * types for you.
618 */
619 template<typename _Container>
620 inline front_insert_iterator<_Container>
621 front_inserter(_Container& __x)
622 { return front_insert_iterator<_Container>(__x); }
623
624 /**
625 * @brief Turns assignment into insertion.
626 *
627 * These are output iterators, constructed from a container-of-T.
628 * Assigning a T to the iterator inserts it in the container at the
629 * %iterator's position, rather than overwriting the value at that
630 * position.
631 *
632 * (Sequences will actually insert a @e copy of the value before the
633 * %iterator's position.)
634 *
635 * Tip: Using the inserter function to create these iterators can
636 * save typing.
637 */
638 template<typename _Container>
639 class insert_iterator
640 : public iterator<output_iterator_tag, void, void, void, void>
641 {
642 protected:
643 _Container* container;
644 typename _Container::iterator iter;
645
646 public:
647 /// A nested typedef for the type of whatever container you used.
648 typedef _Container container_type;
649
650 /**
651 * The only way to create this %iterator is with a container and an
652 * initial position (a normal %iterator into the container).
653 */
654 insert_iterator(_Container& __x, typename _Container::iterator __i)
655 : container(std::__addressof(__x)), iter(__i) {}
656
657 /**
658 * @param __value An instance of whatever type
659 * container_type::const_reference is; presumably a
660 * reference-to-const T for container<T>.
661 * @return This %iterator, for chained operations.
662 *
663 * This kind of %iterator maintains its own position in the
664 * container. Assigning a value to the %iterator will insert the
665 * value into the container at the place before the %iterator.
666 *
667 * The position is maintained such that subsequent assignments will
668 * insert values immediately after one another. For example,
669 * @code
670 * // vector v contains A and Z
671 *
672 * insert_iterator i (v, ++v.begin());
673 * i = 1;
674 * i = 2;
675 * i = 3;
676 *
677 * // vector v contains A, 1, 2, 3, and Z
678 * @endcode
679 */
680#if __cplusplus201103L < 201103L
681 insert_iterator&
682 operator=(typename _Container::const_reference __value)
683 {
684 iter = container->insert(iter, __value);
685 ++iter;
686 return *this;
687 }
688#else
689 insert_iterator&
690 operator=(const typename _Container::value_type& __value)
691 {
692 iter = container->insert(iter, __value);
693 ++iter;
694 return *this;
695 }
696
697 insert_iterator&
698 operator=(typename _Container::value_type&& __value)
699 {
700 iter = container->insert(iter, std::move(__value));
701 ++iter;
702 return *this;
703 }
704#endif
705
706 /// Simply returns *this.
707 insert_iterator&
708 operator*()
709 { return *this; }
710
711 /// Simply returns *this. (This %iterator does not @a move.)
712 insert_iterator&
713 operator++()
714 { return *this; }
715
716 /// Simply returns *this. (This %iterator does not @a move.)
717 insert_iterator&
718 operator++(int)
719 { return *this; }
720 };
721
722 /**
723 * @param __x A container of arbitrary type.
724 * @return An instance of insert_iterator working on @p __x.
725 *
726 * This wrapper function helps in creating insert_iterator instances.
727 * Typing the name of the %iterator requires knowing the precise full
728 * type of the container, which can be tedious and impedes generic
729 * programming. Using this function lets you take advantage of automatic
730 * template parameter deduction, making the compiler match the correct
731 * types for you.
732 */
733 template<typename _Container, typename _Iterator>
734 inline insert_iterator<_Container>
735 inserter(_Container& __x, _Iterator __i)
736 {
737 return insert_iterator<_Container>(__x,
738 typename _Container::iterator(__i));
739 }
740
741 // @} group iterators
742
743_GLIBCXX_END_NAMESPACE_VERSION
744} // namespace
745
746namespace __gnu_cxx _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
747{
748_GLIBCXX_BEGIN_NAMESPACE_VERSION
749
750 // This iterator adapter is @a normal in the sense that it does not
751 // change the semantics of any of the operators of its iterator
752 // parameter. Its primary purpose is to convert an iterator that is
753 // not a class, e.g. a pointer, into an iterator that is a class.
754 // The _Container parameter exists solely so that different containers
755 // using this template can instantiate different types, even if the
756 // _Iterator parameter is the same.
757 using std::iterator_traits;
758 using std::iterator;
759 template<typename _Iterator, typename _Container>
760 class __normal_iterator
761 {
762 protected:
763 _Iterator _M_current;
764
765 typedef iterator_traits<_Iterator> __traits_type;
766
767 public:
768 typedef _Iterator iterator_type;
769 typedef typename __traits_type::iterator_category iterator_category;
770 typedef typename __traits_type::value_type value_type;
771 typedef typename __traits_type::difference_type difference_type;
772 typedef typename __traits_type::reference reference;
773 typedef typename __traits_type::pointer pointer;
774
775 _GLIBCXX_CONSTEXPRconstexpr __normal_iterator() _GLIBCXX_NOEXCEPTnoexcept
776 : _M_current(_Iterator()) { }
777
778 explicit
779 __normal_iterator(const _Iterator& __i) _GLIBCXX_NOEXCEPTnoexcept
780 : _M_current(__i) { }
781
782 // Allow iterator to const_iterator conversion
783 template<typename _Iter>
784 __normal_iterator(const __normal_iterator<_Iter,
785 typename __enable_if<
786 (std::__are_same<_Iter, typename _Container::pointer>::__value),
787 _Container>::__type>& __i) _GLIBCXX_NOEXCEPTnoexcept
788 : _M_current(__i.base()) { }
789
790 // Forward iterator requirements
791 reference
792 operator*() const _GLIBCXX_NOEXCEPTnoexcept
793 { return *_M_current; }
794
795 pointer
796 operator->() const _GLIBCXX_NOEXCEPTnoexcept
797 { return _M_current; }
798
799 __normal_iterator&
800 operator++() _GLIBCXX_NOEXCEPTnoexcept
801 {
802 ++_M_current;
803 return *this;
804 }
805
806 __normal_iterator
807 operator++(int) _GLIBCXX_NOEXCEPTnoexcept
808 { return __normal_iterator(_M_current++); }
809
810 // Bidirectional iterator requirements
811 __normal_iterator&
812 operator--() _GLIBCXX_NOEXCEPTnoexcept
813 {
814 --_M_current;
815 return *this;
816 }
817
818 __normal_iterator
819 operator--(int) _GLIBCXX_NOEXCEPTnoexcept
820 { return __normal_iterator(_M_current--); }
821
822 // Random access iterator requirements
823 reference
824 operator[](difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
825 { return _M_current[__n]; }
826
827 __normal_iterator&
828 operator+=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
829 { _M_current += __n; return *this; }
830
831 __normal_iterator
832 operator+(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
833 { return __normal_iterator(_M_current + __n); }
834
835 __normal_iterator&
836 operator-=(difference_type __n) _GLIBCXX_NOEXCEPTnoexcept
837 { _M_current -= __n; return *this; }
838
839 __normal_iterator
840 operator-(difference_type __n) const _GLIBCXX_NOEXCEPTnoexcept
841 { return __normal_iterator(_M_current - __n); }
842
843 const _Iterator&
844 base() const _GLIBCXX_NOEXCEPTnoexcept
845 { return _M_current; }
846 };
847
848 // Note: In what follows, the left- and right-hand-side iterators are
849 // allowed to vary in types (conceptually in cv-qualification) so that
850 // comparison between cv-qualified and non-cv-qualified iterators be
851 // valid. However, the greedy and unfriendly operators in std::rel_ops
852 // will make overload resolution ambiguous (when in scope) if we don't
853 // provide overloads whose operands are of the same type. Can someone
854 // remind me what generic programming is about? -- Gaby
855
856 // Forward iterator requirements
857 template<typename _IteratorL, typename _IteratorR, typename _Container>
858 inline bool
859 operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,
860 const __normal_iterator<_IteratorR, _Container>& __rhs)
861 _GLIBCXX_NOEXCEPTnoexcept
862 { return __lhs.base() == __rhs.base(); }
863
864 template<typename _Iterator, typename _Container>
865 inline bool
866 operator==(const __normal_iterator<_Iterator, _Container>& __lhs,
867 const __normal_iterator<_Iterator, _Container>& __rhs)
868 _GLIBCXX_NOEXCEPTnoexcept
869 { return __lhs.base() == __rhs.base(); }
870
871 template<typename _IteratorL, typename _IteratorR, typename _Container>
872 inline bool
873 operator!=(const __normal_iterator<_IteratorL, _Container>& __lhs,
874 const __normal_iterator<_IteratorR, _Container>& __rhs)
875 _GLIBCXX_NOEXCEPTnoexcept
876 { return __lhs.base() != __rhs.base(); }
877
878 template<typename _Iterator, typename _Container>
879 inline bool
880 operator!=(const __normal_iterator<_Iterator, _Container>& __lhs,
881 const __normal_iterator<_Iterator, _Container>& __rhs)
882 _GLIBCXX_NOEXCEPTnoexcept
883 { return __lhs.base() != __rhs.base(); }
884
885 // Random access iterator requirements
886 template<typename _IteratorL, typename _IteratorR, typename _Container>
887 inline bool
888 operator<(const __normal_iterator<_IteratorL, _Container>& __lhs,
889 const __normal_iterator<_IteratorR, _Container>& __rhs)
890 _GLIBCXX_NOEXCEPTnoexcept
891 { return __lhs.base() < __rhs.base(); }
892
893 template<typename _Iterator, typename _Container>
894 inline bool
895 operator<(const __normal_iterator<_Iterator, _Container>& __lhs,
896 const __normal_iterator<_Iterator, _Container>& __rhs)
897 _GLIBCXX_NOEXCEPTnoexcept
898 { return __lhs.base() < __rhs.base(); }
899
900 template<typename _IteratorL, typename _IteratorR, typename _Container>
901 inline bool
902 operator>(const __normal_iterator<_IteratorL, _Container>& __lhs,
903 const __normal_iterator<_IteratorR, _Container>& __rhs)
904 _GLIBCXX_NOEXCEPTnoexcept
905 { return __lhs.base() > __rhs.base(); }
906
907 template<typename _Iterator, typename _Container>
908 inline bool
909 operator>(const __normal_iterator<_Iterator, _Container>& __lhs,
910 const __normal_iterator<_Iterator, _Container>& __rhs)
911 _GLIBCXX_NOEXCEPTnoexcept
912 { return __lhs.base() > __rhs.base(); }
913
914 template<typename _IteratorL, typename _IteratorR, typename _Container>
915 inline bool
916 operator<=(const __normal_iterator<_IteratorL, _Container>& __lhs,
917 const __normal_iterator<_IteratorR, _Container>& __rhs)
918 _GLIBCXX_NOEXCEPTnoexcept
919 { return __lhs.base() <= __rhs.base(); }
920
921 template<typename _Iterator, typename _Container>
922 inline bool
923 operator<=(const __normal_iterator<_Iterator, _Container>& __lhs,
924 const __normal_iterator<_Iterator, _Container>& __rhs)
925 _GLIBCXX_NOEXCEPTnoexcept
926 { return __lhs.base() <= __rhs.base(); }
927
928 template<typename _IteratorL, typename _IteratorR, typename _Container>
929 inline bool
930 operator>=(const __normal_iterator<_IteratorL, _Container>& __lhs,
931 const __normal_iterator<_IteratorR, _Container>& __rhs)
932 _GLIBCXX_NOEXCEPTnoexcept
933 { return __lhs.base() >= __rhs.base(); }
934
935 template<typename _Iterator, typename _Container>
936 inline bool
937 operator>=(const __normal_iterator<_Iterator, _Container>& __lhs,
938 const __normal_iterator<_Iterator, _Container>& __rhs)
939 _GLIBCXX_NOEXCEPTnoexcept
940 { return __lhs.base() >= __rhs.base(); }
941
942 // _GLIBCXX_RESOLVE_LIB_DEFECTS
943 // According to the resolution of DR179 not only the various comparison
944 // operators but also operator- must accept mixed iterator/const_iterator
945 // parameters.
946 template<typename _IteratorL, typename _IteratorR, typename _Container>
947#if __cplusplus201103L >= 201103L
948 // DR 685.
949 inline auto
950 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
951 const __normal_iterator<_IteratorR, _Container>& __rhs) noexcept
952 -> decltype(__lhs.base() - __rhs.base())
953#else
954 inline typename __normal_iterator<_IteratorL, _Container>::difference_type
955 operator-(const __normal_iterator<_IteratorL, _Container>& __lhs,
956 const __normal_iterator<_IteratorR, _Container>& __rhs)
957#endif
958 { return __lhs.base() - __rhs.base(); }
959
960 template<typename _Iterator, typename _Container>
961 inline typename __normal_iterator<_Iterator, _Container>::difference_type
962 operator-(const __normal_iterator<_Iterator, _Container>& __lhs,
963 const __normal_iterator<_Iterator, _Container>& __rhs)
964 _GLIBCXX_NOEXCEPTnoexcept
965 { return __lhs.base() - __rhs.base(); }
966
967 template<typename _Iterator, typename _Container>
968 inline __normal_iterator<_Iterator, _Container>
969 operator+(typename __normal_iterator<_Iterator, _Container>::difference_type
970 __n, const __normal_iterator<_Iterator, _Container>& __i)
971 _GLIBCXX_NOEXCEPTnoexcept
972 { return __normal_iterator<_Iterator, _Container>(__i.base() + __n); }
973
974_GLIBCXX_END_NAMESPACE_VERSION
975} // namespace
976
977namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
978{
979_GLIBCXX_BEGIN_NAMESPACE_VERSION
980
981 template<typename _Iterator, typename _Container>
982 _Iterator
983 __niter_base(__gnu_cxx::__normal_iterator<_Iterator, _Container> __it)
984 { return __it.base(); }
985
986_GLIBCXX_END_NAMESPACE_VERSION
987} // namespace
988
989#if __cplusplus201103L >= 201103L
990
991namespace std _GLIBCXX_VISIBILITY(default)__attribute__ ((__visibility__ ("default")))
992{
993_GLIBCXX_BEGIN_NAMESPACE_VERSION
994
995 /**
996 * @addtogroup iterators
997 * @{
998 */
999
1000 // 24.4.3 Move iterators
1001 /**
1002 * Class template move_iterator is an iterator adapter with the same
1003 * behavior as the underlying iterator except that its dereference
1004 * operator implicitly converts the value returned by the underlying
1005 * iterator's dereference operator to an rvalue reference. Some
1006 * generic algorithms can be called with move iterators to replace
1007 * copying with moving.
1008 */
1009 template<typename _Iterator>
1010 class move_iterator
1011 {
1012 protected:
1013 _Iterator _M_current;
1014
1015 typedef iterator_traits<_Iterator> __traits_type;
1016 typedef typename __traits_type::reference __base_ref;
1017
1018 public:
1019 typedef _Iterator iterator_type;
1020 typedef typename __traits_type::iterator_category iterator_category;
1021 typedef typename __traits_type::value_type value_type;
1022 typedef typename __traits_type::difference_type difference_type;
1023 // NB: DR 680.
1024 typedef _Iterator pointer;
1025 // _GLIBCXX_RESOLVE_LIB_DEFECTS
1026 // 2106. move_iterator wrapping iterators returning prvalues
1027 typedef typename conditional<is_reference<__base_ref>::value,
1028 typename remove_reference<__base_ref>::type&&,
1029 __base_ref>::type reference;
1030
1031 _GLIBCXX17_CONSTEXPR
1032 move_iterator()
1033 : _M_current() { }
1034
1035 explicit _GLIBCXX17_CONSTEXPR
1036 move_iterator(iterator_type __i)
1037 : _M_current(__i) { }
1038
1039 template<typename _Iter>
1040 _GLIBCXX17_CONSTEXPR
1041 move_iterator(const move_iterator<_Iter>& __i)
1042 : _M_current(__i.base()) { }
1043
1044 _GLIBCXX17_CONSTEXPR iterator_type
1045 base() const
1046 { return _M_current; }
1047
1048 _GLIBCXX17_CONSTEXPR reference
1049 operator*() const
1050 { return static_cast<reference>(*_M_current); }
1051
1052 _GLIBCXX17_CONSTEXPR pointer
1053 operator->() const
1054 { return _M_current; }
1055
1056 _GLIBCXX17_CONSTEXPR move_iterator&
1057 operator++()
1058 {
1059 ++_M_current;
1060 return *this;
1061 }
1062
1063 _GLIBCXX17_CONSTEXPR move_iterator
1064 operator++(int)
1065 {
1066 move_iterator __tmp = *this;
1067 ++_M_current;
1068 return __tmp;
1069 }
1070
1071 _GLIBCXX17_CONSTEXPR move_iterator&
1072 operator--()
1073 {
1074 --_M_current;
1075 return *this;
1076 }
1077
1078 _GLIBCXX17_CONSTEXPR move_iterator
1079 operator--(int)
1080 {
1081 move_iterator __tmp = *this;
1082 --_M_current;
1083 return __tmp;
1084 }
1085
1086 _GLIBCXX17_CONSTEXPR move_iterator
1087 operator+(difference_type __n) const
1088 { return move_iterator(_M_current + __n); }
1089
1090 _GLIBCXX17_CONSTEXPR move_iterator&
1091 operator+=(difference_type __n)
1092 {
1093 _M_current += __n;
1094 return *this;
1095 }
1096
1097 _GLIBCXX17_CONSTEXPR move_iterator
1098 operator-(difference_type __n) const
1099 { return move_iterator(_M_current - __n); }
1100
1101 _GLIBCXX17_CONSTEXPR move_iterator&
1102 operator-=(difference_type __n)
1103 {
1104 _M_current -= __n;
1105 return *this;
1106 }
1107
1108 _GLIBCXX17_CONSTEXPR reference
1109 operator[](difference_type __n) const
1110 { return std::move(_M_current[__n]); }
1111 };
1112
1113 // Note: See __normal_iterator operators note from Gaby to understand
1114 // why there are always 2 versions for most of the move_iterator
1115 // operators.
1116 template<typename _IteratorL, typename _IteratorR>
1117 inline _GLIBCXX17_CONSTEXPR bool
1118 operator==(const move_iterator<_IteratorL>& __x,
1119 const move_iterator<_IteratorR>& __y)
1120 { return __x.base() == __y.base(); }
1121
1122 template<typename _Iterator>
1123 inline _GLIBCXX17_CONSTEXPR bool
1124 operator==(const move_iterator<_Iterator>& __x,
1125 const move_iterator<_Iterator>& __y)
1126 { return __x.base() == __y.base(); }
1127
1128 template<typename _IteratorL, typename _IteratorR>
1129 inline _GLIBCXX17_CONSTEXPR bool
1130 operator!=(const move_iterator<_IteratorL>& __x,
1131 const move_iterator<_IteratorR>& __y)
1132 { return !(__x == __y); }
1133
1134 template<typename _Iterator>
1135 inline _GLIBCXX17_CONSTEXPR bool
1136 operator!=(const move_iterator<_Iterator>& __x,
1137 const move_iterator<_Iterator>& __y)
1138 { return !(__x == __y); }
1139
1140 template<typename _IteratorL, typename _IteratorR>
1141 inline _GLIBCXX17_CONSTEXPR bool
1142 operator<(const move_iterator<_IteratorL>& __x,
1143 const move_iterator<_IteratorR>& __y)
1144 { return __x.base() < __y.base(); }
1145
1146 template<typename _Iterator>
1147 inline _GLIBCXX17_CONSTEXPR bool
1148 operator<(const move_iterator<_Iterator>& __x,
1149 const move_iterator<_Iterator>& __y)
1150 { return __x.base() < __y.base(); }
1151
1152 template<typename _IteratorL, typename _IteratorR>
1153 inline _GLIBCXX17_CONSTEXPR bool
1154 operator<=(const move_iterator<_IteratorL>& __x,
1155 const move_iterator<_IteratorR>& __y)
1156 { return !(__y < __x); }
1157
1158 template<typename _Iterator>
1159 inline _GLIBCXX17_CONSTEXPR bool
1160 operator<=(const move_iterator<_Iterator>& __x,
1161 const move_iterator<_Iterator>& __y)
1162 { return !(__y < __x); }
1163
1164 template<typename _IteratorL, typename _IteratorR>
1165 inline _GLIBCXX17_CONSTEXPR bool
1166 operator>(const move_iterator<_IteratorL>& __x,
1167 const move_iterator<_IteratorR>& __y)
1168 { return __y < __x; }
1169
1170 template<typename _Iterator>
1171 inline _GLIBCXX17_CONSTEXPR bool
1172 operator>(const move_iterator<_Iterator>& __x,
1173 const move_iterator<_Iterator>& __y)
1174 { return __y < __x; }
1175
1176 template<typename _IteratorL, typename _IteratorR>
1177 inline _GLIBCXX17_CONSTEXPR bool
1178 operator>=(const move_iterator<_IteratorL>& __x,
1179 const move_iterator<_IteratorR>& __y)
1180 { return !(__x < __y); }
1181
1182 template<typename _Iterator>
1183 inline _GLIBCXX17_CONSTEXPR bool
1184 operator>=(const move_iterator<_Iterator>& __x,
1185 const move_iterator<_Iterator>& __y)
1186 { return !(__x < __y); }
1187
1188 // DR 685.
1189 template<typename _IteratorL, typename _IteratorR>
1190 inline _GLIBCXX17_CONSTEXPR auto
1191 operator-(const move_iterator<_IteratorL>& __x,
1192 const move_iterator<_IteratorR>& __y)
1193 -> decltype(__x.base() - __y.base())
1194 { return __x.base() - __y.base(); }
1195
1196 template<typename _Iterator>
1197 inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator>
1198 operator+(typename move_iterator<_Iterator>::difference_type __n,
1199 const move_iterator<_Iterator>& __x)
1200 { return __x + __n; }
1201
1202 template<typename _Iterator>
1203 inline _GLIBCXX17_CONSTEXPR move_iterator<_Iterator>
1204 make_move_iterator(_Iterator __i)
1205 { return move_iterator<_Iterator>(__i); }
1206
1207 template<typename _Iterator, typename _ReturnType
1208 = typename conditional<__move_if_noexcept_cond
1209 <typename iterator_traits<_Iterator>::value_type>::value,
1210 _Iterator, move_iterator<_Iterator>>::type>
1211 inline _GLIBCXX17_CONSTEXPR _ReturnType
1212 __make_move_if_noexcept_iterator(_Iterator __i)
1213 { return _ReturnType(__i); }
1214
1215 // Overload for pointers that matches std::move_if_noexcept more closely,
1216 // returning a constant iterator when we don't want to move.
1217 template<typename _Tp, typename _ReturnType
1218 = typename conditional<__move_if_noexcept_cond<_Tp>::value,
1219 const _Tp*, move_iterator<_Tp*>>::type>
1220 inline _GLIBCXX17_CONSTEXPR _ReturnType
1221 __make_move_if_noexcept_iterator(_Tp* __i)
1222 { return _ReturnType(__i); }
1223
1224 // @} group iterators
1225
1226 template<typename _Iterator>
1227 auto
1228 __niter_base(move_iterator<_Iterator> __it)
1229 -> decltype(make_move_iterator(__niter_base(__it.base())))
1230 { return make_move_iterator(__niter_base(__it.base())); }
1231
1232 template<typename _Iterator>
1233 struct __is_move_iterator<move_iterator<_Iterator> >
1234 {
1235 enum { __value = 1 };
1236 typedef __true_type __type;
1237 };
1238
1239 template<typename _Iterator>
1240 auto
1241 __miter_base(move_iterator<_Iterator> __it)
1242 -> decltype(__miter_base(__it.base()))
1243 { return __miter_base(__it.base()); }
1244
1245_GLIBCXX_END_NAMESPACE_VERSION
1246} // namespace
1247
1248#define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) std::make_move_iterator(_Iter)
1249#define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) \
1250 std::__make_move_if_noexcept_iterator(_Iter)
1251#else
1252#define _GLIBCXX_MAKE_MOVE_ITERATOR(_Iter)std::make_move_iterator(_Iter) (_Iter)
1253#define _GLIBCXX_MAKE_MOVE_IF_NOEXCEPT_ITERATOR(_Iter)std::__make_move_if_noexcept_iterator(_Iter) (_Iter)
1254#endif // C++11
1255
1256#ifdef _GLIBCXX_DEBUG
1257# include <debug/stl_iterator.h>
1258#endif
1259
1260#endif

/build/llvm-toolchain-snapshot-6.0~svn318211/include/llvm/Support/Casting.h

1//===- llvm/Support/Casting.h - Allow flexible, checked, casts --*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5