Bug Summary

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

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 -fhalf-no-semantic-interposition -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-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-13/lib/clang/13.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-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/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-13/lib/clang/13.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-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -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-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Sema/SemaLookup.cpp

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

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h

1//===- llvm/ADT/SmallVector.h - 'Normally small' vectors --------*- 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 the SmallVector class.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_ADT_SMALLVECTOR_H
14#define LLVM_ADT_SMALLVECTOR_H
15
16#include "llvm/ADT/iterator_range.h"
17#include "llvm/Support/Compiler.h"
18#include "llvm/Support/ErrorHandling.h"
19#include "llvm/Support/MathExtras.h"
20#include "llvm/Support/MemAlloc.h"
21#include "llvm/Support/type_traits.h"
22#include <algorithm>
23#include <cassert>
24#include <cstddef>
25#include <cstdlib>
26#include <cstring>
27#include <initializer_list>
28#include <iterator>
29#include <limits>
30#include <memory>
31#include <new>
32#include <type_traits>
33#include <utility>
34
35namespace llvm {
36
37/// This is all the stuff common to all SmallVectors.
38///
39/// The template parameter specifies the type which should be used to hold the
40/// Size and Capacity of the SmallVector, so it can be adjusted.
41/// Using 32 bit size is desirable to shrink the size of the SmallVector.
42/// Using 64 bit size is desirable for cases like SmallVector<char>, where a
43/// 32 bit size would limit the vector to ~4GB. SmallVectors are used for
44/// buffering bitcode output - which can exceed 4GB.
45template <class Size_T> class SmallVectorBase {
46protected:
47 void *BeginX;
48 Size_T Size = 0, Capacity;
49
50 /// The maximum value of the Size_T used.
51 static constexpr size_t SizeTypeMax() {
52 return std::numeric_limits<Size_T>::max();
53 }
54
55 SmallVectorBase() = delete;
56 SmallVectorBase(void *FirstEl, size_t TotalCapacity)
57 : BeginX(FirstEl), Capacity(TotalCapacity) {}
58
59 /// This is a helper for \a grow() that's out of line to reduce code
60 /// duplication. This function will report a fatal error if it can't grow at
61 /// least to \p MinSize.
62 void *mallocForGrow(size_t MinSize, size_t TSize, size_t &NewCapacity);
63
64 /// This is an implementation of the grow() method which only works
65 /// on POD-like data types and is out of line to reduce code duplication.
66 /// This function will report a fatal error if it cannot increase capacity.
67 void grow_pod(void *FirstEl, size_t MinSize, size_t TSize);
68
69public:
70 size_t size() const { return Size; }
71 size_t capacity() const { return Capacity; }
72
73 LLVM_NODISCARD[[clang::warn_unused_result]] bool empty() const { return !Size; }
10
Assuming field 'Size' is not equal to 0
11
Returning zero, which participates in a condition later
74
75 /// Set the array size to \p N, which the current array must have enough
76 /// capacity for.
77 ///
78 /// This does not construct or destroy any elements in the vector.
79 ///
80 /// Clients can use this in conjunction with capacity() to write past the end
81 /// of the buffer when they know that more elements are available, and only
82 /// update the size later. This avoids the cost of value initializing elements
83 /// which will only be overwritten.
84 void set_size(size_t N) {
85 assert(N <= capacity())(static_cast <bool> (N <= capacity()) ? void (0) : __assert_fail
("N <= capacity()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 85, __extension__ __PRETTY_FUNCTION__))
;
86 Size = N;
87 }
88};
89
90template <class T>
91using SmallVectorSizeType =
92 typename std::conditional<sizeof(T) < 4 && sizeof(void *) >= 8, uint64_t,
93 uint32_t>::type;
94
95/// Figure out the offset of the first element.
96template <class T, typename = void> struct SmallVectorAlignmentAndSize {
97 alignas(SmallVectorBase<SmallVectorSizeType<T>>) char Base[sizeof(
98 SmallVectorBase<SmallVectorSizeType<T>>)];
99 alignas(T) char FirstEl[sizeof(T)];
100};
101
102/// This is the part of SmallVectorTemplateBase which does not depend on whether
103/// the type T is a POD. The extra dummy template argument is used by ArrayRef
104/// to avoid unnecessarily requiring T to be complete.
105template <typename T, typename = void>
106class SmallVectorTemplateCommon
107 : public SmallVectorBase<SmallVectorSizeType<T>> {
108 using Base = SmallVectorBase<SmallVectorSizeType<T>>;
109
110 /// Find the address of the first element. For this pointer math to be valid
111 /// with small-size of 0 for T with lots of alignment, it's important that
112 /// SmallVectorStorage is properly-aligned even for small-size of 0.
113 void *getFirstEl() const {
114 return const_cast<void *>(reinterpret_cast<const void *>(
115 reinterpret_cast<const char *>(this) +
116 offsetof(SmallVectorAlignmentAndSize<T>, FirstEl)__builtin_offsetof(SmallVectorAlignmentAndSize<T>, FirstEl
)
));
117 }
118 // Space after 'FirstEl' is clobbered, do not add any instance vars after it.
119
120protected:
121 SmallVectorTemplateCommon(size_t Size) : Base(getFirstEl(), Size) {}
122
123 void grow_pod(size_t MinSize, size_t TSize) {
124 Base::grow_pod(getFirstEl(), MinSize, TSize);
125 }
126
127 /// Return true if this is a smallvector which has not had dynamic
128 /// memory allocated for it.
129 bool isSmall() const { return this->BeginX == getFirstEl(); }
130
131 /// Put this vector in a state of being small.
132 void resetToSmall() {
133 this->BeginX = getFirstEl();
134 this->Size = this->Capacity = 0; // FIXME: Setting Capacity to 0 is suspect.
135 }
136
137 /// Return true if V is an internal reference to the given range.
138 bool isReferenceToRange(const void *V, const void *First, const void *Last) const {
139 // Use std::less to avoid UB.
140 std::less<> LessThan;
141 return !LessThan(V, First) && LessThan(V, Last);
142 }
143
144 /// Return true if V is an internal reference to this vector.
145 bool isReferenceToStorage(const void *V) const {
146 return isReferenceToRange(V, this->begin(), this->end());
147 }
148
149 /// Return true if First and Last form a valid (possibly empty) range in this
150 /// vector's storage.
151 bool isRangeInStorage(const void *First, const void *Last) const {
152 // Use std::less to avoid UB.
153 std::less<> LessThan;
154 return !LessThan(First, this->begin()) && !LessThan(Last, First) &&
155 !LessThan(this->end(), Last);
156 }
157
158 /// Return true unless Elt will be invalidated by resizing the vector to
159 /// NewSize.
160 bool isSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
161 // Past the end.
162 if (LLVM_LIKELY(!isReferenceToStorage(Elt))__builtin_expect((bool)(!isReferenceToStorage(Elt)), true))
163 return true;
164
165 // Return false if Elt will be destroyed by shrinking.
166 if (NewSize <= this->size())
167 return Elt < this->begin() + NewSize;
168
169 // Return false if we need to grow.
170 return NewSize <= this->capacity();
171 }
172
173 /// Check whether Elt will be invalidated by resizing the vector to NewSize.
174 void assertSafeToReferenceAfterResize(const void *Elt, size_t NewSize) {
175 assert(isSafeToReferenceAfterResize(Elt, NewSize) &&(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
176 "Attempting to reference an element of the vector in an operation "(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
177 "that invalidates it")(static_cast <bool> (isSafeToReferenceAfterResize(Elt, NewSize
) && "Attempting to reference an element of the vector in an operation "
"that invalidates it") ? void (0) : __assert_fail ("isSafeToReferenceAfterResize(Elt, NewSize) && \"Attempting to reference an element of the vector in an operation \" \"that invalidates it\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 177, __extension__ __PRETTY_FUNCTION__))
;
178 }
179
180 /// Check whether Elt will be invalidated by increasing the size of the
181 /// vector by N.
182 void assertSafeToAdd(const void *Elt, size_t N = 1) {
183 this->assertSafeToReferenceAfterResize(Elt, this->size() + N);
184 }
185
186 /// Check whether any part of the range will be invalidated by clearing.
187 void assertSafeToReferenceAfterClear(const T *From, const T *To) {
188 if (From == To)
189 return;
190 this->assertSafeToReferenceAfterResize(From, 0);
191 this->assertSafeToReferenceAfterResize(To - 1, 0);
192 }
193 template <
194 class ItTy,
195 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
196 bool> = false>
197 void assertSafeToReferenceAfterClear(ItTy, ItTy) {}
198
199 /// Check whether any part of the range will be invalidated by growing.
200 void assertSafeToAddRange(const T *From, const T *To) {
201 if (From == To)
202 return;
203 this->assertSafeToAdd(From, To - From);
204 this->assertSafeToAdd(To - 1, To - From);
205 }
206 template <
207 class ItTy,
208 std::enable_if_t<!std::is_same<std::remove_const_t<ItTy>, T *>::value,
209 bool> = false>
210 void assertSafeToAddRange(ItTy, ItTy) {}
211
212 /// Reserve enough space to add one element, and return the updated element
213 /// pointer in case it was a reference to the storage.
214 template <class U>
215 static const T *reserveForParamAndGetAddressImpl(U *This, const T &Elt,
216 size_t N) {
217 size_t NewSize = This->size() + N;
218 if (LLVM_LIKELY(NewSize <= This->capacity())__builtin_expect((bool)(NewSize <= This->capacity()), true
)
)
219 return &Elt;
220
221 bool ReferencesStorage = false;
222 int64_t Index = -1;
223 if (!U::TakesParamByValue) {
224 if (LLVM_UNLIKELY(This->isReferenceToStorage(&Elt))__builtin_expect((bool)(This->isReferenceToStorage(&Elt
)), false)
) {
225 ReferencesStorage = true;
226 Index = &Elt - This->begin();
227 }
228 }
229 This->grow(NewSize);
230 return ReferencesStorage ? This->begin() + Index : &Elt;
231 }
232
233public:
234 using size_type = size_t;
235 using difference_type = ptrdiff_t;
236 using value_type = T;
237 using iterator = T *;
238 using const_iterator = const T *;
239
240 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
241 using reverse_iterator = std::reverse_iterator<iterator>;
242
243 using reference = T &;
244 using const_reference = const T &;
245 using pointer = T *;
246 using const_pointer = const T *;
247
248 using Base::capacity;
249 using Base::empty;
250 using Base::size;
251
252 // forward iterator creation methods.
253 iterator begin() { return (iterator)this->BeginX; }
254 const_iterator begin() const { return (const_iterator)this->BeginX; }
255 iterator end() { return begin() + size(); }
256 const_iterator end() const { return begin() + size(); }
257
258 // reverse iterator creation methods.
259 reverse_iterator rbegin() { return reverse_iterator(end()); }
260 const_reverse_iterator rbegin() const{ return const_reverse_iterator(end()); }
261 reverse_iterator rend() { return reverse_iterator(begin()); }
262 const_reverse_iterator rend() const { return const_reverse_iterator(begin());}
263
264 size_type size_in_bytes() const { return size() * sizeof(T); }
265 size_type max_size() const {
266 return std::min(this->SizeTypeMax(), size_type(-1) / sizeof(T));
267 }
268
269 size_t capacity_in_bytes() const { return capacity() * sizeof(T); }
270
271 /// Return a pointer to the vector's buffer, even if empty().
272 pointer data() { return pointer(begin()); }
273 /// Return a pointer to the vector's buffer, even if empty().
274 const_pointer data() const { return const_pointer(begin()); }
275
276 reference operator[](size_type idx) {
277 assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 277, __extension__ __PRETTY_FUNCTION__))
;
278 return begin()[idx];
279 }
280 const_reference operator[](size_type idx) const {
281 assert(idx < size())(static_cast <bool> (idx < size()) ? void (0) : __assert_fail
("idx < size()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 281, __extension__ __PRETTY_FUNCTION__))
;
282 return begin()[idx];
283 }
284
285 reference front() {
286 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 286, __extension__ __PRETTY_FUNCTION__))
;
287 return begin()[0];
288 }
289 const_reference front() const {
290 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 290, __extension__ __PRETTY_FUNCTION__))
;
291 return begin()[0];
292 }
293
294 reference back() {
295 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 295, __extension__ __PRETTY_FUNCTION__))
;
296 return end()[-1];
297 }
298 const_reference back() const {
299 assert(!empty())(static_cast <bool> (!empty()) ? void (0) : __assert_fail
("!empty()", "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include/llvm/ADT/SmallVector.h"
, 299, __extension__ __PRETTY_FUNCTION__))
;
300 return end()[-1];
301 }
302};
303
304/// SmallVectorTemplateBase<TriviallyCopyable = false> - This is where we put
305/// method implementations that are designed to work with non-trivial T's.
306///
307/// We approximate is_trivially_copyable with trivial move/copy construction and
308/// trivial destruction. While the standard doesn't specify that you're allowed
309/// copy these types with memcpy, there is no way for the type to observe this.
310/// This catches the important case of std::pair<POD, POD>, which is not
311/// trivially assignable.
312template <typename T, bool = (is_trivially_copy_constructible<T>::value) &&
313 (is_trivially_move_constructible<T>::value) &&
314 std::is_trivially_destructible<T>::value>
315class SmallVectorTemplateBase : public SmallVectorTemplateCommon<T> {
316 friend class SmallVectorTemplateCommon<T>;
317
318protected:
319 static constexpr bool TakesParamByValue = false;
320 using ValueParamT = const T &;
321
322 SmallVectorTemplateBase(size_t Size) : SmallVectorTemplateCommon<T>(Size) {}
323
324 static void destroy_range(T *S, T *E) {
325 while (S != E) {
326 --E;
327 E->~T();
328 }
329 }
330
331 /// Move the range [I, E) into the uninitialized memory starting with "Dest",
332 /// constructing elements as needed.
333 template<typename It1, typename It2>
334 static void uninitialized_move(It1 I, It1 E, It2 Dest) {
335 std::uninitialized_copy(std::make_move_iterator(I),
336 std::make_move_iterator(E), Dest);
337 }
338
339 /// Copy the range [I, E) onto the uninitialized memory starting with "Dest",
340 /// constructing elements as needed.
341 template<typename It1, typename It2>
342 static void uninitialized_copy(It1 I, It1 E, It2 Dest) {
343 std::uninitialized_copy(I, E, Dest);
344 }
345
346 /// Grow the allocated memory (without initializing new elements), doubling
347 /// the size of the allocated memory. Guarantees space for at least one more
348 /// element, or MinSize more elements if specified.
349 void grow(size_t MinSize = 0);
350
351 /// Create a new allocation big enough for \p MinSize and pass back its size
352 /// in \p NewCapacity. This is the first section of \a grow().
353 T *mallocForGrow(size_t MinSize, size_t &NewCapacity) {
354 return static_cast<T *>(
355 SmallVectorBase<SmallVectorSizeType<T>>::mallocForGrow(
356 MinSize, sizeof(T), NewCapacity));
357 }
358
359 /// Move existing elements over to the new allocation \p NewElts, the middle
360 /// section of \a grow().
361 void moveElementsForGrow(T *NewElts);
362
363 /// Transfer ownership of the allocation, finishing up \a grow().
364 void takeAllocationForGrow(T *NewElts, size_t NewCapacity);
365
366 /// Reserve enough space to add one element, and return the updated element
367 /// pointer in case it was a reference to the storage.
368 const T *reserveForParamAndGetAddress(const T &Elt, size_t N = 1) {
369 return this->reserveForParamAndGetAddressImpl(this, Elt, N);
370 }
371
372 /// Reserve enough space to add one element, and return the updated element
373 /// pointer in case it was a reference to the storage.
374 T *reserveForParamAndGetAddress(T &Elt, size_t N = 1) {
375 return const_cast<T *>(
376 this->reserveForParamAndGetAddressImpl(this, Elt, N));
377 }
378
379