Coverage Report

Created: 2022-05-17 06:19

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