Coverage Report

Created: 2020-02-25 14:32

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