Bug Summary

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