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 -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/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-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-08-28-193554-24367-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/clang/lib/Sema/SemaLookup.cpp

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

/build/llvm-toolchain-snapshot-14~++20210828111110+16086d47c0d0/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();
14
'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) {
15
Assuming the condition is false
16
Taking false branch
65 Row = new unsigned[n + 1];
66 Allocated.reset(Row);
67 }
68
69 for (unsigned i = 1; i <= n; ++i)
17
Assuming 'i' is > 'n'
18
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) {
19
Assuming 'y' is > 'm'
20
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];
21
Assigned value is garbage or undefined
97 return Result;
98}
99
100} // End llvm namespace
101
102#endif