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