Coverage Report

Created: 2024-01-17 10:31

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