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