Coverage Report

Created: 2019-07-24 05:18

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