Coverage Report

Created: 2020-09-19 12:23

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