Bug Summary

File:llvm/include/llvm/ADT/edit_distance.h
Warning:line 96, column 3
Assigned value is garbage or undefined

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaLookup.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-12-11-181444-25759-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaLookup.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/Sema/SemaLookup.cpp

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

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/edit_distance.h

1//===-- llvm/ADT/edit_distance.h - Array edit distance function --- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines a Levenshtein distance function that works for any two
10// sequences, with each element of each sequence being analogous to a character
11// in a string.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_ADT_EDIT_DISTANCE_H
16#define LLVM_ADT_EDIT_DISTANCE_H
17
18#include "llvm/ADT/ArrayRef.h"
19#include <algorithm>
20#include <memory>
21
22namespace llvm {
23
24/// Determine the edit distance between two sequences.
25///
26/// \param FromArray the first sequence to compare.
27///
28/// \param ToArray the second sequence to compare.
29///
30/// \param AllowReplacements whether to allow element replacements (change one
31/// element into another) as a single operation, rather than as two operations
32/// (an insertion and a removal).
33///
34/// \param MaxEditDistance If non-zero, the maximum edit distance that this
35/// routine is allowed to compute. If the edit distance will exceed that
36/// maximum, returns \c MaxEditDistance+1.
37///
38/// \returns the minimum number of element insertions, removals, or (if
39/// \p AllowReplacements is \c true) replacements needed to transform one of
40/// the given sequences into the other. If zero, the sequences are identical.
41template<typename T>
42unsigned ComputeEditDistance(ArrayRef<T> FromArray, ArrayRef<T> ToArray,
43 bool AllowReplacements = true,
44 unsigned MaxEditDistance = 0) {
45 // The algorithm implemented below is the "classic"
46 // dynamic-programming algorithm for computing the Levenshtein
47 // distance, which is described here:
48 //
49 // http://en.wikipedia.org/wiki/Levenshtein_distance
50 //
51 // Although the algorithm is typically described using an m x n
52 // array, only one row plus one element are used at a time, so this
53 // implementation just keeps one vector for the row. To update one entry,
54 // only the entries to the left, top, and top-left are needed. The left
55 // entry is in Row[x-1], the top entry is what's in Row[x] from the last
56 // iteration, and the top-left entry is stored in Previous.
57 typename ArrayRef<T>::size_type m = FromArray.size();
58 typename ArrayRef<T>::size_type n = ToArray.size();
12
'n' initialized here
59
60 const unsigned SmallBufferSize = 64;
61 unsigned SmallBuffer[SmallBufferSize];
62 std::unique_ptr<unsigned[]> Allocated;
63 unsigned *Row = SmallBuffer;
64 if (n + 1 > SmallBufferSize) {
13
Assuming the condition is false
14
Taking false branch
65 Row = new unsigned[n + 1];
66 Allocated.reset(Row);
67 }
68
69 for (unsigned i = 1; i <= n; ++i)
15
Assuming 'i' is > 'n'
16
Loop condition is false. Execution continues on line 72
70 Row[i] = i;
71
72 for (typename ArrayRef<T>::size_type y = 1; y <= m; ++y) {
17
Assuming 'y' is > 'm'
18
Loop condition is false. Execution continues on line 96
73 Row[0] = y;
74 unsigned BestThisRow = Row[0];
75
76 unsigned Previous = y - 1;
77 for (typename ArrayRef<T>::size_type x = 1; x <= n; ++x) {
78 int OldRow = Row[x];
79 if (AllowReplacements) {
80 Row[x] = std::min(
81 Previous + (FromArray[y-1] == ToArray[x-1] ? 0u : 1u),
82 std::min(Row[x-1], Row[x])+1);
83 }
84 else {
85 if (FromArray[y-1] == ToArray[x-1]) Row[x] = Previous;
86 else Row[x] = std::min(Row[x-1], Row[x]) + 1;
87 }
88 Previous = OldRow;
89 BestThisRow = std::min(BestThisRow, Row[x]);
90 }
91
92 if (MaxEditDistance && BestThisRow > MaxEditDistance)
93 return MaxEditDistance + 1;
94 }
95
96 unsigned Result = Row[n];
19
Assigned value is garbage or undefined
97 return Result;
98}
99
100} // End llvm namespace
101
102#endif