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