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