Coverage Report

Created: 2021-01-19 06:58

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