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 ()__anon4331d3480111::UnqualUsingEntry::Comparator76 bool operator()(const UnqualUsingEntry &L, const UnqualUsingEntry &R) {
77 return L.getCommonAncestor() < R.getCommonAncestor();
78 }
79
operator ()__anon4331d3480111::UnqualUsingEntry::Comparator80 bool operator()(const UnqualUsingEntry &E, const DeclContext *DC) {
81 return E.getCommonAncestor() < DC;
82 }
83
operator ()__anon4331d3480111::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__anon4331d3480211::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__anon4331d3480211::FindLocalExternScope1193 void restore() {
1194 R.setFindLocalExtern(OldFindLocalExtern);
1195 }
~FindLocalExternScope__anon4331d3480211::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 /// Callback that looks for any member of a class with the given name.
LookupAnyMember(const CXXBaseSpecifier * Specifier,CXXBasePath & Path,DeclarationName Name)2089 static bool LookupAnyMember(const CXXBaseSpecifier *Specifier,
2090 CXXBasePath &Path, DeclarationName Name) {
2091 RecordDecl *BaseRecord = Specifier->getType()->castAs<RecordType>()->getDecl();
2092
2093 Path.Decls = BaseRecord->lookup(Name);
2094 return !Path.Decls.empty();
2095 }
2096
2097 /// Determine whether the given set of member declarations contains only
2098 /// static members, nested types, and enumerators.
2099 template<typename InputIterator>
HasOnlyStaticMembers(InputIterator First,InputIterator Last)2100 static bool HasOnlyStaticMembers(InputIterator First, InputIterator Last) {
2101 Decl *D = (*First)->getUnderlyingDecl();
2102 if (isa<VarDecl>(D) || isa<TypeDecl>(D) || isa<EnumConstantDecl>(D))
2103 return true;
2104
2105 if (isa<CXXMethodDecl>(D)) {
2106 // Determine whether all of the methods are static.
2107 bool AllMethodsAreStatic = true;
2108 for(; First != Last; ++First) {
2109 D = (*First)->getUnderlyingDecl();
2110
2111 if (!isa<CXXMethodDecl>(D)) {
2112 assert(isa<TagDecl>(D) && "Non-function must be a tag decl");
2113 break;
2114 }
2115
2116 if (!cast<CXXMethodDecl>(D)->isStatic()) {
2117 AllMethodsAreStatic = false;
2118 break;
2119 }
2120 }
2121
2122 if (AllMethodsAreStatic)
2123 return true;
2124 }
2125
2126 return false;
2127 }
2128
2129 /// Perform qualified name lookup into a given context.
2130 ///
2131 /// Qualified name lookup (C++ [basic.lookup.qual]) is used to find
2132 /// names when the context of those names is explicit specified, e.g.,
2133 /// "std::vector" or "x->member", or as part of unqualified name lookup.
2134 ///
2135 /// Different lookup criteria can find different names. For example, a
2136 /// particular scope can have both a struct and a function of the same
2137 /// name, and each can be found by certain lookup criteria. For more
2138 /// information about lookup criteria, see the documentation for the
2139 /// class LookupCriteria.
2140 ///
2141 /// \param R captures both the lookup criteria and any lookup results found.
2142 ///
2143 /// \param LookupCtx The context in which qualified name lookup will
2144 /// search. If the lookup criteria permits, name lookup may also search
2145 /// in the parent contexts or (for C++ classes) base classes.
2146 ///
2147 /// \param InUnqualifiedLookup true if this is qualified name lookup that
2148 /// occurs as part of unqualified name lookup.
2149 ///
2150 /// \returns true if lookup succeeded, false if it failed.
LookupQualifiedName(LookupResult & R,DeclContext * LookupCtx,bool InUnqualifiedLookup)2151 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2152 bool InUnqualifiedLookup) {
2153 assert(LookupCtx && "Sema::LookupQualifiedName requires a lookup context");
2154
2155 if (!R.getLookupName())
2156 return false;
2157
2158 // Make sure that the declaration context is complete.
2159 assert((!isa<TagDecl>(LookupCtx) ||
2160 LookupCtx->isDependentContext() ||
2161 cast<TagDecl>(LookupCtx)->isCompleteDefinition() ||
2162 cast<TagDecl>(LookupCtx)->isBeingDefined()) &&
2163 "Declaration context must already be complete!");
2164
2165 struct QualifiedLookupInScope {
2166 bool oldVal;
2167 DeclContext *Context;
2168 // Set flag in DeclContext informing debugger that we're looking for qualified name
2169 QualifiedLookupInScope(DeclContext *ctx) : Context(ctx) {
2170 oldVal = ctx->setUseQualifiedLookup();
2171 }
2172 ~QualifiedLookupInScope() {
2173 Context->setUseQualifiedLookup(oldVal);
2174 }
2175 } QL(LookupCtx);
2176
2177 if (LookupDirect(*this, R, LookupCtx)) {
2178 R.resolveKind();
2179 if (isa<CXXRecordDecl>(LookupCtx))
2180 R.setNamingClass(cast<CXXRecordDecl>(LookupCtx));
2181 return true;
2182 }
2183
2184 // Don't descend into implied contexts for redeclarations.
2185 // C++98 [namespace.qual]p6:
2186 // In a declaration for a namespace member in which the
2187 // declarator-id is a qualified-id, given that the qualified-id
2188 // for the namespace member has the form
2189 // nested-name-specifier unqualified-id
2190 // the unqualified-id shall name a member of the namespace
2191 // designated by the nested-name-specifier.
2192 // See also [class.mfct]p5 and [class.static.data]p2.
2193 if (R.isForRedeclaration())
2194 return false;
2195
2196 // If this is a namespace, look it up in the implied namespaces.
2197 if (LookupCtx->isFileContext())
2198 return LookupQualifiedNameInUsingDirectives(*this, R, LookupCtx);
2199
2200 // If this isn't a C++ class, we aren't allowed to look into base
2201 // classes, we're done.
2202 CXXRecordDecl *LookupRec = dyn_cast<CXXRecordDecl>(LookupCtx);
2203 if (!LookupRec || !LookupRec->getDefinition())
2204 return false;
2205
2206 // If we're performing qualified name lookup into a dependent class,
2207 // then we are actually looking into a current instantiation. If we have any
2208 // dependent base classes, then we either have to delay lookup until
2209 // template instantiation time (at which point all bases will be available)
2210 // or we have to fail.
2211 if (!InUnqualifiedLookup && LookupRec->isDependentContext() &&
2212 LookupRec->hasAnyDependentBases()) {
2213 R.setNotFoundInCurrentInstantiation();
2214 return false;
2215 }
2216
2217 // Perform lookup into our base classes.
2218 CXXBasePaths Paths;
2219 Paths.setOrigin(LookupRec);
2220
2221 // Look for this member in our base classes
2222 bool (*BaseCallback)(const CXXBaseSpecifier *Specifier, CXXBasePath &Path,
2223 DeclarationName Name) = nullptr;
2224 switch (R.getLookupKind()) {
2225 case LookupObjCImplicitSelfParam:
2226 case LookupOrdinaryName:
2227 case LookupMemberName:
2228 case LookupRedeclarationWithLinkage:
2229 case LookupLocalFriendName:
2230 case LookupDestructorName:
2231 BaseCallback = &CXXRecordDecl::FindOrdinaryMember;
2232 break;
2233
2234 case LookupTagName:
2235 BaseCallback = &CXXRecordDecl::FindTagMember;
2236 break;
2237
2238 case LookupAnyName:
2239 BaseCallback = &LookupAnyMember;
2240 break;
2241
2242 case LookupOMPReductionName:
2243 BaseCallback = &CXXRecordDecl::FindOMPReductionMember;
2244 break;
2245
2246 case LookupOMPMapperName:
2247 BaseCallback = &CXXRecordDecl::FindOMPMapperMember;
2248 break;
2249
2250 case LookupUsingDeclName:
2251 // This lookup is for redeclarations only.
2252
2253 case LookupOperatorName:
2254 case LookupNamespaceName:
2255 case LookupObjCProtocolName:
2256 case LookupLabel:
2257 // These lookups will never find a member in a C++ class (or base class).
2258 return false;
2259
2260 case LookupNestedNameSpecifierName:
2261 BaseCallback = &CXXRecordDecl::FindNestedNameSpecifierMember;
2262 break;
2263 }
2264
2265 DeclarationName Name = R.getLookupName();
2266 if (!LookupRec->lookupInBases(
2267 [=](const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
2268 return BaseCallback(Specifier, Path, Name);
2269 },
2270 Paths))
2271 return false;
2272
2273 R.setNamingClass(LookupRec);
2274
2275 // C++ [class.member.lookup]p2:
2276 // [...] If the resulting set of declarations are not all from
2277 // sub-objects of the same type, or the set has a nonstatic member
2278 // and includes members from distinct sub-objects, there is an
2279 // ambiguity and the program is ill-formed. Otherwise that set is
2280 // the result of the lookup.
2281 QualType SubobjectType;
2282 int SubobjectNumber = 0;
2283 AccessSpecifier SubobjectAccess = AS_none;
2284
2285 for (CXXBasePaths::paths_iterator Path = Paths.begin(), PathEnd = Paths.end();
2286 Path != PathEnd; ++Path) {
2287 const CXXBasePathElement &PathElement = Path->back();
2288
2289 // Pick the best (i.e. most permissive i.e. numerically lowest) access
2290 // across all paths.
2291 SubobjectAccess = std::min(SubobjectAccess, Path->Access);
2292
2293 // Determine whether we're looking at a distinct sub-object or not.
2294 if (SubobjectType.isNull()) {
2295 // This is the first subobject we've looked at. Record its type.
2296 SubobjectType = Context.getCanonicalType(PathElement.Base->getType());
2297 SubobjectNumber = PathElement.SubobjectNumber;
2298 continue;
2299 }
2300
2301 if (SubobjectType
2302 != Context.getCanonicalType(PathElement.Base->getType())) {
2303 // We found members of the given name in two subobjects of
2304 // different types. If the declaration sets aren't the same, this
2305 // lookup is ambiguous.
2306 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end())) {
2307 CXXBasePaths::paths_iterator FirstPath = Paths.begin();
2308 DeclContext::lookup_iterator FirstD = FirstPath->Decls.begin();
2309 DeclContext::lookup_iterator CurrentD = Path->Decls.begin();
2310
2311 // Get the decl that we should use for deduplicating this lookup.
2312 auto GetRepresentativeDecl = [&](NamedDecl *D) -> Decl * {
2313 // C++ [temp.local]p3:
2314 // A lookup that finds an injected-class-name (10.2) can result in
2315 // an ambiguity in certain cases (for example, if it is found in
2316 // more than one base class). If all of the injected-class-names
2317 // that are found refer to specializations of the same class
2318 // template, and if the name is used as a template-name, the
2319 // reference refers to the class template itself and not a
2320 // specialization thereof, and is not ambiguous.
2321 if (R.isTemplateNameLookup())
2322 if (auto *TD = getAsTemplateNameDecl(D))
2323 D = TD;
2324 return D->getUnderlyingDecl()->getCanonicalDecl();
2325 };
2326
2327 while (FirstD != FirstPath->Decls.end() &&
2328 CurrentD != Path->Decls.end()) {
2329 if (GetRepresentativeDecl(*FirstD) !=
2330 GetRepresentativeDecl(*CurrentD))
2331 break;
2332
2333 ++FirstD;
2334 ++CurrentD;
2335 }
2336
2337 if (FirstD == FirstPath->Decls.end() &&
2338 CurrentD == Path->Decls.end())
2339 continue;
2340 }
2341
2342 R.setAmbiguousBaseSubobjectTypes(Paths);
2343 return true;
2344 }
2345
2346 if (SubobjectNumber != PathElement.SubobjectNumber) {
2347 // We have a different subobject of the same type.
2348
2349 // C++ [class.member.lookup]p5:
2350 // A static member, a nested type or an enumerator defined in
2351 // a base class T can unambiguously be found even if an object
2352 // has more than one base class subobject of type T.
2353 if (HasOnlyStaticMembers(Path->Decls.begin(), Path->Decls.end()))
2354 continue;
2355
2356 // We have found a nonstatic member name in multiple, distinct
2357 // subobjects. Name lookup is ambiguous.
2358 R.setAmbiguousBaseSubobjects(Paths);
2359 return true;
2360 }
2361 }
2362
2363 // Lookup in a base class succeeded; return these results.
2364
2365 for (auto *D : Paths.front().Decls) {
2366 AccessSpecifier AS = CXXRecordDecl::MergeAccess(SubobjectAccess,
2367 D->getAccess());
2368 R.addDecl(D, AS);
2369 }
2370 R.resolveKind();
2371 return true;
2372 }
2373
2374 /// Performs qualified name lookup or special type of lookup for
2375 /// "__super::" scope specifier.
2376 ///
2377 /// This routine is a convenience overload meant to be called from contexts
2378 /// that need to perform a qualified name lookup with an optional C++ scope
2379 /// specifier that might require special kind of lookup.
2380 ///
2381 /// \param R captures both the lookup criteria and any lookup results found.
2382 ///
2383 /// \param LookupCtx The context in which qualified name lookup will
2384 /// search.
2385 ///
2386 /// \param SS An optional C++ scope-specifier.
2387 ///
2388 /// \returns true if lookup succeeded, false if it failed.
LookupQualifiedName(LookupResult & R,DeclContext * LookupCtx,CXXScopeSpec & SS)2389 bool Sema::LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx,
2390 CXXScopeSpec &SS) {
2391 auto *NNS = SS.getScopeRep();
2392 if (NNS && NNS->getKind() == NestedNameSpecifier::Super)
2393 return LookupInSuper(R, NNS->getAsRecordDecl());
2394 else
2395
2396 return LookupQualifiedName(R, LookupCtx);
2397 }
2398
2399 /// Performs name lookup for a name that was parsed in the
2400 /// source code, and may contain a C++ scope specifier.
2401 ///
2402 /// This routine is a convenience routine meant to be called from
2403 /// contexts that receive a name and an optional C++ scope specifier
2404 /// (e.g., "N::M::x"). It will then perform either qualified or
2405 /// unqualified name lookup (with LookupQualifiedName or LookupName,
2406 /// respectively) on the given name and return those results. It will
2407 /// perform a special type of lookup for "__super::" scope specifier.
2408 ///
2409 /// @param S The scope from which unqualified name lookup will
2410 /// begin.
2411 ///
2412 /// @param SS An optional C++ scope-specifier, e.g., "::N::M".
2413 ///
2414 /// @param EnteringContext Indicates whether we are going to enter the
2415 /// context of the scope-specifier SS (if present).
2416 ///
2417 /// @returns True if any decls were found (but possibly ambiguous)
LookupParsedName(LookupResult & R,Scope * S,CXXScopeSpec * SS,bool AllowBuiltinCreation,bool EnteringContext)2418 bool Sema::LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS,
2419 bool AllowBuiltinCreation, bool EnteringContext) {
2420 if (SS && SS->isInvalid()) {
2421 // When the scope specifier is invalid, don't even look for
2422 // anything.
2423 return false;
2424 }
2425
2426 if (SS && SS->isSet()) {
2427 NestedNameSpecifier *NNS = SS->getScopeRep();
2428 if (NNS->getKind() == NestedNameSpecifier::Super)
2429 return LookupInSuper(R, NNS->getAsRecordDecl());
2430
2431 if (DeclContext *DC = computeDeclContext(*SS, EnteringContext)) {
2432 // We have resolved the scope specifier to a particular declaration
2433 // contex, and will perform name lookup in that context.
2434 if (!DC->isDependentContext() && RequireCompleteDeclContext(*SS, DC))
2435 return false;
2436
2437 R.setContextRange(SS->getRange());
2438 return LookupQualifiedName(R, DC);
2439 }
2440
2441 // We could not resolve the scope specified to a specific declaration
2442 // context, which means that SS refers to an unknown specialization.
2443 // Name lookup can't find anything in this case.
2444 R.setNotFoundInCurrentInstantiation();
2445 R.setContextRange(SS->getRange());
2446 return false;
2447 }
2448
2449 // Perform unqualified name lookup starting in the given scope.
2450 return LookupName(R, S, AllowBuiltinCreation);
2451 }
2452
2453 /// Perform qualified name lookup into all base classes of the given
2454 /// class.
2455 ///
2456 /// \param R captures both the lookup criteria and any lookup results found.
2457 ///
2458 /// \param Class The context in which qualified name lookup will
2459 /// search. Name lookup will search in all base classes merging the results.
2460 ///
2461 /// @returns True if any decls were found (but possibly ambiguous)
LookupInSuper(LookupResult & R,CXXRecordDecl * Class)2462 bool Sema::LookupInSuper(LookupResult &R, CXXRecordDecl *Class) {
2463 // The access-control rules we use here are essentially the rules for
2464 // doing a lookup in Class that just magically skipped the direct
2465 // members of Class itself. That is, the naming class is Class, and the
2466 // access includes the access of the base.
2467 for (const auto &BaseSpec : Class->bases()) {
2468 CXXRecordDecl *RD = cast<CXXRecordDecl>(
2469 BaseSpec.getType()->castAs<RecordType>()->getDecl());
2470 LookupResult Result(*this, R.getLookupNameInfo(), R.getLookupKind());
2471 Result.setBaseObjectType(Context.getRecordType(Class));
2472 LookupQualifiedName(Result, RD);
2473
2474 // Copy the lookup results into the target, merging the base's access into
2475 // the path access.
2476 for (auto I = Result.begin(), E = Result.end(); I != E; ++I) {
2477 R.addDecl(I.getDecl(),
2478 CXXRecordDecl::MergeAccess(BaseSpec.getAccessSpecifier(),
2479 I.getAccess()));
2480 }
2481
2482 Result.suppressDiagnostics();
2483 }
2484
2485 R.resolveKind();
2486 R.setNamingClass(Class);
2487
2488 return !R.empty();
2489 }
2490
2491 /// Produce a diagnostic describing the ambiguity that resulted
2492 /// from name lookup.
2493 ///
2494 /// \param Result The result of the ambiguous lookup to be diagnosed.
DiagnoseAmbiguousLookup(LookupResult & Result)2495 void Sema::DiagnoseAmbiguousLookup(LookupResult &Result) {
2496 assert(Result.isAmbiguous() && "Lookup result must be ambiguous");
2497
2498 DeclarationName Name = Result.getLookupName();
2499 SourceLocation NameLoc = Result.getNameLoc();
2500 SourceRange LookupRange = Result.getContextRange();
2501
2502 switch (Result.getAmbiguityKind()) {
2503 case LookupResult::AmbiguousBaseSubobjects: {
2504 CXXBasePaths *Paths = Result.getBasePaths();
2505 QualType SubobjectType = Paths->front().back().Base->getType();
2506 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobjects)
2507 << Name << SubobjectType << getAmbiguousPathsDisplayString(*Paths)
2508 << LookupRange;
2509
2510 DeclContext::lookup_iterator Found = Paths->front().Decls.begin();
2511 while (isa<CXXMethodDecl>(*Found) &&
2512 cast<CXXMethodDecl>(*Found)->isStatic())
2513 ++Found;
2514
2515 Diag((*Found)->getLocation(), diag::note_ambiguous_member_found);
2516 break;
2517 }
2518
2519 case LookupResult::AmbiguousBaseSubobjectTypes: {
2520 Diag(NameLoc, diag::err_ambiguous_member_multiple_subobject_types)
2521 << Name << LookupRange;
2522
2523 CXXBasePaths *Paths = Result.getBasePaths();
2524 std::set<Decl *> DeclsPrinted;
2525 for (CXXBasePaths::paths_iterator Path = Paths->begin(),
2526 PathEnd = Paths->end();
2527 Path != PathEnd; ++Path) {
2528 Decl *D = Path->Decls.front();
2529 if (DeclsPrinted.insert(D).second)
2530 Diag(D->getLocation(), diag::note_ambiguous_member_found);
2531 }
2532 break;
2533 }
2534
2535 case LookupResult::AmbiguousTagHiding: {
2536 Diag(NameLoc, diag::err_ambiguous_tag_hiding) << Name << LookupRange;
2537
2538 llvm::SmallPtrSet<NamedDecl*, 8> TagDecls;
2539
2540 for (auto *D : Result)
2541 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2542 TagDecls.insert(TD);
2543 Diag(TD->getLocation(), diag::note_hidden_tag);
2544 }
2545
2546 for (auto *D : Result)
2547 if (!isa<TagDecl>(D))
2548 Diag(D->getLocation(), diag::note_hiding_object);
2549
2550 // For recovery purposes, go ahead and implement the hiding.
2551 LookupResult::Filter F = Result.makeFilter();
2552 while (F.hasNext()) {
2553 if (TagDecls.count(F.next()))
2554 F.erase();
2555 }
2556 F.done();
2557 break;
2558 }
2559
2560 case LookupResult::AmbiguousReference: {
2561 Diag(NameLoc, diag::err_ambiguous_reference) << Name << LookupRange;
2562
2563 for (auto *D : Result)
2564 Diag(D->getLocation(), diag::note_ambiguous_candidate) << D;
2565 break;
2566 }
2567 }
2568 }
2569
2570 namespace {
2571 struct AssociatedLookup {
AssociatedLookup__anon4331d3480a11::AssociatedLookup2572 AssociatedLookup(Sema &S, SourceLocation InstantiationLoc,
2573 Sema::AssociatedNamespaceSet &Namespaces,
2574 Sema::AssociatedClassSet &Classes)
2575 : S(S), Namespaces(Namespaces), Classes(Classes),
2576 InstantiationLoc(InstantiationLoc) {
2577 }
2578
addClassTransitive__anon4331d3480a11::AssociatedLookup2579 bool addClassTransitive(CXXRecordDecl *RD) {
2580 Classes.insert(RD);
2581 return ClassesTransitive.insert(RD);
2582 }
2583
2584 Sema &S;
2585 Sema::AssociatedNamespaceSet &Namespaces;
2586 Sema::AssociatedClassSet &Classes;
2587 SourceLocation InstantiationLoc;
2588
2589 private:
2590 Sema::AssociatedClassSet ClassesTransitive;
2591 };
2592 } // end anonymous namespace
2593
2594 static void
2595 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType T);
2596
2597 // Given the declaration context \param Ctx of a class, class template or
2598 // enumeration, add the associated namespaces to \param Namespaces as described
2599 // in [basic.lookup.argdep]p2.
CollectEnclosingNamespace(Sema::AssociatedNamespaceSet & Namespaces,DeclContext * Ctx)2600 static void CollectEnclosingNamespace(Sema::AssociatedNamespaceSet &Namespaces,
2601 DeclContext *Ctx) {
2602 // The exact wording has been changed in C++14 as a result of
2603 // CWG 1691 (see also CWG 1690 and CWG 1692). We apply it unconditionally
2604 // to all language versions since it is possible to return a local type
2605 // from a lambda in C++11.
2606 //
2607 // C++14 [basic.lookup.argdep]p2:
2608 // If T is a class type [...]. Its associated namespaces are the innermost
2609 // enclosing namespaces of its associated classes. [...]
2610 //
2611 // If T is an enumeration type, its associated namespace is the innermost
2612 // enclosing namespace of its declaration. [...]
2613
2614 // We additionally skip inline namespaces. The innermost non-inline namespace
2615 // contains all names of all its nested inline namespaces anyway, so we can
2616 // replace the entire inline namespace tree with its root.
2617 while (!Ctx->isFileContext() || Ctx->isInlineNamespace())
2618 Ctx = Ctx->getParent();
2619
2620 Namespaces.insert(Ctx->getPrimaryContext());
2621 }
2622
2623 // Add the associated classes and namespaces for argument-dependent
2624 // lookup that involves a template argument (C++ [basic.lookup.argdep]p2).
2625 static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,const TemplateArgument & Arg)2626 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2627 const TemplateArgument &Arg) {
2628 // C++ [basic.lookup.argdep]p2, last bullet:
2629 // -- [...] ;
2630 switch (Arg.getKind()) {
2631 case TemplateArgument::Null:
2632 break;
2633
2634 case TemplateArgument::Type:
2635 // [...] the namespaces and classes associated with the types of the
2636 // template arguments provided for template type parameters (excluding
2637 // template template parameters)
2638 addAssociatedClassesAndNamespaces(Result, Arg.getAsType());
2639 break;
2640
2641 case TemplateArgument::Template:
2642 case TemplateArgument::TemplateExpansion: {
2643 // [...] the namespaces in which any template template arguments are
2644 // defined; and the classes in which any member templates used as
2645 // template template arguments are defined.
2646 TemplateName Template = Arg.getAsTemplateOrTemplatePattern();
2647 if (ClassTemplateDecl *ClassTemplate
2648 = dyn_cast<ClassTemplateDecl>(Template.getAsTemplateDecl())) {
2649 DeclContext *Ctx = ClassTemplate->getDeclContext();
2650 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2651 Result.Classes.insert(EnclosingClass);
2652 // Add the associated namespace for this class.
2653 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2654 }
2655 break;
2656 }
2657
2658 case TemplateArgument::Declaration:
2659 case TemplateArgument::Integral:
2660 case TemplateArgument::Expression:
2661 case TemplateArgument::NullPtr:
2662 // [Note: non-type template arguments do not contribute to the set of
2663 // associated namespaces. ]
2664 break;
2665
2666 case TemplateArgument::Pack:
2667 for (const auto &P : Arg.pack_elements())
2668 addAssociatedClassesAndNamespaces(Result, P);
2669 break;
2670 }
2671 }
2672
2673 // Add the associated classes and namespaces for argument-dependent lookup
2674 // with an argument of class type (C++ [basic.lookup.argdep]p2).
2675 static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,CXXRecordDecl * Class)2676 addAssociatedClassesAndNamespaces(AssociatedLookup &Result,
2677 CXXRecordDecl *Class) {
2678
2679 // Just silently ignore anything whose name is __va_list_tag.
2680 if (Class->getDeclName() == Result.S.VAListTagName)
2681 return;
2682
2683 // C++ [basic.lookup.argdep]p2:
2684 // [...]
2685 // -- If T is a class type (including unions), its associated
2686 // classes are: the class itself; the class of which it is a
2687 // member, if any; and its direct and indirect base classes.
2688 // Its associated namespaces are the innermost enclosing
2689 // namespaces of its associated classes.
2690
2691 // Add the class of which it is a member, if any.
2692 DeclContext *Ctx = Class->getDeclContext();
2693 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2694 Result.Classes.insert(EnclosingClass);
2695
2696 // Add the associated namespace for this class.
2697 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2698
2699 // -- If T is a template-id, its associated namespaces and classes are
2700 // the namespace in which the template is defined; for member
2701 // templates, the member template's class; the namespaces and classes
2702 // associated with the types of the template arguments provided for
2703 // template type parameters (excluding template template parameters); the
2704 // namespaces in which any template template arguments are defined; and
2705 // the classes in which any member templates used as template template
2706 // arguments are defined. [Note: non-type template arguments do not
2707 // contribute to the set of associated namespaces. ]
2708 if (ClassTemplateSpecializationDecl *Spec
2709 = dyn_cast<ClassTemplateSpecializationDecl>(Class)) {
2710 DeclContext *Ctx = Spec->getSpecializedTemplate()->getDeclContext();
2711 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2712 Result.Classes.insert(EnclosingClass);
2713 // Add the associated namespace for this class.
2714 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2715
2716 const TemplateArgumentList &TemplateArgs = Spec->getTemplateArgs();
2717 for (unsigned I = 0, N = TemplateArgs.size(); I != N; ++I)
2718 addAssociatedClassesAndNamespaces(Result, TemplateArgs[I]);
2719 }
2720
2721 // Add the class itself. If we've already transitively visited this class,
2722 // we don't need to visit base classes.
2723 if (!Result.addClassTransitive(Class))
2724 return;
2725
2726 // Only recurse into base classes for complete types.
2727 if (!Result.S.isCompleteType(Result.InstantiationLoc,
2728 Result.S.Context.getRecordType(Class)))
2729 return;
2730
2731 // Add direct and indirect base classes along with their associated
2732 // namespaces.
2733 SmallVector<CXXRecordDecl *, 32> Bases;
2734 Bases.push_back(Class);
2735 while (!Bases.empty()) {
2736 // Pop this class off the stack.
2737 Class = Bases.pop_back_val();
2738
2739 // Visit the base classes.
2740 for (const auto &Base : Class->bases()) {
2741 const RecordType *BaseType = Base.getType()->getAs<RecordType>();
2742 // In dependent contexts, we do ADL twice, and the first time around,
2743 // the base type might be a dependent TemplateSpecializationType, or a
2744 // TemplateTypeParmType. If that happens, simply ignore it.
2745 // FIXME: If we want to support export, we probably need to add the
2746 // namespace of the template in a TemplateSpecializationType, or even
2747 // the classes and namespaces of known non-dependent arguments.
2748 if (!BaseType)
2749 continue;
2750 CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(BaseType->getDecl());
2751 if (Result.addClassTransitive(BaseDecl)) {
2752 // Find the associated namespace for this base class.
2753 DeclContext *BaseCtx = BaseDecl->getDeclContext();
2754 CollectEnclosingNamespace(Result.Namespaces, BaseCtx);
2755
2756 // Make sure we visit the bases of this base class.
2757 if (BaseDecl->bases_begin() != BaseDecl->bases_end())
2758 Bases.push_back(BaseDecl);
2759 }
2760 }
2761 }
2762 }
2763
2764 // Add the associated classes and namespaces for
2765 // argument-dependent lookup with an argument of type T
2766 // (C++ [basic.lookup.koenig]p2).
2767 static void
addAssociatedClassesAndNamespaces(AssociatedLookup & Result,QualType Ty)2768 addAssociatedClassesAndNamespaces(AssociatedLookup &Result, QualType Ty) {
2769 // C++ [basic.lookup.koenig]p2:
2770 //
2771 // For each argument type T in the function call, there is a set
2772 // of zero or more associated namespaces and a set of zero or more
2773 // associated classes to be considered. The sets of namespaces and
2774 // classes is determined entirely by the types of the function
2775 // arguments (and the namespace of any template template
2776 // argument). Typedef names and using-declarations used to specify
2777 // the types do not contribute to this set. The sets of namespaces
2778 // and classes are determined in the following way:
2779
2780 SmallVector<const Type *, 16> Queue;
2781 const Type *T = Ty->getCanonicalTypeInternal().getTypePtr();
2782
2783 while (true) {
2784 switch (T->getTypeClass()) {
2785
2786 #define TYPE(Class, Base)
2787 #define DEPENDENT_TYPE(Class, Base) case Type::Class:
2788 #define NON_CANONICAL_TYPE(Class, Base) case Type::Class:
2789 #define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) case Type::Class:
2790 #define ABSTRACT_TYPE(Class, Base)
2791 #include "clang/AST/TypeNodes.inc"
2792 // T is canonical. We can also ignore dependent types because
2793 // we don't need to do ADL at the definition point, but if we
2794 // wanted to implement template export (or if we find some other
2795 // use for associated classes and namespaces...) this would be
2796 // wrong.
2797 break;
2798
2799 // -- If T is a pointer to U or an array of U, its associated
2800 // namespaces and classes are those associated with U.
2801 case Type::Pointer:
2802 T = cast<PointerType>(T)->getPointeeType().getTypePtr();
2803 continue;
2804 case Type::ConstantArray:
2805 case Type::IncompleteArray:
2806 case Type::VariableArray:
2807 T = cast<ArrayType>(T)->getElementType().getTypePtr();
2808 continue;
2809
2810 // -- If T is a fundamental type, its associated sets of
2811 // namespaces and classes are both empty.
2812 case Type::Builtin:
2813 break;
2814
2815 // -- If T is a class type (including unions), its associated
2816 // classes are: the class itself; the class of which it is
2817 // a member, if any; and its direct and indirect base classes.
2818 // Its associated namespaces are the innermost enclosing
2819 // namespaces of its associated classes.
2820 case Type::Record: {
2821 CXXRecordDecl *Class =
2822 cast<CXXRecordDecl>(cast<RecordType>(T)->getDecl());
2823 addAssociatedClassesAndNamespaces(Result, Class);
2824 break;
2825 }
2826
2827 // -- If T is an enumeration type, its associated namespace
2828 // is the innermost enclosing namespace of its declaration.
2829 // If it is a class member, its associated class is the
2830 // member’s class; else it has no associated class.
2831 case Type::Enum: {
2832 EnumDecl *Enum = cast<EnumType>(T)->getDecl();
2833
2834 DeclContext *Ctx = Enum->getDeclContext();
2835 if (CXXRecordDecl *EnclosingClass = dyn_cast<CXXRecordDecl>(Ctx))
2836 Result.Classes.insert(EnclosingClass);
2837
2838 // Add the associated namespace for this enumeration.
2839 CollectEnclosingNamespace(Result.Namespaces, Ctx);
2840
2841 break;
2842 }
2843
2844 // -- If T is a function type, its associated namespaces and
2845 // classes are those associated with the function parameter
2846 // types and those associated with the return type.
2847 case Type::FunctionProto: {
2848 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2849 for (const auto &Arg : Proto->param_types())
2850 Queue.push_back(Arg.getTypePtr());
2851 // fallthrough
2852 LLVM_FALLTHROUGH;
2853 }
2854 case Type::FunctionNoProto: {
2855 const FunctionType *FnType = cast<FunctionType>(T);
2856 T = FnType->getReturnType().getTypePtr();
2857 continue;
2858 }
2859
2860 // -- If T is a pointer to a member function of a class X, its
2861 // associated namespaces and classes are those associated
2862 // with the function parameter types and return type,
2863 // together with those associated with X.
2864 //
2865 // -- If T is a pointer to a data member of class X, its
2866 // associated namespaces and classes are those associated
2867 // with the member type together with those associated with
2868 // X.
2869 case Type::MemberPointer: {
2870 const MemberPointerType *MemberPtr = cast<MemberPointerType>(T);
2871
2872 // Queue up the class type into which this points.
2873 Queue.push_back(MemberPtr->getClass());
2874
2875 // And directly continue with the pointee type.
2876 T = MemberPtr->getPointeeType().getTypePtr();
2877 continue;
2878 }
2879
2880 // As an extension, treat this like a normal pointer.
2881 case Type::BlockPointer:
2882 T = cast<BlockPointerType>(T)->getPointeeType().getTypePtr();
2883 continue;
2884
2885 // References aren't covered by the standard, but that's such an
2886 // obvious defect that we cover them anyway.
2887 case Type::LValueReference:
2888 case Type::RValueReference:
2889 T = cast<ReferenceType>(T)->getPointeeType().getTypePtr();
2890 continue;
2891
2892 // These are fundamental types.
2893 case Type::Vector:
2894 case Type::ExtVector:
2895 case Type::ConstantMatrix:
2896 case Type::Complex:
2897 case Type::ExtInt:
2898 break;
2899
2900 // Non-deduced auto types only get here for error cases.
2901 case Type::Auto:
2902 case Type::DeducedTemplateSpecialization:
2903 break;
2904
2905 // If T is an Objective-C object or interface type, or a pointer to an
2906 // object or interface type, the associated namespace is the global
2907 // namespace.
2908 case Type::ObjCObject:
2909 case Type::ObjCInterface:
2910 case Type::ObjCObjectPointer:
2911 Result.Namespaces.insert(Result.S.Context.getTranslationUnitDecl());
2912 break;
2913
2914 // Atomic types are just wrappers; use the associations of the
2915 // contained type.
2916 case Type::Atomic:
2917 T = cast<AtomicType>(T)->getValueType().getTypePtr();
2918 continue;
2919 case Type::Pipe:
2920 T = cast<PipeType>(T)->getElementType().getTypePtr();
2921 continue;
2922 }
2923
2924 if (Queue.empty())
2925 break;
2926 T = Queue.pop_back_val();
2927 }
2928 }
2929
2930 /// Find the associated classes and namespaces for
2931 /// argument-dependent lookup for a call with the given set of
2932 /// arguments.
2933 ///
2934 /// This routine computes the sets of associated classes and associated
2935 /// namespaces searched by argument-dependent lookup
2936 /// (C++ [basic.lookup.argdep]) for a given set of arguments.
FindAssociatedClassesAndNamespaces(SourceLocation InstantiationLoc,ArrayRef<Expr * > Args,AssociatedNamespaceSet & AssociatedNamespaces,AssociatedClassSet & AssociatedClasses)2937 void Sema::FindAssociatedClassesAndNamespaces(
2938 SourceLocation InstantiationLoc, ArrayRef<Expr *> Args,
2939 AssociatedNamespaceSet &AssociatedNamespaces,
2940 AssociatedClassSet &AssociatedClasses) {
2941 AssociatedNamespaces.clear();
2942 AssociatedClasses.clear();
2943
2944 AssociatedLookup Result(*this, InstantiationLoc,
2945 AssociatedNamespaces, AssociatedClasses);
2946
2947 // C++ [basic.lookup.koenig]p2:
2948 // For each argument type T in the function call, there is a set
2949 // of zero or more associated namespaces and a set of zero or more
2950 // associated classes to be considered. The sets of namespaces and
2951 // classes is determined entirely by the types of the function
2952 // arguments (and the namespace of any template template
2953 // argument).
2954 for (unsigned ArgIdx = 0; ArgIdx != Args.size(); ++ArgIdx) {
2955 Expr *Arg = Args[ArgIdx];
2956
2957 if (Arg->getType() != Context.OverloadTy) {
2958 addAssociatedClassesAndNamespaces(Result, Arg->getType());
2959 continue;
2960 }
2961
2962 // [...] In addition, if the argument is the name or address of a
2963 // set of overloaded functions and/or function templates, its
2964 // associated classes and namespaces are the union of those
2965 // associated with each of the members of the set: the namespace
2966 // in which the function or function template is defined and the
2967 // classes and namespaces associated with its (non-dependent)
2968 // parameter types and return type.
2969 OverloadExpr *OE = OverloadExpr::find(Arg).Expression;
2970
2971 for (const NamedDecl *D : OE->decls()) {
2972 // Look through any using declarations to find the underlying function.
2973 const FunctionDecl *FDecl = D->getUnderlyingDecl()->getAsFunction();
2974
2975 // Add the classes and namespaces associated with the parameter
2976 // types and return type of this function.
2977 addAssociatedClassesAndNamespaces(Result, FDecl->getType());
2978 }
2979 }
2980 }
2981
LookupSingleName(Scope * S,DeclarationName Name,SourceLocation Loc,LookupNameKind NameKind,RedeclarationKind Redecl)2982 NamedDecl *Sema::LookupSingleName(Scope *S, DeclarationName Name,
2983 SourceLocation Loc,
2984 LookupNameKind NameKind,
2985 RedeclarationKind Redecl) {
2986 LookupResult R(*this, Name, Loc, NameKind, Redecl);
2987 LookupName(R, S);
2988 return R.getAsSingle<NamedDecl>();
2989 }
2990
2991 /// Find the protocol with the given name, if any.
LookupProtocol(IdentifierInfo * II,SourceLocation IdLoc,RedeclarationKind Redecl)2992 ObjCProtocolDecl *Sema::LookupProtocol(IdentifierInfo *II,
2993 SourceLocation IdLoc,
2994 RedeclarationKind Redecl) {
2995 Decl *D = LookupSingleName(TUScope, II, IdLoc,
2996 LookupObjCProtocolName, Redecl);
2997 return cast_or_null<ObjCProtocolDecl>(D);
2998 }
2999
LookupOverloadedOperatorName(OverloadedOperatorKind Op,Scope * S,UnresolvedSetImpl & Functions)3000 void Sema::LookupOverloadedOperatorName(OverloadedOperatorKind Op, Scope *S,
3001 UnresolvedSetImpl &Functions) {
3002 // C++ [over.match.oper]p3:
3003 // -- The set of non-member candidates is the result of the
3004 // unqualified lookup of operator@ in the context of the
3005 // expression according to the usual rules for name lookup in
3006 // unqualified function calls (3.4.2) except that all member
3007 // functions are ignored.
3008 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3009 LookupResult Operators(*this, OpName, SourceLocation(), LookupOperatorName);
3010 LookupName(Operators, S);
3011
3012 assert(!Operators.isAmbiguous() && "Operator lookup cannot be ambiguous");
3013 Functions.append(Operators.begin(), Operators.end());
3014 }
3015
LookupSpecialMember(CXXRecordDecl * RD,CXXSpecialMember SM,bool ConstArg,bool VolatileArg,bool RValueThis,bool ConstThis,bool VolatileThis)3016 Sema::SpecialMemberOverloadResult Sema::LookupSpecialMember(CXXRecordDecl *RD,
3017 CXXSpecialMember SM,
3018 bool ConstArg,
3019 bool VolatileArg,
3020 bool RValueThis,
3021 bool ConstThis,
3022 bool VolatileThis) {
3023 assert(CanDeclareSpecialMemberFunction(RD) &&
3024 "doing special member lookup into record that isn't fully complete");
3025 RD = RD->getDefinition();
3026 if (RValueThis || ConstThis || VolatileThis)
3027 assert((SM == CXXCopyAssignment || SM == CXXMoveAssignment) &&
3028 "constructors and destructors always have unqualified lvalue this");
3029 if (ConstArg || VolatileArg)
3030 assert((SM != CXXDefaultConstructor && SM != CXXDestructor) &&
3031 "parameter-less special members can't have qualified arguments");
3032
3033 // FIXME: Get the caller to pass in a location for the lookup.
3034 SourceLocation LookupLoc = RD->getLocation();
3035
3036 llvm::FoldingSetNodeID ID;
3037 ID.AddPointer(RD);
3038 ID.AddInteger(SM);
3039 ID.AddInteger(ConstArg);
3040 ID.AddInteger(VolatileArg);
3041 ID.AddInteger(RValueThis);
3042 ID.AddInteger(ConstThis);
3043 ID.AddInteger(VolatileThis);
3044
3045 void *InsertPoint;
3046 SpecialMemberOverloadResultEntry *Result =
3047 SpecialMemberCache.FindNodeOrInsertPos(ID, InsertPoint);
3048
3049 // This was already cached
3050 if (Result)
3051 return *Result;
3052
3053 Result = BumpAlloc.Allocate<SpecialMemberOverloadResultEntry>();
3054 Result = new (Result) SpecialMemberOverloadResultEntry(ID);
3055 SpecialMemberCache.InsertNode(Result, InsertPoint);
3056
3057 if (SM == CXXDestructor) {
3058 if (RD->needsImplicitDestructor()) {
3059 runWithSufficientStackSpace(RD->getLocation(), [&] {
3060 DeclareImplicitDestructor(RD);
3061 });
3062 }
3063 CXXDestructorDecl *DD = RD->getDestructor();
3064 Result->setMethod(DD);
3065 Result->setKind(DD && !DD->isDeleted()
3066 ? SpecialMemberOverloadResult::Success
3067 : SpecialMemberOverloadResult::NoMemberOrDeleted);
3068 return *Result;
3069 }
3070
3071 // Prepare for overload resolution. Here we construct a synthetic argument
3072 // if necessary and make sure that implicit functions are declared.
3073 CanQualType CanTy = Context.getCanonicalType(Context.getTagDeclType(RD));
3074 DeclarationName Name;
3075 Expr *Arg = nullptr;
3076 unsigned NumArgs;
3077
3078 QualType ArgType = CanTy;
3079 ExprValueKind VK = VK_LValue;
3080
3081 if (SM == CXXDefaultConstructor) {
3082 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3083 NumArgs = 0;
3084 if (RD->needsImplicitDefaultConstructor()) {
3085 runWithSufficientStackSpace(RD->getLocation(), [&] {
3086 DeclareImplicitDefaultConstructor(RD);
3087 });
3088 }
3089 } else {
3090 if (SM == CXXCopyConstructor || SM == CXXMoveConstructor) {
3091 Name = Context.DeclarationNames.getCXXConstructorName(CanTy);
3092 if (RD->needsImplicitCopyConstructor()) {
3093 runWithSufficientStackSpace(RD->getLocation(), [&] {
3094 DeclareImplicitCopyConstructor(RD);
3095 });
3096 }
3097 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveConstructor()) {
3098 runWithSufficientStackSpace(RD->getLocation(), [&] {
3099 DeclareImplicitMoveConstructor(RD);
3100 });
3101 }
3102 } else {
3103 Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
3104 if (RD->needsImplicitCopyAssignment()) {
3105 runWithSufficientStackSpace(RD->getLocation(), [&] {
3106 DeclareImplicitCopyAssignment(RD);
3107 });
3108 }
3109 if (getLangOpts().CPlusPlus11 && RD->needsImplicitMoveAssignment()) {
3110 runWithSufficientStackSpace(RD->getLocation(), [&] {
3111 DeclareImplicitMoveAssignment(RD);
3112 });
3113 }
3114 }
3115
3116 if (ConstArg)
3117 ArgType.addConst();
3118 if (VolatileArg)
3119 ArgType.addVolatile();
3120
3121 // This isn't /really/ specified by the standard, but it's implied
3122 // we should be working from an RValue in the case of move to ensure
3123 // that we prefer to bind to rvalue references, and an LValue in the
3124 // case of copy to ensure we don't bind to rvalue references.
3125 // Possibly an XValue is actually correct in the case of move, but
3126 // there is no semantic difference for class types in this restricted
3127 // case.
3128 if (SM == CXXCopyConstructor || SM == CXXCopyAssignment)
3129 VK = VK_LValue;
3130 else
3131 VK = VK_RValue;
3132 }
3133
3134 OpaqueValueExpr FakeArg(LookupLoc, ArgType, VK);
3135
3136 if (SM != CXXDefaultConstructor) {
3137 NumArgs = 1;
3138 Arg = &FakeArg;
3139 }
3140
3141 // Create the object argument
3142 QualType ThisTy = CanTy;
3143 if (ConstThis)
3144 ThisTy.addConst();
3145 if (VolatileThis)
3146 ThisTy.addVolatile();
3147 Expr::Classification Classification =
3148 OpaqueValueExpr(LookupLoc, ThisTy,
3149 RValueThis ? VK_RValue : VK_LValue).Classify(Context);
3150
3151 // Now we perform lookup on the name we computed earlier and do overload
3152 // resolution. Lookup is only performed directly into the class since there
3153 // will always be a (possibly implicit) declaration to shadow any others.
3154 OverloadCandidateSet OCS(LookupLoc, OverloadCandidateSet::CSK_Normal);
3155 DeclContext::lookup_result R = RD->lookup(Name);
3156
3157 if (R.empty()) {
3158 // We might have no default constructor because we have a lambda's closure
3159 // type, rather than because there's some other declared constructor.
3160 // Every class has a copy/move constructor, copy/move assignment, and
3161 // destructor.
3162 assert(SM == CXXDefaultConstructor &&
3163 "lookup for a constructor or assignment operator was empty");
3164 Result->setMethod(nullptr);
3165 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3166 return *Result;
3167 }
3168
3169 // Copy the candidates as our processing of them may load new declarations
3170 // from an external source and invalidate lookup_result.
3171 SmallVector<NamedDecl *, 8> Candidates(R.begin(), R.end());
3172
3173 for (NamedDecl *CandDecl : Candidates) {
3174 if (CandDecl->isInvalidDecl())
3175 continue;
3176
3177 DeclAccessPair Cand = DeclAccessPair::make(CandDecl, AS_public);
3178 auto CtorInfo = getConstructorInfo(Cand);
3179 if (CXXMethodDecl *M = dyn_cast<CXXMethodDecl>(Cand->getUnderlyingDecl())) {
3180 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3181 AddMethodCandidate(M, Cand, RD, ThisTy, Classification,
3182 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3183 else if (CtorInfo)
3184 AddOverloadCandidate(CtorInfo.Constructor, CtorInfo.FoundDecl,
3185 llvm::makeArrayRef(&Arg, NumArgs), OCS,
3186 /*SuppressUserConversions*/ true);
3187 else
3188 AddOverloadCandidate(M, Cand, llvm::makeArrayRef(&Arg, NumArgs), OCS,
3189 /*SuppressUserConversions*/ true);
3190 } else if (FunctionTemplateDecl *Tmpl =
3191 dyn_cast<FunctionTemplateDecl>(Cand->getUnderlyingDecl())) {
3192 if (SM == CXXCopyAssignment || SM == CXXMoveAssignment)
3193 AddMethodTemplateCandidate(
3194 Tmpl, Cand, RD, nullptr, ThisTy, Classification,
3195 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3196 else if (CtorInfo)
3197 AddTemplateOverloadCandidate(
3198 CtorInfo.ConstructorTmpl, CtorInfo.FoundDecl, nullptr,
3199 llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3200 else
3201 AddTemplateOverloadCandidate(
3202 Tmpl, Cand, nullptr, llvm::makeArrayRef(&Arg, NumArgs), OCS, true);
3203 } else {
3204 assert(isa<UsingDecl>(Cand.getDecl()) &&
3205 "illegal Kind of operator = Decl");
3206 }
3207 }
3208
3209 OverloadCandidateSet::iterator Best;
3210 switch (OCS.BestViableFunction(*this, LookupLoc, Best)) {
3211 case OR_Success:
3212 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3213 Result->setKind(SpecialMemberOverloadResult::Success);
3214 break;
3215
3216 case OR_Deleted:
3217 Result->setMethod(cast<CXXMethodDecl>(Best->Function));
3218 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3219 break;
3220
3221 case OR_Ambiguous:
3222 Result->setMethod(nullptr);
3223 Result->setKind(SpecialMemberOverloadResult::Ambiguous);
3224 break;
3225
3226 case OR_No_Viable_Function:
3227 Result->setMethod(nullptr);
3228 Result->setKind(SpecialMemberOverloadResult::NoMemberOrDeleted);
3229 break;
3230 }
3231
3232 return *Result;
3233 }
3234
3235 /// Look up the default constructor for the given class.
LookupDefaultConstructor(CXXRecordDecl * Class)3236 CXXConstructorDecl *Sema::LookupDefaultConstructor(CXXRecordDecl *Class) {
3237 SpecialMemberOverloadResult Result =
3238 LookupSpecialMember(Class, CXXDefaultConstructor, false, false, false,
3239 false, false);
3240
3241 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3242 }
3243
3244 /// Look up the copying constructor for the given class.
LookupCopyingConstructor(CXXRecordDecl * Class,unsigned Quals)3245 CXXConstructorDecl *Sema::LookupCopyingConstructor(CXXRecordDecl *Class,
3246 unsigned Quals) {
3247 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3248 "non-const, non-volatile qualifiers for copy ctor arg");
3249 SpecialMemberOverloadResult Result =
3250 LookupSpecialMember(Class, CXXCopyConstructor, Quals & Qualifiers::Const,
3251 Quals & Qualifiers::Volatile, false, false, false);
3252
3253 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3254 }
3255
3256 /// Look up the moving constructor for the given class.
LookupMovingConstructor(CXXRecordDecl * Class,unsigned Quals)3257 CXXConstructorDecl *Sema::LookupMovingConstructor(CXXRecordDecl *Class,
3258 unsigned Quals) {
3259 SpecialMemberOverloadResult Result =
3260 LookupSpecialMember(Class, CXXMoveConstructor, Quals & Qualifiers::Const,
3261 Quals & Qualifiers::Volatile, false, false, false);
3262
3263 return cast_or_null<CXXConstructorDecl>(Result.getMethod());
3264 }
3265
3266 /// Look up the constructors for the given class.
LookupConstructors(CXXRecordDecl * Class)3267 DeclContext::lookup_result Sema::LookupConstructors(CXXRecordDecl *Class) {
3268 // If the implicit constructors have not yet been declared, do so now.
3269 if (CanDeclareSpecialMemberFunction(Class)) {
3270 runWithSufficientStackSpace(Class->getLocation(), [&] {
3271 if (Class->needsImplicitDefaultConstructor())
3272 DeclareImplicitDefaultConstructor(Class);
3273 if (Class->needsImplicitCopyConstructor())
3274 DeclareImplicitCopyConstructor(Class);
3275 if (getLangOpts().CPlusPlus11 && Class->needsImplicitMoveConstructor())
3276 DeclareImplicitMoveConstructor(Class);
3277 });
3278 }
3279
3280 CanQualType T = Context.getCanonicalType(Context.getTypeDeclType(Class));
3281 DeclarationName Name = Context.DeclarationNames.getCXXConstructorName(T);
3282 return Class->lookup(Name);
3283 }
3284
3285 /// Look up the copying assignment operator for the given class.
LookupCopyingAssignment(CXXRecordDecl * Class,unsigned Quals,bool RValueThis,unsigned ThisQuals)3286 CXXMethodDecl *Sema::LookupCopyingAssignment(CXXRecordDecl *Class,
3287 unsigned Quals, bool RValueThis,
3288 unsigned ThisQuals) {
3289 assert(!(Quals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3290 "non-const, non-volatile qualifiers for copy assignment arg");
3291 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3292 "non-const, non-volatile qualifiers for copy assignment this");
3293 SpecialMemberOverloadResult Result =
3294 LookupSpecialMember(Class, CXXCopyAssignment, Quals & Qualifiers::Const,
3295 Quals & Qualifiers::Volatile, RValueThis,
3296 ThisQuals & Qualifiers::Const,
3297 ThisQuals & Qualifiers::Volatile);
3298
3299 return Result.getMethod();
3300 }
3301
3302 /// Look up the moving assignment operator for the given class.
LookupMovingAssignment(CXXRecordDecl * Class,unsigned Quals,bool RValueThis,unsigned ThisQuals)3303 CXXMethodDecl *Sema::LookupMovingAssignment(CXXRecordDecl *Class,
3304 unsigned Quals,
3305 bool RValueThis,
3306 unsigned ThisQuals) {
3307 assert(!(ThisQuals & ~(Qualifiers::Const | Qualifiers::Volatile)) &&
3308 "non-const, non-volatile qualifiers for copy assignment this");
3309 SpecialMemberOverloadResult Result =
3310 LookupSpecialMember(Class, CXXMoveAssignment, Quals & Qualifiers::Const,
3311 Quals & Qualifiers::Volatile, RValueThis,
3312 ThisQuals & Qualifiers::Const,
3313 ThisQuals & Qualifiers::Volatile);
3314
3315 return Result.getMethod();
3316 }
3317
3318 /// Look for the destructor of the given class.
3319 ///
3320 /// During semantic analysis, this routine should be used in lieu of
3321 /// CXXRecordDecl::getDestructor().
3322 ///
3323 /// \returns The destructor for this class.
LookupDestructor(CXXRecordDecl * Class)3324 CXXDestructorDecl *Sema::LookupDestructor(CXXRecordDecl *Class) {
3325 return cast<CXXDestructorDecl>(LookupSpecialMember(Class, CXXDestructor,
3326 false, false, false,
3327 false, false).getMethod());
3328 }
3329
3330 /// LookupLiteralOperator - Determine which literal operator should be used for
3331 /// a user-defined literal, per C++11 [lex.ext].
3332 ///
3333 /// Normal overload resolution is not used to select which literal operator to
3334 /// call for a user-defined literal. Look up the provided literal operator name,
3335 /// and filter the results to the appropriate set for the given argument types.
3336 Sema::LiteralOperatorLookupResult
LookupLiteralOperator(Scope * S,LookupResult & R,ArrayRef<QualType> ArgTys,bool AllowRaw,bool AllowTemplate,bool AllowStringTemplatePack,bool DiagnoseMissing,StringLiteral * StringLit)3337 Sema::LookupLiteralOperator(Scope *S, LookupResult &R,
3338 ArrayRef<QualType> ArgTys, bool AllowRaw,
3339 bool AllowTemplate, bool AllowStringTemplatePack,
3340 bool DiagnoseMissing, StringLiteral *StringLit) {
3341 LookupName(R, S);
3342 assert(R.getResultKind() != LookupResult::Ambiguous &&
3343 "literal operator lookup can't be ambiguous");
3344
3345 // Filter the lookup results appropriately.
3346 LookupResult::Filter F = R.makeFilter();
3347
3348 bool AllowCooked = true;
3349 bool FoundRaw = false;
3350 bool FoundTemplate = false;
3351 bool FoundStringTemplatePack = false;
3352 bool FoundCooked = false;
3353
3354 while (F.hasNext()) {
3355 Decl *D = F.next();
3356 if (UsingShadowDecl *USD = dyn_cast<UsingShadowDecl>(D))
3357 D = USD->getTargetDecl();
3358
3359 // If the declaration we found is invalid, skip it.
3360 if (D->isInvalidDecl()) {
3361 F.erase();
3362 continue;
3363 }
3364
3365 bool IsRaw = false;
3366 bool IsTemplate = false;
3367 bool IsStringTemplatePack = false;
3368 bool IsCooked = false;
3369
3370 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3371 if (FD->getNumParams() == 1 &&
3372 FD->getParamDecl(0)->getType()->getAs<PointerType>())
3373 IsRaw = true;
3374 else if (FD->getNumParams() == ArgTys.size()) {
3375 IsCooked = true;
3376 for (unsigned ArgIdx = 0; ArgIdx != ArgTys.size(); ++ArgIdx) {
3377 QualType ParamTy = FD->getParamDecl(ArgIdx)->getType();
3378 if (!Context.hasSameUnqualifiedType(ArgTys[ArgIdx], ParamTy)) {
3379 IsCooked = false;
3380 break;
3381 }
3382 }
3383 }
3384 }
3385 if (FunctionTemplateDecl *FD = dyn_cast<FunctionTemplateDecl>(D)) {
3386 TemplateParameterList *Params = FD->getTemplateParameters();
3387 if (Params->size() == 1) {
3388 IsTemplate = true;
3389
3390 // A string literal template is only considered if the string literal
3391 // is a well-formed template argument for the template parameter.
3392 if (StringLit) {
3393 SFINAETrap Trap(*this);
3394 SmallVector<TemplateArgument, 1> Checked;
3395 TemplateArgumentLoc Arg(TemplateArgument(StringLit), StringLit);
3396 if (CheckTemplateArgument(Params->getParam(0), Arg, FD,
3397 R.getNameLoc(), R.getNameLoc(), 0,
3398 Checked) ||
3399 Trap.hasErrorOccurred())
3400 IsTemplate = false;
3401 }
3402 } else {
3403 IsStringTemplatePack = true;
3404 }
3405 }
3406
3407 if (AllowTemplate && StringLit && IsTemplate) {
3408 FoundTemplate = true;
3409 AllowRaw = false;
3410 AllowCooked = false;
3411 AllowStringTemplatePack = false;
3412 if (FoundRaw || FoundCooked || FoundStringTemplatePack) {
3413 F.restart();
3414 FoundRaw = FoundCooked = FoundStringTemplatePack = false;
3415 }
3416 } else if (AllowCooked && IsCooked) {
3417 FoundCooked = true;
3418 AllowRaw = false;
3419 AllowTemplate = StringLit;
3420 AllowStringTemplatePack = false;
3421 if (FoundRaw || FoundTemplate || FoundStringTemplatePack) {
3422 // Go through again and remove the raw and template decls we've
3423 // already found.
3424 F.restart();
3425 FoundRaw = FoundTemplate = FoundStringTemplatePack = false;
3426 }
3427 } else if (AllowRaw && IsRaw) {
3428 FoundRaw = true;
3429 } else if (AllowTemplate && IsTemplate) {
3430 FoundTemplate = true;
3431 } else if (AllowStringTemplatePack && IsStringTemplatePack) {
3432 FoundStringTemplatePack = true;
3433 } else {
3434 F.erase();
3435 }
3436 }
3437
3438 F.done();
3439
3440 // Per C++20 [lex.ext]p5, we prefer the template form over the non-template
3441 // form for string literal operator templates.
3442 if (StringLit && FoundTemplate)
3443 return LOLR_Template;
3444
3445 // C++11 [lex.ext]p3, p4: If S contains a literal operator with a matching
3446 // parameter type, that is used in preference to a raw literal operator
3447 // or literal operator template.
3448 if (FoundCooked)
3449 return LOLR_Cooked;
3450
3451 // C++11 [lex.ext]p3, p4: S shall contain a raw literal operator or a literal
3452 // operator template, but not both.
3453 if (FoundRaw && FoundTemplate) {
3454 Diag(R.getNameLoc(), diag::err_ovl_ambiguous_call) << R.getLookupName();
3455 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
3456 NoteOverloadCandidate(*I, (*I)->getUnderlyingDecl()->getAsFunction());
3457 return LOLR_Error;
3458 }
3459
3460 if (FoundRaw)
3461 return LOLR_Raw;
3462
3463 if (FoundTemplate)
3464 return LOLR_Template;
3465
3466 if (FoundStringTemplatePack)
3467 return LOLR_StringTemplatePack;
3468
3469 // Didn't find anything we could use.
3470 if (DiagnoseMissing) {
3471 Diag(R.getNameLoc(), diag::err_ovl_no_viable_literal_operator)
3472 << R.getLookupName() << (int)ArgTys.size() << ArgTys[0]
3473 << (ArgTys.size() == 2 ? ArgTys[1] : QualType()) << AllowRaw
3474 << (AllowTemplate || AllowStringTemplatePack);
3475 return LOLR_Error;
3476 }
3477
3478 return LOLR_ErrorNoDiagnostic;
3479 }
3480
insert(NamedDecl * New)3481 void ADLResult::insert(NamedDecl *New) {
3482 NamedDecl *&Old = Decls[cast<NamedDecl>(New->getCanonicalDecl())];
3483
3484 // If we haven't yet seen a decl for this key, or the last decl
3485 // was exactly this one, we're done.
3486 if (Old == nullptr || Old == New) {
3487 Old = New;
3488 return;
3489 }
3490
3491 // Otherwise, decide which is a more recent redeclaration.
3492 FunctionDecl *OldFD = Old->getAsFunction();
3493 FunctionDecl *NewFD = New->getAsFunction();
3494
3495 FunctionDecl *Cursor = NewFD;
3496 while (true) {
3497 Cursor = Cursor->getPreviousDecl();
3498
3499 // If we got to the end without finding OldFD, OldFD is the newer
3500 // declaration; leave things as they are.
3501 if (!Cursor) return;
3502
3503 // If we do find OldFD, then NewFD is newer.
3504 if (Cursor == OldFD) break;
3505
3506 // Otherwise, keep looking.
3507 }
3508
3509 Old = New;
3510 }
3511
ArgumentDependentLookup(DeclarationName Name,SourceLocation Loc,ArrayRef<Expr * > Args,ADLResult & Result)3512 void Sema::ArgumentDependentLookup(DeclarationName Name, SourceLocation Loc,
3513 ArrayRef<Expr *> Args, ADLResult &Result) {
3514 // Find all of the associated namespaces and classes based on the
3515 // arguments we have.
3516 AssociatedNamespaceSet AssociatedNamespaces;
3517 AssociatedClassSet AssociatedClasses;
3518 FindAssociatedClassesAndNamespaces(Loc, Args,
3519 AssociatedNamespaces,
3520 AssociatedClasses);
3521
3522 // C++ [basic.lookup.argdep]p3:
3523 // Let X be the lookup set produced by unqualified lookup (3.4.1)
3524 // and let Y be the lookup set produced by argument dependent
3525 // lookup (defined as follows). If X contains [...] then Y is
3526 // empty. Otherwise Y is the set of declarations found in the
3527 // namespaces associated with the argument types as described
3528 // below. The set of declarations found by the lookup of the name
3529 // is the union of X and Y.
3530 //
3531 // Here, we compute Y and add its members to the overloaded
3532 // candidate set.
3533 for (auto *NS : AssociatedNamespaces) {
3534 // When considering an associated namespace, the lookup is the
3535 // same as the lookup performed when the associated namespace is
3536 // used as a qualifier (3.4.3.2) except that:
3537 //
3538 // -- Any using-directives in the associated namespace are
3539 // ignored.
3540 //
3541 // -- Any namespace-scope friend functions declared in
3542 // associated classes are visible within their respective
3543 // namespaces even if they are not visible during an ordinary
3544 // lookup (11.4).
3545 DeclContext::lookup_result R = NS->lookup(Name);
3546 for (auto *D : R) {
3547 auto *Underlying = D;
3548 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
3549 Underlying = USD->getTargetDecl();
3550
3551 if (!isa<FunctionDecl>(Underlying) &&
3552 !isa<FunctionTemplateDecl>(Underlying))
3553 continue;
3554
3555 // The declaration is visible to argument-dependent lookup if either
3556 // it's ordinarily visible or declared as a friend in an associated
3557 // class.
3558 bool Visible = false;
3559 for (D = D->getMostRecentDecl(); D;
3560 D = cast_or_null<NamedDecl>(D->getPreviousDecl())) {
3561 if (D->getIdentifierNamespace() & Decl::IDNS_Ordinary) {
3562 if (isVisible(D)) {
3563 Visible = true;
3564 break;
3565 }
3566 } else if (D->getFriendObjectKind()) {
3567 auto *RD = cast<CXXRecordDecl>(D->getLexicalDeclContext());
3568 if (AssociatedClasses.count(RD) && isVisible(D)) {
3569 Visible = true;
3570 break;
3571 }
3572 }
3573 }
3574
3575 // FIXME: Preserve D as the FoundDecl.
3576 if (Visible)
3577 Result.insert(Underlying);
3578 }
3579 }
3580 }
3581
3582 //----------------------------------------------------------------------------
3583 // Search for all visible declarations.
3584 //----------------------------------------------------------------------------
~VisibleDeclConsumer()3585 VisibleDeclConsumer::~VisibleDeclConsumer() { }
3586
includeHiddenDecls() const3587 bool VisibleDeclConsumer::includeHiddenDecls() const { return false; }
3588
3589 namespace {
3590
3591 class ShadowContextRAII;
3592
3593 class VisibleDeclsRecord {
3594 public:
3595 /// An entry in the shadow map, which is optimized to store a
3596 /// single declaration (the common case) but can also store a list
3597 /// of declarations.
3598 typedef llvm::TinyPtrVector<NamedDecl*> ShadowMapEntry;
3599
3600 private:
3601 /// A mapping from declaration names to the declarations that have
3602 /// this name within a particular scope.
3603 typedef llvm::DenseMap<DeclarationName, ShadowMapEntry> ShadowMap;
3604
3605 /// A list of shadow maps, which is used to model name hiding.
3606 std::list<ShadowMap> ShadowMaps;
3607
3608 /// The declaration contexts we have already visited.
3609 llvm::SmallPtrSet<DeclContext *, 8> VisitedContexts;
3610
3611 friend class ShadowContextRAII;
3612
3613 public:
3614 /// Determine whether we have already visited this context
3615 /// (and, if not, note that we are going to visit that context now).
visitedContext(DeclContext * Ctx)3616 bool visitedContext(DeclContext *Ctx) {
3617 return !VisitedContexts.insert(Ctx).second;
3618 }
3619
alreadyVisitedContext(DeclContext * Ctx)3620 bool alreadyVisitedContext(DeclContext *Ctx) {
3621 return VisitedContexts.count(Ctx);
3622 }
3623
3624 /// Determine whether the given declaration is hidden in the
3625 /// current scope.
3626 ///
3627 /// \returns the declaration that hides the given declaration, or
3628 /// NULL if no such declaration exists.
3629 NamedDecl *checkHidden(NamedDecl *ND);
3630
3631 /// Add a declaration to the current shadow map.
add(NamedDecl * ND)3632 void add(NamedDecl *ND) {
3633 ShadowMaps.back()[ND->getDeclName()].push_back(ND);
3634 }
3635 };
3636
3637 /// RAII object that records when we've entered a shadow context.
3638 class ShadowContextRAII {
3639 VisibleDeclsRecord &Visible;
3640
3641 typedef VisibleDeclsRecord::ShadowMap ShadowMap;
3642
3643 public:
ShadowContextRAII(VisibleDeclsRecord & Visible)3644 ShadowContextRAII(VisibleDeclsRecord &Visible) : Visible(Visible) {
3645 Visible.ShadowMaps.emplace_back();
3646 }
3647
~ShadowContextRAII()3648 ~ShadowContextRAII() {
3649 Visible.ShadowMaps.pop_back();
3650 }
3651 };
3652
3653 } // end anonymous namespace
3654
checkHidden(NamedDecl * ND)3655 NamedDecl *VisibleDeclsRecord::checkHidden(NamedDecl *ND) {
3656 unsigned IDNS = ND->getIdentifierNamespace();
3657 std::list<ShadowMap>::reverse_iterator SM = ShadowMaps.rbegin();
3658 for (std::list<ShadowMap>::reverse_iterator SMEnd = ShadowMaps.rend();
3659 SM != SMEnd; ++SM) {
3660 ShadowMap::iterator Pos = SM->find(ND->getDeclName());
3661 if (Pos == SM->end())
3662 continue;
3663
3664 for (auto *D : Pos->second) {
3665 // A tag declaration does not hide a non-tag declaration.
3666 if (D->hasTagIdentifierNamespace() &&
3667 (IDNS & (Decl::IDNS_Member | Decl::IDNS_Ordinary |
3668 Decl::IDNS_ObjCProtocol)))
3669 continue;
3670
3671 // Protocols are in distinct namespaces from everything else.
3672 if (((D->getIdentifierNamespace() & Decl::IDNS_ObjCProtocol)
3673 || (IDNS & Decl::IDNS_ObjCProtocol)) &&
3674 D->getIdentifierNamespace() != IDNS)
3675 continue;
3676
3677 // Functions and function templates in the same scope overload
3678 // rather than hide. FIXME: Look for hiding based on function
3679 // signatures!
3680 if (D->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3681 ND->getUnderlyingDecl()->isFunctionOrFunctionTemplate() &&
3682 SM == ShadowMaps.rbegin())
3683 continue;
3684
3685 // A shadow declaration that's created by a resolved using declaration
3686 // is not hidden by the same using declaration.
3687 if (isa<UsingShadowDecl>(ND) && isa<UsingDecl>(D) &&
3688 cast<UsingShadowDecl>(ND)->getUsingDecl() == D)
3689 continue;
3690
3691 // We've found a declaration that hides this one.
3692 return D;
3693 }
3694 }
3695
3696 return nullptr;
3697 }
3698
3699 namespace {
3700 class LookupVisibleHelper {
3701 public:
LookupVisibleHelper(VisibleDeclConsumer & Consumer,bool IncludeDependentBases,bool LoadExternal)3702 LookupVisibleHelper(VisibleDeclConsumer &Consumer, bool IncludeDependentBases,
3703 bool LoadExternal)
3704 : Consumer(Consumer), IncludeDependentBases(IncludeDependentBases),
3705 LoadExternal(LoadExternal) {}
3706
lookupVisibleDecls(Sema & SemaRef,Scope * S,Sema::LookupNameKind Kind,bool IncludeGlobalScope)3707 void lookupVisibleDecls(Sema &SemaRef, Scope *S, Sema::LookupNameKind Kind,
3708 bool IncludeGlobalScope) {
3709 // Determine the set of using directives available during
3710 // unqualified name lookup.
3711 Scope *Initial = S;
3712 UnqualUsingDirectiveSet UDirs(SemaRef);
3713 if (SemaRef.getLangOpts().CPlusPlus) {
3714 // Find the first namespace or translation-unit scope.
3715 while (S && !isNamespaceOrTranslationUnitScope(S))
3716 S = S->getParent();
3717
3718 UDirs.visitScopeChain(Initial, S);
3719 }
3720 UDirs.done();
3721
3722 // Look for visible declarations.
3723 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
3724 Result.setAllowHidden(Consumer.includeHiddenDecls());
3725 if (!IncludeGlobalScope)
3726 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
3727 ShadowContextRAII Shadow(Visited);
3728 lookupInScope(Initial, Result, UDirs);
3729 }
3730
lookupVisibleDecls(Sema & SemaRef,DeclContext * Ctx,Sema::LookupNameKind Kind,bool IncludeGlobalScope)3731 void lookupVisibleDecls(Sema &SemaRef, DeclContext *Ctx,
3732 Sema::LookupNameKind Kind, bool IncludeGlobalScope) {
3733 LookupResult Result(SemaRef, DeclarationName(), SourceLocation(), Kind);
3734 Result.setAllowHidden(Consumer.includeHiddenDecls());
3735 if (!IncludeGlobalScope)
3736 Visited.visitedContext(SemaRef.getASTContext().getTranslationUnitDecl());
3737
3738 ShadowContextRAII Shadow(Visited);
3739 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/true,
3740 /*InBaseClass=*/false);
3741 }
3742
3743 private:
lookupInDeclContext(DeclContext * Ctx,LookupResult & Result,bool QualifiedNameLookup,bool InBaseClass)3744 void lookupInDeclContext(DeclContext *Ctx, LookupResult &Result,
3745 bool QualifiedNameLookup, bool InBaseClass) {
3746 if (!Ctx)
3747 return;
3748
3749 // Make sure we don't visit the same context twice.
3750 if (Visited.visitedContext(Ctx->getPrimaryContext()))
3751 return;
3752
3753 Consumer.EnteredContext(Ctx);
3754
3755 // Outside C++, lookup results for the TU live on identifiers.
3756 if (isa<TranslationUnitDecl>(Ctx) &&
3757 !Result.getSema().getLangOpts().CPlusPlus) {
3758 auto &S = Result.getSema();
3759 auto &Idents = S.Context.Idents;
3760
3761 // Ensure all external identifiers are in the identifier table.
3762 if (LoadExternal)
3763 if (IdentifierInfoLookup *External =
3764 Idents.getExternalIdentifierLookup()) {
3765 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
3766 for (StringRef Name = Iter->Next(); !Name.empty();
3767 Name = Iter->Next())
3768 Idents.get(Name);
3769 }
3770
3771 // Walk all lookup results in the TU for each identifier.
3772 for (const auto &Ident : Idents) {
3773 for (auto I = S.IdResolver.begin(Ident.getValue()),
3774 E = S.IdResolver.end();
3775 I != E; ++I) {
3776 if (S.IdResolver.isDeclInScope(*I, Ctx)) {
3777 if (NamedDecl *ND = Result.getAcceptableDecl(*I)) {
3778 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3779 Visited.add(ND);
3780 }
3781 }
3782 }
3783 }
3784
3785 return;
3786 }
3787
3788 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx))
3789 Result.getSema().ForceDeclarationOfImplicitMembers(Class);
3790
3791 // We sometimes skip loading namespace-level results (they tend to be huge).
3792 bool Load = LoadExternal ||
3793 !(isa<TranslationUnitDecl>(Ctx) || isa<NamespaceDecl>(Ctx));
3794 // Enumerate all of the results in this context.
3795 for (DeclContextLookupResult R :
3796 Load ? Ctx->lookups()
3797 : Ctx->noload_lookups(/*PreserveInternalState=*/false)) {
3798 for (auto *D : R) {
3799 if (auto *ND = Result.getAcceptableDecl(D)) {
3800 Consumer.FoundDecl(ND, Visited.checkHidden(ND), Ctx, InBaseClass);
3801 Visited.add(ND);
3802 }
3803 }
3804 }
3805
3806 // Traverse using directives for qualified name lookup.
3807 if (QualifiedNameLookup) {
3808 ShadowContextRAII Shadow(Visited);
3809 for (auto I : Ctx->using_directives()) {
3810 if (!Result.getSema().isVisible(I))
3811 continue;
3812 lookupInDeclContext(I->getNominatedNamespace(), Result,
3813 QualifiedNameLookup, InBaseClass);
3814 }
3815 }
3816
3817 // Traverse the contexts of inherited C++ classes.
3818 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Ctx)) {
3819 if (!Record->hasDefinition())
3820 return;
3821
3822 for (const auto &B : Record->bases()) {
3823 QualType BaseType = B.getType();
3824
3825 RecordDecl *RD;
3826 if (BaseType->isDependentType()) {
3827 if (!IncludeDependentBases) {
3828 // Don't look into dependent bases, because name lookup can't look
3829 // there anyway.
3830 continue;
3831 }
3832 const auto *TST = BaseType->getAs<TemplateSpecializationType>();
3833 if (!TST)
3834 continue;
3835 TemplateName TN = TST->getTemplateName();
3836 const auto *TD =
3837 dyn_cast_or_null<ClassTemplateDecl>(TN.getAsTemplateDecl());
3838 if (!TD)
3839 continue;
3840 RD = TD->getTemplatedDecl();
3841 } else {
3842 const auto *Record = BaseType->getAs<RecordType>();
3843 if (!Record)
3844 continue;
3845 RD = Record->getDecl();
3846 }
3847
3848 // FIXME: It would be nice to be able to determine whether referencing
3849 // a particular member would be ambiguous. For example, given
3850 //
3851 // struct A { int member; };
3852 // struct B { int member; };
3853 // struct C : A, B { };
3854 //
3855 // void f(C *c) { c->### }
3856 //
3857 // accessing 'member' would result in an ambiguity. However, we
3858 // could be smart enough to qualify the member with the base
3859 // class, e.g.,
3860 //
3861 // c->B::member
3862 //
3863 // or
3864 //
3865 // c->A::member
3866
3867 // Find results in this base class (and its bases).
3868 ShadowContextRAII Shadow(Visited);
3869 lookupInDeclContext(RD, Result, QualifiedNameLookup,
3870 /*InBaseClass=*/true);
3871 }
3872 }
3873
3874 // Traverse the contexts of Objective-C classes.
3875 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(Ctx)) {
3876 // Traverse categories.
3877 for (auto *Cat : IFace->visible_categories()) {
3878 ShadowContextRAII Shadow(Visited);
3879 lookupInDeclContext(Cat, Result, QualifiedNameLookup,
3880 /*InBaseClass=*/false);
3881 }
3882
3883 // Traverse protocols.
3884 for (auto *I : IFace->all_referenced_protocols()) {
3885 ShadowContextRAII Shadow(Visited);
3886 lookupInDeclContext(I, Result, QualifiedNameLookup,
3887 /*InBaseClass=*/false);
3888 }
3889
3890 // Traverse the superclass.
3891 if (IFace->getSuperClass()) {
3892 ShadowContextRAII Shadow(Visited);
3893 lookupInDeclContext(IFace->getSuperClass(), Result, QualifiedNameLookup,
3894 /*InBaseClass=*/true);
3895 }
3896
3897 // If there is an implementation, traverse it. We do this to find
3898 // synthesized ivars.
3899 if (IFace->getImplementation()) {
3900 ShadowContextRAII Shadow(Visited);
3901 lookupInDeclContext(IFace->getImplementation(), Result,
3902 QualifiedNameLookup, InBaseClass);
3903 }
3904 } else if (ObjCProtocolDecl *Protocol = dyn_cast<ObjCProtocolDecl>(Ctx)) {
3905 for (auto *I : Protocol->protocols()) {
3906 ShadowContextRAII Shadow(Visited);
3907 lookupInDeclContext(I, Result, QualifiedNameLookup,
3908 /*InBaseClass=*/false);
3909 }
3910 } else if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(Ctx)) {
3911 for (auto *I : Category->protocols()) {
3912 ShadowContextRAII Shadow(Visited);
3913 lookupInDeclContext(I, Result, QualifiedNameLookup,
3914 /*InBaseClass=*/false);
3915 }
3916
3917 // If there is an implementation, traverse it.
3918 if (Category->getImplementation()) {
3919 ShadowContextRAII Shadow(Visited);
3920 lookupInDeclContext(Category->getImplementation(), Result,
3921 QualifiedNameLookup, /*InBaseClass=*/true);
3922 }
3923 }
3924 }
3925
lookupInScope(Scope * S,LookupResult & Result,UnqualUsingDirectiveSet & UDirs)3926 void lookupInScope(Scope *S, LookupResult &Result,
3927 UnqualUsingDirectiveSet &UDirs) {
3928 // No clients run in this mode and it's not supported. Please add tests and
3929 // remove the assertion if you start relying on it.
3930 assert(!IncludeDependentBases && "Unsupported flag for lookupInScope");
3931
3932 if (!S)
3933 return;
3934
3935 if (!S->getEntity() ||
3936 (!S->getParent() && !Visited.alreadyVisitedContext(S->getEntity())) ||
3937 (S->getEntity())->isFunctionOrMethod()) {
3938 FindLocalExternScope FindLocals(Result);
3939 // Walk through the declarations in this Scope. The consumer might add new
3940 // decls to the scope as part of deserialization, so make a copy first.
3941 SmallVector<Decl *, 8> ScopeDecls(S->decls().begin(), S->decls().end());
3942 for (Decl *D : ScopeDecls) {
3943 if (NamedDecl *ND = dyn_cast<NamedDecl>(D))
3944 if ((ND = Result.getAcceptableDecl(ND))) {
3945 Consumer.FoundDecl(ND, Visited.checkHidden(ND), nullptr, false);
3946 Visited.add(ND);
3947 }
3948 }
3949 }
3950
3951 DeclContext *Entity = S->getLookupEntity();
3952 if (Entity) {
3953 // Look into this scope's declaration context, along with any of its
3954 // parent lookup contexts (e.g., enclosing classes), up to the point
3955 // where we hit the context stored in the next outer scope.
3956 DeclContext *OuterCtx = findOuterContext(S);
3957
3958 for (DeclContext *Ctx = Entity; Ctx && !Ctx->Equals(OuterCtx);
3959 Ctx = Ctx->getLookupParent()) {
3960 if (ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(Ctx)) {
3961 if (Method->isInstanceMethod()) {
3962 // For instance methods, look for ivars in the method's interface.
3963 LookupResult IvarResult(Result.getSema(), Result.getLookupName(),
3964 Result.getNameLoc(),
3965 Sema::LookupMemberName);
3966 if (ObjCInterfaceDecl *IFace = Method->getClassInterface()) {
3967 lookupInDeclContext(IFace, IvarResult,
3968 /*QualifiedNameLookup=*/false,
3969 /*InBaseClass=*/false);
3970 }
3971 }
3972
3973 // We've already performed all of the name lookup that we need
3974 // to for Objective-C methods; the next context will be the
3975 // outer scope.
3976 break;
3977 }
3978
3979 if (Ctx->isFunctionOrMethod())
3980 continue;
3981
3982 lookupInDeclContext(Ctx, Result, /*QualifiedNameLookup=*/false,
3983 /*InBaseClass=*/false);
3984 }
3985 } else if (!S->getParent()) {
3986 // Look into the translation unit scope. We walk through the translation
3987 // unit's declaration context, because the Scope itself won't have all of
3988 // the declarations if we loaded a precompiled header.
3989 // FIXME: We would like the translation unit's Scope object to point to
3990 // the translation unit, so we don't need this special "if" branch.
3991 // However, doing so would force the normal C++ name-lookup code to look
3992 // into the translation unit decl when the IdentifierInfo chains would
3993 // suffice. Once we fix that problem (which is part of a more general
3994 // "don't look in DeclContexts unless we have to" optimization), we can
3995 // eliminate this.
3996 Entity = Result.getSema().Context.getTranslationUnitDecl();
3997 lookupInDeclContext(Entity, Result, /*QualifiedNameLookup=*/false,
3998 /*InBaseClass=*/false);
3999 }
4000
4001 if (Entity) {
4002 // Lookup visible declarations in any namespaces found by using
4003 // directives.
4004 for (const UnqualUsingEntry &UUE : UDirs.getNamespacesFor(Entity))
4005 lookupInDeclContext(
4006 const_cast<DeclContext *>(UUE.getNominatedNamespace()), Result,
4007 /*QualifiedNameLookup=*/false,
4008 /*InBaseClass=*/false);
4009 }
4010
4011 // Lookup names in the parent scope.
4012 ShadowContextRAII Shadow(Visited);
4013 lookupInScope(S->getParent(), Result, UDirs);
4014 }
4015
4016 private:
4017 VisibleDeclsRecord Visited;
4018 VisibleDeclConsumer &Consumer;
4019 bool IncludeDependentBases;
4020 bool LoadExternal;
4021 };
4022 } // namespace
4023
LookupVisibleDecls(Scope * S,LookupNameKind Kind,VisibleDeclConsumer & Consumer,bool IncludeGlobalScope,bool LoadExternal)4024 void Sema::LookupVisibleDecls(Scope *S, LookupNameKind Kind,
4025 VisibleDeclConsumer &Consumer,
4026 bool IncludeGlobalScope, bool LoadExternal) {
4027 LookupVisibleHelper H(Consumer, /*IncludeDependentBases=*/false,
4028 LoadExternal);
4029 H.lookupVisibleDecls(*this, S, Kind, IncludeGlobalScope);
4030 }
4031
LookupVisibleDecls(DeclContext * Ctx,LookupNameKind Kind,VisibleDeclConsumer & Consumer,bool IncludeGlobalScope,bool IncludeDependentBases,bool LoadExternal)4032 void Sema::LookupVisibleDecls(DeclContext *Ctx, LookupNameKind Kind,
4033 VisibleDeclConsumer &Consumer,
4034 bool IncludeGlobalScope,
4035 bool IncludeDependentBases, bool LoadExternal) {
4036 LookupVisibleHelper H(Consumer, IncludeDependentBases, LoadExternal);
4037 H.lookupVisibleDecls(*this, Ctx, Kind, IncludeGlobalScope);
4038 }
4039
4040 /// LookupOrCreateLabel - Do a name lookup of a label with the specified name.
4041 /// If GnuLabelLoc is a valid source location, then this is a definition
4042 /// of an __label__ label name, otherwise it is a normal label definition
4043 /// or use.
LookupOrCreateLabel(IdentifierInfo * II,SourceLocation Loc,SourceLocation GnuLabelLoc)4044 LabelDecl *Sema::LookupOrCreateLabel(IdentifierInfo *II, SourceLocation Loc,
4045 SourceLocation GnuLabelLoc) {
4046 // Do a lookup to see if we have a label with this name already.
4047 NamedDecl *Res = nullptr;
4048
4049 if (GnuLabelLoc.isValid()) {
4050 // Local label definitions always shadow existing labels.
4051 Res = LabelDecl::Create(Context, CurContext, Loc, II, GnuLabelLoc);
4052 Scope *S = CurScope;
4053 PushOnScopeChains(Res, S, true);
4054 return cast<LabelDecl>(Res);
4055 }
4056
4057 // Not a GNU local label.
4058 Res = LookupSingleName(CurScope, II, Loc, LookupLabel, NotForRedeclaration);
4059 // If we found a label, check to see if it is in the same context as us.
4060 // When in a Block, we don't want to reuse a label in an enclosing function.
4061 if (Res && Res->getDeclContext() != CurContext)
4062 Res = nullptr;
4063 if (!Res) {
4064 // If not forward referenced or defined already, create the backing decl.
4065 Res = LabelDecl::Create(Context, CurContext, Loc, II);
4066 Scope *S = CurScope->getFnParent();
4067 assert(S && "Not in a function?");
4068 PushOnScopeChains(Res, S, true);
4069 }
4070 return cast<LabelDecl>(Res);
4071 }
4072
4073 //===----------------------------------------------------------------------===//
4074 // Typo correction
4075 //===----------------------------------------------------------------------===//
4076
isCandidateViable(CorrectionCandidateCallback & CCC,TypoCorrection & Candidate)4077 static bool isCandidateViable(CorrectionCandidateCallback &CCC,
4078 TypoCorrection &Candidate) {
4079 Candidate.setCallbackDistance(CCC.RankCandidate(Candidate));
4080 return Candidate.getEditDistance(false) != TypoCorrection::InvalidDistance;
4081 }
4082
4083 static void LookupPotentialTypoResult(Sema &SemaRef,
4084 LookupResult &Res,
4085 IdentifierInfo *Name,
4086 Scope *S, CXXScopeSpec *SS,
4087 DeclContext *MemberContext,
4088 bool EnteringContext,
4089 bool isObjCIvarLookup,
4090 bool FindHidden);
4091
4092 /// Check whether the declarations found for a typo correction are
4093 /// visible. Set the correction's RequiresImport flag to true if none of the
4094 /// declarations are visible, false otherwise.
checkCorrectionVisibility(Sema & SemaRef,TypoCorrection & TC)4095 static void checkCorrectionVisibility(Sema &SemaRef, TypoCorrection &TC) {
4096 TypoCorrection::decl_iterator DI = TC.begin(), DE = TC.end();
4097
4098 for (/**/; DI != DE; ++DI)
4099 if (!LookupResult::isVisible(SemaRef, *DI))
4100 break;
4101 // No filtering needed if all decls are visible.
4102 if (DI == DE) {
4103 TC.setRequiresImport(false);
4104 return;
4105 }
4106
4107 llvm::SmallVector<NamedDecl*, 4> NewDecls(TC.begin(), DI);
4108 bool AnyVisibleDecls = !NewDecls.empty();
4109
4110 for (/**/; DI != DE; ++DI) {
4111 if (LookupResult::isVisible(SemaRef, *DI)) {
4112 if (!AnyVisibleDecls) {
4113 // Found a visible decl, discard all hidden ones.
4114 AnyVisibleDecls = true;
4115 NewDecls.clear();
4116 }
4117 NewDecls.push_back(*DI);
4118 } else if (!AnyVisibleDecls && !(*DI)->isModulePrivate())
4119 NewDecls.push_back(*DI);
4120 }
4121
4122 if (NewDecls.empty())
4123 TC = TypoCorrection();
4124 else {
4125 TC.setCorrectionDecls(NewDecls);
4126 TC.setRequiresImport(!AnyVisibleDecls);
4127 }
4128 }
4129
4130 // Fill the supplied vector with the IdentifierInfo pointers for each piece of
4131 // the given NestedNameSpecifier (i.e. given a NestedNameSpecifier "foo::bar::",
4132 // fill the vector with the IdentifierInfo pointers for "foo" and "bar").
getNestedNameSpecifierIdentifiers(NestedNameSpecifier * NNS,SmallVectorImpl<const IdentifierInfo * > & Identifiers)4133 static void getNestedNameSpecifierIdentifiers(
4134 NestedNameSpecifier *NNS,
4135 SmallVectorImpl<const IdentifierInfo*> &Identifiers) {
4136 if (NestedNameSpecifier *Prefix = NNS->getPrefix())
4137 getNestedNameSpecifierIdentifiers(Prefix, Identifiers);
4138 else
4139 Identifiers.clear();
4140
4141 const IdentifierInfo *II = nullptr;
4142
4143 switch (NNS->getKind()) {
4144 case NestedNameSpecifier::Identifier:
4145 II = NNS->getAsIdentifier();
4146 break;
4147
4148 case NestedNameSpecifier::Namespace:
4149 if (NNS->getAsNamespace()->isAnonymousNamespace())
4150 return;
4151 II = NNS->getAsNamespace()->getIdentifier();
4152 break;
4153
4154 case NestedNameSpecifier::NamespaceAlias:
4155 II = NNS->getAsNamespaceAlias()->getIdentifier();
4156 break;
4157
4158 case NestedNameSpecifier::TypeSpecWithTemplate:
4159 case NestedNameSpecifier::TypeSpec:
4160 II = QualType(NNS->getAsType(), 0).getBaseTypeIdentifier();
4161 break;
4162
4163 case NestedNameSpecifier::Global:
4164 case NestedNameSpecifier::Super:
4165 return;
4166 }
4167
4168 if (II)
4169 Identifiers.push_back(II);
4170 }
4171
FoundDecl(NamedDecl * ND,NamedDecl * Hiding,DeclContext * Ctx,bool InBaseClass)4172 void TypoCorrectionConsumer::FoundDecl(NamedDecl *ND, NamedDecl *Hiding,
4173 DeclContext *Ctx, bool InBaseClass) {
4174 // Don't consider hidden names for typo correction.
4175 if (Hiding)
4176 return;
4177
4178 // Only consider entities with identifiers for names, ignoring
4179 // special names (constructors, overloaded operators, selectors,
4180 // etc.).
4181 IdentifierInfo *Name = ND->getIdentifier();
4182 if (!Name)
4183 return;
4184
4185 // Only consider visible declarations and declarations from modules with
4186 // names that exactly match.
4187 if (!LookupResult::isVisible(SemaRef, ND) && Name != Typo)
4188 return;
4189
4190 FoundName(Name->getName());
4191 }
4192
FoundName(StringRef Name)4193 void TypoCorrectionConsumer::FoundName(StringRef Name) {
4194 // Compute the edit distance between the typo and the name of this
4195 // entity, and add the identifier to the list of results.
4196 addName(Name, nullptr);
4197 }
4198
addKeywordResult(StringRef Keyword)4199 void TypoCorrectionConsumer::addKeywordResult(StringRef Keyword) {
4200 // Compute the edit distance between the typo and this keyword,
4201 // and add the keyword to the list of results.
4202 addName(Keyword, nullptr, nullptr, true);
4203 }
4204
addName(StringRef Name,NamedDecl * ND,NestedNameSpecifier * NNS,bool isKeyword)4205 void TypoCorrectionConsumer::addName(StringRef Name, NamedDecl *ND,
4206 NestedNameSpecifier *NNS, bool isKeyword) {
4207 // Use a simple length-based heuristic to determine the minimum possible
4208 // edit distance. If the minimum isn't good enough, bail out early.
4209 StringRef TypoStr = Typo->getName();
4210 unsigned MinED = abs((int)Name.size() - (int)TypoStr.size());
4211 if (MinED && TypoStr.size() / MinED < 3)
4212 return;
4213
4214 // Compute an upper bound on the allowable edit distance, so that the
4215 // edit-distance algorithm can short-circuit.
4216 unsigned UpperBound = (TypoStr.size() + 2) / 3;
4217 unsigned ED = TypoStr.edit_distance(Name, true, UpperBound);
4218 if (ED > UpperBound) return;
4219
4220 TypoCorrection TC(&SemaRef.Context.Idents.get(Name), ND, NNS, ED);
4221 if (isKeyword) TC.makeKeyword();
4222 TC.setCorrectionRange(nullptr, Result.getLookupNameInfo());
4223 addCorrection(TC);
4224 }
4225
4226 static const unsigned MaxTypoDistanceResultSets = 5;
4227
addCorrection(TypoCorrection Correction)4228 void TypoCorrectionConsumer::addCorrection(TypoCorrection Correction) {
4229 StringRef TypoStr = Typo->getName();
4230 StringRef Name = Correction.getCorrectionAsIdentifierInfo()->getName();
4231
4232 // For very short typos, ignore potential corrections that have a different
4233 // base identifier from the typo or which have a normalized edit distance
4234 // longer than the typo itself.
4235 if (TypoStr.size() < 3 &&
4236 (Name != TypoStr || Correction.getEditDistance(true) > TypoStr.size()))
4237 return;
4238
4239 // If the correction is resolved but is not viable, ignore it.
4240 if (Correction.isResolved()) {
4241 checkCorrectionVisibility(SemaRef, Correction);
4242 if (!Correction || !isCandidateViable(*CorrectionValidator, Correction))
4243 return;
4244 }
4245
4246 TypoResultList &CList =
4247 CorrectionResults[Correction.getEditDistance(false)][Name];
4248
4249 if (!CList.empty() && !CList.back().isResolved())
4250 CList.pop_back();
4251 if (NamedDecl *NewND = Correction.getCorrectionDecl()) {
4252 std::string CorrectionStr = Correction.getAsString(SemaRef.getLangOpts());
4253 for (TypoResultList::iterator RI = CList.begin(), RIEnd = CList.end();
4254 RI != RIEnd; ++RI) {
4255 // If the Correction refers to a decl already in the result list,
4256 // replace the existing result if the string representation of Correction
4257 // comes before the current result alphabetically, then stop as there is
4258 // nothing more to be done to add Correction to the candidate set.
4259 if (RI->getCorrectionDecl() == NewND) {
4260 if (CorrectionStr < RI->getAsString(SemaRef.getLangOpts()))
4261 *RI = Correction;
4262 return;
4263 }
4264 }
4265 }
4266 if (CList.empty() || Correction.isResolved())
4267 CList.push_back(Correction);
4268
4269 while (CorrectionResults.size() > MaxTypoDistanceResultSets)
4270 CorrectionResults.erase(std::prev(CorrectionResults.end()));
4271 }
4272
addNamespaces(const llvm::MapVector<NamespaceDecl *,bool> & KnownNamespaces)4273 void TypoCorrectionConsumer::addNamespaces(
4274 const llvm::MapVector<NamespaceDecl *, bool> &KnownNamespaces) {
4275 SearchNamespaces = true;
4276
4277 for (auto KNPair : KnownNamespaces)
4278 Namespaces.addNameSpecifier(KNPair.first);
4279
4280 bool SSIsTemplate = false;
4281 if (NestedNameSpecifier *NNS =
4282 (SS && SS->isValid()) ? SS->getScopeRep() : nullptr) {
4283 if (const Type *T = NNS->getAsType())
4284 SSIsTemplate = T->getTypeClass() == Type::TemplateSpecialization;
4285 }
4286 // Do not transform this into an iterator-based loop. The loop body can
4287 // trigger the creation of further types (through lazy deserialization) and
4288 // invalid iterators into this list.
4289 auto &Types = SemaRef.getASTContext().getTypes();
4290 for (unsigned I = 0; I != Types.size(); ++I) {
4291 const auto *TI = Types[I];
4292 if (CXXRecordDecl *CD = TI->getAsCXXRecordDecl()) {
4293 CD = CD->getCanonicalDecl();
4294 if (!CD->isDependentType() && !CD->isAnonymousStructOrUnion() &&
4295 !CD->isUnion() && CD->getIdentifier() &&
4296 (SSIsTemplate || !isa<ClassTemplateSpecializationDecl>(CD)) &&
4297 (CD->isBeingDefined() || CD->isCompleteDefinition()))
4298 Namespaces.addNameSpecifier(CD);
4299 }
4300 }
4301 }
4302
getNextCorrection()4303 const TypoCorrection &TypoCorrectionConsumer::getNextCorrection() {
4304 if (++CurrentTCIndex < ValidatedCorrections.size())
4305 return ValidatedCorrections[CurrentTCIndex];
4306
4307 CurrentTCIndex = ValidatedCorrections.size();
4308 while (!CorrectionResults.empty()) {
4309 auto DI = CorrectionResults.begin();
4310 if (DI->second.empty()) {
4311 CorrectionResults.erase(DI);
4312 continue;
4313 }
4314
4315 auto RI = DI->second.begin();
4316 if (RI->second.empty()) {
4317 DI->second.erase(RI);
4318 performQualifiedLookups();
4319 continue;
4320 }
4321
4322 TypoCorrection TC = RI->second.pop_back_val();
4323 if (TC.isResolved() || TC.requiresImport() || resolveCorrection(TC)) {
4324 ValidatedCorrections.push_back(TC);
4325 return ValidatedCorrections[CurrentTCIndex];
4326 }
4327 }
4328 return ValidatedCorrections[0]; // The empty correction.
4329 }
4330
resolveCorrection(TypoCorrection & Candidate)4331 bool TypoCorrectionConsumer::resolveCorrection(TypoCorrection &Candidate) {
4332 IdentifierInfo *Name = Candidate.getCorrectionAsIdentifierInfo();
4333 DeclContext *TempMemberContext = MemberContext;
4334 CXXScopeSpec *TempSS = SS.get();
4335 retry_lookup:
4336 LookupPotentialTypoResult(SemaRef, Result, Name, S, TempSS, TempMemberContext,
4337 EnteringContext,
4338 CorrectionValidator->IsObjCIvarLookup,
4339 Name == Typo && !Candidate.WillReplaceSpecifier());
4340 switch (Result.getResultKind()) {
4341 case LookupResult::NotFound:
4342 case LookupResult::NotFoundInCurrentInstantiation:
4343 case LookupResult::FoundUnresolvedValue:
4344 if (TempSS) {
4345 // Immediately retry the lookup without the given CXXScopeSpec
4346 TempSS = nullptr;
4347 Candidate.WillReplaceSpecifier(true);
4348 goto retry_lookup;
4349 }
4350 if (TempMemberContext) {
4351 if (SS && !TempSS)
4352 TempSS = SS.get();
4353 TempMemberContext = nullptr;
4354 goto retry_lookup;
4355 }
4356 if (SearchNamespaces)
4357 QualifiedResults.push_back(Candidate);
4358 break;
4359
4360 case LookupResult::Ambiguous:
4361 // We don't deal with ambiguities.
4362 break;
4363
4364 case LookupResult::Found:
4365 case LookupResult::FoundOverloaded:
4366 // Store all of the Decls for overloaded symbols
4367 for (auto *TRD : Result)
4368 Candidate.addCorrectionDecl(TRD);
4369 checkCorrectionVisibility(SemaRef, Candidate);
4370 if (!isCandidateViable(*CorrectionValidator, Candidate)) {
4371 if (SearchNamespaces)
4372 QualifiedResults.push_back(Candidate);
4373 break;
4374 }
4375 Candidate.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4376 return true;
4377 }
4378 return false;
4379 }
4380
performQualifiedLookups()4381 void TypoCorrectionConsumer::performQualifiedLookups() {
4382 unsigned TypoLen = Typo->getName().size();
4383 for (const TypoCorrection &QR : QualifiedResults) {
4384 for (const auto &NSI : Namespaces) {
4385 DeclContext *Ctx = NSI.DeclCtx;
4386 const Type *NSType = NSI.NameSpecifier->getAsType();
4387
4388 // If the current NestedNameSpecifier refers to a class and the
4389 // current correction candidate is the name of that class, then skip
4390 // it as it is unlikely a qualified version of the class' constructor
4391 // is an appropriate correction.
4392 if (CXXRecordDecl *NSDecl = NSType ? NSType->getAsCXXRecordDecl() :
4393 nullptr) {
4394 if (NSDecl->getIdentifier() == QR.getCorrectionAsIdentifierInfo())
4395 continue;
4396 }
4397
4398 TypoCorrection TC(QR);
4399 TC.ClearCorrectionDecls();
4400 TC.setCorrectionSpecifier(NSI.NameSpecifier);
4401 TC.setQualifierDistance(NSI.EditDistance);
4402 TC.setCallbackDistance(0); // Reset the callback distance
4403
4404 // If the current correction candidate and namespace combination are
4405 // too far away from the original typo based on the normalized edit
4406 // distance, then skip performing a qualified name lookup.
4407 unsigned TmpED = TC.getEditDistance(true);
4408 if (QR.getCorrectionAsIdentifierInfo() != Typo && TmpED &&
4409 TypoLen / TmpED < 3)
4410 continue;
4411
4412 Result.clear();
4413 Result.setLookupName(QR.getCorrectionAsIdentifierInfo());
4414 if (!SemaRef.LookupQualifiedName(Result, Ctx))
4415 continue;
4416
4417 // Any corrections added below will be validated in subsequent
4418 // iterations of the main while() loop over the Consumer's contents.
4419 switch (Result.getResultKind()) {
4420 case LookupResult::Found:
4421 case LookupResult::FoundOverloaded: {
4422 if (SS && SS->isValid()) {
4423 std::string NewQualified = TC.getAsString(SemaRef.getLangOpts());
4424 std::string OldQualified;
4425 llvm::raw_string_ostream OldOStream(OldQualified);
4426 SS->getScopeRep()->print(OldOStream, SemaRef.getPrintingPolicy());
4427 OldOStream << Typo->getName();
4428 // If correction candidate would be an identical written qualified
4429 // identifier, then the existing CXXScopeSpec probably included a
4430 // typedef that didn't get accounted for properly.
4431 if (OldOStream.str() == NewQualified)
4432 break;
4433 }
4434 for (LookupResult::iterator TRD = Result.begin(), TRDEnd = Result.end();
4435 TRD != TRDEnd; ++TRD) {
4436 if (SemaRef.CheckMemberAccess(TC.getCorrectionRange().getBegin(),
4437 NSType ? NSType->getAsCXXRecordDecl()
4438 : nullptr,
4439 TRD.getPair()) == Sema::AR_accessible)
4440 TC.addCorrectionDecl(*TRD);
4441 }
4442 if (TC.isResolved()) {
4443 TC.setCorrectionRange(SS.get(), Result.getLookupNameInfo());
4444 addCorrection(TC);
4445 }
4446 break;
4447 }
4448 case LookupResult::NotFound:
4449 case LookupResult::NotFoundInCurrentInstantiation:
4450 case LookupResult::Ambiguous:
4451 case LookupResult::FoundUnresolvedValue:
4452 break;
4453 }
4454 }
4455 }
4456 QualifiedResults.clear();
4457 }
4458
NamespaceSpecifierSet(ASTContext & Context,DeclContext * CurContext,CXXScopeSpec * CurScopeSpec)4459 TypoCorrectionConsumer::NamespaceSpecifierSet::NamespaceSpecifierSet(
4460 ASTContext &Context, DeclContext *CurContext, CXXScopeSpec *CurScopeSpec)
4461 : Context(Context), CurContextChain(buildContextChain(CurContext)) {
4462 if (NestedNameSpecifier *NNS =
4463 CurScopeSpec ? CurScopeSpec->getScopeRep() : nullptr) {
4464 llvm::raw_string_ostream SpecifierOStream(CurNameSpecifier);
4465 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4466
4467 getNestedNameSpecifierIdentifiers(NNS, CurNameSpecifierIdentifiers);
4468 }
4469 // Build the list of identifiers that would be used for an absolute
4470 // (from the global context) NestedNameSpecifier referring to the current
4471 // context.
4472 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4473 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C))
4474 CurContextIdentifiers.push_back(ND->getIdentifier());
4475 }
4476
4477 // Add the global context as a NestedNameSpecifier
4478 SpecifierInfo SI = {cast<DeclContext>(Context.getTranslationUnitDecl()),
4479 NestedNameSpecifier::GlobalSpecifier(Context), 1};
4480 DistanceMap[1].push_back(SI);
4481 }
4482
buildContextChain(DeclContext * Start)4483 auto TypoCorrectionConsumer::NamespaceSpecifierSet::buildContextChain(
4484 DeclContext *Start) -> DeclContextList {
4485 assert(Start && "Building a context chain from a null context");
4486 DeclContextList Chain;
4487 for (DeclContext *DC = Start->getPrimaryContext(); DC != nullptr;
4488 DC = DC->getLookupParent()) {
4489 NamespaceDecl *ND = dyn_cast_or_null<NamespaceDecl>(DC);
4490 if (!DC->isInlineNamespace() && !DC->isTransparentContext() &&
4491 !(ND && ND->isAnonymousNamespace()))
4492 Chain.push_back(DC->getPrimaryContext());
4493 }
4494 return Chain;
4495 }
4496
4497 unsigned
buildNestedNameSpecifier(DeclContextList & DeclChain,NestedNameSpecifier * & NNS)4498 TypoCorrectionConsumer::NamespaceSpecifierSet::buildNestedNameSpecifier(
4499 DeclContextList &DeclChain, NestedNameSpecifier *&NNS) {
4500 unsigned NumSpecifiers = 0;
4501 for (DeclContext *C : llvm::reverse(DeclChain)) {
4502 if (auto *ND = dyn_cast_or_null<NamespaceDecl>(C)) {
4503 NNS = NestedNameSpecifier::Create(Context, NNS, ND);
4504 ++NumSpecifiers;
4505 } else if (auto *RD = dyn_cast_or_null<RecordDecl>(C)) {
4506 NNS = NestedNameSpecifier::Create(Context, NNS, RD->isTemplateDecl(),
4507 RD->getTypeForDecl());
4508 ++NumSpecifiers;
4509 }
4510 }
4511 return NumSpecifiers;
4512 }
4513
addNameSpecifier(DeclContext * Ctx)4514 void TypoCorrectionConsumer::NamespaceSpecifierSet::addNameSpecifier(
4515 DeclContext *Ctx) {
4516 NestedNameSpecifier *NNS = nullptr;
4517 unsigned NumSpecifiers = 0;
4518 DeclContextList NamespaceDeclChain(buildContextChain(Ctx));
4519 DeclContextList FullNamespaceDeclChain(NamespaceDeclChain);
4520
4521 // Eliminate common elements from the two DeclContext chains.
4522 for (DeclContext *C : llvm::reverse(CurContextChain)) {
4523 if (NamespaceDeclChain.empty() || NamespaceDeclChain.back() != C)
4524 break;
4525 NamespaceDeclChain.pop_back();
4526 }
4527
4528 // Build the NestedNameSpecifier from what is left of the NamespaceDeclChain
4529 NumSpecifiers = buildNestedNameSpecifier(NamespaceDeclChain, NNS);
4530
4531 // Add an explicit leading '::' specifier if needed.
4532 if (NamespaceDeclChain.empty()) {
4533 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4534 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4535 NumSpecifiers =
4536 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4537 } else if (NamedDecl *ND =
4538 dyn_cast_or_null<NamedDecl>(NamespaceDeclChain.back())) {
4539 IdentifierInfo *Name = ND->getIdentifier();
4540 bool SameNameSpecifier = false;
4541 if (std::find(CurNameSpecifierIdentifiers.begin(),
4542 CurNameSpecifierIdentifiers.end(),
4543 Name) != CurNameSpecifierIdentifiers.end()) {
4544 std::string NewNameSpecifier;
4545 llvm::raw_string_ostream SpecifierOStream(NewNameSpecifier);
4546 SmallVector<const IdentifierInfo *, 4> NewNameSpecifierIdentifiers;
4547 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4548 NNS->print(SpecifierOStream, Context.getPrintingPolicy());
4549 SpecifierOStream.flush();
4550 SameNameSpecifier = NewNameSpecifier == CurNameSpecifier;
4551 }
4552 if (SameNameSpecifier || llvm::find(CurContextIdentifiers, Name) !=
4553 CurContextIdentifiers.end()) {
4554 // Rebuild the NestedNameSpecifier as a globally-qualified specifier.
4555 NNS = NestedNameSpecifier::GlobalSpecifier(Context);
4556 NumSpecifiers =
4557 buildNestedNameSpecifier(FullNamespaceDeclChain, NNS);
4558 }
4559 }
4560
4561 // If the built NestedNameSpecifier would be replacing an existing
4562 // NestedNameSpecifier, use the number of component identifiers that
4563 // would need to be changed as the edit distance instead of the number
4564 // of components in the built NestedNameSpecifier.
4565 if (NNS && !CurNameSpecifierIdentifiers.empty()) {
4566 SmallVector<const IdentifierInfo*, 4> NewNameSpecifierIdentifiers;
4567 getNestedNameSpecifierIdentifiers(NNS, NewNameSpecifierIdentifiers);
4568 NumSpecifiers = llvm::ComputeEditDistance(
4569 llvm::makeArrayRef(CurNameSpecifierIdentifiers),
4570 llvm::makeArrayRef(NewNameSpecifierIdentifiers));
4571 }
4572
4573 SpecifierInfo SI = {Ctx, NNS, NumSpecifiers};
4574 DistanceMap[NumSpecifiers].push_back(SI);
4575 }
4576
4577 /// 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)4578 static void LookupPotentialTypoResult(Sema &SemaRef,
4579 LookupResult &Res,
4580 IdentifierInfo *Name,
4581 Scope *S, CXXScopeSpec *SS,
4582 DeclContext *MemberContext,
4583 bool EnteringContext,
4584 bool isObjCIvarLookup,
4585 bool FindHidden) {
4586 Res.suppressDiagnostics();
4587 Res.clear();
4588 Res.setLookupName(Name);
4589 Res.setAllowHidden(FindHidden);
4590 if (MemberContext) {
4591 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(MemberContext)) {
4592 if (isObjCIvarLookup) {
4593 if (ObjCIvarDecl *Ivar = Class->lookupInstanceVariable(Name)) {
4594 Res.addDecl(Ivar);
4595 Res.resolveKind();
4596 return;
4597 }
4598 }
4599
4600 if (ObjCPropertyDecl *Prop = Class->FindPropertyDeclaration(
4601 Name, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
4602 Res.addDecl(Prop);
4603 Res.resolveKind();
4604 return;
4605 }
4606 }
4607
4608 SemaRef.LookupQualifiedName(Res, MemberContext);
4609 return;
4610 }
4611
4612 SemaRef.LookupParsedName(Res, S, SS, /*AllowBuiltinCreation=*/false,
4613 EnteringContext);
4614
4615 // Fake ivar lookup; this should really be part of
4616 // LookupParsedName.
4617 if (ObjCMethodDecl *Method = SemaRef.getCurMethodDecl()) {
4618 if (Method->isInstanceMethod() && Method->getClassInterface() &&
4619 (Res.empty() ||
4620 (Res.isSingleResult() &&
4621 Res.getFoundDecl()->isDefinedOutsideFunctionOrMethod()))) {
4622 if (ObjCIvarDecl *IV
4623 = Method->getClassInterface()->lookupInstanceVariable(Name)) {
4624 Res.addDecl(IV);
4625 Res.resolveKind();
4626 }
4627 }
4628 }
4629 }
4630
4631 /// Add keywords to the consumer as possible typo corrections.
AddKeywordsToConsumer(Sema & SemaRef,TypoCorrectionConsumer & Consumer,Scope * S,CorrectionCandidateCallback & CCC,bool AfterNestedNameSpecifier)4632 static void AddKeywordsToConsumer(Sema &SemaRef,
4633 TypoCorrectionConsumer &Consumer,
4634 Scope *S, CorrectionCandidateCallback &CCC,
4635 bool AfterNestedNameSpecifier) {
4636 if (AfterNestedNameSpecifier) {
4637 // For 'X::', we know exactly which keywords can appear next.
4638 Consumer.addKeywordResult("template");
4639 if (CCC.WantExpressionKeywords)
4640 Consumer.addKeywordResult("operator");
4641 return;
4642 }
4643
4644 if (CCC.WantObjCSuper)
4645 Consumer.addKeywordResult("super");
4646
4647 if (CCC.WantTypeSpecifiers) {
4648 // Add type-specifier keywords to the set of results.
4649 static const char *const CTypeSpecs[] = {
4650 "char", "const", "double", "enum", "float", "int", "long", "short",
4651 "signed", "struct", "union", "unsigned", "void", "volatile",
4652 "_Complex", "_Imaginary",
4653 // storage-specifiers as well
4654 "extern", "inline", "static", "typedef"
4655 };
4656
4657 const unsigned NumCTypeSpecs = llvm::array_lengthof(CTypeSpecs);
4658 for (unsigned I = 0; I != NumCTypeSpecs; ++I)
4659 Consumer.addKeywordResult(CTypeSpecs[I]);
4660
4661 if (SemaRef.getLangOpts().C99)
4662 Consumer.addKeywordResult("restrict");
4663 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus)
4664 Consumer.addKeywordResult("bool");
4665 else if (SemaRef.getLangOpts().C99)
4666 Consumer.addKeywordResult("_Bool");
4667
4668 if (SemaRef.getLangOpts().CPlusPlus) {
4669 Consumer.addKeywordResult("class");
4670 Consumer.addKeywordResult("typename");
4671 Consumer.addKeywordResult("wchar_t");
4672
4673 if (SemaRef.getLangOpts().CPlusPlus11) {
4674 Consumer.addKeywordResult("char16_t");
4675 Consumer.addKeywordResult("char32_t");
4676 Consumer.addKeywordResult("constexpr");
4677 Consumer.addKeywordResult("decltype");
4678 Consumer.addKeywordResult("thread_local");
4679 }
4680 }
4681
4682 if (SemaRef.getLangOpts().GNUKeywords)
4683 Consumer.addKeywordResult("typeof");
4684 } else if (CCC.WantFunctionLikeCasts) {
4685 static const char *const CastableTypeSpecs[] = {
4686 "char", "double", "float", "int", "long", "short",
4687 "signed", "unsigned", "void"
4688 };
4689 for (auto *kw : CastableTypeSpecs)
4690 Consumer.addKeywordResult(kw);
4691 }
4692
4693 if (CCC.WantCXXNamedCasts && SemaRef.getLangOpts().CPlusPlus) {
4694 Consumer.addKeywordResult("const_cast");
4695 Consumer.addKeywordResult("dynamic_cast");
4696 Consumer.addKeywordResult("reinterpret_cast");
4697 Consumer.addKeywordResult("static_cast");
4698 }
4699
4700 if (CCC.WantExpressionKeywords) {
4701 Consumer.addKeywordResult("sizeof");
4702 if (SemaRef.getLangOpts().Bool || SemaRef.getLangOpts().CPlusPlus) {
4703 Consumer.addKeywordResult("false");
4704 Consumer.addKeywordResult("true");
4705 }
4706
4707 if (SemaRef.getLangOpts().CPlusPlus) {
4708 static const char *const CXXExprs[] = {
4709 "delete", "new", "operator", "throw", "typeid"
4710 };
4711 const unsigned NumCXXExprs = llvm::array_lengthof(CXXExprs);
4712 for (unsigned I = 0; I != NumCXXExprs; ++I)
4713 Consumer.addKeywordResult(CXXExprs[I]);
4714
4715 if (isa<CXXMethodDecl>(SemaRef.CurContext) &&
4716 cast<CXXMethodDecl>(SemaRef.CurContext)->isInstance())
4717 Consumer.addKeywordResult("this");
4718
4719 if (SemaRef.getLangOpts().CPlusPlus11) {
4720 Consumer.addKeywordResult("alignof");
4721 Consumer.addKeywordResult("nullptr");
4722 }
4723 }
4724
4725 if (SemaRef.getLangOpts().C11) {
4726 // FIXME: We should not suggest _Alignof if the alignof macro
4727 // is present.
4728 Consumer.addKeywordResult("_Alignof");
4729 }
4730 }
4731
4732 if (CCC.WantRemainingKeywords) {
4733 if (SemaRef.getCurFunctionOrMethodDecl() || SemaRef.getCurBlock()) {
4734 // Statements.
4735 static const char *const CStmts[] = {
4736 "do", "else", "for", "goto", "if", "return", "switch", "while" };
4737 const unsigned NumCStmts = llvm::array_lengthof(CStmts);
4738 for (unsigned I = 0; I != NumCStmts; ++I)
4739 Consumer.addKeywordResult(CStmts[I]);
4740
4741 if (SemaRef.getLangOpts().CPlusPlus) {
4742 Consumer.addKeywordResult("catch");
4743 Consumer.addKeywordResult("try");
4744 }
4745
4746 if (S && S->getBreakParent())
4747 Consumer.addKeywordResult("break");
4748
4749 if (S && S->getContinueParent())
4750 Consumer.addKeywordResult("continue");
4751
4752 if (SemaRef.getCurFunction() &&
4753 !SemaRef.getCurFunction()->SwitchStack.empty()) {
4754 Consumer.addKeywordResult("case");
4755 Consumer.addKeywordResult("default");
4756 }
4757 } else {
4758 if (SemaRef.getLangOpts().CPlusPlus) {
4759 Consumer.addKeywordResult("namespace");
4760 Consumer.addKeywordResult("template");
4761 }
4762
4763 if (S && S->isClassScope()) {
4764 Consumer.addKeywordResult("explicit");
4765 Consumer.addKeywordResult("friend");
4766 Consumer.addKeywordResult("mutable");
4767 Consumer.addKeywordResult("private");
4768 Consumer.addKeywordResult("protected");
4769 Consumer.addKeywordResult("public");
4770 Consumer.addKeywordResult("virtual");
4771 }
4772 }
4773
4774 if (SemaRef.getLangOpts().CPlusPlus) {
4775 Consumer.addKeywordResult("using");
4776
4777 if (SemaRef.getLangOpts().CPlusPlus11)
4778 Consumer.addKeywordResult("static_assert");
4779 }
4780 }
4781 }
4782
makeTypoCorrectionConsumer(const DeclarationNameInfo & TypoName,Sema::LookupNameKind LookupKind,Scope * S,CXXScopeSpec * SS,CorrectionCandidateCallback & CCC,DeclContext * MemberContext,bool EnteringContext,const ObjCObjectPointerType * OPT,bool ErrorRecovery)4783 std::unique_ptr<TypoCorrectionConsumer> Sema::makeTypoCorrectionConsumer(
4784 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
4785 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
4786 DeclContext *MemberContext, bool EnteringContext,
4787 const ObjCObjectPointerType *OPT, bool ErrorRecovery) {
4788
4789 if (Diags.hasFatalErrorOccurred() || !getLangOpts().SpellChecking ||
4790 DisableTypoCorrection)
4791 return nullptr;
4792
4793 // In Microsoft mode, don't perform typo correction in a template member
4794 // function dependent context because it interferes with the "lookup into
4795 // dependent bases of class templates" feature.
4796 if (getLangOpts().MSVCCompat && CurContext->isDependentContext() &&
4797 isa<CXXMethodDecl>(CurContext))
4798 return nullptr;
4799
4800 // We only attempt to correct typos for identifiers.
4801 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4802 if (!Typo)
4803 return nullptr;
4804
4805 // If the scope specifier itself was invalid, don't try to correct
4806 // typos.
4807 if (SS && SS->isInvalid())
4808 return nullptr;
4809
4810 // Never try to correct typos during any kind of code synthesis.
4811 if (!CodeSynthesisContexts.empty())
4812 return nullptr;
4813
4814 // Don't try to correct 'super'.
4815 if (S && S->isInObjcMethodScope() && Typo == getSuperIdentifier())
4816 return nullptr;
4817
4818 // Abort if typo correction already failed for this specific typo.
4819 IdentifierSourceLocations::iterator locs = TypoCorrectionFailures.find(Typo);
4820 if (locs != TypoCorrectionFailures.end() &&
4821 locs->second.count(TypoName.getLoc()))
4822 return nullptr;
4823
4824 // Don't try to correct the identifier "vector" when in AltiVec mode.
4825 // TODO: Figure out why typo correction misbehaves in this case, fix it, and
4826 // remove this workaround.
4827 if ((getLangOpts().AltiVec || getLangOpts().ZVector) && Typo->isStr("vector"))
4828 return nullptr;
4829
4830 // Provide a stop gap for files that are just seriously broken. Trying
4831 // to correct all typos can turn into a HUGE performance penalty, causing
4832 // some files to take minutes to get rejected by the parser.
4833 unsigned Limit = getDiagnostics().getDiagnosticOptions().SpellCheckingLimit;
4834 if (Limit && TyposCorrected >= Limit)
4835 return nullptr;
4836 ++TyposCorrected;
4837
4838 // If we're handling a missing symbol error, using modules, and the
4839 // special search all modules option is used, look for a missing import.
4840 if (ErrorRecovery && getLangOpts().Modules &&
4841 getLangOpts().ModulesSearchAll) {
4842 // The following has the side effect of loading the missing module.
4843 getModuleLoader().lookupMissingImports(Typo->getName(),
4844 TypoName.getBeginLoc());
4845 }
4846
4847 // Extend the lifetime of the callback. We delayed this until here
4848 // to avoid allocations in the hot path (which is where no typo correction
4849 // occurs). Note that CorrectionCandidateCallback is polymorphic and
4850 // initially stack-allocated.
4851 std::unique_ptr<CorrectionCandidateCallback> ClonedCCC = CCC.clone();
4852 auto Consumer = std::make_unique<TypoCorrectionConsumer>(
4853 *this, TypoName, LookupKind, S, SS, std::move(ClonedCCC), MemberContext,
4854 EnteringContext);
4855
4856 // Perform name lookup to find visible, similarly-named entities.
4857 bool IsUnqualifiedLookup = false;
4858 DeclContext *QualifiedDC = MemberContext;
4859 if (MemberContext) {
4860 LookupVisibleDecls(MemberContext, LookupKind, *Consumer);
4861
4862 // Look in qualified interfaces.
4863 if (OPT) {
4864 for (auto *I : OPT->quals())
4865 LookupVisibleDecls(I, LookupKind, *Consumer);
4866 }
4867 } else if (SS && SS->isSet()) {
4868 QualifiedDC = computeDeclContext(*SS, EnteringContext);
4869 if (!QualifiedDC)
4870 return nullptr;
4871
4872 LookupVisibleDecls(QualifiedDC, LookupKind, *Consumer);
4873 } else {
4874 IsUnqualifiedLookup = true;
4875 }
4876
4877 // Determine whether we are going to search in the various namespaces for
4878 // corrections.
4879 bool SearchNamespaces
4880 = getLangOpts().CPlusPlus &&
4881 (IsUnqualifiedLookup || (SS && SS->isSet()));
4882
4883 if (IsUnqualifiedLookup || SearchNamespaces) {
4884 // For unqualified lookup, look through all of the names that we have
4885 // seen in this translation unit.
4886 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4887 for (const auto &I : Context.Idents)
4888 Consumer->FoundName(I.getKey());
4889
4890 // Walk through identifiers in external identifier sources.
4891 // FIXME: Re-add the ability to skip very unlikely potential corrections.
4892 if (IdentifierInfoLookup *External
4893 = Context.Idents.getExternalIdentifierLookup()) {
4894 std::unique_ptr<IdentifierIterator> Iter(External->getIdentifiers());
4895 do {
4896 StringRef Name = Iter->Next();
4897 if (Name.empty())
4898 break;
4899
4900 Consumer->FoundName(Name);
4901 } while (true);
4902 }
4903 }
4904
4905 AddKeywordsToConsumer(*this, *Consumer, S,
4906 *Consumer->getCorrectionValidator(),
4907 SS && SS->isNotEmpty());
4908
4909 // Build the NestedNameSpecifiers for the KnownNamespaces, if we're going
4910 // to search those namespaces.
4911 if (SearchNamespaces) {
4912 // Load any externally-known namespaces.
4913 if (ExternalSource && !LoadedExternalKnownNamespaces) {
4914 SmallVector<NamespaceDecl *, 4> ExternalKnownNamespaces;
4915 LoadedExternalKnownNamespaces = true;
4916 ExternalSource->ReadKnownNamespaces(ExternalKnownNamespaces);
4917 for (auto *N : ExternalKnownNamespaces)
4918 KnownNamespaces[N] = true;
4919 }
4920
4921 Consumer->addNamespaces(KnownNamespaces);
4922 }
4923
4924 return Consumer;
4925 }
4926
4927 /// Try to "correct" a typo in the source code by finding
4928 /// visible declarations whose names are similar to the name that was
4929 /// present in the source code.
4930 ///
4931 /// \param TypoName the \c DeclarationNameInfo structure that contains
4932 /// the name that was present in the source code along with its location.
4933 ///
4934 /// \param LookupKind the name-lookup criteria used to search for the name.
4935 ///
4936 /// \param S the scope in which name lookup occurs.
4937 ///
4938 /// \param SS the nested-name-specifier that precedes the name we're
4939 /// looking for, if present.
4940 ///
4941 /// \param CCC A CorrectionCandidateCallback object that provides further
4942 /// validation of typo correction candidates. It also provides flags for
4943 /// determining the set of keywords permitted.
4944 ///
4945 /// \param MemberContext if non-NULL, the context in which to look for
4946 /// a member access expression.
4947 ///
4948 /// \param EnteringContext whether we're entering the context described by
4949 /// the nested-name-specifier SS.
4950 ///
4951 /// \param OPT when non-NULL, the search for visible declarations will
4952 /// also walk the protocols in the qualified interfaces of \p OPT.
4953 ///
4954 /// \returns a \c TypoCorrection containing the corrected name if the typo
4955 /// along with information such as the \c NamedDecl where the corrected name
4956 /// was declared, and any additional \c NestedNameSpecifier needed to access
4957 /// 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)4958 TypoCorrection Sema::CorrectTypo(const DeclarationNameInfo &TypoName,
4959 Sema::LookupNameKind LookupKind,
4960 Scope *S, CXXScopeSpec *SS,
4961 CorrectionCandidateCallback &CCC,
4962 CorrectTypoKind Mode,
4963 DeclContext *MemberContext,
4964 bool EnteringContext,
4965 const ObjCObjectPointerType *OPT,
4966 bool RecordFailure) {
4967 // Always let the ExternalSource have the first chance at correction, even
4968 // if we would otherwise have given up.
4969 if (ExternalSource) {
4970 if (TypoCorrection Correction =
4971 ExternalSource->CorrectTypo(TypoName, LookupKind, S, SS, CCC,
4972 MemberContext, EnteringContext, OPT))
4973 return Correction;
4974 }
4975
4976 // Ugly hack equivalent to CTC == CTC_ObjCMessageReceiver;
4977 // WantObjCSuper is only true for CTC_ObjCMessageReceiver and for
4978 // some instances of CTC_Unknown, while WantRemainingKeywords is true
4979 // for CTC_Unknown but not for CTC_ObjCMessageReceiver.
4980 bool ObjCMessageReceiver = CCC.WantObjCSuper && !CCC.WantRemainingKeywords;
4981
4982 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
4983 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
4984 MemberContext, EnteringContext,
4985 OPT, Mode == CTK_ErrorRecovery);
4986
4987 if (!Consumer)
4988 return TypoCorrection();
4989
4990 // If we haven't found anything, we're done.
4991 if (Consumer->empty())
4992 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
4993
4994 // Make sure the best edit distance (prior to adding any namespace qualifiers)
4995 // is not more that about a third of the length of the typo's identifier.
4996 unsigned ED = Consumer->getBestEditDistance(true);
4997 unsigned TypoLen = Typo->getName().size();
4998 if (ED > 0 && TypoLen / ED < 3)
4999 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5000
5001 TypoCorrection BestTC = Consumer->getNextCorrection();
5002 TypoCorrection SecondBestTC = Consumer->getNextCorrection();
5003 if (!BestTC)
5004 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5005
5006 ED = BestTC.getEditDistance();
5007
5008 if (TypoLen >= 3 && ED > 0 && TypoLen / ED < 3) {
5009 // If this was an unqualified lookup and we believe the callback
5010 // object wouldn't have filtered out possible corrections, note
5011 // that no correction was found.
5012 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5013 }
5014
5015 // If only a single name remains, return that result.
5016 if (!SecondBestTC ||
5017 SecondBestTC.getEditDistance(false) > BestTC.getEditDistance(false)) {
5018 const TypoCorrection &Result = BestTC;
5019
5020 // Don't correct to a keyword that's the same as the typo; the keyword
5021 // wasn't actually in scope.
5022 if (ED == 0 && Result.isKeyword())
5023 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5024
5025 TypoCorrection TC = Result;
5026 TC.setCorrectionRange(SS, TypoName);
5027 checkCorrectionVisibility(*this, TC);
5028 return TC;
5029 } else if (SecondBestTC && ObjCMessageReceiver) {
5030 // Prefer 'super' when we're completing in a message-receiver
5031 // context.
5032
5033 if (BestTC.getCorrection().getAsString() != "super") {
5034 if (SecondBestTC.getCorrection().getAsString() == "super")
5035 BestTC = SecondBestTC;
5036 else if ((*Consumer)["super"].front().isKeyword())
5037 BestTC = (*Consumer)["super"].front();
5038 }
5039 // Don't correct to a keyword that's the same as the typo; the keyword
5040 // wasn't actually in scope.
5041 if (BestTC.getEditDistance() == 0 ||
5042 BestTC.getCorrection().getAsString() != "super")
5043 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure);
5044
5045 BestTC.setCorrectionRange(SS, TypoName);
5046 return BestTC;
5047 }
5048
5049 // Record the failure's location if needed and return an empty correction. If
5050 // this was an unqualified lookup and we believe the callback object did not
5051 // filter out possible corrections, also cache the failure for the typo.
5052 return FailedCorrection(Typo, TypoName.getLoc(), RecordFailure && !SecondBestTC);
5053 }
5054
5055 /// Try to "correct" a typo in the source code by finding
5056 /// visible declarations whose names are similar to the name that was
5057 /// present in the source code.
5058 ///
5059 /// \param TypoName the \c DeclarationNameInfo structure that contains
5060 /// the name that was present in the source code along with its location.
5061 ///
5062 /// \param LookupKind the name-lookup criteria used to search for the name.
5063 ///
5064 /// \param S the scope in which name lookup occurs.
5065 ///
5066 /// \param SS the nested-name-specifier that precedes the name we're
5067 /// looking for, if present.
5068 ///
5069 /// \param CCC A CorrectionCandidateCallback object that provides further
5070 /// validation of typo correction candidates. It also provides flags for
5071 /// determining the set of keywords permitted.
5072 ///
5073 /// \param TDG A TypoDiagnosticGenerator functor that will be used to print
5074 /// diagnostics when the actual typo correction is attempted.
5075 ///
5076 /// \param TRC A TypoRecoveryCallback functor that will be used to build an
5077 /// Expr from a typo correction candidate.
5078 ///
5079 /// \param MemberContext if non-NULL, the context in which to look for
5080 /// a member access expression.
5081 ///
5082 /// \param EnteringContext whether we're entering the context described by
5083 /// the nested-name-specifier SS.
5084 ///
5085 /// \param OPT when non-NULL, the search for visible declarations will
5086 /// also walk the protocols in the qualified interfaces of \p OPT.
5087 ///
5088 /// \returns a new \c TypoExpr that will later be replaced in the AST with an
5089 /// Expr representing the result of performing typo correction, or nullptr if
5090 /// typo correction is not possible. If nullptr is returned, no diagnostics will
5091 /// be emitted and it is the responsibility of the caller to emit any that are
5092 /// 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)5093 TypoExpr *Sema::CorrectTypoDelayed(
5094 const DeclarationNameInfo &TypoName, Sema::LookupNameKind LookupKind,
5095 Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC,
5096 TypoDiagnosticGenerator TDG, TypoRecoveryCallback TRC, CorrectTypoKind Mode,
5097 DeclContext *MemberContext, bool EnteringContext,
5098 const ObjCObjectPointerType *OPT) {
5099 auto Consumer = makeTypoCorrectionConsumer(TypoName, LookupKind, S, SS, CCC,
5100 MemberContext, EnteringContext,
5101 OPT, Mode == CTK_ErrorRecovery);
5102
5103 // Give the external sema source a chance to correct the typo.
5104 TypoCorrection ExternalTypo;
5105 if (ExternalSource && Consumer) {
5106 ExternalTypo = ExternalSource->CorrectTypo(
5107 TypoName, LookupKind, S, SS, *Consumer->getCorrectionValidator(),
5108 MemberContext, EnteringContext, OPT);
5109 if (ExternalTypo)
5110 Consumer->addCorrection(ExternalTypo);
5111 }
5112
5113 if (!Consumer || Consumer->empty())
5114 return nullptr;
5115
5116 // Make sure the best edit distance (prior to adding any namespace qualifiers)
5117 // is not more that about a third of the length of the typo's identifier.
5118 unsigned ED = Consumer->getBestEditDistance(true);
5119 IdentifierInfo *Typo = TypoName.getName().getAsIdentifierInfo();
5120 if (!ExternalTypo && ED > 0 && Typo->getName().size() / ED < 3)
5121 return nullptr;
5122 ExprEvalContexts.back().NumTypos++;
5123 return createDelayedTypo(std::move(Consumer), std::move(TDG), std::move(TRC),
5124 TypoName.getLoc());
5125 }
5126
addCorrectionDecl(NamedDecl * CDecl)5127 void TypoCorrection::addCorrectionDecl(NamedDecl *CDecl) {
5128 if (!CDecl) return;
5129
5130 if (isKeyword())
5131 CorrectionDecls.clear();
5132
5133 CorrectionDecls.push_back(CDecl);
5134
5135 if (!CorrectionName)
5136 CorrectionName = CDecl->getDeclName();
5137 }
5138
getAsString(const LangOptions & LO) const5139 std::string TypoCorrection::getAsString(const LangOptions &LO) const {
5140 if (CorrectionNameSpec) {
5141 std::string tmpBuffer;
5142 llvm::raw_string_ostream PrefixOStream(tmpBuffer);
5143 CorrectionNameSpec->print(PrefixOStream, PrintingPolicy(LO));
5144 PrefixOStream << CorrectionName;
5145 return PrefixOStream.str();
5146 }
5147
5148 return CorrectionName.getAsString();
5149 }
5150
ValidateCandidate(const TypoCorrection & candidate)5151 bool CorrectionCandidateCallback::ValidateCandidate(
5152 const TypoCorrection &candidate) {
5153 if (!candidate.isResolved())
5154 return true;
5155
5156 if (candidate.isKeyword())
5157 return WantTypeSpecifiers || WantExpressionKeywords || WantCXXNamedCasts ||
5158 WantRemainingKeywords || WantObjCSuper;
5159
5160 bool HasNonType = false;
5161 bool HasStaticMethod = false;
5162 bool HasNonStaticMethod = false;
5163 for (Decl *D : candidate) {
5164 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(D))
5165 D = FTD->getTemplatedDecl();
5166 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
5167 if (Method->isStatic())
5168 HasStaticMethod = true;
5169 else
5170 HasNonStaticMethod = true;
5171 }
5172 if (!isa<TypeDecl>(D))
5173 HasNonType = true;
5174 }
5175
5176 if (IsAddressOfOperand && HasNonStaticMethod && !HasStaticMethod &&
5177 !candidate.getCorrectionSpecifier())
5178 return false;
5179
5180 return WantTypeSpecifiers || HasNonType;
5181 }
5182
FunctionCallFilterCCC(Sema & SemaRef,unsigned NumArgs,bool HasExplicitTemplateArgs,MemberExpr * ME)5183 FunctionCallFilterCCC::FunctionCallFilterCCC(Sema &SemaRef, unsigned NumArgs,
5184 bool HasExplicitTemplateArgs,
5185 MemberExpr *ME)
5186 : NumArgs(NumArgs), HasExplicitTemplateArgs(HasExplicitTemplateArgs),
5187 CurContext(SemaRef.CurContext), MemberFn(ME) {
5188 WantTypeSpecifiers = false;
5189 WantFunctionLikeCasts = SemaRef.getLangOpts().CPlusPlus &&
5190 !HasExplicitTemplateArgs && NumArgs == 1;
5191 WantCXXNamedCasts = HasExplicitTemplateArgs && NumArgs == 1;
5192 WantRemainingKeywords = false;
5193 }
5194
ValidateCandidate(const TypoCorrection & candidate)5195 bool FunctionCallFilterCCC::ValidateCandidate(const TypoCorrection &candidate) {
5196 if (!candidate.getCorrectionDecl())
5197 return candidate.isKeyword();
5198
5199 for (auto *C : candidate) {
5200 FunctionDecl *FD = nullptr;
5201 NamedDecl *ND = C->getUnderlyingDecl();
5202 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
5203 FD = FTD->getTemplatedDecl();
5204 if (!HasExplicitTemplateArgs && !FD) {
5205 if (!(FD = dyn_cast<FunctionDecl>(ND)) && isa<ValueDecl>(ND)) {
5206 // If the Decl is neither a function nor a template function,
5207 // determine if it is a pointer or reference to a function. If so,
5208 // check against the number of arguments expected for the pointee.
5209 QualType ValType = cast<ValueDecl>(ND)->getType();
5210 if (ValType.isNull())
5211 continue;
5212 if (ValType->isAnyPointerType() || ValType->isReferenceType())
5213 ValType = ValType->getPointeeType();
5214 if (const FunctionProtoType *FPT = ValType->getAs<FunctionProtoType>())
5215 if (FPT->getNumParams() == NumArgs)
5216 return true;
5217 }
5218 }
5219
5220 // A typo for a function-style cast can look like a function call in C++.
5221 if ((HasExplicitTemplateArgs ? getAsTypeTemplateDecl(ND) != nullptr
5222 : isa<TypeDecl>(ND)) &&
5223 CurContext->getParentASTContext().getLangOpts().CPlusPlus)
5224 // Only a class or class template can take two or more arguments.
5225 return NumArgs <= 1 || HasExplicitTemplateArgs || isa<CXXRecordDecl>(ND);
5226
5227 // Skip the current candidate if it is not a FunctionDecl or does not accept
5228 // the current number of arguments.
5229 if (!FD || !(FD->getNumParams() >= NumArgs &&
5230 FD->getMinRequiredArguments() <= NumArgs))
5231 continue;
5232
5233 // If the current candidate is a non-static C++ method, skip the candidate
5234 // unless the method being corrected--or the current DeclContext, if the
5235 // function being corrected is not a method--is a method in the same class
5236 // or a descendent class of the candidate's parent class.
5237 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
5238 if (MemberFn || !MD->isStatic()) {
5239 CXXMethodDecl *CurMD =
5240 MemberFn
5241 ? dyn_cast_or_null<CXXMethodDecl>(MemberFn->getMemberDecl())
5242 : dyn_cast_or_null<CXXMethodDecl>(CurContext);
5243 CXXRecordDecl *CurRD =
5244 CurMD ? CurMD->getParent()->getCanonicalDecl() : nullptr;
5245 CXXRecordDecl *RD = MD->getParent()->getCanonicalDecl();
5246 if (!CurRD || (CurRD != RD && !CurRD->isDerivedFrom(RD)))
5247 continue;
5248 }
5249 }
5250 return true;
5251 }
5252 return false;
5253 }
5254
diagnoseTypo(const TypoCorrection & Correction,const PartialDiagnostic & TypoDiag,bool ErrorRecovery)5255 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5256 const PartialDiagnostic &TypoDiag,
5257 bool ErrorRecovery) {
5258 diagnoseTypo(Correction, TypoDiag, PDiag(diag::note_previous_decl),
5259 ErrorRecovery);
5260 }
5261
5262 /// Find which declaration we should import to provide the definition of
5263 /// the given declaration.
getDefinitionToImport(NamedDecl * D)5264 static NamedDecl *getDefinitionToImport(NamedDecl *D) {
5265 if (VarDecl *VD = dyn_cast<VarDecl>(D))
5266 return VD->getDefinition();
5267 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
5268 return FD->getDefinition();
5269 if (TagDecl *TD = dyn_cast<TagDecl>(D))
5270 return TD->getDefinition();
5271 // The first definition for this ObjCInterfaceDecl might be in the TU
5272 // and not associated with any module. Use the one we know to be complete
5273 // and have just seen in a module.
5274 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D))
5275 return ID;
5276 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D))
5277 return PD->getDefinition();
5278 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
5279 if (NamedDecl *TTD = TD->getTemplatedDecl())
5280 return getDefinitionToImport(TTD);
5281 return nullptr;
5282 }
5283
diagnoseMissingImport(SourceLocation Loc,NamedDecl * Decl,MissingImportKind MIK,bool Recover)5284 void Sema::diagnoseMissingImport(SourceLocation Loc, NamedDecl *Decl,
5285 MissingImportKind MIK, bool Recover) {
5286 // Suggest importing a module providing the definition of this entity, if
5287 // possible.
5288 NamedDecl *Def = getDefinitionToImport(Decl);
5289 if (!Def)
5290 Def = Decl;
5291
5292 Module *Owner = getOwningModule(Def);
5293 assert(Owner && "definition of hidden declaration is not in a module");
5294
5295 llvm::SmallVector<Module*, 8> OwningModules;
5296 OwningModules.push_back(Owner);
5297 auto Merged = Context.getModulesWithMergedDefinition(Def);
5298 OwningModules.insert(OwningModules.end(), Merged.begin(), Merged.end());
5299
5300 diagnoseMissingImport(Loc, Def, Def->getLocation(), OwningModules, MIK,
5301 Recover);
5302 }
5303
5304 /// Get a "quoted.h" or <angled.h> include path to use in a diagnostic
5305 /// suggesting the addition of a #include of the specified file.
getHeaderNameForHeader(Preprocessor & PP,const FileEntry * E,llvm::StringRef IncludingFile)5306 static std::string getHeaderNameForHeader(Preprocessor &PP, const FileEntry *E,
5307 llvm::StringRef IncludingFile) {
5308 bool IsSystem = false;
5309 auto Path = PP.getHeaderSearchInfo().suggestPathToFileForDiagnostics(
5310 E, IncludingFile, &IsSystem);
5311 return (IsSystem ? '<' : '"') + Path + (IsSystem ? '>' : '"');
5312 }
5313
diagnoseMissingImport(SourceLocation UseLoc,NamedDecl * Decl,SourceLocation DeclLoc,ArrayRef<Module * > Modules,MissingImportKind MIK,bool Recover)5314 void Sema::diagnoseMissingImport(SourceLocation UseLoc, NamedDecl *Decl,
5315 SourceLocation DeclLoc,
5316 ArrayRef<Module *> Modules,
5317 MissingImportKind MIK, bool Recover) {
5318 assert(!Modules.empty());
5319
5320 auto NotePrevious = [&] {
5321 // FIXME: Suppress the note backtrace even under
5322 // -fdiagnostics-show-note-include-stack. We don't care how this
5323 // declaration was previously reached.
5324 Diag(DeclLoc, diag::note_unreachable_entity) << (int)MIK;
5325 };
5326
5327 // Weed out duplicates from module list.
5328 llvm::SmallVector<Module*, 8> UniqueModules;
5329 llvm::SmallDenseSet<Module*, 8> UniqueModuleSet;
5330 for (auto *M : Modules) {
5331 if (M->Kind == Module::GlobalModuleFragment)
5332 continue;
5333 if (UniqueModuleSet.insert(M).second)
5334 UniqueModules.push_back(M);
5335 }
5336
5337 // Try to find a suitable header-name to #include.
5338 std::string HeaderName;
5339 if (const FileEntry *Header =
5340 PP.getHeaderToIncludeForDiagnostics(UseLoc, DeclLoc)) {
5341 if (const FileEntry *FE =
5342 SourceMgr.getFileEntryForID(SourceMgr.getFileID(UseLoc)))
5343 HeaderName = getHeaderNameForHeader(PP, Header, FE->tryGetRealPathName());
5344 }
5345
5346 // If we have a #include we should suggest, or if all definition locations
5347 // were in global module fragments, don't suggest an import.
5348 if (!HeaderName.empty() || UniqueModules.empty()) {
5349 // FIXME: Find a smart place to suggest inserting a #include, and add
5350 // a FixItHint there.
5351 Diag(UseLoc, diag::err_module_unimported_use_header)
5352 << (int)MIK << Decl << !HeaderName.empty() << HeaderName;
5353 // Produce a note showing where the entity was declared.
5354 NotePrevious();
5355 if (Recover)
5356 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5357 return;
5358 }
5359
5360 Modules = UniqueModules;
5361
5362 if (Modules.size() > 1) {
5363 std::string ModuleList;
5364 unsigned N = 0;
5365 for (Module *M : Modules) {
5366 ModuleList += "\n ";
5367 if (++N == 5 && N != Modules.size()) {
5368 ModuleList += "[...]";
5369 break;
5370 }
5371 ModuleList += M->getFullModuleName();
5372 }
5373
5374 Diag(UseLoc, diag::err_module_unimported_use_multiple)
5375 << (int)MIK << Decl << ModuleList;
5376 } else {
5377 // FIXME: Add a FixItHint that imports the corresponding module.
5378 Diag(UseLoc, diag::err_module_unimported_use)
5379 << (int)MIK << Decl << Modules[0]->getFullModuleName();
5380 }
5381
5382 NotePrevious();
5383
5384 // Try to recover by implicitly importing this module.
5385 if (Recover)
5386 createImplicitModuleImportForErrorRecovery(UseLoc, Modules[0]);
5387 }
5388
5389 /// Diagnose a successfully-corrected typo. Separated from the correction
5390 /// itself to allow external validation of the result, etc.
5391 ///
5392 /// \param Correction The result of performing typo correction.
5393 /// \param TypoDiag The diagnostic to produce. This will have the corrected
5394 /// string added to it (and usually also a fixit).
5395 /// \param PrevNote A note to use when indicating the location of the entity to
5396 /// which we are correcting. Will have the correction string added to it.
5397 /// \param ErrorRecovery If \c true (the default), the caller is going to
5398 /// recover from the typo as if the corrected string had been typed.
5399 /// In this case, \c PDiag must be an error, and we will attach a fixit
5400 /// to it.
diagnoseTypo(const TypoCorrection & Correction,const PartialDiagnostic & TypoDiag,const PartialDiagnostic & PrevNote,bool ErrorRecovery)5401 void Sema::diagnoseTypo(const TypoCorrection &Correction,
5402 const PartialDiagnostic &TypoDiag,
5403 const PartialDiagnostic &PrevNote,
5404 bool ErrorRecovery) {
5405 std::string CorrectedStr = Correction.getAsString(getLangOpts());
5406 std::string CorrectedQuotedStr = Correction.getQuoted(getLangOpts());
5407 FixItHint FixTypo = FixItHint::CreateReplacement(
5408 Correction.getCorrectionRange(), CorrectedStr);
5409
5410 // Maybe we're just missing a module import.
5411 if (Correction.requiresImport()) {
5412 NamedDecl *Decl = Correction.getFoundDecl();
5413 assert(Decl && "import required but no declaration to import");
5414
5415 diagnoseMissingImport(Correction.getCorrectionRange().getBegin(), Decl,
5416 MissingImportKind::Declaration, ErrorRecovery);
5417 return;
5418 }
5419
5420 Diag(Correction.getCorrectionRange().getBegin(), TypoDiag)
5421 << CorrectedQuotedStr << (ErrorRecovery ? FixTypo : FixItHint());
5422
5423 NamedDecl *ChosenDecl =
5424 Correction.isKeyword() ? nullptr : Correction.getFoundDecl();
5425 if (PrevNote.getDiagID() && ChosenDecl)
5426 Diag(ChosenDecl->getLocation(), PrevNote)
5427 << CorrectedQuotedStr << (ErrorRecovery ? FixItHint() : FixTypo);
5428
5429 // Add any extra diagnostics.
5430 for (const PartialDiagnostic &PD : Correction.getExtraDiagnostics())
5431 Diag(Correction.getCorrectionRange().getBegin(), PD);
5432 }
5433
createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,TypoDiagnosticGenerator TDG,TypoRecoveryCallback TRC,SourceLocation TypoLoc)5434 TypoExpr *Sema::createDelayedTypo(std::unique_ptr<TypoCorrectionConsumer> TCC,
5435 TypoDiagnosticGenerator TDG,
5436 TypoRecoveryCallback TRC,
5437 SourceLocation TypoLoc) {
5438 assert(TCC && "createDelayedTypo requires a valid TypoCorrectionConsumer");
5439 auto TE = new (Context) TypoExpr(Context.DependentTy, TypoLoc);
5440 auto &State = DelayedTypos[TE];
5441 State.Consumer = std::move(TCC);
5442 State.DiagHandler = std::move(TDG);
5443 State.RecoveryHandler = std::move(TRC);
5444 if (TE)
5445 TypoExprs.push_back(TE);
5446 return TE;
5447 }
5448
getTypoExprState(TypoExpr * TE) const5449 const Sema::TypoExprState &Sema::getTypoExprState(TypoExpr *TE) const {
5450 auto Entry = DelayedTypos.find(TE);
5451 assert(Entry != DelayedTypos.end() &&
5452 "Failed to get the state for a TypoExpr!");
5453 return Entry->second;
5454 }
5455
clearDelayedTypo(TypoExpr * TE)5456 void Sema::clearDelayedTypo(TypoExpr *TE) {
5457 DelayedTypos.erase(TE);
5458 }
5459
ActOnPragmaDump(Scope * S,SourceLocation IILoc,IdentifierInfo * II)5460 void Sema::ActOnPragmaDump(Scope *S, SourceLocation IILoc, IdentifierInfo *II) {
5461 DeclarationNameInfo Name(II, IILoc);
5462 LookupResult R(*this, Name, LookupAnyName, Sema::NotForRedeclaration);
5463 R.suppressDiagnostics();
5464 R.setHideTags(false);
5465 LookupName(R, S);
5466 R.dump();
5467 }
5468