Bug Summary

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

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name SemaLookup.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/include -I /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/llvm/include -D NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-14/lib/clang/14.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/build-llvm/tools/clang/lib/Sema -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-09-04-040900-46481-1 -x c++ /build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaLookup.cpp

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/lib/Sema/SemaLookup.cpp

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

/build/llvm-toolchain-snapshot-14~++20210903100615+fd66b44ec19e/clang/include/clang/AST/DeclBase.h

1//===- DeclBase.h - Base Classes for representing declarations --*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Decl and DeclContext interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_DECLBASE_H
14#define LLVM_CLANG_AST_DECLBASE_H
15
16#include "clang/AST/ASTDumperUtils.h"
17#include "clang/AST/AttrIterator.h"
18#include "clang/AST/DeclarationName.h"
19#include "clang/Basic/IdentifierTable.h"
20#include "clang/Basic/LLVM.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/Specifiers.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/PointerIntPair.h"
25#include "llvm/ADT/PointerUnion.h"
26#include "llvm/ADT/iterator.h"
27#include "llvm/ADT/iterator_range.h"
28#include "llvm/Support/Casting.h"
29#include "llvm/Support/Compiler.h"
30#include "llvm/Support/PrettyStackTrace.h"
31#include "llvm/Support/VersionTuple.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <iterator>
36#include <string>
37#include <type_traits>
38#include <utility>
39
40namespace clang {
41
42class ASTContext;
43class ASTMutationListener;
44class Attr;
45class BlockDecl;
46class DeclContext;
47class ExternalSourceSymbolAttr;
48class FunctionDecl;
49class FunctionType;
50class IdentifierInfo;
51enum Linkage : unsigned char;
52class LinkageSpecDecl;
53class Module;
54class NamedDecl;
55class ObjCCategoryDecl;
56class ObjCCategoryImplDecl;
57class ObjCContainerDecl;
58class ObjCImplDecl;
59class ObjCImplementationDecl;
60class ObjCInterfaceDecl;
61class ObjCMethodDecl;
62class ObjCProtocolDecl;
63struct PrintingPolicy;
64class RecordDecl;
65class SourceManager;
66class Stmt;
67class StoredDeclsMap;
68class TemplateDecl;
69class TemplateParameterList;
70class TranslationUnitDecl;
71class UsingDirectiveDecl;
72
73/// Captures the result of checking the availability of a
74/// declaration.
75enum AvailabilityResult {
76 AR_Available = 0,
77 AR_NotYetIntroduced,
78 AR_Deprecated,
79 AR_Unavailable
80};
81
82/// Decl - This represents one declaration (or definition), e.g. a variable,
83/// typedef, function, struct, etc.
84///
85/// Note: There are objects tacked on before the *beginning* of Decl
86/// (and its subclasses) in its Decl::operator new(). Proper alignment
87/// of all subclasses (not requiring more than the alignment of Decl) is
88/// asserted in DeclBase.cpp.
89class alignas(8) Decl {
90public:
91 /// Lists the kind of concrete classes of Decl.
92 enum Kind {
93#define DECL(DERIVED, BASE) DERIVED,
94#define ABSTRACT_DECL(DECL)
95#define DECL_RANGE(BASE, START, END) \
96 first##BASE = START, last##BASE = END,
97#define LAST_DECL_RANGE(BASE, START, END) \
98 first##BASE = START, last##BASE = END
99#include "clang/AST/DeclNodes.inc"
100 };
101
102 /// A placeholder type used to construct an empty shell of a
103 /// decl-derived type that will be filled in later (e.g., by some
104 /// deserialization method).
105 struct EmptyShell {};
106
107 /// IdentifierNamespace - The different namespaces in which
108 /// declarations may appear. According to C99 6.2.3, there are
109 /// four namespaces, labels, tags, members and ordinary
110 /// identifiers. C++ describes lookup completely differently:
111 /// certain lookups merely "ignore" certain kinds of declarations,
112 /// usually based on whether the declaration is of a type, etc.
113 ///
114 /// These are meant as bitmasks, so that searches in
115 /// C++ can look into the "tag" namespace during ordinary lookup.
116 ///
117 /// Decl currently provides 15 bits of IDNS bits.
118 enum IdentifierNamespace {
119 /// Labels, declared with 'x:' and referenced with 'goto x'.
120 IDNS_Label = 0x0001,
121
122 /// Tags, declared with 'struct foo;' and referenced with
123 /// 'struct foo'. All tags are also types. This is what
124 /// elaborated-type-specifiers look for in C.
125 /// This also contains names that conflict with tags in the
126 /// same scope but that are otherwise ordinary names (non-type
127 /// template parameters and indirect field declarations).
128 IDNS_Tag = 0x0002,
129
130 /// Types, declared with 'struct foo', typedefs, etc.
131 /// This is what elaborated-type-specifiers look for in C++,
132 /// but note that it's ill-formed to find a non-tag.
133 IDNS_Type = 0x0004,
134
135 /// Members, declared with object declarations within tag
136 /// definitions. In C, these can only be found by "qualified"
137 /// lookup in member expressions. In C++, they're found by
138 /// normal lookup.
139 IDNS_Member = 0x0008,
140
141 /// Namespaces, declared with 'namespace foo {}'.
142 /// Lookup for nested-name-specifiers find these.
143 IDNS_Namespace = 0x0010,
144
145 /// Ordinary names. In C, everything that's not a label, tag,
146 /// member, or function-local extern ends up here.
147 IDNS_Ordinary = 0x0020,
148
149 /// Objective C \@protocol.
150 IDNS_ObjCProtocol = 0x0040,
151
152 /// This declaration is a friend function. A friend function
153 /// declaration is always in this namespace but may also be in
154 /// IDNS_Ordinary if it was previously declared.
155 IDNS_OrdinaryFriend = 0x0080,
156
157 /// This declaration is a friend class. A friend class
158 /// declaration is always in this namespace but may also be in
159 /// IDNS_Tag|IDNS_Type if it was previously declared.
160 IDNS_TagFriend = 0x0100,
161
162 /// This declaration is a using declaration. A using declaration
163 /// *introduces* a number of other declarations into the current
164 /// scope, and those declarations use the IDNS of their targets,
165 /// but the actual using declarations go in this namespace.
166 IDNS_Using = 0x0200,
167
168 /// This declaration is a C++ operator declared in a non-class
169 /// context. All such operators are also in IDNS_Ordinary.
170 /// C++ lexical operator lookup looks for these.
171 IDNS_NonMemberOperator = 0x0400,
172
173 /// This declaration is a function-local extern declaration of a
174 /// variable or function. This may also be IDNS_Ordinary if it
175 /// has been declared outside any function. These act mostly like
176 /// invisible friend declarations, but are also visible to unqualified
177 /// lookup within the scope of the declaring function.
178 IDNS_LocalExtern = 0x0800,
179
180 /// This declaration is an OpenMP user defined reduction construction.
181 IDNS_OMPReduction = 0x1000,
182
183 /// This declaration is an OpenMP user defined mapper.
184 IDNS_OMPMapper = 0x2000,
185 };
186
187 /// ObjCDeclQualifier - 'Qualifiers' written next to the return and
188 /// parameter types in method declarations. Other than remembering
189 /// them and mangling them into the method's signature string, these
190 /// are ignored by the compiler; they are consumed by certain
191 /// remote-messaging frameworks.
192 ///
193 /// in, inout, and out are mutually exclusive and apply only to
194 /// method parameters. bycopy and byref are mutually exclusive and
195 /// apply only to method parameters (?). oneway applies only to
196 /// results. All of these expect their corresponding parameter to
197 /// have a particular type. None of this is currently enforced by
198 /// clang.
199 ///
200 /// This should be kept in sync with ObjCDeclSpec::ObjCDeclQualifier.
201 enum ObjCDeclQualifier {
202 OBJC_TQ_None = 0x0,
203 OBJC_TQ_In = 0x1,
204 OBJC_TQ_Inout = 0x2,
205 OBJC_TQ_Out = 0x4,
206 OBJC_TQ_Bycopy = 0x8,
207 OBJC_TQ_Byref = 0x10,
208 OBJC_TQ_Oneway = 0x20,
209
210 /// The nullability qualifier is set when the nullability of the
211 /// result or parameter was expressed via a context-sensitive
212 /// keyword.
213 OBJC_TQ_CSNullability = 0x40
214 };
215
216 /// The kind of ownership a declaration has, for visibility purposes.
217 /// This enumeration is designed such that higher values represent higher
218 /// levels of name hiding.
219 enum class ModuleOwnershipKind : unsigned {
220 /// This declaration is not owned by a module.
221 Unowned,
222
223 /// This declaration has an owning module, but is globally visible
224 /// (typically because its owning module is visible and we know that
225 /// modules cannot later become hidden in this compilation).
226 /// After serialization and deserialization, this will be converted
227 /// to VisibleWhenImported.
228 Visible,
229
230 /// This declaration has an owning module, and is visible when that
231 /// module is imported.
232 VisibleWhenImported,
233
234 /// This declaration has an owning module, but is only visible to
235 /// lookups that occur within that module.
236 ModulePrivate
237 };
238
239protected:
240 /// The next declaration within the same lexical
241 /// DeclContext. These pointers form the linked list that is
242 /// traversed via DeclContext's decls_begin()/decls_end().
243 ///
244 /// The extra two bits are used for the ModuleOwnershipKind.
245 llvm::PointerIntPair<Decl *, 2, ModuleOwnershipKind> NextInContextAndBits;
246
247private:
248 friend class DeclContext;
249
250 struct MultipleDC {
251 DeclContext *SemanticDC;
252 DeclContext *LexicalDC;
253 };
254
255 /// DeclCtx - Holds either a DeclContext* or a MultipleDC*.
256 /// For declarations that don't contain C++ scope specifiers, it contains
257 /// the DeclContext where the Decl was declared.
258 /// For declarations with C++ scope specifiers, it contains a MultipleDC*
259 /// with the context where it semantically belongs (SemanticDC) and the
260 /// context where it was lexically declared (LexicalDC).
261 /// e.g.:
262 ///
263 /// namespace A {
264 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
265 /// }
266 /// void A::f(); // SemanticDC == namespace 'A'
267 /// // LexicalDC == global namespace
268 llvm::PointerUnion<DeclContext*, MultipleDC*> DeclCtx;
269
270 bool isInSemaDC() const { return DeclCtx.is<DeclContext*>(); }
271 bool isOutOfSemaDC() const { return DeclCtx.is<MultipleDC*>(); }
272
273 MultipleDC *getMultipleDC() const {
274 return DeclCtx.get<MultipleDC*>();
275 }
276
277 DeclContext *getSemanticDC() const {
278 return DeclCtx.get<DeclContext*>();
279 }
280
281 /// Loc - The location of this decl.
282 SourceLocation Loc;
283
284 /// DeclKind - This indicates which class this is.
285 unsigned DeclKind : 7;
286
287 /// InvalidDecl - This indicates a semantic error occurred.
288 unsigned InvalidDecl : 1;
289
290 /// HasAttrs - This indicates whether the decl has attributes or not.
291 unsigned HasAttrs : 1;
292
293 /// Implicit - Whether this declaration was implicitly generated by
294 /// the implementation rather than explicitly written by the user.
295 unsigned Implicit : 1;
296
297 /// Whether this declaration was "used", meaning that a definition is
298 /// required.
299 unsigned Used : 1;
300
301 /// Whether this declaration was "referenced".
302 /// The difference with 'Used' is whether the reference appears in a
303 /// evaluated context or not, e.g. functions used in uninstantiated templates
304 /// are regarded as "referenced" but not "used".
305 unsigned Referenced : 1;
306
307 /// Whether this declaration is a top-level declaration (function,
308 /// global variable, etc.) that is lexically inside an objc container
309 /// definition.
310 unsigned TopLevelDeclInObjCContainer : 1;
311
312 /// Whether statistic collection is enabled.
313 static bool StatisticsEnabled;
314
315protected:
316 friend class ASTDeclReader;
317 friend class ASTDeclWriter;
318 friend class ASTNodeImporter;
319 friend class ASTReader;
320 friend class CXXClassMemberWrapper;
321 friend class LinkageComputer;
322 template<typename decl_type> friend class Redeclarable;
323
324 /// Access - Used by C++ decls for the access specifier.
325 // NOTE: VC++ treats enums as signed, avoid using the AccessSpecifier enum
326 unsigned Access : 2;
327
328 /// Whether this declaration was loaded from an AST file.
329 unsigned FromASTFile : 1;
330
331 /// IdentifierNamespace - This specifies what IDNS_* namespace this lives in.
332 unsigned IdentifierNamespace : 14;
333
334 /// If 0, we have not computed the linkage of this declaration.
335 /// Otherwise, it is the linkage + 1.
336 mutable unsigned CacheValidAndLinkage : 3;
337
338 /// Allocate memory for a deserialized declaration.
339 ///
340 /// This routine must be used to allocate memory for any declaration that is
341 /// deserialized from a module file.
342 ///
343 /// \param Size The size of the allocated object.
344 /// \param Ctx The context in which we will allocate memory.
345 /// \param ID The global ID of the deserialized declaration.
346 /// \param Extra The amount of extra space to allocate after the object.
347 void *operator new(std::size_t Size, const ASTContext &Ctx, unsigned ID,
348 std::size_t Extra = 0);
349
350 /// Allocate memory for a non-deserialized declaration.
351 void *operator new(std::size_t Size, const ASTContext &Ctx,
352 DeclContext *Parent, std::size_t Extra = 0);
353
354private:
355 bool AccessDeclContextSanity() const;
356
357 /// Get the module ownership kind to use for a local lexical child of \p DC,
358 /// which may be either a local or (rarely) an imported declaration.
359 static ModuleOwnershipKind getModuleOwnershipKindForChildOf(DeclContext *DC) {
360 if (DC) {
361 auto *D = cast<Decl>(DC);
362 auto MOK = D->getModuleOwnershipKind();
363 if (MOK != ModuleOwnershipKind::Unowned &&
364 (!D->isFromASTFile() || D->hasLocalOwningModuleStorage()))
365 return MOK;
366 // If D is not local and we have no local module storage, then we don't
367 // need to track module ownership at all.
368 }
369 return ModuleOwnershipKind::Unowned;
370 }
371
372public:
373 Decl() = delete;
374 Decl(const Decl&) = delete;
375 Decl(Decl &&) = delete;
376 Decl &operator=(const Decl&) = delete;
377 Decl &operator=(Decl&&) = delete;
378
379protected:
380 Decl(Kind DK, DeclContext *DC, SourceLocation L)
381 : NextInContextAndBits(nullptr, getModuleOwnershipKindForChildOf(DC)),
382 DeclCtx(DC), Loc(L), DeclKind(DK), InvalidDecl(false), HasAttrs(false),
383 Implicit(false), Used(false), Referenced(false),
384 TopLevelDeclInObjCContainer(false), Access(AS_none), FromASTFile(0),
385 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
386 CacheValidAndLinkage(0) {
387 if (StatisticsEnabled) add(DK);
388 }
389
390 Decl(Kind DK, EmptyShell Empty)
391 : DeclKind(DK), InvalidDecl(false), HasAttrs(false), Implicit(false),
392 Used(false), Referenced(false), TopLevelDeclInObjCContainer(false),
393 Access(AS_none), FromASTFile(0),
394 IdentifierNamespace(getIdentifierNamespaceForKind(DK)),
395 CacheValidAndLinkage(0) {
396 if (StatisticsEnabled) add(DK);
397 }
398
399 virtual ~Decl();
400
401 /// Update a potentially out-of-date declaration.
402 void updateOutOfDate(IdentifierInfo &II) const;
403
404 Linkage getCachedLinkage() const {
405 return Linkage(CacheValidAndLinkage - 1);
406 }
407
408 void setCachedLinkage(Linkage L) const {
409 CacheValidAndLinkage = L + 1;
410 }
411
412 bool hasCachedLinkage() const {
413 return CacheValidAndLinkage;
414 }
415
416public:
417 /// Source range that this declaration covers.
418 virtual SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) {
419 return SourceRange(getLocation(), getLocation());
420 }
421
422 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
423 return getSourceRange().getBegin();
424 }
425
426 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
427 return getSourceRange().getEnd();
428 }
429
430 SourceLocation getLocation() const { return Loc; }
431 void setLocation(SourceLocation L) { Loc = L; }
432
433 Kind getKind() const { return static_cast<Kind>(DeclKind); }
434 const char *getDeclKindName() const;
435
436 Decl *getNextDeclInContext() { return NextInContextAndBits.getPointer(); }
437 const Decl *getNextDeclInContext() const {return NextInContextAndBits.getPointer();}
438
439 DeclContext *getDeclContext() {
440 if (isInSemaDC())
441 return getSemanticDC();
442 return getMultipleDC()->SemanticDC;
443 }
444 const DeclContext *getDeclContext() const {
445 return const_cast<Decl*>(this)->getDeclContext();
446 }
447
448 /// Find the innermost non-closure ancestor of this declaration,
449 /// walking up through blocks, lambdas, etc. If that ancestor is
450 /// not a code context (!isFunctionOrMethod()), returns null.
451 ///
452 /// A declaration may be its own non-closure context.
453 Decl *getNonClosureContext();
454 const Decl *getNonClosureContext() const {
455 return const_cast<Decl*>(this)->getNonClosureContext();
456 }
457
458 TranslationUnitDecl *getTranslationUnitDecl();
459 const TranslationUnitDecl *getTranslationUnitDecl() const {
460 return const_cast<Decl*>(this)->getTranslationUnitDecl();
461 }
462
463 bool isInAnonymousNamespace() const;
464
465 bool isInStdNamespace() const;
466
467 ASTContext &getASTContext() const LLVM_READONLY__attribute__((__pure__));
468
469 /// Helper to get the language options from the ASTContext.
470 /// Defined out of line to avoid depending on ASTContext.h.
471 const LangOptions &getLangOpts() const LLVM_READONLY__attribute__((__pure__));
472
473 void setAccess(AccessSpecifier AS) {
474 Access = AS;
475 assert(AccessDeclContextSanity())(static_cast<void> (0));
476 }
477
478 AccessSpecifier getAccess() const {
479 assert(AccessDeclContextSanity())(static_cast<void> (0));
480 return AccessSpecifier(Access);
481 }
482
483 /// Retrieve the access specifier for this declaration, even though
484 /// it may not yet have been properly set.
485 AccessSpecifier getAccessUnsafe() const {
486 return AccessSpecifier(Access);
487 }
488
489 bool hasAttrs() const { return HasAttrs; }
490
491 void setAttrs(const AttrVec& Attrs) {
492 return setAttrsImpl(Attrs, getASTContext());
493 }
494
495 AttrVec &getAttrs() {
496 return const_cast<AttrVec&>(const_cast<const Decl*>(this)->getAttrs());
497 }
498
499 const AttrVec &getAttrs() const;
500 void dropAttrs();
501 void addAttr(Attr *A);
502
503 using attr_iterator = AttrVec::const_iterator;
504 using attr_range = llvm::iterator_range<attr_iterator>;
505
506 attr_range attrs() const {
507 return attr_range(attr_begin(), attr_end());
508 }
509
510 attr_iterator attr_begin() const {
511 return hasAttrs() ? getAttrs().begin() : nullptr;
512 }
513 attr_iterator attr_end() const {
514 return hasAttrs() ? getAttrs().end() : nullptr;
515 }
516
517 template <typename T>
518 void dropAttr() {
519 if (!HasAttrs) return;
520
521 AttrVec &Vec = getAttrs();
522 llvm::erase_if(Vec, [](Attr *A) { return isa<T>(A); });
523
524 if (Vec.empty())
525 HasAttrs = false;
526 }
527
528 template <typename T>
529 llvm::iterator_range<specific_attr_iterator<T>> specific_attrs() const {
530 return llvm::make_range(specific_attr_begin<T>(), specific_attr_end<T>());
531 }
532
533 template <typename T>
534 specific_attr_iterator<T> specific_attr_begin() const {
535 return specific_attr_iterator<T>(attr_begin());
536 }
537
538 template <typename T>
539 specific_attr_iterator<T> specific_attr_end() const {
540 return specific_attr_iterator<T>(attr_end());
541 }
542
543 template<typename T> T *getAttr() const {
544 return hasAttrs() ? getSpecificAttr<T>(getAttrs()) : nullptr;
545 }
546
547 template<typename T> bool hasAttr() const {
548 return hasAttrs() && hasSpecificAttr<T>(getAttrs());
549 }
550
551 /// getMaxAlignment - return the maximum alignment specified by attributes
552 /// on this decl, 0 if there are none.
553 unsigned getMaxAlignment() const;
554
555 /// setInvalidDecl - Indicates the Decl had a semantic error. This
556 /// allows for graceful error recovery.
557 void setInvalidDecl(bool Invalid = true);
558 bool isInvalidDecl() const { return (bool) InvalidDecl; }
559
560 /// isImplicit - Indicates whether the declaration was implicitly
561 /// generated by the implementation. If false, this declaration
562 /// was written explicitly in the source code.
563 bool isImplicit() const { return Implicit; }
564 void setImplicit(bool I = true) { Implicit = I; }
565
566 /// Whether *any* (re-)declaration of the entity was used, meaning that
567 /// a definition is required.
568 ///
569 /// \param CheckUsedAttr When true, also consider the "used" attribute
570 /// (in addition to the "used" bit set by \c setUsed()) when determining
571 /// whether the function is used.
572 bool isUsed(bool CheckUsedAttr = true) const;
573
574 /// Set whether the declaration is used, in the sense of odr-use.
575 ///
576 /// This should only be used immediately after creating a declaration.
577 /// It intentionally doesn't notify any listeners.
578 void setIsUsed() { getCanonicalDecl()->Used = true; }
579
580 /// Mark the declaration used, in the sense of odr-use.
581 ///
582 /// This notifies any mutation listeners in addition to setting a bit
583 /// indicating the declaration is used.
584 void markUsed(ASTContext &C);
585
586 /// Whether any declaration of this entity was referenced.
587 bool isReferenced() const;
588
589 /// Whether this declaration was referenced. This should not be relied
590 /// upon for anything other than debugging.
591 bool isThisDeclarationReferenced() const { return Referenced; }
592
593 void setReferenced(bool R = true) { Referenced = R; }
594
595 /// Whether this declaration is a top-level declaration (function,
596 /// global variable, etc.) that is lexically inside an objc container
597 /// definition.
598 bool isTopLevelDeclInObjCContainer() const {
599 return TopLevelDeclInObjCContainer;
600 }
601
602 void setTopLevelDeclInObjCContainer(bool V = true) {
603 TopLevelDeclInObjCContainer = V;
604 }
605
606 /// Looks on this and related declarations for an applicable
607 /// external source symbol attribute.
608 ExternalSourceSymbolAttr *getExternalSourceSymbolAttr() const;
609
610 /// Whether this declaration was marked as being private to the
611 /// module in which it was defined.
612 bool isModulePrivate() const {
613 return getModuleOwnershipKind() == ModuleOwnershipKind::ModulePrivate;
614 }
615
616 /// Return true if this declaration has an attribute which acts as
617 /// definition of the entity, such as 'alias' or 'ifunc'.
618 bool hasDefiningAttr() const;
619
620 /// Return this declaration's defining attribute if it has one.
621 const Attr *getDefiningAttr() const;
622
623protected:
624 /// Specify that this declaration was marked as being private
625 /// to the module in which it was defined.
626 void setModulePrivate() {
627 // The module-private specifier has no effect on unowned declarations.
628 // FIXME: We should track this in some way for source fidelity.
629 if (getModuleOwnershipKind() == ModuleOwnershipKind::Unowned)
630 return;
631 setModuleOwnershipKind(ModuleOwnershipKind::ModulePrivate);
632 }
633
634public:
635 /// Set the FromASTFile flag. This indicates that this declaration
636 /// was deserialized and not parsed from source code and enables
637 /// features such as module ownership information.
638 void setFromASTFile() {
639 FromASTFile = true;
640 }
641
642 /// Set the owning module ID. This may only be called for
643 /// deserialized Decls.
644 void setOwningModuleID(unsigned ID) {
645 assert(isFromASTFile() && "Only works on a deserialized declaration")(static_cast<void> (0));
646 *((unsigned*)this - 2) = ID;
647 }
648
649public:
650 /// Determine the availability of the given declaration.
651 ///
652 /// This routine will determine the most restrictive availability of
653 /// the given declaration (e.g., preferring 'unavailable' to
654 /// 'deprecated').
655 ///
656 /// \param Message If non-NULL and the result is not \c
657 /// AR_Available, will be set to a (possibly empty) message
658 /// describing why the declaration has not been introduced, is
659 /// deprecated, or is unavailable.
660 ///
661 /// \param EnclosingVersion The version to compare with. If empty, assume the
662 /// deployment target version.
663 ///
664 /// \param RealizedPlatform If non-NULL and the availability result is found
665 /// in an available attribute it will set to the platform which is written in
666 /// the available attribute.
667 AvailabilityResult
668 getAvailability(std::string *Message = nullptr,
669 VersionTuple EnclosingVersion = VersionTuple(),
670 StringRef *RealizedPlatform = nullptr) const;
671
672 /// Retrieve the version of the target platform in which this
673 /// declaration was introduced.
674 ///
675 /// \returns An empty version tuple if this declaration has no 'introduced'
676 /// availability attributes, or the version tuple that's specified in the
677 /// attribute otherwise.
678 VersionTuple getVersionIntroduced() const;
679
680 /// Determine whether this declaration is marked 'deprecated'.
681 ///
682 /// \param Message If non-NULL and the declaration is deprecated,
683 /// this will be set to the message describing why the declaration
684 /// was deprecated (which may be empty).
685 bool isDeprecated(std::string *Message = nullptr) const {
686 return getAvailability(Message) == AR_Deprecated;
687 }
688
689 /// Determine whether this declaration is marked 'unavailable'.
690 ///
691 /// \param Message If non-NULL and the declaration is unavailable,
692 /// this will be set to the message describing why the declaration
693 /// was made unavailable (which may be empty).
694 bool isUnavailable(std::string *Message = nullptr) const {
695 return getAvailability(Message) == AR_Unavailable;
696 }
697
698 /// Determine whether this is a weak-imported symbol.
699 ///
700 /// Weak-imported symbols are typically marked with the
701 /// 'weak_import' attribute, but may also be marked with an
702 /// 'availability' attribute where we're targing a platform prior to
703 /// the introduction of this feature.
704 bool isWeakImported() const;
705
706 /// Determines whether this symbol can be weak-imported,
707 /// e.g., whether it would be well-formed to add the weak_import
708 /// attribute.
709 ///
710 /// \param IsDefinition Set to \c true to indicate that this
711 /// declaration cannot be weak-imported because it has a definition.
712 bool canBeWeakImported(bool &IsDefinition) const;
713
714 /// Determine whether this declaration came from an AST file (such as
715 /// a precompiled header or module) rather than having been parsed.
716 bool isFromASTFile() const { return FromASTFile; }
717
718 /// Retrieve the global declaration ID associated with this
719 /// declaration, which specifies where this Decl was loaded from.
720 unsigned getGlobalID() const {
721 if (isFromASTFile())
722 return *((const unsigned*)this - 1);
723 return 0;
724 }
725
726 /// Retrieve the global ID of the module that owns this particular
727 /// declaration.
728 unsigned getOwningModuleID() const {
729 if (isFromASTFile())
730 return *((const unsigned*)this - 2);
731 return 0;
732 }
733
734private:
735 Module *getOwningModuleSlow() const;
736
737protected:
738 bool hasLocalOwningModuleStorage() const;
739
740public:
741 /// Get the imported owning module, if this decl is from an imported
742 /// (non-local) module.
743 Module *getImportedOwningModule() const {
744 if (!isFromASTFile() || !hasOwningModule())
745 return nullptr;
746
747 return getOwningModuleSlow();
748 }
749
750 /// Get the local owning module, if known. Returns nullptr if owner is
751 /// not yet known or declaration is not from a module.
752 Module *getLocalOwningModule() const {
753 if (isFromASTFile() || !hasOwningModule())
754 return nullptr;
755
756 assert(hasLocalOwningModuleStorage() &&(static_cast<void> (0))
757 "owned local decl but no local module storage")(static_cast<void> (0));
758 return reinterpret_cast<Module *const *>(this)[-1];
759 }
760 void setLocalOwningModule(Module *M) {
761 assert(!isFromASTFile() && hasOwningModule() &&(static_cast<void> (0))
762 hasLocalOwningModuleStorage() &&(static_cast<void> (0))
763 "should not have a cached owning module")(static_cast<void> (0));
764 reinterpret_cast<Module **>(this)[-1] = M;
765 }
766
767 /// Is this declaration owned by some module?
768 bool hasOwningModule() const {
769 return getModuleOwnershipKind() != ModuleOwnershipKind::Unowned;
770 }
771
772 /// Get the module that owns this declaration (for visibility purposes).
773 Module *getOwningModule() const {
774 return isFromASTFile() ? getImportedOwningModule() : getLocalOwningModule();
775 }
776
777 /// Get the module that owns this declaration for linkage purposes.
778 /// There only ever is such a module under the C++ Modules TS.
779 ///
780 /// \param IgnoreLinkage Ignore the linkage of the entity; assume that
781 /// all declarations in a global module fragment are unowned.
782 Module *getOwningModuleForLinkage(bool IgnoreLinkage = false) const;
783
784 /// Determine whether this declaration is definitely visible to name lookup,
785 /// independent of whether the owning module is visible.
786 /// Note: The declaration may be visible even if this returns \c false if the
787 /// owning module is visible within the query context. This is a low-level
788 /// helper function; most code should be calling Sema::isVisible() instead.
789 bool isUnconditionallyVisible() const {
790 return (int)getModuleOwnershipKind() <= (int)ModuleOwnershipKind::Visible;
791 }
792
793 /// Set that this declaration is globally visible, even if it came from a
794 /// module that is not visible.
795 void setVisibleDespiteOwningModule() {
796 if (!isUnconditionallyVisible())
797 setModuleOwnershipKind(ModuleOwnershipKind::Visible);
798 }
799
800 /// Get the kind of module ownership for this declaration.
801 ModuleOwnershipKind getModuleOwnershipKind() const {
802 return NextInContextAndBits.getInt();
803 }
804
805 /// Set whether this declaration is hidden from name lookup.
806 void setModuleOwnershipKind(ModuleOwnershipKind MOK) {
807 assert(!(getModuleOwnershipKind() == ModuleOwnershipKind::Unowned &&(static_cast<void> (0))
808 MOK != ModuleOwnershipKind::Unowned && !isFromASTFile() &&(static_cast<void> (0))
809 !hasLocalOwningModuleStorage()) &&(static_cast<void> (0))
810 "no storage available for owning module for this declaration")(static_cast<void> (0));
811 NextInContextAndBits.setInt(MOK);
812 }
813
814 unsigned getIdentifierNamespace() const {
815 return IdentifierNamespace;
816 }
817
818 bool isInIdentifierNamespace(unsigned NS) const {
819 return getIdentifierNamespace() & NS;
820 }
821
822 static unsigned getIdentifierNamespaceForKind(Kind DK);
823
824 bool hasTagIdentifierNamespace() const {
825 return isTagIdentifierNamespace(getIdentifierNamespace());
826 }
827
828 static bool isTagIdentifierNamespace(unsigned NS) {
829 // TagDecls have Tag and Type set and may also have TagFriend.
830 return (NS & ~IDNS_TagFriend) == (IDNS_Tag | IDNS_Type);
831 }
832
833 /// getLexicalDeclContext - The declaration context where this Decl was
834 /// lexically declared (LexicalDC). May be different from
835 /// getDeclContext() (SemanticDC).
836 /// e.g.:
837 ///
838 /// namespace A {
839 /// void f(); // SemanticDC == LexicalDC == 'namespace A'
840 /// }
841 /// void A::f(); // SemanticDC == namespace 'A'
842 /// // LexicalDC == global namespace
843 DeclContext *getLexicalDeclContext() {
844 if (isInSemaDC())
845 return getSemanticDC();
846 return getMultipleDC()->LexicalDC;
847 }
848 const DeclContext *getLexicalDeclContext() const {
849 return const_cast<Decl*>(this)->getLexicalDeclContext();
850 }
851
852 /// Determine whether this declaration is declared out of line (outside its
853 /// semantic context).
854 virtual bool isOutOfLine() const;
855
856 /// setDeclContext - Set both the semantic and lexical DeclContext
857 /// to DC.
858 void setDeclContext(DeclContext *DC);
859
860 void setLexicalDeclContext(DeclContext *DC);
861
862 /// Determine whether this declaration is a templated entity (whether it is
863 // within the scope of a template parameter).
864 bool isTemplated() const;
865
866 /// Determine the number of levels of template parameter surrounding this
867 /// declaration.
868 unsigned getTemplateDepth() const;
869
870 /// isDefinedOutsideFunctionOrMethod - This predicate returns true if this
871 /// scoped decl is defined outside the current function or method. This is
872 /// roughly global variables and functions, but also handles enums (which
873 /// could be defined inside or outside a function etc).
874 bool isDefinedOutsideFunctionOrMethod() const {
875 return getParentFunctionOrMethod() == nullptr;
876 }
877
878 /// Determine whether a substitution into this declaration would occur as
879 /// part of a substitution into a dependent local scope. Such a substitution
880 /// transitively substitutes into all constructs nested within this
881 /// declaration.
882 ///
883 /// This recognizes non-defining declarations as well as members of local
884 /// classes and lambdas:
885 /// \code
886 /// template<typename T> void foo() { void bar(); }
887 /// template<typename T> void foo2() { class ABC { void bar(); }; }
888 /// template<typename T> inline int x = [](){ return 0; }();
889 /// \endcode
890 bool isInLocalScopeForInstantiation() const;
891
892 /// If this decl is defined inside a function/method/block it returns
893 /// the corresponding DeclContext, otherwise it returns null.
894 const DeclContext *getParentFunctionOrMethod() const;
895 DeclContext *getParentFunctionOrMethod() {
896 return const_cast<DeclContext*>(
897 const_cast<const Decl*>(this)->getParentFunctionOrMethod());
898 }
899
900 /// Retrieves the "canonical" declaration of the given declaration.
901 virtual Decl *getCanonicalDecl() { return this; }
902 const Decl *getCanonicalDecl() const {
903 return const_cast<Decl*>(this)->getCanonicalDecl();
904 }
905
906 /// Whether this particular Decl is a canonical one.
907 bool isCanonicalDecl() const { return getCanonicalDecl() == this; }
908
909protected:
910 /// Returns the next redeclaration or itself if this is the only decl.
911 ///
912 /// Decl subclasses that can be redeclared should override this method so that
913 /// Decl::redecl_iterator can iterate over them.
914 virtual Decl *getNextRedeclarationImpl() { return this; }
915
916 /// Implementation of getPreviousDecl(), to be overridden by any
917 /// subclass that has a redeclaration chain.
918 virtual Decl *getPreviousDeclImpl() { return nullptr; }
919
920 /// Implementation of getMostRecentDecl(), to be overridden by any
921 /// subclass that has a redeclaration chain.
922 virtual Decl *getMostRecentDeclImpl() { return this; }
923
924public:
925 /// Iterates through all the redeclarations of the same decl.
926 class redecl_iterator {
927 /// Current - The current declaration.
928 Decl *Current = nullptr;
929 Decl *Starter;
930
931 public:
932 using value_type = Decl *;
933 using reference = const value_type &;
934 using pointer = const value_type *;
935 using iterator_category = std::forward_iterator_tag;
936 using difference_type = std::ptrdiff_t;
937
938 redecl_iterator() = default;
939 explicit redecl_iterator(Decl *C) : Current(C), Starter(C) {}
940
941 reference operator*() const { return Current; }
942 value_type operator->() const { return Current; }
943
944 redecl_iterator& operator++() {
945 assert(Current && "Advancing while iterator has reached end")(static_cast<void> (0));
946 // Get either previous decl or latest decl.
947 Decl *Next = Current->getNextRedeclarationImpl();
948 assert(Next && "Should return next redeclaration or itself, never null!")(static_cast<void> (0));
949 Current = (Next != Starter) ? Next : nullptr;
950 return *this;
951 }
952
953 redecl_iterator operator++(int) {
954 redecl_iterator tmp(*this);
955 ++(*this);
956 return tmp;
957 }
958
959 friend bool operator==(redecl_iterator x, redecl_iterator y) {
960 return x.Current == y.Current;
961 }
962
963 friend bool operator!=(redecl_iterator x, redecl_iterator y) {
964 return x.Current != y.Current;
965 }
966 };
967
968 using redecl_range = llvm::iterator_range<redecl_iterator>;
969
970 /// Returns an iterator range for all the redeclarations of the same
971 /// decl. It will iterate at least once (when this decl is the only one).
972 redecl_range redecls() const {
973 return redecl_range(redecls_begin(), redecls_end());
974 }
975
976 redecl_iterator redecls_begin() const {
977 return redecl_iterator(const_cast<Decl *>(this));
978 }
979
980 redecl_iterator redecls_end() const { return redecl_iterator(); }
981
982 /// Retrieve the previous declaration that declares the same entity
983 /// as this declaration, or NULL if there is no previous declaration.
984 Decl *getPreviousDecl() { return getPreviousDeclImpl(); }
985
986 /// Retrieve the previous declaration that declares the same entity
987 /// as this declaration, or NULL if there is no previous declaration.
988 const Decl *getPreviousDecl() const {
989 return const_cast<Decl *>(this)->getPreviousDeclImpl();
990 }
991
992 /// True if this is the first declaration in its redeclaration chain.
993 bool isFirstDecl() const {
994 return getPreviousDecl() == nullptr;
995 }
996
997 /// Retrieve the most recent declaration that declares the same entity
998 /// as this declaration (which may be this declaration).
999 Decl *getMostRecentDecl() { return getMostRecentDeclImpl(); }
1000
1001 /// Retrieve the most recent declaration that declares the same entity
1002 /// as this declaration (which may be this declaration).
1003 const Decl *getMostRecentDecl() const {
1004 return const_cast<Decl *>(this)->getMostRecentDeclImpl();
1005 }
1006
1007 /// getBody - If this Decl represents a declaration for a body of code,
1008 /// such as a function or method definition, this method returns the
1009 /// top-level Stmt* of that body. Otherwise this method returns null.
1010 virtual Stmt* getBody() const { return nullptr; }
1011
1012 /// Returns true if this \c Decl represents a declaration for a body of
1013 /// code, such as a function or method definition.
1014 /// Note that \c hasBody can also return true if any redeclaration of this
1015 /// \c Decl represents a declaration for a body of code.
1016 virtual bool hasBody() const { return getBody() != nullptr; }
1017
1018 /// getBodyRBrace - Gets the right brace of the body, if a body exists.
1019 /// This works whether the body is a CompoundStmt or a CXXTryStmt.
1020 SourceLocation getBodyRBrace() const;
1021
1022 // global temp stats (until we have a per-module visitor)
1023 static void add(Kind k);
1024 static void EnableStatistics();
1025 static void PrintStats();
1026
1027 /// isTemplateParameter - Determines whether this declaration is a
1028 /// template parameter.
1029 bool isTemplateParameter() const;
1030
1031 /// isTemplateParameter - Determines whether this declaration is a
1032 /// template parameter pack.
1033 bool isTemplateParameterPack() const;
1034
1035 /// Whether this declaration is a parameter pack.
1036 bool isParameterPack() const;
1037
1038 /// returns true if this declaration is a template
1039 bool isTemplateDecl() const;
1040
1041 /// Whether this declaration is a function or function template.
1042 bool isFunctionOrFunctionTemplate() const {
1043 return (DeclKind >= Decl::firstFunction &&
1044 DeclKind <= Decl::lastFunction) ||
1045 DeclKind == FunctionTemplate;
1046 }
1047
1048 /// If this is a declaration that describes some template, this
1049 /// method returns that template declaration.
1050 ///
1051 /// Note that this returns nullptr for partial specializations, because they
1052 /// are not modeled as TemplateDecls. Use getDescribedTemplateParams to handle
1053 /// those cases.
1054 TemplateDecl *getDescribedTemplate() const;
1055
1056 /// If this is a declaration that describes some template or partial
1057 /// specialization, this returns the corresponding template parameter list.
1058 const TemplateParameterList *getDescribedTemplateParams() const;
1059
1060 /// Returns the function itself, or the templated function if this is a
1061 /// function template.
1062 FunctionDecl *getAsFunction() LLVM_READONLY__attribute__((__pure__));
1063
1064 const FunctionDecl *getAsFunction() const {
1065 return const_cast<Decl *>(this)->getAsFunction();
1066 }
1067
1068 /// Changes the namespace of this declaration to reflect that it's
1069 /// a function-local extern declaration.
1070 ///
1071 /// These declarations appear in the lexical context of the extern
1072 /// declaration, but in the semantic context of the enclosing namespace
1073 /// scope.
1074 void setLocalExternDecl() {
1075 Decl *Prev = getPreviousDecl();
1076 IdentifierNamespace &= ~IDNS_Ordinary;
1077
1078 // It's OK for the declaration to still have the "invisible friend" flag or
1079 // the "conflicts with tag declarations in this scope" flag for the outer
1080 // scope.
1081 assert((IdentifierNamespace & ~(IDNS_OrdinaryFriend | IDNS_Tag)) == 0 &&(static_cast<void> (0))
1082 "namespace is not ordinary")(static_cast<void> (0));
1083
1084 IdentifierNamespace |= IDNS_LocalExtern;
1085 if (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary)
1086 IdentifierNamespace |= IDNS_Ordinary;
1087 }
1088
1089 /// Determine whether this is a block-scope declaration with linkage.
1090 /// This will either be a local variable declaration declared 'extern', or a
1091 /// local function declaration.
1092 bool isLocalExternDecl() {
1093 return IdentifierNamespace & IDNS_LocalExtern;
1094 }
1095
1096 /// Changes the namespace of this declaration to reflect that it's
1097 /// the object of a friend declaration.
1098 ///
1099 /// These declarations appear in the lexical context of the friending
1100 /// class, but in the semantic context of the actual entity. This property
1101 /// applies only to a specific decl object; other redeclarations of the
1102 /// same entity may not (and probably don't) share this property.
1103 void setObjectOfFriendDecl(bool PerformFriendInjection = false) {
1104 unsigned OldNS = IdentifierNamespace;
1105 assert((OldNS & (IDNS_Tag | IDNS_Ordinary |(static_cast<void> (0))
1106 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast<void> (0))
1107 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast<void> (0))
1108 "namespace includes neither ordinary nor tag")(static_cast<void> (0));
1109 assert(!(OldNS & ~(IDNS_Tag | IDNS_Ordinary | IDNS_Type |(static_cast<void> (0))
1110 IDNS_TagFriend | IDNS_OrdinaryFriend |(static_cast<void> (0))
1111 IDNS_LocalExtern | IDNS_NonMemberOperator)) &&(static_cast<void> (0))
1112 "namespace includes other than ordinary or tag")(static_cast<void> (0));
1113
1114 Decl *Prev = getPreviousDecl();
1115 IdentifierNamespace &= ~(IDNS_Ordinary | IDNS_Tag | IDNS_Type);
1116
1117 if (OldNS & (IDNS_Tag | IDNS_TagFriend)) {
1118 IdentifierNamespace |= IDNS_TagFriend;
1119 if (PerformFriendInjection ||
1120 (Prev && Prev->getIdentifierNamespace() & IDNS_Tag))
1121 IdentifierNamespace |= IDNS_Tag | IDNS_Type;
1122 }
1123
1124 if (OldNS & (IDNS_Ordinary | IDNS_OrdinaryFriend |
1125 IDNS_LocalExtern | IDNS_NonMemberOperator)) {
1126 IdentifierNamespace |= IDNS_OrdinaryFriend;
1127 if (PerformFriendInjection ||
1128 (Prev && Prev->getIdentifierNamespace() & IDNS_Ordinary))
1129 IdentifierNamespace |= IDNS_Ordinary;
1130 }
1131 }
1132
1133 enum FriendObjectKind {
1134 FOK_None, ///< Not a friend object.
1135 FOK_Declared, ///< A friend of a previously-declared entity.
1136 FOK_Undeclared ///< A friend of a previously-undeclared entity.
1137 };
1138
1139 /// Determines whether this declaration is the object of a
1140 /// friend declaration and, if so, what kind.
1141 ///
1142 /// There is currently no direct way to find the associated FriendDecl.
1143 FriendObjectKind getFriendObjectKind() const {
1144 unsigned mask =
1145 (IdentifierNamespace & (IDNS_TagFriend | IDNS_OrdinaryFriend));
1146 if (!mask) return FOK_None;
1147 return (IdentifierNamespace & (IDNS_Tag | IDNS_Ordinary) ? FOK_Declared
1148 : FOK_Undeclared);
1149 }
1150
1151 /// Specifies that this declaration is a C++ overloaded non-member.
1152 void setNonMemberOperator() {
1153 assert(getKind() == Function || getKind() == FunctionTemplate)(static_cast<void> (0));
1154 assert((IdentifierNamespace & IDNS_Ordinary) &&(static_cast<void> (0))
1155 "visible non-member operators should be in ordinary namespace")(static_cast<void> (0));
1156 IdentifierNamespace |= IDNS_NonMemberOperator;
1157 }
1158
1159 static bool classofKind(Kind K) { return true; }
1160 static DeclContext *castToDeclContext(const Decl *);
1161 static Decl *castFromDeclContext(const DeclContext *);
1162
1163 void print(raw_ostream &Out, unsigned Indentation = 0,
1164 bool PrintInstantiation = false) const;
1165 void print(raw_ostream &Out, const PrintingPolicy &Policy,
1166 unsigned Indentation = 0, bool PrintInstantiation = false) const;
1167 static void printGroup(Decl** Begin, unsigned NumDecls,
1168 raw_ostream &Out, const PrintingPolicy &Policy,
1169 unsigned Indentation = 0);
1170
1171 // Debuggers don't usually respect default arguments.
1172 void dump() const;
1173
1174 // Same as dump(), but forces color printing.
1175 void dumpColor() const;
1176
1177 void dump(raw_ostream &Out, bool Deserialize = false,
1178 ASTDumpOutputFormat OutputFormat = ADOF_Default) const;
1179
1180 /// \return Unique reproducible object identifier
1181 int64_t getID() const;
1182
1183 /// Looks through the Decl's underlying type to extract a FunctionType
1184 /// when possible. Will return null if the type underlying the Decl does not
1185 /// have a FunctionType.
1186 const FunctionType *getFunctionType(bool BlocksToo = true) const;
1187
1188private:
1189 void setAttrsImpl(const AttrVec& Attrs, ASTContext &Ctx);
1190 void setDeclContextsImpl(DeclContext *SemaDC, DeclContext *LexicalDC,
1191 ASTContext &Ctx);
1192
1193protected:
1194 ASTMutationListener *getASTMutationListener() const;
1195};
1196
1197/// Determine whether two declarations declare the same entity.
1198inline bool declaresSameEntity(const Decl *D1, const Decl *D2) {
1199 if (!D1 || !D2)
1200 return false;
1201
1202 if (D1 == D2)
1203 return true;
1204
1205 return D1->getCanonicalDecl() == D2->getCanonicalDecl();
1206}
1207
1208/// PrettyStackTraceDecl - If a crash occurs, indicate that it happened when
1209/// doing something to a specific decl.
1210class PrettyStackTraceDecl : public llvm::PrettyStackTraceEntry {
1211 const Decl *TheDecl;
1212 SourceLocation Loc;
1213 SourceManager &SM;
1214 const char *Message;
1215
1216public:
1217 PrettyStackTraceDecl(const Decl *theDecl, SourceLocation L,
1218 SourceManager &sm, const char *Msg)
1219 : TheDecl(theDecl), Loc(L), SM(sm), Message(Msg) {}
1220
1221 void print(raw_ostream &OS) const override;
1222};
1223} // namespace clang
1224
1225// Required to determine the layout of the PointerUnion<NamedDecl*> before
1226// seeing the NamedDecl definition being first used in DeclListNode::operator*.
1227namespace llvm {
1228 template <> struct PointerLikeTypeTraits<::clang::NamedDecl *> {
1229 static inline void *getAsVoidPointer(::clang::NamedDecl *P) { return P; }
1230 static inline ::clang::NamedDecl *getFromVoidPointer(void *P) {
1231 return static_cast<::clang::NamedDecl *>(P);
1232 }
1233 static constexpr int NumLowBitsAvailable = 3;
1234 };
1235}
1236
1237namespace clang {
1238/// A list storing NamedDecls in the lookup tables.
1239class DeclListNode {
1240 friend class ASTContext; // allocate, deallocate nodes.
1241 friend class StoredDeclsList;
1242public:
1243 using Decls = llvm::PointerUnion<NamedDecl*, DeclListNode*>;
1244 class iterator {
1245 friend class DeclContextLookupResult;
1246 friend class StoredDeclsList;
1247
1248 Decls Ptr;
1249 iterator(Decls Node) : Ptr(Node) { }
1250 public:
1251 using difference_type = ptrdiff_t;
1252 using value_type = NamedDecl*;
1253 using pointer = void;
1254 using reference = value_type;
1255 using iterator_category = std::forward_iterator_tag;
1256
1257 iterator() = default;
1258
1259 reference operator*() const {
1260 assert(Ptr && "dereferencing end() iterator")(static_cast<void> (0));
1261 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1262 return CurNode->D;
1263 return Ptr.get<NamedDecl*>();
1264 }
1265 void operator->() const { } // Unsupported.
1266 bool operator==(const iterator &X) const { return Ptr == X.Ptr; }
1267 bool operator!=(const iterator &X) const { return Ptr != X.Ptr; }
1268 inline iterator &operator++() { // ++It
1269 assert(!Ptr.isNull() && "Advancing empty iterator")(static_cast<void> (0));
1270
1271 if (DeclListNode *CurNode = Ptr.dyn_cast<DeclListNode*>())
1272 Ptr = CurNode->Rest;
1273 else
1274 Ptr = nullptr;
1275 return *this;
1276 }
1277 iterator operator++(int) { // It++
1278 iterator temp = *this;
1279 ++(*this);
1280 return temp;
1281 }
1282 // Enables the pattern for (iterator I =..., E = I.end(); I != E; ++I)
1283 iterator end() { return iterator(); }
1284 };
1285private:
1286 NamedDecl *D = nullptr;
1287 Decls Rest = nullptr;
1288 DeclListNode(NamedDecl *ND) : D(ND) {}
1289};
1290
1291/// The results of name lookup within a DeclContext.
1292class DeclContextLookupResult {
1293 using Decls = DeclListNode::Decls;
1294
1295 /// When in collection form, this is what the Data pointer points to.
1296 Decls Result;
1297
1298public:
1299 DeclContextLookupResult() = default;
1300 DeclContextLookupResult(Decls Result) : Result(Result) {}
1301
1302 using iterator = DeclListNode::iterator;
1303 using const_iterator = iterator;
1304 using reference = iterator::reference;
1305
1306 iterator begin() { return iterator(Result); }
1307 iterator end() { return iterator(); }
1308 const_iterator begin() const {
1309 return const_cast<DeclContextLookupResult*>(this)->begin();
1310 }
1311 const_iterator end() const { return iterator(); }
1312
1313 bool empty() const { return Result.isNull(); }
1314 bool isSingleResult() const { return Result.dyn_cast<NamedDecl*>(); }
1315 reference front() const { return *begin(); }
1316
1317 // Find the first declaration of the given type in the list. Note that this
1318 // is not in general the earliest-declared declaration, and should only be
1319 // used when it's not possible for there to be more than one match or where
1320 // it doesn't matter which one is found.
1321 template<class T> T *find_first() const {
1322 for (auto *D : *this)
1323 if (T *Decl = dyn_cast<T>(D))
1324 return Decl;
1325
1326 return nullptr;
1327 }
1328};
1329
1330/// DeclContext - This is used only as base class of specific decl types that
1331/// can act as declaration contexts. These decls are (only the top classes
1332/// that directly derive from DeclContext are mentioned, not their subclasses):
1333///
1334/// TranslationUnitDecl
1335/// ExternCContext
1336/// NamespaceDecl
1337/// TagDecl
1338/// OMPDeclareReductionDecl
1339/// OMPDeclareMapperDecl
1340/// FunctionDecl
1341/// ObjCMethodDecl
1342/// ObjCContainerDecl
1343/// LinkageSpecDecl
1344/// ExportDecl
1345/// BlockDecl
1346/// CapturedDecl
1347class DeclContext {
1348 /// For makeDeclVisibleInContextImpl
1349 friend class ASTDeclReader;
1350 /// For reconcileExternalVisibleStorage, CreateStoredDeclsMap,
1351 /// hasNeedToReconcileExternalVisibleStorage
1352 friend class ExternalASTSource;
1353 /// For CreateStoredDeclsMap
1354 friend class DependentDiagnostic;
1355 /// For hasNeedToReconcileExternalVisibleStorage,
1356 /// hasLazyLocalLexicalLookups, hasLazyExternalLexicalLookups
1357 friend class ASTWriter;
1358
1359 // We use uint64_t in the bit-fields below since some bit-fields
1360 // cross the unsigned boundary and this breaks the packing.
1361
1362 /// Stores the bits used by DeclContext.
1363 /// If modified NumDeclContextBit, the ctor of DeclContext and the accessor
1364 /// methods in DeclContext should be updated appropriately.
1365 class DeclContextBitfields {
1366 friend class DeclContext;
1367 /// DeclKind - This indicates which class this is.
1368 uint64_t DeclKind : 7;
1369
1370 /// Whether this declaration context also has some external
1371 /// storage that contains additional declarations that are lexically
1372 /// part of this context.
1373 mutable uint64_t ExternalLexicalStorage : 1;
1374
1375 /// Whether this declaration context also has some external
1376 /// storage that contains additional declarations that are visible
1377 /// in this context.
1378 mutable uint64_t ExternalVisibleStorage : 1;
1379
1380 /// Whether this declaration context has had externally visible
1381 /// storage added since the last lookup. In this case, \c LookupPtr's
1382 /// invariant may not hold and needs to be fixed before we perform
1383 /// another lookup.
1384 mutable uint64_t NeedToReconcileExternalVisibleStorage : 1;
1385
1386 /// If \c true, this context may have local lexical declarations
1387 /// that are missing from the lookup table.
1388 mutable uint64_t HasLazyLocalLexicalLookups : 1;
1389
1390 /// If \c true, the external source may have lexical declarations
1391 /// that are missing from the lookup table.
1392 mutable uint64_t HasLazyExternalLexicalLookups : 1;
1393
1394 /// If \c true, lookups should only return identifier from
1395 /// DeclContext scope (for example TranslationUnit). Used in
1396 /// LookupQualifiedName()
1397 mutable uint64_t UseQualifiedLookup : 1;
1398 };
1399
1400 /// Number of bits in DeclContextBitfields.
1401 enum { NumDeclContextBits = 13 };
1402
1403 /// Stores the bits used by TagDecl.
1404 /// If modified NumTagDeclBits and the accessor
1405 /// methods in TagDecl should be updated appropriately.
1406 class TagDeclBitfields {
1407 friend class TagDecl;
1408 /// For the bits in DeclContextBitfields
1409 uint64_t : NumDeclContextBits;
1410
1411 /// The TagKind enum.
1412 uint64_t TagDeclKind : 3;
1413
1414 /// True if this is a definition ("struct foo {};"), false if it is a
1415 /// declaration ("struct foo;"). It is not considered a definition
1416 /// until the definition has been fully processed.
1417 uint64_t IsCompleteDefinition : 1;
1418
1419 /// True if this is currently being defined.
1420 uint64_t IsBeingDefined : 1;
1421
1422 /// True if this tag declaration is "embedded" (i.e., defined or declared
1423 /// for the very first time) in the syntax of a declarator.
1424 uint64_t IsEmbeddedInDeclarator : 1;
1425
1426 /// True if this tag is free standing, e.g. "struct foo;".
1427 uint64_t IsFreeStanding : 1;
1428
1429 /// Indicates whether it is possible for declarations of this kind
1430 /// to have an out-of-date definition.
1431 ///
1432 /// This option is only enabled when modules are enabled.
1433 uint64_t MayHaveOutOfDateDef : 1;
1434
1435 /// Has the full definition of this type been required by a use somewhere in
1436 /// the TU.
1437 uint64_t IsCompleteDefinitionRequired : 1;
1438 };
1439
1440 /// Number of non-inherited bits in TagDeclBitfields.
1441 enum { NumTagDeclBits = 9 };
1442
1443 /// Stores the bits used by EnumDecl.
1444 /// If modified NumEnumDeclBit and the accessor
1445 /// methods in EnumDecl should be updated appropriately.
1446 class EnumDeclBitfields {
1447 friend class EnumDecl;
1448 /// For the bits in DeclContextBitfields.
1449 uint64_t : NumDeclContextBits;
1450 /// For the bits in TagDeclBitfields.
1451 uint64_t : NumTagDeclBits;
1452
1453 /// Width in bits required to store all the non-negative
1454 /// enumerators of this enum.
1455 uint64_t NumPositiveBits : 8;
1456
1457 /// Width in bits required to store all the negative
1458 /// enumerators of this enum.
1459 uint64_t NumNegativeBits : 8;
1460
1461 /// True if this tag declaration is a scoped enumeration. Only
1462 /// possible in C++11 mode.
1463 uint64_t IsScoped : 1;
1464
1465 /// If this tag declaration is a scoped enum,
1466 /// then this is true if the scoped enum was declared using the class
1467 /// tag, false if it was declared with the struct tag. No meaning is
1468 /// associated if this tag declaration is not a scoped enum.
1469 uint64_t IsScopedUsingClassTag : 1;
1470
1471 /// True if this is an enumeration with fixed underlying type. Only
1472 /// possible in C++11, Microsoft extensions, or Objective C mode.
1473 uint64_t IsFixed : 1;
1474
1475 /// True if a valid hash is stored in ODRHash.
1476 uint64_t HasODRHash : 1;
1477 };
1478
1479 /// Number of non-inherited bits in EnumDeclBitfields.
1480 enum { NumEnumDeclBits = 20 };
1481
1482 /// Stores the bits used by RecordDecl.
1483 /// If modified NumRecordDeclBits and the accessor
1484 /// methods in RecordDecl should be updated appropriately.
1485 class RecordDeclBitfields {
1486 friend class RecordDecl;
1487 /// For the bits in DeclContextBitfields.
1488 uint64_t : NumDeclContextBits;
1489 /// For the bits in TagDeclBitfields.
1490 uint64_t : NumTagDeclBits;
1491
1492 /// This is true if this struct ends with a flexible
1493 /// array member (e.g. int X[]) or if this union contains a struct that does.
1494 /// If so, this cannot be contained in arrays or other structs as a member.
1495 uint64_t HasFlexibleArrayMember : 1;
1496
1497 /// Whether this is the type of an anonymous struct or union.
1498 uint64_t AnonymousStructOrUnion : 1;
1499
1500 /// This is true if this struct has at least one member
1501 /// containing an Objective-C object pointer type.
1502 uint64_t HasObjectMember : 1;
1503
1504 /// This is true if struct has at least one member of
1505 /// 'volatile' type.
1506 uint64_t HasVolatileMember : 1;
1507
1508 /// Whether the field declarations of this record have been loaded
1509 /// from external storage. To avoid unnecessary deserialization of
1510 /// methods/nested types we allow deserialization of just the fields
1511 /// when needed.
1512 mutable uint64_t LoadedFieldsFromExternalStorage : 1;
1513
1514 /// Basic properties of non-trivial C structs.
1515 uint64_t NonTrivialToPrimitiveDefaultInitialize : 1;
1516 uint64_t NonTrivialToPrimitiveCopy : 1;
1517 uint64_t NonTrivialToPrimitiveDestroy : 1;
1518
1519 /// The following bits indicate whether this is or contains a C union that
1520 /// is non-trivial to default-initialize, destruct, or copy. These bits
1521 /// imply the associated basic non-triviality predicates declared above.
1522 uint64_t HasNonTrivialToPrimitiveDefaultInitializeCUnion : 1;
1523 uint64_t HasNonTrivialToPrimitiveDestructCUnion : 1;
1524 uint64_t HasNonTrivialToPrimitiveCopyCUnion : 1;
1525
1526 /// Indicates whether this struct is destroyed in the callee.
1527 uint64_t ParamDestroyedInCallee : 1;
1528
1529 /// Represents the way this type is passed to a function.
1530 uint64_t ArgPassingRestrictions : 2;
1531 };
1532
1533 /// Number of non-inherited bits in RecordDeclBitfields.
1534 enum { NumRecordDeclBits = 14 };
1535
1536 /// Stores the bits used by OMPDeclareReductionDecl.
1537 /// If modified NumOMPDeclareReductionDeclBits and the accessor
1538 /// methods in OMPDeclareReductionDecl should be updated appropriately.
1539 class OMPDeclareReductionDeclBitfields {
1540 friend class OMPDeclareReductionDecl;
1541 /// For the bits in DeclContextBitfields
1542 uint64_t : NumDeclContextBits;
1543
1544 /// Kind of initializer,
1545 /// function call or omp_priv<init_expr> initializtion.
1546 uint64_t InitializerKind : 2;
1547 };
1548
1549 /// Number of non-inherited bits in OMPDeclareReductionDeclBitfields.
1550 enum { NumOMPDeclareReductionDeclBits = 2 };
1551
1552 /// Stores the bits used by FunctionDecl.
1553 /// If modified NumFunctionDeclBits and the accessor
1554 /// methods in FunctionDecl and CXXDeductionGuideDecl
1555 /// (for IsCopyDeductionCandidate) should be updated appropriately.
1556 class FunctionDeclBitfields {
1557 friend class FunctionDecl;
1558 /// For IsCopyDeductionCandidate
1559 friend class CXXDeductionGuideDecl;
1560 /// For the bits in DeclContextBitfields.
1561 uint64_t : NumDeclContextBits;
1562
1563 uint64_t SClass : 3;
1564 uint64_t IsInline : 1;
1565 uint64_t IsInlineSpecified : 1;
1566
1567 uint64_t IsVirtualAsWritten : 1;
1568 uint64_t IsPure : 1;
1569 uint64_t HasInheritedPrototype : 1;
1570 uint64_t HasWrittenPrototype : 1;
1571 uint64_t IsDeleted : 1;
1572 /// Used by CXXMethodDecl
1573 uint64_t IsTrivial : 1;
1574
1575 /// This flag indicates whether this function is trivial for the purpose of
1576 /// calls. This is meaningful only when this function is a copy/move
1577 /// constructor or a destructor.
1578 uint64_t IsTrivialForCall : 1;
1579
1580 uint64_t IsDefaulted : 1;
1581 uint64_t IsExplicitlyDefaulted : 1;
1582 uint64_t HasDefaultedFunctionInfo : 1;
1583 uint64_t HasImplicitReturnZero : 1;
1584 uint64_t IsLateTemplateParsed : 1;
1585
1586 /// Kind of contexpr specifier as defined by ConstexprSpecKind.
1587 uint64_t ConstexprKind : 2;
1588 uint64_t InstantiationIsPending : 1;
1589
1590 /// Indicates if the function uses __try.
1591 uint64_t UsesSEHTry : 1;
1592
1593 /// Indicates if the function was a definition
1594 /// but its body was skipped.
1595 uint64_t HasSkippedBody : 1;
1596
1597 /// Indicates if the function declaration will
1598 /// have a body, once we're done parsing it.
1599 uint64_t WillHaveBody : 1;
1600
1601 /// Indicates that this function is a multiversioned
1602 /// function using attribute 'target'.
1603 uint64_t IsMultiVersion : 1;
1604
1605 /// [C++17] Only used by CXXDeductionGuideDecl. Indicates that
1606 /// the Deduction Guide is the implicitly generated 'copy
1607 /// deduction candidate' (is used during overload resolution).
1608 uint64_t IsCopyDeductionCandidate : 1;
1609
1610 /// Store the ODRHash after first calculation.
1611 uint64_t HasODRHash : 1;
1612
1613 /// Indicates if the function uses Floating Point Constrained Intrinsics
1614 uint64_t UsesFPIntrin : 1;
1615 };
1616
1617 /// Number of non-inherited bits in FunctionDeclBitfields.
1618 enum { NumFunctionDeclBits = 27 };
1619
1620 /// Stores the bits used by CXXConstructorDecl. If modified
1621 /// NumCXXConstructorDeclBits and the accessor
1622 /// methods in CXXConstructorDecl should be updated appropriately.
1623 class CXXConstructorDeclBitfields {
1624 friend class CXXConstructorDecl;
1625 /// For the bits in DeclContextBitfields.
1626 uint64_t : NumDeclContextBits;
1627 /// For the bits in FunctionDeclBitfields.
1628 uint64_t : NumFunctionDeclBits;
1629
1630 /// 24 bits to fit in the remaining available space.
1631 /// Note that this makes CXXConstructorDeclBitfields take
1632 /// exactly 64 bits and thus the width of NumCtorInitializers
1633 /// will need to be shrunk if some bit is added to NumDeclContextBitfields,
1634 /// NumFunctionDeclBitfields or CXXConstructorDeclBitfields.
1635 uint64_t NumCtorInitializers : 21;
1636 uint64_t IsInheritingConstructor : 1;
1637
1638 /// Whether this constructor has a trail-allocated explicit specifier.
1639 uint64_t HasTrailingExplicitSpecifier : 1;
1640 /// If this constructor does't have a trail-allocated explicit specifier.
1641 /// Whether this constructor is explicit specified.
1642 uint64_t IsSimpleExplicit : 1;
1643 };
1644
1645 /// Number of non-inherited bits in CXXConstructorDeclBitfields.
1646 enum {
1647 NumCXXConstructorDeclBits = 64 - NumDeclContextBits - NumFunctionDeclBits
1648 };
1649
1650 /// Stores the bits used by ObjCMethodDecl.
1651 /// If modified NumObjCMethodDeclBits and the accessor
1652 /// methods in ObjCMethodDecl should be updated appropriately.
1653 class ObjCMethodDeclBitfields {
1654 friend class ObjCMethodDecl;
1655
1656 /// For the bits in DeclContextBitfields.
1657 uint64_t : NumDeclContextBits;
1658
1659 /// The conventional meaning of this method; an ObjCMethodFamily.
1660 /// This is not serialized; instead, it is computed on demand and
1661 /// cached.
1662 mutable uint64_t Family : ObjCMethodFamilyBitWidth;
1663
1664 /// instance (true) or class (false) method.
1665 uint64_t IsInstance : 1;
1666 uint64_t IsVariadic : 1;
1667
1668 /// True if this method is the getter or setter for an explicit property.
1669 uint64_t IsPropertyAccessor : 1;
1670
1671 /// True if this method is a synthesized property accessor stub.
1672 uint64_t IsSynthesizedAccessorStub : 1;
1673
1674 /// Method has a definition.
1675 uint64_t IsDefined : 1;
1676
1677 /// Method redeclaration in the same interface.
1678 uint64_t IsRedeclaration : 1;
1679
1680 /// Is redeclared in the same interface.
1681 mutable uint64_t HasRedeclaration : 1;
1682
1683 /// \@required/\@optional
1684 uint64_t DeclImplementation : 2;
1685
1686 /// in, inout, etc.
1687 uint64_t objcDeclQualifier : 7;
1688
1689 /// Indicates whether this method has a related result type.
1690 uint64_t RelatedResultType : 1;
1691
1692 /// Whether the locations of the selector identifiers are in a
1693 /// "standard" position, a enum SelectorLocationsKind.
1694 uint64_t SelLocsKind : 2;
1695
1696 /// Whether this method overrides any other in the class hierarchy.
1697 ///
1698 /// A method is said to override any method in the class's
1699 /// base classes, its protocols, or its categories' protocols, that has
1700 /// the same selector and is of the same kind (class or instance).
1701 /// A method in an implementation is not considered as overriding the same
1702 /// method in the interface or its categories.
1703 uint64_t IsOverriding : 1;
1704
1705 /// Indicates if the method was a definition but its body was skipped.
1706 uint64_t HasSkippedBody : 1;
1707 };
1708
1709 /// Number of non-inherited bits in ObjCMethodDeclBitfields.
1710 enum { NumObjCMethodDeclBits = 24 };
1711
1712 /// Stores the bits used by ObjCContainerDecl.
1713 /// If modified NumObjCContainerDeclBits and the accessor
1714 /// methods in ObjCContainerDecl should be updated appropriately.
1715 class ObjCContainerDeclBitfields {
1716 friend class ObjCContainerDecl;
1717 /// For the bits in DeclContextBitfields
1718 uint32_t : NumDeclContextBits;
1719
1720 // Not a bitfield but this saves space.
1721 // Note that ObjCContainerDeclBitfields is full.
1722 SourceLocation AtStart;
1723 };
1724
1725 /// Number of non-inherited bits in ObjCContainerDeclBitfields.
1726 /// Note that here we rely on the fact that SourceLocation is 32 bits
1727 /// wide. We check this with the static_assert in the ctor of DeclContext.
1728 enum { NumObjCContainerDeclBits = 64 - NumDeclContextBits };
1729
1730 /// Stores the bits used by LinkageSpecDecl.
1731 /// If modified NumLinkageSpecDeclBits and the accessor
1732 /// methods in LinkageSpecDecl should be updated appropriately.
1733 class LinkageSpecDeclBitfields {
1734 friend class LinkageSpecDecl;
1735 /// For the bits in DeclContextBitfields.
1736 uint64_t : NumDeclContextBits;
1737
1738 /// The language for this linkage specification with values
1739 /// in the enum LinkageSpecDecl::LanguageIDs.
1740 uint64_t Language : 3;
1741
1742 /// True if this linkage spec has braces.
1743 /// This is needed so that hasBraces() returns the correct result while the
1744 /// linkage spec body is being parsed. Once RBraceLoc has been set this is
1745 /// not used, so it doesn't need to be serialized.
1746 uint64_t HasBraces : 1;
1747 };
1748
1749 /// Number of non-inherited bits in LinkageSpecDeclBitfields.
1750 enum { NumLinkageSpecDeclBits = 4 };
1751
1752 /// Stores the bits used by BlockDecl.
1753 /// If modified NumBlockDeclBits and the accessor
1754 /// methods in BlockDecl should be updated appropriately.
1755 class BlockDeclBitfields {
1756 friend class BlockDecl;
1757 /// For the bits in DeclContextBitfields.
1758 uint64_t : NumDeclContextBits;
1759
1760 uint64_t IsVariadic : 1;
1761 uint64_t CapturesCXXThis : 1;
1762 uint64_t BlockMissingReturnType : 1;
1763 uint64_t IsConversionFromLambda : 1;
1764
1765 /// A bit that indicates this block is passed directly to a function as a
1766 /// non-escaping parameter.
1767 uint64_t DoesNotEscape : 1;
1768
1769 /// A bit that indicates whether it's possible to avoid coying this block to
1770 /// the heap when it initializes or is assigned to a local variable with
1771 /// automatic storage.
1772 uint64_t CanAvoidCopyToHeap : 1;
1773 };
1774
1775 /// Number of non-inherited bits in BlockDeclBitfields.
1776 enum { NumBlockDeclBits = 5 };
1777
1778 /// Pointer to the data structure used to lookup declarations
1779 /// within this context (or a DependentStoredDeclsMap if this is a
1780 /// dependent context). We maintain the invariant that, if the map
1781 /// contains an entry for a DeclarationName (and we haven't lazily
1782 /// omitted anything), then it contains all relevant entries for that
1783 /// name (modulo the hasExternalDecls() flag).
1784 mutable StoredDeclsMap *LookupPtr = nullptr;
1785
1786protected:
1787 /// This anonymous union stores the bits belonging to DeclContext and classes
1788 /// deriving from it. The goal is to use otherwise wasted
1789 /// space in DeclContext to store data belonging to derived classes.
1790 /// The space saved is especially significient when pointers are aligned
1791 /// to 8 bytes. In this case due to alignment requirements we have a
1792 /// little less than 8 bytes free in DeclContext which we can use.
1793 /// We check that none of the classes in this union is larger than
1794 /// 8 bytes with static_asserts in the ctor of DeclContext.
1795 union {
1796 DeclContextBitfields DeclContextBits;
1797 TagDeclBitfields TagDeclBits;
1798 EnumDeclBitfields EnumDeclBits;
1799 RecordDeclBitfields RecordDeclBits;
1800 OMPDeclareReductionDeclBitfields OMPDeclareReductionDeclBits;
1801 FunctionDeclBitfields FunctionDeclBits;
1802 CXXConstructorDeclBitfields CXXConstructorDeclBits;
1803 ObjCMethodDeclBitfields ObjCMethodDeclBits;
1804 ObjCContainerDeclBitfields ObjCContainerDeclBits;
1805 LinkageSpecDeclBitfields LinkageSpecDeclBits;
1806 BlockDeclBitfields BlockDeclBits;
1807
1808 static_assert(sizeof(DeclContextBitfields) <= 8,
1809 "DeclContextBitfields is larger than 8 bytes!");
1810 static_assert(sizeof(TagDeclBitfields) <= 8,
1811 "TagDeclBitfields is larger than 8 bytes!");
1812 static_assert(sizeof(EnumDeclBitfields) <= 8,
1813 "EnumDeclBitfields is larger than 8 bytes!");
1814 static_assert(sizeof(RecordDeclBitfields) <= 8,
1815 "RecordDeclBitfields is larger than 8 bytes!");
1816 static_assert(sizeof(OMPDeclareReductionDeclBitfields) <= 8,
1817 "OMPDeclareReductionDeclBitfields is larger than 8 bytes!");
1818 static_assert(sizeof(FunctionDeclBitfields) <= 8,
1819 "FunctionDeclBitfields is larger than 8 bytes!");
1820 static_assert(sizeof(CXXConstructorDeclBitfields) <= 8,
1821 "CXXConstructorDeclBitfields is larger than 8 bytes!");
1822 static_assert(sizeof(ObjCMethodDeclBitfields) <= 8,
1823 "ObjCMethodDeclBitfields is larger than 8 bytes!");
1824 static_assert(sizeof(ObjCContainerDeclBitfields) <= 8,
1825 "ObjCContainerDeclBitfields is larger than 8 bytes!");
1826 static_assert(sizeof(LinkageSpecDeclBitfields) <= 8,
1827 "LinkageSpecDeclBitfields is larger than 8 bytes!");
1828 static_assert(sizeof(BlockDeclBitfields) <= 8,
1829 "BlockDeclBitfields is larger than 8 bytes!");
1830 };
1831
1832 /// FirstDecl - The first declaration stored within this declaration
1833 /// context.
1834 mutable Decl *FirstDecl = nullptr;
1835
1836 /// LastDecl - The last declaration stored within this declaration
1837 /// context. FIXME: We could probably cache this value somewhere
1838 /// outside of the DeclContext, to reduce the size of DeclContext by
1839 /// another pointer.
1840 mutable Decl *LastDecl = nullptr;
1841
1842 /// Build up a chain of declarations.
1843 ///
1844 /// \returns the first/last pair of declarations.
1845 static std::pair<Decl *, Decl *>
1846 BuildDeclChain(ArrayRef<Decl*> Decls, bool FieldsAlreadyLoaded);
1847
1848 DeclContext(Decl::Kind K);
1849
1850public:
1851 ~DeclContext();
1852
1853 Decl::Kind getDeclKind() const {
1854 return static_cast<Decl::Kind>(DeclContextBits.DeclKind);
1855 }
1856
1857 const char *getDeclKindName() const;
1858
1859 /// getParent - Returns the containing DeclContext.
1860 DeclContext *getParent() {
1861 return cast<Decl>(this)->getDeclContext();
1862 }
1863 const DeclContext *getParent() const {
1864 return const_cast<DeclContext*>(this)->getParent();
1865 }
1866
1867 /// getLexicalParent - Returns the containing lexical DeclContext. May be
1868 /// different from getParent, e.g.:
1869 ///
1870 /// namespace A {
1871 /// struct S;
1872 /// }
1873 /// struct A::S {}; // getParent() == namespace 'A'
1874 /// // getLexicalParent() == translation unit
1875 ///
1876 DeclContext *getLexicalParent() {
1877 return cast<Decl>(this)->getLexicalDeclContext();
1878 }
1879 const DeclContext *getLexicalParent() const {
1880 return const_cast<DeclContext*>(this)->getLexicalParent();
1881 }
1882
1883 DeclContext *getLookupParent();
1884
1885 const DeclContext *getLookupParent() const {
1886 return const_cast<DeclContext*>(this)->getLookupParent();
1887 }
1888
1889 ASTContext &getParentASTContext() const {
1890 return cast<Decl>(this)->getASTContext();
1891 }
1892
1893 bool isClosure() const { return getDeclKind() == Decl::Block; }
1894
1895 /// Return this DeclContext if it is a BlockDecl. Otherwise, return the
1896 /// innermost enclosing BlockDecl or null if there are no enclosing blocks.
1897 const BlockDecl *getInnermostBlockDecl() const;
1898
1899 bool isObjCContainer() const {
1900 switch (getDeclKind()) {
1901 case Decl::ObjCCategory:
1902 case Decl::ObjCCategoryImpl:
1903 case Decl::ObjCImplementation:
1904 case Decl::ObjCInterface:
1905 case Decl::ObjCProtocol:
1906 return true;
1907 default:
1908 return false;
1909 }
1910 }
1911
1912 bool isFunctionOrMethod() const {
1913 switch (getDeclKind()) {
1914 case Decl::Block:
1915 case Decl::Captured:
1916 case Decl::ObjCMethod:
1917 return true;
1918 default:
1919 return getDeclKind() >= Decl::firstFunction &&
1920 getDeclKind() <= Decl::lastFunction;
1921 }
1922 }
1923
1924 /// Test whether the context supports looking up names.
1925 bool isLookupContext() const {
1926 return !isFunctionOrMethod() && getDeclKind() != Decl::LinkageSpec &&
1927 getDeclKind() != Decl::Export;
1928 }
1929
1930 bool isFileContext() const {
1931 return getDeclKind() == Decl::TranslationUnit ||
1932 getDeclKind() == Decl::Namespace;
1933 }
1934
1935 bool isTranslationUnit() const {
1936 return getDeclKind() == Decl::TranslationUnit;
8
Assuming the condition is false
9
Returning zero, which participates in a condition later
1937 }
1938
1939 bool isRecord() const {
1940 return getDeclKind() >= Decl::firstRecord &&
1941 getDeclKind() <= Decl::lastRecord;
1942 }
1943
1944 bool isNamespace() const { return getDeclKind() == Decl::Namespace; }
1945
1946 bool isStdNamespace() const;
1947
1948 bool isInlineNamespace() const;
1949
1950 /// Determines whether this context is dependent on a
1951 /// template parameter.
1952 bool isDependentContext() const;
1953
1954 /// isTransparentContext - Determines whether this context is a
1955 /// "transparent" context, meaning that the members declared in this
1956 /// context are semantically declared in the nearest enclosing
1957 /// non-transparent (opaque) context but are lexically declared in
1958 /// this context. For example, consider the enumerators of an
1959 /// enumeration type:
1960 /// @code
1961 /// enum E {
1962 /// Val1
1963 /// };
1964 /// @endcode
1965 /// Here, E is a transparent context, so its enumerator (Val1) will
1966 /// appear (semantically) that it is in the same context of E.
1967 /// Examples of transparent contexts include: enumerations (except for
1968 /// C++0x scoped enums), and C++ linkage specifications.
1969 bool isTransparentContext() const;
1970
1971 /// Determines whether this context or some of its ancestors is a
1972 /// linkage specification context that specifies C linkage.
1973 bool isExternCContext() const;
1974
1975 /// Retrieve the nearest enclosing C linkage specification context.
1976 const LinkageSpecDecl *getExternCContext() const;
1977
1978 /// Determines whether this context or some of its ancestors is a
1979 /// linkage specification context that specifies C++ linkage.
1980 bool isExternCXXContext() const;
1981
1982 /// Determine whether this declaration context is equivalent
1983 /// to the declaration context DC.
1984 bool Equals(const DeclContext *DC) const {
1985 return DC && this->getPrimaryContext() == DC->getPrimaryContext();
1986 }
1987
1988 /// Determine whether this declaration context encloses the
1989 /// declaration context DC.
1990 bool Encloses(const DeclContext *DC) const;
1991
1992 /// Find the nearest non-closure ancestor of this context,
1993 /// i.e. the innermost semantic parent of this context which is not
1994 /// a closure. A context may be its own non-closure ancestor.
1995 Decl *getNonClosureAncestor();
1996 const Decl *getNonClosureAncestor() const {
1997 return const_cast<DeclContext*>(this)->getNonClosureAncestor();
1998 }
1999
2000 // Retrieve the nearest context that is not a transparent context.
2001 DeclContext *getNonTransparentContext();
2002 const DeclContext *getNonTransparentContext() const {
2003 return const_cast<DeclContext *>(this)->getNonTransparentContext();
2004 }
2005
2006 /// getPrimaryContext - There may be many different
2007 /// declarations of the same entity (including forward declarations
2008 /// of classes, multiple definitions of namespaces, etc.), each with
2009 /// a different set of declarations. This routine returns the
2010 /// "primary" DeclContext structure, which will contain the
2011 /// information needed to perform name lookup into this context.
2012 DeclContext *getPrimaryContext();
2013 const DeclContext *getPrimaryContext() const {
2014 return const_cast<DeclContext*>(this)->getPrimaryContext();
2015 }
2016
2017 /// getRedeclContext - Retrieve the context in which an entity conflicts with
2018 /// other entities of the same name, or where it is a redeclaration if the
2019 /// two entities are compatible. This skips through transparent contexts.
2020 DeclContext *getRedeclContext();
2021 const DeclContext *getRedeclContext() const {
2022 return const_cast<DeclContext *>(this)->getRedeclContext();
2023 }
2024
2025 /// Retrieve the nearest enclosing namespace context.
2026 DeclContext *getEnclosingNamespaceContext();
2027 const DeclContext *getEnclosingNamespaceContext() const {
2028 return const_cast<DeclContext *>(this)->getEnclosingNamespaceContext();
2029 }
2030
2031 /// Retrieve the outermost lexically enclosing record context.
2032 RecordDecl *getOuterLexicalRecordContext();
2033 const RecordDecl *getOuterLexicalRecordContext() const {
2034 return const_cast<DeclContext *>(this)->getOuterLexicalRecordContext();
2035 }
2036
2037 /// Test if this context is part of the enclosing namespace set of
2038 /// the context NS, as defined in C++0x [namespace.def]p9. If either context
2039 /// isn't a namespace, this is equivalent to Equals().
2040 ///
2041 /// The enclosing namespace set of a namespace is the namespace and, if it is
2042 /// inline, its enclosing namespace, recursively.
2043 bool InEnclosingNamespaceSetOf(const DeclContext *NS) const;
2044
2045 /// Collects all of the declaration contexts that are semantically
2046 /// connected to this declaration context.
2047 ///
2048 /// For declaration contexts that have multiple semantically connected but
2049 /// syntactically distinct contexts, such as C++ namespaces, this routine
2050 /// retrieves the complete set of such declaration contexts in source order.
2051 /// For example, given:
2052 ///
2053 /// \code
2054 /// namespace N {
2055 /// int x;
2056 /// }
2057 /// namespace N {
2058 /// int y;
2059 /// }
2060 /// \endcode
2061 ///
2062 /// The \c Contexts parameter will contain both definitions of N.
2063 ///
2064 /// \param Contexts Will be cleared and set to the set of declaration
2065 /// contexts that are semanticaly connected to this declaration context,
2066 /// in source order, including this context (which may be the only result,
2067 /// for non-namespace contexts).
2068 void collectAllContexts(SmallVectorImpl<DeclContext *> &Contexts);
2069
2070 /// decl_iterator - Iterates through the declarations stored
2071 /// within this context.
2072 class decl_iterator {
2073 /// Current - The current declaration.
2074 Decl *Current = nullptr;
2075
2076 public:
2077 using value_type = Decl *;
2078 using reference = const value_type &;
2079 using pointer = const value_type *;
2080 using iterator_category = std::forward_iterator_tag;
2081 using difference_type = std::ptrdiff_t;
2082
2083 decl_iterator() = default;
2084 explicit decl_iterator(Decl *C) : Current(C) {}
2085
2086 reference operator*() const { return Current; }
2087
2088 // This doesn't meet the iterator requirements, but it's convenient
2089 value_type operator->() const { return Current; }
2090
2091 decl_iterator& operator++() {
2092 Current = Current->getNextDeclInContext();
2093 return *this;
2094 }
2095
2096 decl_iterator operator++(int) {
2097 decl_iterator tmp(*this);
2098 ++(*this);
2099 return tmp;
2100 }
2101
2102 friend bool operator==(decl_iterator x, decl_iterator y) {
2103 return x.Current == y.Current;
2104 }
2105
2106 friend bool operator!=(decl_iterator x, decl_iterator y) {
2107 return x.Current != y.Current;
2108 }
2109 };
2110
2111 using decl_range = llvm::iterator_range<decl_iterator>;
2112
2113 /// decls_begin/decls_end - Iterate over the declarations stored in
2114 /// this context.
2115 decl_range decls() const { return decl_range(decls_begin(), decls_end()); }
2116 decl_iterator decls_begin() const;
2117 decl_iterator decls_end() const { return decl_iterator(); }
2118 bool decls_empty() const;
2119
2120 /// noload_decls_begin/end - Iterate over the declarations stored in this
2121 /// context that are currently loaded; don't attempt to retrieve anything
2122 /// from an external source.
2123 decl_range noload_decls() const {
2124 return decl_range(noload_decls_begin(), noload_decls_end());
2125 }
2126 decl_iterator noload_decls_begin() const { return decl_iterator(FirstDecl); }
2127 decl_iterator noload_decls_end() const { return decl_iterator(); }
2128
2129 /// specific_decl_iterator - Iterates over a subrange of
2130 /// declarations stored in a DeclContext, providing only those that
2131 /// are of type SpecificDecl (or a class derived from it). This
2132 /// iterator is used, for example, to provide iteration over just
2133 /// the fields within a RecordDecl (with SpecificDecl = FieldDecl).
2134 template<typename SpecificDecl>
2135 class specific_decl_iterator {
2136 /// Current - The current, underlying declaration iterator, which
2137 /// will either be NULL or will point to a declaration of
2138 /// type SpecificDecl.
2139 DeclContext::decl_iterator Current;
2140
2141 /// SkipToNextDecl - Advances the current position up to the next
2142 /// declaration of type SpecificDecl that also meets the criteria
2143 /// required by Acceptable.
2144 void SkipToNextDecl() {
2145 while (*Current && !isa<SpecificDecl>(*Current))
2146 ++Current;
2147 }
2148
2149 public:
2150 using value_type = SpecificDecl *;
2151 // TODO: Add reference and pointer types (with some appropriate proxy type)
2152 // if we ever have a need for them.
2153 using reference = void;
2154 using pointer = void;
2155 using difference_type =
2156 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2157 using iterator_category = std::forward_iterator_tag;
2158
2159 specific_decl_iterator() = default;
2160
2161 /// specific_decl_iterator - Construct a new iterator over a
2162 /// subset of the declarations the range [C,
2163 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2164 /// member function of SpecificDecl that should return true for
2165 /// all of the SpecificDecl instances that will be in the subset
2166 /// of iterators. For example, if you want Objective-C instance
2167 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2168 /// &ObjCMethodDecl::isInstanceMethod.
2169 explicit specific_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2170 SkipToNextDecl();
2171 }
2172
2173 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2174
2175 // This doesn't meet the iterator requirements, but it's convenient
2176 value_type operator->() const { return **this; }
2177
2178 specific_decl_iterator& operator++() {
2179 ++Current;
2180 SkipToNextDecl();
2181 return *this;
2182 }
2183
2184 specific_decl_iterator operator++(int) {
2185 specific_decl_iterator tmp(*this);
2186 ++(*this);
2187 return tmp;
2188 }
2189
2190 friend bool operator==(const specific_decl_iterator& x,
2191 const specific_decl_iterator& y) {
2192 return x.Current == y.Current;
2193 }
2194
2195 friend bool operator!=(const specific_decl_iterator& x,
2196 const specific_decl_iterator& y) {
2197 return x.Current != y.Current;
2198 }
2199 };
2200
2201 /// Iterates over a filtered subrange of declarations stored
2202 /// in a DeclContext.
2203 ///
2204 /// This iterator visits only those declarations that are of type
2205 /// SpecificDecl (or a class derived from it) and that meet some
2206 /// additional run-time criteria. This iterator is used, for
2207 /// example, to provide access to the instance methods within an
2208 /// Objective-C interface (with SpecificDecl = ObjCMethodDecl and
2209 /// Acceptable = ObjCMethodDecl::isInstanceMethod).
2210 template<typename SpecificDecl, bool (SpecificDecl::*Acceptable)() const>
2211 class filtered_decl_iterator {
2212 /// Current - The current, underlying declaration iterator, which
2213 /// will either be NULL or will point to a declaration of
2214 /// type SpecificDecl.
2215 DeclContext::decl_iterator Current;
2216
2217 /// SkipToNextDecl - Advances the current position up to the next
2218 /// declaration of type SpecificDecl that also meets the criteria
2219 /// required by Acceptable.
2220 void SkipToNextDecl() {
2221 while (*Current &&
2222 (!isa<SpecificDecl>(*Current) ||
2223 (Acceptable && !(cast<SpecificDecl>(*Current)->*Acceptable)())))
2224 ++Current;
2225 }
2226
2227 public:
2228 using value_type = SpecificDecl *;
2229 // TODO: Add reference and pointer types (with some appropriate proxy type)
2230 // if we ever have a need for them.
2231 using reference = void;
2232 using pointer = void;
2233 using difference_type =
2234 std::iterator_traits<DeclContext::decl_iterator>::difference_type;
2235 using iterator_category = std::forward_iterator_tag;
2236
2237 filtered_decl_iterator() = default;
2238
2239 /// filtered_decl_iterator - Construct a new iterator over a
2240 /// subset of the declarations the range [C,
2241 /// end-of-declarations). If A is non-NULL, it is a pointer to a
2242 /// member function of SpecificDecl that should return true for
2243 /// all of the SpecificDecl instances that will be in the subset
2244 /// of iterators. For example, if you want Objective-C instance
2245 /// methods, SpecificDecl will be ObjCMethodDecl and A will be
2246 /// &ObjCMethodDecl::isInstanceMethod.
2247 explicit filtered_decl_iterator(DeclContext::decl_iterator C) : Current(C) {
2248 SkipToNextDecl();
2249 }
2250
2251 value_type operator*() const { return cast<SpecificDecl>(*Current); }
2252 value_type operator->() const { return cast<SpecificDecl>(*Current); }
2253
2254 filtered_decl_iterator& operator++() {
2255 ++Current;
2256 SkipToNextDecl();
2257 return *this;
2258 }
2259
2260 filtered_decl_iterator operator++(int) {
2261 filtered_decl_iterator tmp(*this);
2262 ++(*this);
2263 return tmp;
2264 }
2265
2266 friend bool operator==(const filtered_decl_iterator& x,
2267 const filtered_decl_iterator& y) {
2268 return x.Current == y.Current;
2269 }
2270
2271 friend bool operator!=(const filtered_decl_iterator& x,
2272 const filtered_decl_iterator& y) {
2273 return x.Current != y.Current;
2274 }
2275 };
2276
2277 /// Add the declaration D into this context.
2278 ///
2279 /// This routine should be invoked when the declaration D has first
2280 /// been declared, to place D into the context where it was
2281 /// (lexically) defined. Every declaration must be added to one
2282 /// (and only one!) context, where it can be visited via
2283 /// [decls_begin(), decls_end()). Once a declaration has been added
2284 /// to its lexical context, the corresponding DeclContext owns the
2285 /// declaration.
2286 ///
2287 /// If D is also a NamedDecl, it will be made visible within its
2288 /// semantic context via makeDeclVisibleInContext.
2289 void addDecl(Decl *D);
2290
2291 /// Add the declaration D into this context, but suppress
2292 /// searches for external declarations with the same name.
2293 ///
2294 /// Although analogous in function to addDecl, this removes an
2295 /// important check. This is only useful if the Decl is being
2296 /// added in response to an external search; in all other cases,
2297 /// addDecl() is the right function to use.
2298 /// See the ASTImporter for use cases.
2299 void addDeclInternal(Decl *D);
2300
2301 /// Add the declaration D to this context without modifying
2302 /// any lookup tables.
2303 ///
2304 /// This is useful for some operations in dependent contexts where
2305 /// the semantic context might not be dependent; this basically
2306 /// only happens with friends.
2307 void addHiddenDecl(Decl *D);
2308
2309 /// Removes a declaration from this context.
2310 void removeDecl(Decl *D);
2311
2312 /// Checks whether a declaration is in this context.
2313 bool containsDecl(Decl *D) const;
2314
2315 /// Checks whether a declaration is in this context.
2316 /// This also loads the Decls from the external source before the check.
2317 bool containsDeclAndLoad(Decl *D) const;
2318
2319 using lookup_result = DeclContextLookupResult;
2320 using lookup_iterator = lookup_result::iterator;
2321
2322 /// lookup - Find the declarations (if any) with the given Name in
2323 /// this context. Returns a range of iterators that contains all of
2324 /// the declarations with this name, with object, function, member,
2325 /// and enumerator names preceding any tag name. Note that this
2326 /// routine will not look into parent contexts.
2327 lookup_result lookup(DeclarationName Name) const;
2328
2329 /// Find the declarations with the given name that are visible
2330 /// within this context; don't attempt to retrieve anything from an
2331 /// external source.
2332 lookup_result noload_lookup(DeclarationName Name);
2333
2334 /// A simplistic name lookup mechanism that performs name lookup
2335 /// into this declaration context without consulting the external source.
2336 ///
2337 /// This function should almost never be used, because it subverts the
2338 /// usual relationship between a DeclContext and the external source.
2339 /// See the ASTImporter for the (few, but important) use cases.
2340 ///
2341 /// FIXME: This is very inefficient; replace uses of it with uses of
2342 /// noload_lookup.
2343 void localUncachedLookup(DeclarationName Name,
2344 SmallVectorImpl<NamedDecl *> &Results);
2345
2346 /// Makes a declaration visible within this context.
2347 ///
2348 /// This routine makes the declaration D visible to name lookup
2349 /// within this context and, if this is a transparent context,
2350 /// within its parent contexts up to the first enclosing
2351 /// non-transparent context. Making a declaration visible within a
2352 /// context does not transfer ownership of a declaration, and a
2353 /// declaration can be visible in many contexts that aren't its
2354 /// lexical context.
2355 ///
2356 /// If D is a redeclaration of an existing declaration that is
2357 /// visible from this context, as determined by
2358 /// NamedDecl::declarationReplaces, the previous declaration will be
2359 /// replaced with D.
2360 void makeDeclVisibleInContext(NamedDecl *D);
2361
2362 /// all_lookups_iterator - An iterator that provides a view over the results
2363 /// of looking up every possible name.
2364 class all_lookups_iterator;
2365
2366 using lookups_range = llvm::iterator_range<all_lookups_iterator>;
2367
2368 lookups_range lookups() const;
2369 // Like lookups(), but avoids loading external declarations.
2370 // If PreserveInternalState, avoids building lookup data structures too.
2371 lookups_range noload_lookups(bool PreserveInternalState) const;
2372
2373 /// Iterators over all possible lookups within this context.
2374 all_lookups_iterator lookups_begin() const;
2375 all_lookups_iterator lookups_end() const;
2376
2377 /// Iterators over all possible lookups within this context that are
2378 /// currently loaded; don't attempt to retrieve anything from an external
2379 /// source.
2380 all_lookups_iterator noload_lookups_begin() const;
2381 all_lookups_iterator noload_lookups_end() const;
2382
2383 struct udir_iterator;
2384
2385 using udir_iterator_base =
2386 llvm::iterator_adaptor_base<udir_iterator, lookup_iterator,
2387 typename lookup_iterator::iterator_category,
2388 UsingDirectiveDecl *>;
2389
2390 struct udir_iterator : udir_iterator_base {
2391 udir_iterator(lookup_iterator I) : udir_iterator_base(I) {}
2392
2393 UsingDirectiveDecl *operator*() const;
2394 };
2395
2396 using udir_range = llvm::iterator_range<udir_iterator>;
2397
2398 udir_range using_directives() const;
2399
2400 // These are all defined in DependentDiagnostic.h.
2401 class ddiag_iterator;
2402
2403 using ddiag_range = llvm::iterator_range<DeclContext::ddiag_iterator>;
2404
2405 inline ddiag_range ddiags() const;
2406
2407 // Low-level accessors
2408
2409 /// Mark that there are external lexical declarations that we need
2410 /// to include in our lookup table (and that are not available as external
2411 /// visible lookups). These extra lookup results will be found by walking
2412 /// the lexical declarations of this context. This should be used only if
2413 /// setHasExternalLexicalStorage() has been called on any decl context for
2414 /// which this is the primary context.
2415 void setMustBuildLookupTable() {
2416 assert(this == getPrimaryContext() &&(static_cast<void> (0))
2417 "should only be called on primary context")(static_cast<void> (0));
2418 DeclContextBits.HasLazyExternalLexicalLookups = true;
2419 }
2420
2421 /// Retrieve the internal representation of the lookup structure.
2422 /// This may omit some names if we are lazily building the structure.
2423 StoredDeclsMap *getLookupPtr() const { return LookupPtr; }
2424
2425 /// Ensure the lookup structure is fully-built and return it.
2426 StoredDeclsMap *buildLookup();
2427
2428 /// Whether this DeclContext has external storage containing
2429 /// additional declarations that are lexically in this context.
2430 bool hasExternalLexicalStorage() const {
2431 return DeclContextBits.ExternalLexicalStorage;
2432 }
2433
2434 /// State whether this DeclContext has external storage for
2435 /// declarations lexically in this context.
2436 void setHasExternalLexicalStorage(bool ES = true) const {
2437 DeclContextBits.ExternalLexicalStorage = ES;
2438 }
2439
2440 /// Whether this DeclContext has external storage containing
2441 /// additional declarations that are visible in this context.
2442 bool hasExternalVisibleStorage() const {
2443 return DeclContextBits.ExternalVisibleStorage;
2444 }
2445
2446 /// State whether this DeclContext has external storage for
2447 /// declarations visible in this context.
2448 void setHasExternalVisibleStorage(bool ES = true) const {
2449 DeclContextBits.ExternalVisibleStorage = ES;
2450 if (ES && LookupPtr)
2451 DeclContextBits.NeedToReconcileExternalVisibleStorage = true;
2452 }
2453
2454 /// Determine whether the given declaration is stored in the list of
2455 /// declarations lexically within this context.
2456 bool isDeclInLexicalTraversal(const Decl *D) const {
2457 return D && (D->NextInContextAndBits.getPointer() || D == FirstDecl ||
2458 D == LastDecl);
2459 }
2460
2461 bool setUseQualifiedLookup(bool use = true) const {
2462 bool old_value = DeclContextBits.UseQualifiedLookup;
2463 DeclContextBits.UseQualifiedLookup = use;
2464 return old_value;
2465 }
2466
2467 bool shouldUseQualifiedLookup() const {
2468 return DeclContextBits.UseQualifiedLookup;
2469 }
2470
2471 static bool classof(const Decl *D);
2472 static bool classof(const DeclContext *D) { return true; }
2473
2474 void dumpDeclContext() const;
2475 void dumpLookups() const;
2476 void dumpLookups(llvm::raw_ostream &OS, bool DumpDecls = false,
2477 bool Deserialize = false) const;
2478
2479private:
2480 /// Whether this declaration context has had externally visible
2481 /// storage added since the last lookup. In this case, \c LookupPtr's
2482 /// invariant may not hold and needs to be fixed before we perform
2483 /// another lookup.
2484 bool hasNeedToReconcileExternalVisibleStorage() const {
2485 return DeclContextBits.NeedToReconcileExternalVisibleStorage;
2486 }
2487
2488 /// State that this declaration context has had externally visible
2489 /// storage added since the last lookup. In this case, \c LookupPtr's
2490 /// invariant may not hold and needs to be fixed before we perform
2491 /// another lookup.
2492 void setNeedToReconcileExternalVisibleStorage(bool Need = true) const {
2493 DeclContextBits.NeedToReconcileExternalVisibleStorage = Need;
2494 }
2495
2496 /// If \c true, this context may have local lexical declarations
2497 /// that are missing from the lookup table.
2498 bool hasLazyLocalLexicalLookups() const {
2499 return DeclContextBits.HasLazyLocalLexicalLookups;
2500 }
2501
2502 /// If \c true, this context may have local lexical declarations
2503 /// that are missing from the lookup table.
2504 void setHasLazyLocalLexicalLookups(bool HasLLLL = true) const {
2505 DeclContextBits.HasLazyLocalLexicalLookups = HasLLLL;
2506 }
2507
2508 /// If \c true, the external source may have lexical declarations
2509 /// that are missing from the lookup table.
2510 bool hasLazyExternalLexicalLookups() const {
2511 return DeclContextBits.HasLazyExternalLexicalLookups;
2512 }
2513
2514 /// If \c true, the external source may have lexical declarations
2515 /// that are missing from the lookup table.
2516 void setHasLazyExternalLexicalLookups(bool HasLELL = true) const {
2517 DeclContextBits.HasLazyExternalLexicalLookups = HasLELL;
2518 }
2519
2520 void reconcileExternalVisibleStorage() const;
2521 bool LoadLexicalDeclsFromExternalStorage() const;
2522
2523 /// Makes a declaration visible within this context, but
2524 /// suppresses searches for external declarations with the same
2525 /// name.
2526 ///
2527 /// Analogous to makeDeclVisibleInContext, but for the exclusive
2528 /// use of addDeclInternal().
2529 void makeDeclVisibleInContextInternal(NamedDecl *D);
2530
2531 StoredDeclsMap *CreateStoredDeclsMap(ASTContext &C) const;
2532
2533 void loadLazyLocalLexicalLookups();
2534 void buildLookupImpl(DeclContext *DCtx, bool Internal);
2535 void makeDeclVisibleInContextWithFlags(NamedDecl *D, bool Internal,
2536 bool Rediscoverable);
2537 void makeDeclVisibleInContextImpl(NamedDecl *D, bool Internal);
2538};
2539
2540inline bool Decl::isTemplateParameter() const {
2541 return getKind() == TemplateTypeParm || getKind() == NonTypeTemplateParm ||
2542 getKind() == TemplateTemplateParm;
2543}
2544
2545// Specialization selected when ToTy is not a known subclass of DeclContext.
2546template <class ToTy,
2547 bool IsKnownSubtype = ::std::is_base_of<DeclContext, ToTy>::value>
2548struct cast_convert_decl_context {
2549 static const ToTy *doit(const DeclContext *Val) {
2550 return static_cast<const ToTy*>(Decl::castFromDeclContext(Val));
2551 }
2552
2553 static ToTy *doit(DeclContext *Val) {
2554 return static_cast<ToTy*>(Decl::castFromDeclContext(Val));
2555 }
2556};
2557
2558// Specialization selected when ToTy is a known subclass of DeclContext.
2559template <class ToTy>
2560struct cast_convert_decl_context<ToTy, true> {
2561 static const ToTy *doit(const DeclContext *Val) {
2562 return static_cast<const ToTy*>(Val);
2563 }
2564
2565 static ToTy *doit(DeclContext *Val) {
2566 return static_cast<ToTy*>(Val);
2567 }
2568};
2569
2570} // namespace clang
2571
2572namespace llvm {
2573
2574/// isa<T>(DeclContext*)
2575template <typename To>
2576struct isa_impl<To, ::clang::DeclContext> {
2577 static bool doit(const ::clang::DeclContext &Val) {
2578 return To::classofKind(Val.getDeclKind());
2579 }
2580};
2581
2582/// cast<T>(DeclContext*)
2583template<class ToTy>
2584struct cast_convert_val<ToTy,
2585 const ::clang::DeclContext,const ::clang::DeclContext> {
2586 static const ToTy &doit(const ::clang::DeclContext &Val) {
2587 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2588 }
2589};
2590
2591template<class ToTy>
2592struct cast_convert_val<ToTy, ::clang::DeclContext, ::clang::DeclContext> {
2593 static ToTy &doit(::clang::DeclContext &Val) {
2594 return *::clang::cast_convert_decl_context<ToTy>::doit(&Val);
2595 }
2596};
2597
2598template<class ToTy>
2599struct cast_convert_val<ToTy,
2600 const ::clang::DeclContext*, const ::clang::DeclContext*> {
2601 static const ToTy *doit(const ::clang::DeclContext *Val) {
2602 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2603 }
2604};
2605
2606template<class ToTy>
2607struct cast_convert_val<ToTy, ::clang::DeclContext*, ::clang::DeclContext*> {
2608 static ToTy *doit(::clang::DeclContext *Val) {
2609 return ::clang::cast_convert_decl_context<ToTy>::doit(Val);
2610 }
2611};
2612
2613/// Implement cast_convert_val for Decl -> DeclContext conversions.
2614template<class FromTy>
2615struct cast_convert_val< ::clang::DeclContext, FromTy, FromTy> {
2616 static ::clang::DeclContext &doit(const FromTy &Val) {
2617 return *FromTy::castToDeclContext(&Val);
2618 }
2619};
2620
2621template<class FromTy>
2622struct cast_convert_val< ::clang::DeclContext, FromTy*, FromTy*> {
2623 static ::clang::DeclContext *doit(const FromTy *Val) {
2624 return FromTy::castToDeclContext(Val);
2625 }
2626};
2627
2628template<class FromTy>
2629struct cast_convert_val< const ::clang::DeclContext, FromTy, FromTy> {
2630 static const ::clang::DeclContext &doit(const FromTy &Val) {
2631 return *FromTy::castToDeclContext(&Val);
2632 }
2633};
2634
2635template<class FromTy>
2636struct cast_convert_val< const ::clang::DeclContext, FromTy*, FromTy*> {
2637 static const ::clang::DeclContext *doit(const FromTy *Val) {
2638 return FromTy::castToDeclContext(Val);
2639 }
2640};
2641
2642} // namespace llvm
2643
2644#endif // LLVM_CLANG_AST_DECLBASE_H