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