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