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