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