Coverage Report

Created: 2021-01-23 06:44

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Sema/SemaAccess.cpp
Line
Count
Source (jump to first uncovered line)
1
//===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
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 provides Sema routines for C++ access control semantics.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Basic/Specifiers.h"
14
#include "clang/Sema/SemaInternal.h"
15
#include "clang/AST/ASTContext.h"
16
#include "clang/AST/CXXInheritance.h"
17
#include "clang/AST/DeclCXX.h"
18
#include "clang/AST/DeclFriend.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DependentDiagnostic.h"
21
#include "clang/AST/ExprCXX.h"
22
#include "clang/Sema/DelayedDiagnostic.h"
23
#include "clang/Sema/Initialization.h"
24
#include "clang/Sema/Lookup.h"
25
26
using namespace clang;
27
using namespace sema;
28
29
/// A copy of Sema's enum without AR_delayed.
30
enum AccessResult {
31
  AR_accessible,
32
  AR_inaccessible,
33
  AR_dependent
34
};
35
36
/// SetMemberAccessSpecifier - Set the access specifier of a member.
37
/// Returns true on error (when the previous member decl access specifier
38
/// is different from the new member decl access specifier).
39
bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
40
                                    NamedDecl *PrevMemberDecl,
41
63.4k
                                    AccessSpecifier LexicalAS) {
42
63.4k
  if (!PrevMemberDecl) {
43
    // Use the lexical access specifier.
44
62.3k
    MemberDecl->setAccess(LexicalAS);
45
62.3k
    return false;
46
62.3k
  }
47
48
  // C++ [class.access.spec]p3: When a member is redeclared its access
49
  // specifier must be same as its initial declaration.
50
1.08k
  if (LexicalAS != AS_none && 
LexicalAS != PrevMemberDecl->getAccess()107
) {
51
4
    Diag(MemberDecl->getLocation(),
52
4
         diag::err_class_redeclared_with_different_access)
53
4
      << MemberDecl << LexicalAS;
54
4
    Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
55
4
      << PrevMemberDecl << PrevMemberDecl->getAccess();
56
57
4
    MemberDecl->setAccess(LexicalAS);
58
4
    return true;
59
4
  }
60
61
1.08k
  MemberDecl->setAccess(PrevMemberDecl->getAccess());
62
1.08k
  return false;
63
1.08k
}
64
65
1.17M
static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66
1.17M
  DeclContext *DC = D->getDeclContext();
67
68
  // This can only happen at top: enum decls only "publish" their
69
  // immediate members.
70
1.17M
  if (isa<EnumDecl>(DC))
71
11.2k
    DC = cast<EnumDecl>(DC)->getDeclContext();
72
73
1.17M
  CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74
1.17M
  while (DeclaringClass->isAnonymousStructOrUnion())
75
0
    DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76
1.17M
  return DeclaringClass;
77
1.17M
}
78
79
namespace {
80
struct EffectiveContext {
81
15
  EffectiveContext() : Inner(nullptr), Dependent(false) {}
82
83
  explicit EffectiveContext(DeclContext *DC)
84
    : Inner(DC),
85
921k
      Dependent(DC->isDependentContext()) {
86
87
    // C++11 [class.access.nest]p1:
88
    //   A nested class is a member and as such has the same access
89
    //   rights as any other member.
90
    // C++11 [class.access]p2:
91
    //   A member of a class can also access all the names to which
92
    //   the class has access.  A local class of a member function
93
    //   may access the same names that the member function itself
94
    //   may access.
95
    // This almost implies that the privileges of nesting are transitive.
96
    // Technically it says nothing about the local classes of non-member
97
    // functions (which can gain privileges through friendship), but we
98
    // take that as an oversight.
99
2.62M
    while (true) {
100
      // We want to add canonical declarations to the EC lists for
101
      // simplicity of checking, but we need to walk up through the
102
      // actual current DC chain.  Otherwise, something like a local
103
      // extern or friend which happens to be the canonical
104
      // declaration will really mess us up.
105
106
2.62M
      if (isa<CXXRecordDecl>(DC)) {
107
939k
        CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
108
939k
        Records.push_back(Record->getCanonicalDecl());
109
939k
        DC = Record->getDeclContext();
110
1.68M
      } else if (isa<FunctionDecl>(DC)) {
111
748k
        FunctionDecl *Function = cast<FunctionDecl>(DC);
112
748k
        Functions.push_back(Function->getCanonicalDecl());
113
748k
        if (Function->getFriendObjectKind())
114
5.83k
          DC = Function->getLexicalDeclContext();
115
742k
        else
116
742k
          DC = Function->getDeclContext();
117
932k
      } else if (DC->isFileContext()) {
118
921k
        break;
119
10.9k
      } else {
120
10.9k
        DC = DC->getParent();
121
10.9k
      }
122
2.62M
    }
123
921k
  }
124
125
99.1k
  bool isDependent() const { return Dependent; }
126
127
8.89k
  bool includesClass(const CXXRecordDecl *R) const {
128
8.89k
    R = R->getCanonicalDecl();
129
8.89k
    return llvm::find(Records, R) != Records.end();
130
8.89k
  }
131
132
  /// Retrieves the innermost "useful" context.  Can be null if we're
133
  /// doing access-control without privileges.
134
97
  DeclContext *getInnerContext() const {
135
97
    return Inner;
136
97
  }
137
138
  typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
139
140
  DeclContext *Inner;
141
  SmallVector<FunctionDecl*, 4> Functions;
142
  SmallVector<CXXRecordDecl*, 4> Records;
143
  bool Dependent;
144
};
145
146
/// Like sema::AccessedEntity, but kindly lets us scribble all over
147
/// it.
148
struct AccessTarget : public AccessedEntity {
149
  AccessTarget(const AccessedEntity &Entity)
150
244k
    : AccessedEntity(Entity) {
151
244k
    initialize();
152
244k
  }
153
154
  AccessTarget(ASTContext &Context,
155
               MemberNonce _,
156
               CXXRecordDecl *NamingClass,
157
               DeclAccessPair FoundDecl,
158
               QualType BaseObjectType)
159
    : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
160
926k
                     FoundDecl, BaseObjectType) {
161
926k
    initialize();
162
926k
  }
163
164
  AccessTarget(ASTContext &Context,
165
               BaseNonce _,
166
               CXXRecordDecl *BaseClass,
167
               CXXRecordDecl *DerivedClass,
168
               AccessSpecifier Access)
169
    : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
170
10.9k
                     Access) {
171
10.9k
    initialize();
172
10.9k
  }
173
174
170k
  bool isInstanceMember() const {
175
170k
    return (isMemberAccess() && 
getTargetDecl()->isCXXInstanceMember()170k
);
176
170k
  }
177
178
168k
  bool hasInstanceContext() const {
179
168k
    return HasInstanceContext;
180
168k
  }
181
182
  class SavedInstanceContext {
183
  public:
184
    SavedInstanceContext(SavedInstanceContext &&S)
185
0
        : Target(S.Target), Has(S.Has) {
186
0
      S.Target = nullptr;
187
0
    }
188
73.2k
    ~SavedInstanceContext() {
189
73.2k
      if (Target)
190
73.2k
        Target->HasInstanceContext = Has;
191
73.2k
    }
192
193
  private:
194
    friend struct AccessTarget;
195
    explicit SavedInstanceContext(AccessTarget &Target)
196
73.2k
        : Target(&Target), Has(Target.HasInstanceContext) {}
197
    AccessTarget *Target;
198
    bool Has;
199
  };
200
201
73.2k
  SavedInstanceContext saveInstanceContext() {
202
73.2k
    return SavedInstanceContext(*this);
203
73.2k
  }
204
205
59.4k
  void suppressInstanceContext() {
206
59.4k
    HasInstanceContext = false;
207
59.4k
  }
208
209
53.1k
  const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
210
53.1k
    assert(HasInstanceContext);
211
53.1k
    if (CalculatedInstanceContext)
212
565
      return InstanceContext;
213
214
52.6k
    CalculatedInstanceContext = true;
215
52.6k
    DeclContext *IC = S.computeDeclContext(getBaseObjectType());
216
52.6k
    InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
217
0
                          : nullptr);
218
52.6k
    return InstanceContext;
219
52.6k
  }
220
221
78.6k
  const CXXRecordDecl *getDeclaringClass() const {
222
78.6k
    return DeclaringClass;
223
78.6k
  }
224
225
  /// The "effective" naming class is the canonical non-anonymous
226
  /// class containing the actual naming class.
227
921k
  const CXXRecordDecl *getEffectiveNamingClass() const {
228
921k
    const CXXRecordDecl *namingClass = getNamingClass();
229
921k
    while (namingClass->isAnonymousStructOrUnion())
230
0
      namingClass = cast<CXXRecordDecl>(namingClass->getParent());
231
921k
    return namingClass->getCanonicalDecl();
232
921k
  }
233
234
private:
235
1.18M
  void initialize() {
236
1.18M
    HasInstanceContext = (isMemberAccess() &&
237
1.17M
                          !getBaseObjectType().isNull() &&
238
525k
                          getTargetDecl()->isCXXInstanceMember());
239
1.18M
    CalculatedInstanceContext = false;
240
1.18M
    InstanceContext = nullptr;
241
242
1.18M
    if (isMemberAccess())
243
1.17M
      DeclaringClass = FindDeclaringClass(getTargetDecl());
244
10.9k
    else
245
10.9k
      DeclaringClass = getBaseClass();
246
1.18M
    DeclaringClass = DeclaringClass->getCanonicalDecl();
247
1.18M
  }
248
249
  bool HasInstanceContext : 1;
250
  mutable bool CalculatedInstanceContext : 1;
251
  mutable const CXXRecordDecl *InstanceContext;
252
  const CXXRecordDecl *DeclaringClass;
253
};
254
255
}
256
257
/// Checks whether one class might instantiate to the other.
258
static bool MightInstantiateTo(const CXXRecordDecl *From,
259
9.41k
                               const CXXRecordDecl *To) {
260
  // Declaration names are always preserved by instantiation.
261
9.41k
  if (From->getDeclName() != To->getDeclName())
262
9.32k
    return false;
263
264
94
  const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
265
94
  const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
266
94
  if (FromDC == ToDC) 
return true86
;
267
8
  if (FromDC->isFileContext() || ToDC->isFileContext()) 
return false0
;
268
269
  // Be conservative.
270
8
  return true;
271
8
}
272
273
/// Checks whether one class is derived from another, inclusively.
274
/// Properly indicates when it couldn't be determined due to
275
/// dependence.
276
///
277
/// This should probably be donated to AST or at least Sema.
278
static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
279
221k
                                           const CXXRecordDecl *Target) {
280
221k
  assert(Derived->getCanonicalDecl() == Derived);
281
221k
  assert(Target->getCanonicalDecl() == Target);
282
283
221k
  if (Derived == Target) 
return AR_accessible161k
;
284
285
60.0k
  bool CheckDependent = Derived->isDependentContext();
286
60.0k
  if (CheckDependent && 
MightInstantiateTo(Derived, Target)1.56k
)
287
24
    return AR_dependent;
288
289
60.0k
  AccessResult OnFailure = AR_inaccessible;
290
60.0k
  SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
291
292
60.6k
  while (true) {
293
60.6k
    if (Derived->isDependentContext() && 
!Derived->hasDefinition()1.54k
&&
294
1
        !Derived->isLambda())
295
1
      return AR_dependent;
296
297
60.6k
    for (const auto &I : Derived->bases()) {
298
59.1k
      const CXXRecordDecl *RD;
299
300
59.1k
      QualType T = I.getType();
301
59.1k
      if (const RecordType *RT = T->getAs<RecordType>()) {
302
59.1k
        RD = cast<CXXRecordDecl>(RT->getDecl());
303
12
      } else if (const InjectedClassNameType *IT
304
0
                   = T->getAs<InjectedClassNameType>()) {
305
0
        RD = IT->getDecl();
306
12
      } else {
307
12
        assert(T->isDependentType() && "non-dependent base wasn't a record?");
308
12
        OnFailure = AR_dependent;
309
12
        continue;
310
12
      }
311
312
59.1k
      RD = RD->getCanonicalDecl();
313
59.1k
      if (RD == Target) 
return AR_accessible58.1k
;
314
997
      if (CheckDependent && 
MightInstantiateTo(RD, Target)169
)
315
0
        OnFailure = AR_dependent;
316
317
997
      Queue.push_back(RD);
318
997
    }
319
320
2.43k
    if (Queue.empty()) 
break1.83k
;
321
322
604
    Derived = Queue.pop_back_val();
323
604
  }
324
325
1.83k
  return OnFailure;
326
60.0k
}
327
328
329
static bool MightInstantiateTo(Sema &S, DeclContext *Context,
330
45
                               DeclContext *Friend) {
331
45
  if (Friend == Context)
332
33
    return true;
333
334
12
  assert(!Friend->isDependentContext() &&
335
12
         "can't handle friends with dependent contexts here");
336
337
12
  if (!Context->isDependentContext())
338
10
    return false;
339
340
2
  if (Friend->isFileContext())
341
0
    return false;
342
343
  // TODO: this is very conservative
344
2
  return true;
345
2
}
346
347
// Asks whether the type in 'context' can ever instantiate to the type
348
// in 'friend'.
349
70
static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
350
70
  if (Friend == Context)
351
34
    return true;
352
353
36
  if (!Friend->isDependentType() && !Context->isDependentType())
354
0
    return false;
355
356
  // TODO: this is very conservative.
357
36
  return true;
358
36
}
359
360
static bool MightInstantiateTo(Sema &S,
361
                               FunctionDecl *Context,
362
1.91k
                               FunctionDecl *Friend) {
363
1.91k
  if (Context->getDeclName() != Friend->getDeclName())
364
1.87k
    return false;
365
366
42
  if (!MightInstantiateTo(S,
367
42
                          Context->getDeclContext(),
368
42
                          Friend->getDeclContext()))
369
7
    return false;
370
371
35
  CanQual<FunctionProtoType> FriendTy
372
35
    = S.Context.getCanonicalType(Friend->getType())
373
35
         ->getAs<FunctionProtoType>();
374
35
  CanQual<FunctionProtoType> ContextTy
375
35
    = S.Context.getCanonicalType(Context->getType())
376
35
         ->getAs<FunctionProtoType>();
377
378
  // There isn't any way that I know of to add qualifiers
379
  // during instantiation.
380
35
  if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
381
0
    return false;
382
383
35
  if (FriendTy->getNumParams() != ContextTy->getNumParams())
384
0
    return false;
385
386
35
  if (!MightInstantiateTo(S, ContextTy->getReturnType(),
387
35
                          FriendTy->getReturnType()))
388
0
    return false;
389
390
70
  
for (unsigned I = 0, E = FriendTy->getNumParams(); 35
I != E;
++I35
)
391
35
    if (!MightInstantiateTo(S, ContextTy->getParamType(I),
392
35
                            FriendTy->getParamType(I)))
393
0
      return false;
394
395
35
  return true;
396
35
}
397
398
static bool MightInstantiateTo(Sema &S,
399
                               FunctionTemplateDecl *Context,
400
1.61k
                               FunctionTemplateDecl *Friend) {
401
1.61k
  return MightInstantiateTo(S,
402
1.61k
                            Context->getTemplatedDecl(),
403
1.61k
                            Friend->getTemplatedDecl());
404
1.61k
}
405
406
static AccessResult MatchesFriend(Sema &S,
407
                                  const EffectiveContext &EC,
408
8.89k
                                  const CXXRecordDecl *Friend) {
409
8.89k
  if (EC.includesClass(Friend))
410
3.26k
    return AR_accessible;
411
412
5.63k
  if (EC.isDependent()) {
413
29
    for (const CXXRecordDecl *Context : EC.Records) {
414
29
      if (MightInstantiateTo(Context, Friend))
415
10
        return AR_dependent;
416
29
    }
417
380
  }
418
419
5.62k
  return AR_inaccessible;
420
5.63k
}
421
422
static AccessResult MatchesFriend(Sema &S,
423
                                  const EffectiveContext &EC,
424
8.89k
                                  CanQualType Friend) {
425
8.89k
  if (const RecordType *RT = Friend->getAs<RecordType>())
426
8.89k
    return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
427
428
  // TODO: we can do better than this
429
0
  if (Friend->isDependentType())
430
0
    return AR_dependent;
431
432
0
  return AR_inaccessible;
433
0
}
434
435
/// Determines whether the given friend class template matches
436
/// anything in the effective context.
437
static AccessResult MatchesFriend(Sema &S,
438
                                  const EffectiveContext &EC,
439
7.02k
                                  ClassTemplateDecl *Friend) {
440
7.02k
  AccessResult OnFailure = AR_inaccessible;
441
442
  // Check whether the friend is the template of a class in the
443
  // context chain.
444
7.02k
  for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
445
12.9k
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I5.94k
) {
446
7.63k
    CXXRecordDecl *Record = *I;
447
448
    // Figure out whether the current class has a template:
449
7.63k
    ClassTemplateDecl *CTD;
450
451
    // A specialization of the template...
452
7.63k
    if (isa<ClassTemplateSpecializationDecl>(Record)) {
453
3.25k
      CTD = cast<ClassTemplateSpecializationDecl>(Record)
454
3.25k
        ->getSpecializedTemplate();
455
456
    // ... or the template pattern itself.
457
4.37k
    } else {
458
4.37k
      CTD = Record->getDescribedClassTemplate();
459
4.37k
      if (!CTD) 
continue651
;
460
6.98k
    }
461
462
    // It's a match.
463
6.98k
    if (Friend == CTD->getCanonicalDecl())
464
1.68k
      return AR_accessible;
465
466
    // If the context isn't dependent, it can't be a dependent match.
467
5.29k
    if (!EC.isDependent())
468
2.29k
      continue;
469
470
    // If the template names don't match, it can't be a dependent
471
    // match.
472
2.99k
    if (CTD->getDeclName() != Friend->getDeclName())
473
2.99k
      continue;
474
475
    // If the class's context can't instantiate to the friend's
476
    // context, it can't be a dependent match.
477
3
    if (!MightInstantiateTo(S, CTD->getDeclContext(),
478
3
                            Friend->getDeclContext()))
479
3
      continue;
480
481
    // Otherwise, it's a dependent match.
482
0
    OnFailure = AR_dependent;
483
0
  }
484
485
5.33k
  return OnFailure;
486
7.02k
}
487
488
/// Determines whether the given friend function matches anything in
489
/// the effective context.
490
static AccessResult MatchesFriend(Sema &S,
491
                                  const EffectiveContext &EC,
492
5.37k
                                  FunctionDecl *Friend) {
493
5.37k
  AccessResult OnFailure = AR_inaccessible;
494
495
5.37k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
496
9.56k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I4.19k
) {
497
5.35k
    if (Friend == *I)
498
1.16k
      return AR_accessible;
499
500
4.19k
    if (EC.isDependent() && 
MightInstantiateTo(S, *I, Friend)302
)
501
35
      OnFailure = AR_dependent;
502
4.19k
  }
503
504
4.20k
  return OnFailure;
505
5.37k
}
506
507
/// Determines whether the given friend function template matches
508
/// anything in the effective context.
509
static AccessResult MatchesFriend(Sema &S,
510
                                  const EffectiveContext &EC,
511
23.3k
                                  FunctionTemplateDecl *Friend) {
512
23.3k
  if (EC.Functions.empty()) 
return AR_inaccessible46
;
513
514
23.2k
  AccessResult OnFailure = AR_inaccessible;
515
516
23.2k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
517
44.4k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I21.1k
) {
518
519
23.2k
    FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
520
23.2k
    if (!FTD)
521
12.4k
      FTD = (*I)->getDescribedFunctionTemplate();
522
23.2k
    if (!FTD)
523
10.1k
      continue;
524
525
13.0k
    FTD = FTD->getCanonicalDecl();
526
527
13.0k
    if (Friend == FTD)
528
2.08k
      return AR_accessible;
529
530
11.0k
    if (EC.isDependent() && 
MightInstantiateTo(S, FTD, Friend)1.61k
)
531
0
      OnFailure = AR_dependent;
532
11.0k
  }
533
534
21.1k
  return OnFailure;
535
23.2k
}
536
537
/// Determines whether the given friend declaration matches anything
538
/// in the effective context.
539
static AccessResult MatchesFriend(Sema &S,
540
                                  const EffectiveContext &EC,
541
44.6k
                                  FriendDecl *FriendD) {
542
  // Whitelist accesses if there's an invalid or unsupported friend
543
  // declaration.
544
44.6k
  if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
545
36
    return AR_accessible;
546
547
44.5k
  if (TypeSourceInfo *T = FriendD->getFriendType())
548
8.89k
    return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
549
550
35.7k
  NamedDecl *Friend
551
35.7k
    = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
552
553
  // FIXME: declarations with dependent or templated scope.
554
555
35.7k
  if (isa<ClassTemplateDecl>(Friend))
556
7.02k
    return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
557
558
28.6k
  if (isa<FunctionTemplateDecl>(Friend))
559
23.3k
    return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
560
561
5.37k
  if (isa<CXXRecordDecl>(Friend))
562
0
    return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
563
564
5.37k
  assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
565
5.37k
  return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
566
5.37k
}
567
568
static AccessResult GetFriendKind(Sema &S,
569
                                  const EffectiveContext &EC,
570
83.1k
                                  const CXXRecordDecl *Class) {
571
83.1k
  AccessResult OnFailure = AR_inaccessible;
572
573
  // Okay, check friends.
574
44.6k
  for (auto *Friend : Class->friends()) {
575
44.6k
    switch (MatchesFriend(S, EC, Friend)) {
576
8.23k
    case AR_accessible:
577
8.23k
      return AR_accessible;
578
579
36.3k
    case AR_inaccessible:
580
36.3k
      continue;
581
582
45
    case AR_dependent:
583
45
      OnFailure = AR_dependent;
584
45
      break;
585
44.6k
    }
586
44.6k
  }
587
588
  // That's it, give up.
589
74.9k
  return OnFailure;
590
83.1k
}
591
592
namespace {
593
594
/// A helper class for checking for a friend which will grant access
595
/// to a protected instance member.
596
struct ProtectedFriendContext {
597
  Sema &S;
598
  const EffectiveContext &EC;
599
  const CXXRecordDecl *NamingClass;
600
  bool CheckDependent;
601
  bool EverDependent;
602
603
  /// The path down to the current base class.
604
  SmallVector<const CXXRecordDecl*, 20> CurPath;
605
606
  ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
607
                         const CXXRecordDecl *InstanceContext,
608
                         const CXXRecordDecl *NamingClass)
609
    : S(S), EC(EC), NamingClass(NamingClass),
610
      CheckDependent(InstanceContext->isDependentContext() ||
611
                     NamingClass->isDependentContext()),
612
678
      EverDependent(false) {}
613
614
  /// Check classes in the current path for friendship, starting at
615
  /// the given index.
616
660
  bool checkFriendshipAlongPath(unsigned I) {
617
660
    assert(I < CurPath.size());
618
1.50k
    for (unsigned E = CurPath.size(); I != E; 
++I849
) {
619
941
      switch (GetFriendKind(S, EC, CurPath[I])) {
620
92
      case AR_accessible:   return true;
621
849
      case AR_inaccessible: continue;
622
0
      case AR_dependent:    EverDependent = true; continue;
623
941
      }
624
941
    }
625
568
    return false;
626
660
  }
627
628
  /// Perform a search starting at the given class.
629
  ///
630
  /// PrivateDepth is the index of the last (least derived) class
631
  /// along the current path such that a notional public member of
632
  /// the final class in the path would have access in that class.
633
991
  bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
634
    // If we ever reach the naming class, check the current path for
635
    // friendship.  We can also stop recursing because we obviously
636
    // won't find the naming class there again.
637
991
    if (Cur == NamingClass)
638
660
      return checkFriendshipAlongPath(PrivateDepth);
639
640
331
    if (CheckDependent && 
MightInstantiateTo(Cur, NamingClass)0
)
641
0
      EverDependent = true;
642
643
    // Recurse into the base classes.
644
313
    for (const auto &I : Cur->bases()) {
645
      // If this is private inheritance, then a public member of the
646
      // base will not have any access in classes derived from Cur.
647
313
      unsigned BasePrivateDepth = PrivateDepth;
648
313
      if (I.getAccessSpecifier() == AS_private)
649
33
        BasePrivateDepth = CurPath.size() - 1;
650
651
313
      const CXXRecordDecl *RD;
652
653
313
      QualType T = I.getType();
654
313
      if (const RecordType *RT = T->getAs<RecordType>()) {
655
313
        RD = cast<CXXRecordDecl>(RT->getDecl());
656
0
      } else if (const InjectedClassNameType *IT
657
0
                   = T->getAs<InjectedClassNameType>()) {
658
0
        RD = IT->getDecl();
659
0
      } else {
660
0
        assert(T->isDependentType() && "non-dependent base wasn't a record?");
661
0
        EverDependent = true;
662
0
        continue;
663
0
      }
664
665
      // Recurse.  We don't need to clean up if this returns true.
666
313
      CurPath.push_back(RD);
667
313
      if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
668
209
        return true;
669
104
      CurPath.pop_back();
670
104
    }
671
672
122
    return false;
673
331
  }
674
675
678
  bool findFriendship(const CXXRecordDecl *Cur) {
676
678
    assert(CurPath.empty());
677
678
    CurPath.push_back(Cur);
678
678
    return findFriendship(Cur, 0);
679
678
  }
680
};
681
}
682
683
/// Search for a class P that EC is a friend of, under the constraint
684
///   InstanceContext <= P
685
/// if InstanceContext exists, or else
686
///   NamingClass <= P
687
/// and with the additional restriction that a protected member of
688
/// NamingClass would have some natural access in P, which implicitly
689
/// imposes the constraint that P <= NamingClass.
690
///
691
/// This isn't quite the condition laid out in the standard.
692
/// Instead of saying that a notional protected member of NamingClass
693
/// would have to have some natural access in P, it says the actual
694
/// target has to have some natural access in P, which opens up the
695
/// possibility that the target (which is not necessarily a member
696
/// of NamingClass) might be more accessible along some path not
697
/// passing through it.  That's really a bad idea, though, because it
698
/// introduces two problems:
699
///   - Most importantly, it breaks encapsulation because you can
700
///     access a forbidden base class's members by directly subclassing
701
///     it elsewhere.
702
///   - It also makes access substantially harder to compute because it
703
///     breaks the hill-climbing algorithm: knowing that the target is
704
///     accessible in some base class would no longer let you change
705
///     the question solely to whether the base class is accessible,
706
///     because the original target might have been more accessible
707
///     because of crazy subclassing.
708
/// So we don't implement that.
709
static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
710
                                           const CXXRecordDecl *InstanceContext,
711
878
                                           const CXXRecordDecl *NamingClass) {
712
878
  assert(InstanceContext == nullptr ||
713
878
         InstanceContext->getCanonicalDecl() == InstanceContext);
714
878
  assert(NamingClass->getCanonicalDecl() == NamingClass);
715
716
  // If we don't have an instance context, our constraints give us
717
  // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
718
  // This is just the usual friendship check.
719
878
  if (!InstanceContext) 
return GetFriendKind(S, EC, NamingClass)200
;
720
721
678
  ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
722
678
  if (PRC.findFriendship(InstanceContext)) 
return AR_accessible92
;
723
586
  if (PRC.EverDependent) 
return AR_dependent0
;
724
586
  return AR_inaccessible;
725
586
}
726
727
static AccessResult HasAccess(Sema &S,
728
                              const EffectiveContext &EC,
729
                              const CXXRecordDecl *NamingClass,
730
                              AccessSpecifier Access,
731
988k
                              const AccessTarget &Target) {
732
988k
  assert(NamingClass->getCanonicalDecl() == NamingClass &&
733
988k
         "declaration should be canonicalized before being passed here");
734
735
988k
  if (Access == AS_public) 
return AR_accessible58.2k
;
736
929k
  assert(Access == AS_private || Access == AS_protected);
737
738
929k
  AccessResult OnFailure = AR_inaccessible;
739
740
929k
  for (EffectiveContext::record_iterator
741
1.00M
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I74.7k
) {
742
    // All the declarations in EC have been canonicalized, so pointer
743
    // equality from this point on will work fine.
744
921k
    const CXXRecordDecl *ECRecord = *I;
745
746
    // [B2] and [M2]
747
921k
    if (Access == AS_private) {
748
752k
      if (ECRecord == NamingClass)
749
679k
        return AR_accessible;
750
751
72.9k
      if (EC.isDependent() && 
MightInstantiateTo(ECRecord, NamingClass)7.65k
)
752
60
        OnFailure = AR_dependent;
753
754
    // [B3] and [M3]
755
169k
    } else {
756
169k
      assert(Access == AS_protected);
757
169k
      switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
758
167k
      case AR_accessible: break;
759
1.64k
      case AR_inaccessible: continue;
760
37
      case AR_dependent: OnFailure = AR_dependent; continue;
761
167k
      }
762
763
      // C++ [class.protected]p1:
764
      //   An additional access check beyond those described earlier in
765
      //   [class.access] is applied when a non-static data member or
766
      //   non-static member function is a protected member of its naming
767
      //   class.  As described earlier, access to a protected member is
768
      //   granted because the reference occurs in a friend or member of
769
      //   some class C.  If the access is to form a pointer to member,
770
      //   the nested-name-specifier shall name C or a class derived from
771
      //   C. All other accesses involve a (possibly implicit) object
772
      //   expression. In this case, the class of the object expression
773
      //   shall be C or a class derived from C.
774
      //
775
      // We interpret this as a restriction on [M3].
776
777
      // In this part of the code, 'C' is just our context class ECRecord.
778
779
      // These rules are different if we don't have an instance context.
780
167k
      if (!Target.hasInstanceContext()) {
781
        // If it's not an instance member, these restrictions don't apply.
782
114k
        if (!Target.isInstanceMember()) 
return AR_accessible114k
;
783
784
        // If it's an instance member, use the pointer-to-member rule
785
        // that the naming class has to be derived from the effective
786
        // context.
787
788
        // Emulate a MSVC bug where the creation of pointer-to-member
789
        // to protected member of base class is allowed but only from
790
        // static member functions.
791
82
        if (S.getLangOpts().MSVCCompat && 
!EC.Functions.empty()4
)
792
4
          if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
793
4
            if (MD->isStatic()) 
return AR_accessible1
;
794
795
        // Despite the standard's confident wording, there is a case
796
        // where you can have an instance member that's neither in a
797
        // pointer-to-member expression nor in a member access:  when
798
        // it names a field in an unevaluated context that can't be an
799
        // implicit member.  Pending clarification, we just apply the
800
        // same naming-class restriction here.
801
        //   FIXME: we're probably not correctly adding the
802
        //   protected-member restriction when we retroactively convert
803
        //   an expression to being evaluated.
804
805
        // We know that ECRecord derives from NamingClass.  The
806
        // restriction says to check whether NamingClass derives from
807
        // ECRecord, but that's not really necessary: two distinct
808
        // classes can't be recursively derived from each other.  So
809
        // along this path, we just need to check whether the classes
810
        // are equal.
811
81
        if (NamingClass == ECRecord) 
return AR_accessible25
;
812
813
        // Otherwise, this context class tells us nothing;  on to the next.
814
56
        continue;
815
56
      }
816
817
52.4k
      assert(Target.isInstanceMember());
818
819
52.4k
      const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
820
52.4k
      if (!InstanceContext) {
821
0
        OnFailure = AR_dependent;
822
0
        continue;
823
0
      }
824
825
52.4k
      switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
826
52.3k
      case AR_accessible: return AR_accessible;
827
113
      case AR_inaccessible: continue;
828
0
      case AR_dependent: OnFailure = AR_dependent; continue;
829
52.4k
      }
830
52.4k
    }
831
921k
  }
832
833
  // [M3] and [B3] say that, if the target is protected in N, we grant
834
  // access if the access occurs in a friend or member of some class P
835
  // that's a subclass of N and where the target has some natural
836
  // access in P.  The 'member' aspect is easy to handle because P
837
  // would necessarily be one of the effective-context records, and we
838
  // address that above.  The 'friend' aspect is completely ridiculous
839
  // to implement because there are no restrictions at all on P
840
  // *unless* the [class.protected] restriction applies.  If it does,
841
  // however, we should ignore whether the naming class is a friend,
842
  // and instead rely on whether any potential P is a friend.
843
82.8k
  if (Access == AS_protected && 
Target.isInstanceMember()2.38k
) {
844
    // Compute the instance context if possible.
845
878
    const CXXRecordDecl *InstanceContext = nullptr;
846
878
    if (Target.hasInstanceContext()) {
847
678
      InstanceContext = Target.resolveInstanceContext(S);
848
678
      if (!InstanceContext) 
return AR_dependent0
;
849
878
    }
850
851
878
    switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
852
95
    case AR_accessible: return AR_accessible;
853
783
    case AR_inaccessible: return OnFailure;
854
0
    case AR_dependent: return AR_dependent;
855
0
    }
856
0
    llvm_unreachable("impossible friendship kind");
857
0
  }
858
859
82.0k
  switch (GetFriendKind(S, EC, NamingClass)) {
860
8.14k
  case AR_accessible: return AR_accessible;
861
73.8k
  case AR_inaccessible: return OnFailure;
862
45
  case AR_dependent: return AR_dependent;
863
0
  }
864
865
  // Silence bogus warnings
866
0
  llvm_unreachable("impossible friendship kind");
867
0
}
868
869
/// Finds the best path from the naming class to the declaring class,
870
/// taking friend declarations into account.
871
///
872
/// C++0x [class.access.base]p5:
873
///   A member m is accessible at the point R when named in class N if
874
///   [M1] m as a member of N is public, or
875
///   [M2] m as a member of N is private, and R occurs in a member or
876
///        friend of class N, or
877
///   [M3] m as a member of N is protected, and R occurs in a member or
878
///        friend of class N, or in a member or friend of a class P
879
///        derived from N, where m as a member of P is public, private,
880
///        or protected, or
881
///   [M4] there exists a base class B of N that is accessible at R, and
882
///        m is accessible at R when named in class B.
883
///
884
/// C++0x [class.access.base]p4:
885
///   A base class B of N is accessible at R, if
886
///   [B1] an invented public member of B would be a public member of N, or
887
///   [B2] R occurs in a member or friend of class N, and an invented public
888
///        member of B would be a private or protected member of N, or
889
///   [B3] R occurs in a member or friend of a class P derived from N, and an
890
///        invented public member of B would be a private or protected member
891
///        of P, or
892
///   [B4] there exists a class S such that B is a base class of S accessible
893
///        at R and S is a base class of N accessible at R.
894
///
895
/// Along a single inheritance path we can restate both of these
896
/// iteratively:
897
///
898
/// First, we note that M1-4 are equivalent to B1-4 if the member is
899
/// treated as a notional base of its declaring class with inheritance
900
/// access equivalent to the member's access.  Therefore we need only
901
/// ask whether a class B is accessible from a class N in context R.
902
///
903
/// Let B_1 .. B_n be the inheritance path in question (i.e. where
904
/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
905
/// B_i).  For i in 1..n, we will calculate ACAB(i), the access to the
906
/// closest accessible base in the path:
907
///   Access(a, b) = (* access on the base specifier from a to b *)
908
///   Merge(a, forbidden) = forbidden
909
///   Merge(a, private) = forbidden
910
///   Merge(a, b) = min(a,b)
911
///   Accessible(c, forbidden) = false
912
///   Accessible(c, private) = (R is c) || IsFriend(c, R)
913
///   Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
914
///   Accessible(c, public) = true
915
///   ACAB(n) = public
916
///   ACAB(i) =
917
///     let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
918
///     if Accessible(B_i, AccessToBase) then public else AccessToBase
919
///
920
/// B is an accessible base of N at R iff ACAB(1) = public.
921
///
922
/// \param FinalAccess the access of the "final step", or AS_public if
923
///   there is no final step.
924
/// \return null if friendship is dependent
925
static CXXBasePath *FindBestPath(Sema &S,
926
                                 const EffectiveContext &EC,
927
                                 AccessTarget &Target,
928
                                 AccessSpecifier FinalAccess,
929
1.15k
                                 CXXBasePaths &Paths) {
930
  // Derive the paths to the desired base.
931
1.15k
  const CXXRecordDecl *Derived = Target.getNamingClass();
932
1.15k
  const CXXRecordDecl *Base = Target.getDeclaringClass();
933
934
  // FIXME: fail correctly when there are dependent paths.
935
1.15k
  bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
936
1.15k
                                          Paths);
937
1.15k
  assert(isDerived && "derived class not actually derived from base");
938
1.15k
  (void) isDerived;
939
940
1.15k
  CXXBasePath *BestPath = nullptr;
941
942
1.15k
  assert(FinalAccess != AS_none && "forbidden access after declaring class");
943
944
1.15k
  bool AnyDependent = false;
945
946
  // Derive the friend-modified access along each path.
947
1.15k
  for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
948
1.89k
         PI != PE; 
++PI740
) {
949
1.15k
    AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
950
951
    // Walk through the path backwards.
952
1.15k
    AccessSpecifier PathAccess = FinalAccess;
953
1.15k
    CXXBasePath::iterator I = PI->end(), E = PI->begin();
954
2.48k
    while (I != E) {
955
1.60k
      --I;
956
957
1.60k
      assert(PathAccess != AS_none);
958
959
      // If the declaration is a private member of a base class, there
960
      // is no level of friendship in derived classes that can make it
961
      // accessible.
962
1.60k
      if (PathAccess == AS_private) {
963
269
        PathAccess = AS_none;
964
269
        break;
965
269
      }
966
967
1.33k
      const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
968
969
1.33k
      AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
970
1.33k
      PathAccess = std::max(PathAccess, BaseAccess);
971
972
1.33k
      switch (HasAccess(S, EC, NC, PathAccess, Target)) {
973
678
      case AR_inaccessible: break;
974
653
      case AR_accessible:
975
653
        PathAccess = AS_public;
976
977
        // Future tests are not against members and so do not have
978
        // instance context.
979
653
        Target.suppressInstanceContext();
980
653
        break;
981
0
      case AR_dependent:
982
0
        AnyDependent = true;
983
0
        goto Next;
984
1.33k
      }
985
1.33k
    }
986
987
    // Note that we modify the path's Access field to the
988
    // friend-modified access.
989
1.15k
    if (BestPath == nullptr || 
PathAccess < BestPath->Access2
) {
990
1.15k
      BestPath = &*PI;
991
1.15k
      BestPath->Access = PathAccess;
992
993
      // Short-circuit if we found a public path.
994
1.15k
      if (BestPath->Access == AS_public)
995
412
        return BestPath;
996
740
    }
997
998
740
  Next: ;
999
740
  }
1000
1001
738
  assert((!BestPath || BestPath->Access != AS_public) &&
1002
738
         "fell out of loop with public path");
1003
1004
  // We didn't find a public path, but at least one path was subject
1005
  // to dependent friendship, so delay the check.
1006
738
  if (AnyDependent)
1007
0
    return nullptr;
1008
1009
738
  return BestPath;
1010
738
}
1011
1012
/// Given that an entity has protected natural access, check whether
1013
/// access might be denied because of the protected member access
1014
/// restriction.
1015
///
1016
/// \return true if a note was emitted
1017
static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1018
210
                                       AccessTarget &Target) {
1019
  // Only applies to instance accesses.
1020
210
  if (!Target.isInstanceMember())
1021
59
    return false;
1022
1023
151
  assert(Target.isMemberAccess());
1024
1025
151
  const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
1026
1027
151
  for (EffectiveContext::record_iterator
1028
189
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I38
) {
1029
73
    const CXXRecordDecl *ECRecord = *I;
1030
73
    switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
1031
35
    case AR_accessible: break;
1032
38
    case AR_inaccessible: continue;
1033
0
    case AR_dependent: continue;
1034
35
    }
1035
1036
    // The effective context is a subclass of the declaring class.
1037
    // Check whether the [class.protected] restriction is limiting
1038
    // access.
1039
1040
    // To get this exactly right, this might need to be checked more
1041
    // holistically;  it's not necessarily the case that gaining
1042
    // access here would grant us access overall.
1043
1044
35
    NamedDecl *D = Target.getTargetDecl();
1045
1046
    // If we don't have an instance context, [class.protected] says the
1047
    // naming class has to equal the context class.
1048
35
    if (!Target.hasInstanceContext()) {
1049
      // If it does, the restriction doesn't apply.
1050
12
      if (NamingClass == ECRecord) 
continue0
;
1051
1052
      // TODO: it would be great to have a fixit here, since this is
1053
      // such an obvious error.
1054
12
      S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1055
12
        << S.Context.getTypeDeclType(ECRecord);
1056
12
      return true;
1057
12
    }
1058
1059
23
    const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1060
23
    assert(InstanceContext && "diagnosing dependent access");
1061
1062
23
    switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1063
0
    case AR_accessible: continue;
1064
0
    case AR_dependent: continue;
1065
23
    case AR_inaccessible:
1066
23
      break;
1067
23
    }
1068
1069
    // Okay, the restriction seems to be what's limiting us.
1070
1071
    // Use a special diagnostic for constructors and destructors.
1072
23
    if (isa<CXXConstructorDecl>(D) || 
isa<CXXDestructorDecl>(D)20
||
1073
17
        (isa<FunctionTemplateDecl>(D) &&
1074
0
         isa<CXXConstructorDecl>(
1075
6
                cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
1076
6
      return S.Diag(D->getLocation(),
1077
6
                    diag::note_access_protected_restricted_ctordtor)
1078
6
             << isa<CXXDestructorDecl>(D->getAsFunction());
1079
6
    }
1080
1081
    // Otherwise, use the generic diagnostic.
1082
17
    return S.Diag(D->getLocation(),
1083
17
                  diag::note_access_protected_restricted_object)
1084
17
           << S.Context.getTypeDeclType(ECRecord);
1085
17
  }
1086
1087
116
  return false;
1088
151
}
1089
1090
/// We are unable to access a given declaration due to its direct
1091
/// access control;  diagnose that.
1092
static void diagnoseBadDirectAccess(Sema &S,
1093
                                    const EffectiveContext &EC,
1094
4.50k
                                    AccessTarget &entity) {
1095
4.50k
  assert(entity.isMemberAccess());
1096
4.50k
  NamedDecl *D = entity.getTargetDecl();
1097
1098
4.50k
  if (D->getAccess() == AS_protected &&
1099
210
      TryDiagnoseProtectedAccess(S, EC, entity))
1100
35
    return;
1101
1102
  // Find an original declaration.
1103
4.49k
  
while (4.46k
D->isOutOfLine()) {
1104
28
    NamedDecl *PrevDecl = nullptr;
1105
28
    if (VarDecl *VD = dyn_cast<VarDecl>(D))
1106
4
      PrevDecl = VD->getPreviousDecl();
1107
24
    else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1108
20
      PrevDecl = FD->getPreviousDecl();
1109
4
    else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1110
0
      PrevDecl = TND->getPreviousDecl();
1111
4
    else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1112
4
      if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1113
0
        break;
1114
4
      PrevDecl = TD->getPreviousDecl();
1115
4
    }
1116
28
    if (!PrevDecl) 
break0
;
1117
28
    D = PrevDecl;
1118
28
  }
1119
1120
4.46k
  CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1121
4.46k
  Decl *ImmediateChild;
1122
4.46k
  if (D->getDeclContext() == DeclaringClass)
1123
4.46k
    ImmediateChild = D;
1124
6
  else {
1125
6
    DeclContext *DC = D->getDeclContext();
1126
6
    while (DC->getParent() != DeclaringClass)
1127
0
      DC = DC->getParent();
1128
6
    ImmediateChild = cast<Decl>(DC);
1129
6
  }
1130
1131
  // Check whether there's an AccessSpecDecl preceding this in the
1132
  // chain of the DeclContext.
1133
4.46k
  bool isImplicit = true;
1134
13.0k
  for (const auto *I : DeclaringClass->decls()) {
1135
13.0k
    if (I == ImmediateChild) 
break3.95k
;
1136
9.11k
    if (isa<AccessSpecDecl>(I)) {
1137
513
      isImplicit = false;
1138
513
      break;
1139
513
    }
1140
9.11k
  }
1141
1142
4.46k
  S.Diag(D->getLocation(), diag::note_access_natural)
1143
4.46k
    << (unsigned) (D->getAccess() == AS_protected)
1144
4.46k
    << isImplicit;
1145
4.46k
}
1146
1147
/// Diagnose the path which caused the given declaration or base class
1148
/// to become inaccessible.
1149
static void DiagnoseAccessPath(Sema &S,
1150
                               const EffectiveContext &EC,
1151
4.74k
                               AccessTarget &entity) {
1152
  // Save the instance context to preserve invariants.
1153
4.74k
  AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
1154
1155
  // This basically repeats the main algorithm but keeps some more
1156
  // information.
1157
1158
  // The natural access so far.
1159
4.74k
  AccessSpecifier accessSoFar = AS_public;
1160
1161
  // Check whether we have special rights to the declaring class.
1162
4.74k
  if (entity.isMemberAccess()) {
1163
4.63k
    NamedDecl *D = entity.getTargetDecl();
1164
4.63k
    accessSoFar = D->getAccess();
1165
4.63k
    const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
1166
1167
4.63k
    switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1168
    // If the declaration is accessible when named in its declaring
1169
    // class, then we must be constrained by the path.
1170
128
    case AR_accessible:
1171
128
      accessSoFar = AS_public;
1172
128
      entity.suppressInstanceContext();
1173
128
      break;
1174
1175
4.50k
    case AR_inaccessible:
1176
4.50k
      if (accessSoFar == AS_private ||
1177
215
          declaringClass == entity.getEffectiveNamingClass())
1178
4.45k
        return diagnoseBadDirectAccess(S, EC, entity);
1179
53
      break;
1180
1181
0
    case AR_dependent:
1182
0
      llvm_unreachable("cannot diagnose dependent access");
1183
291
    }
1184
291
  }
1185
1186
291
  CXXBasePaths paths;
1187
291
  CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1188
291
  assert(path.Access != AS_public);
1189
1190
291
  CXXBasePath::iterator i = path.end(), e = path.begin();
1191
291
  CXXBasePath::iterator constrainingBase = i;
1192
395
  while (i != e) {
1193
311
    --i;
1194
1195
311
    assert(accessSoFar != AS_none && accessSoFar != AS_private);
1196
1197
    // Is the entity accessible when named in the deriving class, as
1198
    // modified by the base specifier?
1199
311
    const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1200
311
    const CXXBaseSpecifier *base = i->Base;
1201
1202
    // If the access to this base is worse than the access we have to
1203
    // the declaration, remember it.
1204
311
    AccessSpecifier baseAccess = base->getAccessSpecifier();
1205
311
    if (baseAccess > accessSoFar) {
1206
243
      constrainingBase = i;
1207
243
      accessSoFar = baseAccess;
1208
243
    }
1209
1210
311
    switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
1211
299
    case AR_inaccessible: break;
1212
12
    case AR_accessible:
1213
12
      accessSoFar = AS_public;
1214
12
      entity.suppressInstanceContext();
1215
12
      constrainingBase = nullptr;
1216
12
      break;
1217
0
    case AR_dependent:
1218
0
      llvm_unreachable("cannot diagnose dependent access");
1219
311
    }
1220
1221
    // If this was private inheritance, but we don't have access to
1222
    // the deriving class, we're done.
1223
311
    if (accessSoFar == AS_private) {
1224
207
      assert(baseAccess == AS_private);
1225
207
      assert(constrainingBase == i);
1226
207
      break;
1227
207
    }
1228
311
  }
1229
1230
  // If we don't have a constraining base, the access failure must be
1231
  // due to the original declaration.
1232
291
  if (constrainingBase == path.end())
1233
48
    return diagnoseBadDirectAccess(S, EC, entity);
1234
1235
  // We're constrained by inheritance, but we want to say
1236
  // "declared private here" if we're diagnosing a hierarchy
1237
  // conversion and this is the final step.
1238
243
  unsigned diagnostic;
1239
243
  if (entity.isMemberAccess() ||
1240
134
      
constrainingBase + 1 != path.end()110
) {
1241
134
    diagnostic = diag::note_access_constrained_by_path;
1242
109
  } else {
1243
109
    diagnostic = diag::note_access_natural;
1244
109
  }
1245
1246
243
  const CXXBaseSpecifier *base = constrainingBase->Base;
1247
1248
243
  S.Diag(base->getSourceRange().getBegin(), diagnostic)
1249
243
    << base->getSourceRange()
1250
243
    << (base->getAccessSpecifier() == AS_protected)
1251
243
    << (base->getAccessSpecifierAsWritten() == AS_none);
1252
1253
243
  if (entity.isMemberAccess())
1254
133
    S.Diag(entity.getTargetDecl()->getLocation(),
1255
133
           diag::note_member_declared_at);
1256
243
}
1257
1258
static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
1259
                              const EffectiveContext &EC,
1260
4.74k
                              AccessTarget &Entity) {
1261
4.74k
  const CXXRecordDecl *NamingClass = Entity.getNamingClass();
1262
4.74k
  const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1263
4.63k
  NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 
nullptr110
);
1264
1265
4.74k
  S.Diag(Loc, Entity.getDiag())
1266
4.74k
    << (Entity.getAccess() == AS_protected)
1267
4.63k
    << (D ? D->getDeclName() : 
DeclarationName()110
)
1268
4.74k
    << S.Context.getTypeDeclType(NamingClass)
1269
4.74k
    << S.Context.getTypeDeclType(DeclaringClass);
1270
4.74k
  DiagnoseAccessPath(S, EC, Entity);
1271
4.74k
}
1272
1273
/// MSVC has a bug where if during an using declaration name lookup,
1274
/// the declaration found is unaccessible (private) and that declaration
1275
/// was bring into scope via another using declaration whose target
1276
/// declaration is accessible (public) then no error is generated.
1277
/// Example:
1278
///   class A {
1279
///   public:
1280
///     int f();
1281
///   };
1282
///   class B : public A {
1283
///   private:
1284
///     using A::f;
1285
///   };
1286
///   class C : public B {
1287
///   private:
1288
///     using B::f;
1289
///   };
1290
///
1291
/// Here, B::f is private so this should fail in Standard C++, but
1292
/// because B::f refers to A::f which is public MSVC accepts it.
1293
static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1294
                                                 SourceLocation AccessLoc,
1295
15
                                                 AccessTarget &Entity) {
1296
15
  if (UsingShadowDecl *Shadow =
1297
2
                         dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1298
2
    const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1299
2
    if (Entity.getTargetDecl()->getAccess() == AS_private &&
1300
2
        (OrigDecl->getAccess() == AS_public ||
1301
2
         
OrigDecl->getAccess() == AS_protected0
)) {
1302
2
      S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
1303
2
        << Shadow->getUsingDecl()->getQualifiedNameAsString()
1304
2
        << OrigDecl->getQualifiedNameAsString();
1305
2
      return true;
1306
2
    }
1307
13
  }
1308
13
  return false;
1309
13
}
1310
1311
/// Determines whether the accessed entity is accessible.  Public members
1312
/// have been weeded out by this point.
1313
static AccessResult IsAccessible(Sema &S,
1314
                                 const EffectiveContext &EC,
1315
921k
                                 AccessTarget &Entity) {
1316
  // Determine the actual naming class.
1317
921k
  const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
1318
1319
921k
  AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1320
921k
  assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1321
1322
  // Before we try to recalculate access paths, try to white-list
1323
  // accesses which just trade in on the final step, i.e. accesses
1324
  // which don't require [M4] or [B4]. These are by far the most
1325
  // common forms of privileged access.
1326
921k
  if (UnprivilegedAccess != AS_none) {
1327
914k
    switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1328
97
    case AR_dependent:
1329
      // This is actually an interesting policy decision.  We don't
1330
      // *have* to delay immediately here: we can do the full access
1331
      // calculation in the hope that friendship on some intermediate
1332
      // class will make the declaration accessible non-dependently.
1333
      // But that's not cheap, and odds are very good (note: assertion
1334
      // made without data) that the friend declaration will determine
1335
      // access.
1336
97
      return AR_dependent;
1337
1338
853k
    case AR_accessible: return AR_accessible;
1339
60.4k
    case AR_inaccessible: break;
1340
67.4k
    }
1341
67.4k
  }
1342
1343
67.4k
  AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
1344
1345
  // We lower member accesses to base accesses by pretending that the
1346
  // member is a base class of its declaring class.
1347
67.4k
  AccessSpecifier FinalAccess;
1348
1349
67.4k
  if (Entity.isMemberAccess()) {
1350
    // Determine if the declaration is accessible from EC when named
1351
    // in its declaring class.
1352
67.2k
    NamedDecl *Target = Entity.getTargetDecl();
1353
67.2k
    const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1354
1355
67.2k
    FinalAccess = Target->getAccess();
1356
67.2k
    switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1357
58.6k
    case AR_accessible:
1358
      // Target is accessible at EC when named in its declaring class.
1359
      // We can now hill-climb and simply check whether the declaring
1360
      // class is accessible as a base of the naming class.  This is
1361
      // equivalent to checking the access of a notional public
1362
      // member with no instance context.
1363
58.6k
      FinalAccess = AS_public;
1364
58.6k
      Entity.suppressInstanceContext();
1365
58.6k
      break;
1366
8.66k
    case AR_inaccessible: break;
1367
0
    case AR_dependent: return AR_dependent; // see above
1368
67.2k
    }
1369
1370
67.2k
    if (DeclaringClass == NamingClass)
1371
66.5k
      return (FinalAccess == AS_public ? 
AR_accessible58.0k
:
AR_inaccessible8.51k
);
1372
128
  } else {
1373
128
    FinalAccess = AS_public;
1374
128
  }
1375
1376
859
  assert(Entity.getDeclaringClass() != NamingClass);
1377
1378
  // Append the declaration's access if applicable.
1379
859
  CXXBasePaths Paths;
1380
859
  CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
1381
859
  if (!Path)
1382
0
    return AR_dependent;
1383
1384
859
  assert(Path->Access <= UnprivilegedAccess &&
1385
859
         "access along best path worse than direct?");
1386
859
  if (Path->Access == AS_public)
1387
412
    return AR_accessible;
1388
447
  return AR_inaccessible;
1389
447
}
1390
1391
static void DelayDependentAccess(Sema &S,
1392
                                 const EffectiveContext &EC,
1393
                                 SourceLocation Loc,
1394
97
                                 const AccessTarget &Entity) {
1395
97
  assert(EC.isDependent() && "delaying non-dependent access");
1396
97
  DeclContext *DC = EC.getInnerContext();
1397
97
  assert(DC->isDependentContext() && "delaying non-dependent access");
1398
97
  DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1399
97
                              Loc,
1400
97
                              Entity.isMemberAccess(),
1401
97
                              Entity.getAccess(),
1402
97
                              Entity.getTargetDecl(),
1403
97
                              Entity.getNamingClass(),
1404
97
                              Entity.getBaseObjectType(),
1405
97
                              Entity.getDiag());
1406
97
}
1407
1408
/// Checks access to an entity from the given effective context.
1409
static AccessResult CheckEffectiveAccess(Sema &S,
1410
                                         const EffectiveContext &EC,
1411
                                         SourceLocation Loc,
1412
919k
                                         AccessTarget &Entity) {
1413
919k
  assert(Entity.getAccess() != AS_public && "called for public access!");
1414
1415
919k
  switch (IsAccessible(S, EC, Entity)) {
1416
97
  case AR_dependent:
1417
97
    DelayDependentAccess(S, EC, Loc, Entity);
1418
97
    return AR_dependent;
1419
1420
8.89k
  case AR_inaccessible:
1421
8.89k
    if (S.getLangOpts().MSVCCompat &&
1422
15
        IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1423
2
      return AR_accessible;
1424
8.89k
    if (!Entity.isQuiet())
1425
4.74k
      DiagnoseBadAccess(S, Loc, EC, Entity);
1426
8.89k
    return AR_inaccessible;
1427
1428
910k
  case AR_accessible:
1429
910k
    return AR_accessible;
1430
0
  }
1431
1432
  // silence unnecessary warning
1433
0
  llvm_unreachable("invalid access result");
1434
0
}
1435
1436
static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
1437
935k
                                      AccessTarget &Entity) {
1438
  // If the access path is public, it's accessible everywhere.
1439
935k
  if (Entity.getAccess() == AS_public)
1440
0
    return Sema::AR_accessible;
1441
1442
  // If we're currently parsing a declaration, we may need to delay
1443
  // access control checking, because our effective context might be
1444
  // different based on what the declaration comes out as.
1445
  //
1446
  // For example, we might be parsing a declaration with a scope
1447
  // specifier, like this:
1448
  //   A::private_type A::foo() { ... }
1449
  //
1450
  // Or we might be parsing something that will turn out to be a friend:
1451
  //   void foo(A::private_type);
1452
  //   void B::foo(A::private_type);
1453
935k
  if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1454
260k
    S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
1455
260k
    return Sema::AR_delayed;
1456
260k
  }
1457
1458
674k
  EffectiveContext EC(S.CurContext);
1459
674k
  switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1460
666k
  case AR_accessible: return Sema::AR_accessible;
1461
8.45k
  case AR_inaccessible: return Sema::AR_inaccessible;
1462
86
  case AR_dependent: return Sema::AR_dependent;
1463
0
  }
1464
0
  llvm_unreachable("invalid access result");
1465
0
}
1466
1467
244k
void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
1468
  // Access control for names used in the declarations of functions
1469
  // and function templates should normally be evaluated in the context
1470
  // of the declaration, just in case it's a friend of something.
1471
  // However, this does not apply to local extern declarations.
1472
1473
244k
  DeclContext *DC = D->getDeclContext();
1474
244k
  if (D->isLocalExternDecl()) {
1475
10
    DC = D->getLexicalDeclContext();
1476
244k
  } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1477
53.0k
    DC = FN;
1478
191k
  } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1479
45.1k
    if (isa<DeclContext>(TD->getTemplatedDecl()))
1480
45.1k
      DC = cast<DeclContext>(TD->getTemplatedDecl());
1481
45.1k
  }
1482
1483
244k
  EffectiveContext EC(DC);
1484
1485
244k
  AccessTarget Target(DD.getAccessData());
1486
1487
244k
  if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
1488
407
    DD.Triggered = true;
1489
244k
}
1490
1491
void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1492
140
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
1493
140
  SourceLocation Loc = DD.getAccessLoc();
1494
140
  AccessSpecifier Access = DD.getAccess();
1495
1496
140
  Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1497
140
                                       TemplateArgs);
1498
140
  if (!NamingD) 
return0
;
1499
140
  Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1500
140
                                       TemplateArgs);
1501
140
  if (!TargetD) 
return0
;
1502
1503
140
  if (DD.isAccessToMember()) {
1504
140
    CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1505
140
    NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1506
140
    QualType BaseObjectType = DD.getAccessBaseObjectType();
1507
140
    if (!BaseObjectType.isNull()) {
1508
131
      BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1509
131
                                 DeclarationName());
1510
131
      if (BaseObjectType.isNull()) 
return0
;
1511
140
    }
1512
1513
140
    AccessTarget Entity(Context,
1514
140
                        AccessTarget::Member,
1515
140
                        NamingClass,
1516
140
                        DeclAccessPair::make(TargetDecl, Access),
1517
140
                        BaseObjectType);
1518
140
    Entity.setDiag(DD.getDiagnostic());
1519
140
    CheckAccess(*this, Loc, Entity);
1520
0
  } else {
1521
0
    AccessTarget Entity(Context,
1522
0
                        AccessTarget::Base,
1523
0
                        cast<CXXRecordDecl>(TargetD),
1524
0
                        cast<CXXRecordDecl>(NamingD),
1525
0
                        Access);
1526
0
    Entity.setDiag(DD.getDiagnostic());
1527
0
    CheckAccess(*this, Loc, Entity);
1528
0
  }
1529
140
}
1530
1531
Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1532
606k
                                                     DeclAccessPair Found) {
1533
606k
  if (!getLangOpts().AccessControl ||
1534
570k
      !E->getNamingClass() ||
1535
52.2k
      Found.getAccess() == AS_public)
1536
601k
    return AR_accessible;
1537
1538
5.21k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1539
5.21k
                      Found, QualType());
1540
5.21k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1541
1542
5.21k
  return CheckAccess(*this, E->getNameLoc(), Entity);
1543
5.21k
}
1544
1545
/// Perform access-control checking on a previously-unresolved member
1546
/// access which has now been resolved to a member.
1547
Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1548
71.7k
                                                     DeclAccessPair Found) {
1549
71.7k
  if (!getLangOpts().AccessControl ||
1550
67.5k
      Found.getAccess() == AS_public)
1551
62.1k
    return AR_accessible;
1552
1553
9.57k
  QualType BaseType = E->getBaseType();
1554
9.57k
  if (E->isArrow())
1555
9.31k
    BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1556
1557
9.57k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1558
9.57k
                      Found, BaseType);
1559
9.57k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1560
1561
9.57k
  return CheckAccess(*this, E->getMemberLoc(), Entity);
1562
9.57k
}
1563
1564
/// Is the given member accessible for the purposes of deciding whether to
1565
/// define a special member function as deleted?
1566
bool Sema::isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1567
                                         DeclAccessPair Found,
1568
                                         QualType ObjectType,
1569
                                         SourceLocation Loc,
1570
242k
                                         const PartialDiagnostic &Diag) {
1571
  // Fast path.
1572
242k
  if (Found.getAccess() == AS_public || 
!getLangOpts().AccessControl64.7k
)
1573
181k
    return true;
1574
1575
61.8k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1576
61.8k
                      ObjectType);
1577
1578
  // Suppress diagnostics.
1579
61.8k
  Entity.setDiag(Diag);
1580
1581
61.8k
  switch (CheckAccess(*this, Loc, Entity)) {
1582
57.8k
  case AR_accessible: return true;
1583
3.97k
  case AR_inaccessible: return false;
1584
0
  case AR_dependent: llvm_unreachable("dependent for =delete computation");
1585
0
  case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1586
0
  }
1587
0
  llvm_unreachable("bad access result");
1588
0
}
1589
1590
Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
1591
                                               CXXDestructorDecl *Dtor,
1592
                                               const PartialDiagnostic &PDiag,
1593
268k
                                               QualType ObjectTy) {
1594
268k
  if (!getLangOpts().AccessControl)
1595
2.22k
    return AR_accessible;
1596
1597
  // There's never a path involved when checking implicit destructor access.
1598
266k
  AccessSpecifier Access = Dtor->getAccess();
1599
266k
  if (Access == AS_public)
1600
263k
    return AR_accessible;
1601
1602
2.58k
  CXXRecordDecl *NamingClass = Dtor->getParent();
1603
2.58k
  if (ObjectTy.isNull()) 
ObjectTy = Context.getTypeDeclType(NamingClass)167
;
1604
1605
2.58k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1606
2.58k
                      DeclAccessPair::make(Dtor, Access),
1607
2.58k
                      ObjectTy);
1608
2.58k
  Entity.setDiag(PDiag); // TODO: avoid copy
1609
1610
2.58k
  return CheckAccess(*this, Loc, Entity);
1611
2.58k
}
1612
1613
/// Checks access to a constructor.
1614
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1615
                                                CXXConstructorDecl *Constructor,
1616
                                                DeclAccessPair Found,
1617
                                                const InitializedEntity &Entity,
1618
328k
                                                bool IsCopyBindingRefToTemp) {
1619
328k
  if (!getLangOpts().AccessControl || 
Found.getAccess() == AS_public325k
)
1620
321k
    return AR_accessible;
1621
1622
6.82k
  PartialDiagnostic PD(PDiag());
1623
6.82k
  switch (Entity.getKind()) {
1624
3.98k
  default:
1625
3.98k
    PD = PDiag(IsCopyBindingRefToTemp
1626
7
                 ? diag::ext_rvalue_to_reference_access_ctor
1627
3.97k
                 : diag::err_access_ctor);
1628
1629
3.98k
    break;
1630
1631
2.81k
  case InitializedEntity::EK_Base:
1632
2.81k
    PD = PDiag(diag::err_access_base_ctor);
1633
2.81k
    PD << Entity.isInheritedVirtualBase()
1634
2.81k
       << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
1635
2.81k
    break;
1636
1637
24
  case InitializedEntity::EK_Member: {
1638
24
    const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
1639
24
    PD = PDiag(diag::err_access_field_ctor);
1640
24
    PD << Field->getType() << getSpecialMember(Constructor);
1641
24
    break;
1642
0
  }
1643
1644
2
  case InitializedEntity::EK_LambdaCapture: {
1645
2
    StringRef VarName = Entity.getCapturedVarName();
1646
2
    PD = PDiag(diag::err_access_lambda_capture);
1647
2
    PD << VarName << Entity.getType() << getSpecialMember(Constructor);
1648
2
    break;
1649
6.82k
  }
1650
1651
6.82k
  }
1652
1653
6.82k
  return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
1654
6.82k
}
1655
1656
/// Checks access to a constructor.
1657
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1658
                                                CXXConstructorDecl *Constructor,
1659
                                                DeclAccessPair Found,
1660
                                                const InitializedEntity &Entity,
1661
6.86k
                                                const PartialDiagnostic &PD) {
1662
6.86k
  if (!getLangOpts().AccessControl ||
1663
6.86k
      Found.getAccess() == AS_public)
1664
34
    return AR_accessible;
1665
1666
6.83k
  CXXRecordDecl *NamingClass = Constructor->getParent();
1667
1668
  // Initializing a base sub-object is an instance method call on an
1669
  // object of the derived class.  Otherwise, we have an instance method
1670
  // call on an object of the constructed type.
1671
  //
1672
  // FIXME: If we have a parent, we're initializing the base class subobject
1673
  // in aggregate initialization. It's not clear whether the object class
1674
  // should be the base class or the derived class in that case.
1675
6.83k
  CXXRecordDecl *ObjectClass;
1676
6.83k
  if ((Entity.getKind() == InitializedEntity::EK_Base ||
1677
4.01k
       Entity.getKind() == InitializedEntity::EK_Delegating) &&
1678
3.02k
      !Entity.getParent()) {
1679
3.02k
    ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1680
3.81k
  } else if (auto *Shadow =
1681
12
                 dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
1682
    // If we're using an inheriting constructor to construct an object,
1683
    // the object class is the derived class, not the base class.
1684
12
    ObjectClass = Shadow->getParent();
1685
3.80k
  } else {
1686
3.80k
    ObjectClass = NamingClass;
1687
3.80k
  }
1688
1689
6.83k
  AccessTarget AccessEntity(
1690
6.83k
      Context, AccessTarget::Member, NamingClass,
1691
6.83k
      DeclAccessPair::make(Constructor, Found.getAccess()),
1692
6.83k
      Context.getTypeDeclType(ObjectClass));
1693
6.83k
  AccessEntity.setDiag(PD);
1694
1695
6.83k
  return CheckAccess(*this, UseLoc, AccessEntity);
1696
6.83k
}
1697
1698
/// Checks access to an overloaded operator new or delete.
1699
Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1700
                                               SourceRange PlacementRange,
1701
                                               CXXRecordDecl *NamingClass,
1702
                                               DeclAccessPair Found,
1703
8.03k
                                               bool Diagnose) {
1704
8.03k
  if (!getLangOpts().AccessControl ||
1705
7.94k
      !NamingClass ||
1706
631
      Found.getAccess() == AS_public)
1707
8.01k
    return AR_accessible;
1708
1709
26
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1710
26
                      QualType());
1711
26
  if (Diagnose)
1712
20
    Entity.setDiag(diag::err_access)
1713
20
      << PlacementRange;
1714
1715
26
  return CheckAccess(*this, OpLoc, Entity);
1716
26
}
1717
1718
/// Checks access to a member.
1719
Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1720
                                           CXXRecordDecl *NamingClass,
1721
1.94k
                                           DeclAccessPair Found) {
1722
1.94k
  if (!getLangOpts().AccessControl ||
1723
1.94k
      !NamingClass ||
1724
830
      Found.getAccess() == AS_public)
1725
1.76k
    return AR_accessible;
1726
1727
175
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1728
175
                      Found, QualType());
1729
1730
175
  return CheckAccess(*this, UseLoc, Entity);
1731
175
}
1732
1733
/// Checks implicit access to a member in a structured binding.
1734
Sema::AccessResult
1735
Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1736
                                         CXXRecordDecl *DecomposedClass,
1737
328
                                         DeclAccessPair Field) {
1738
328
  if (!getLangOpts().AccessControl ||
1739
328
      Field.getAccess() == AS_public)
1740
313
    return AR_accessible;
1741
1742
15
  AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
1743
15
                      Context.getRecordType(DecomposedClass));
1744
15
  Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
1745
1746
15
  return CheckAccess(*this, UseLoc, Entity);
1747
15
}
1748
1749
/// Checks access to an overloaded member operator, including
1750
/// conversion operators.
1751
Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1752
                                                   Expr *ObjectExpr,
1753
                                                   Expr *ArgExpr,
1754
87.6k
                                                   DeclAccessPair Found) {
1755
87.6k
  if (!getLangOpts().AccessControl ||
1756
86.3k
      Found.getAccess() == AS_public)
1757
86.0k
    return AR_accessible;
1758
1759
1.63k
  const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
1760
1.63k
  CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1761
1762
1.63k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1763
1.63k
                      ObjectExpr->getType());
1764
1.63k
  Entity.setDiag(diag::err_access)
1765
1.63k
    << ObjectExpr->getSourceRange()
1766
1.54k
    << (ArgExpr ? ArgExpr->getSourceRange() : 
SourceRange()92
);
1767
1768
1.63k
  return CheckAccess(*this, OpLoc, Entity);
1769
1.63k
}
1770
1771
/// Checks access to the target of a friend declaration.
1772
360
Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
1773
360
  assert(isa<CXXMethodDecl>(target->getAsFunction()));
1774
1775
  // Friendship lookup is a redeclaration lookup, so there's never an
1776
  // inheritance path modifying access.
1777
360
  AccessSpecifier access = target->getAccess();
1778
1779
360
  if (!getLangOpts().AccessControl || access == AS_public)
1780
337
    return AR_accessible;
1781
1782
23
  CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
1783
1784
23
  AccessTarget entity(Context, AccessTarget::Member,
1785
23
                      cast<CXXRecordDecl>(target->getDeclContext()),
1786
23
                      DeclAccessPair::make(target, access),
1787
23
                      /*no instance context*/ QualType());
1788
23
  entity.setDiag(diag::err_access_friend_function)
1789
21
      << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
1790
2
                                 : method->getNameInfo().getSourceRange());
1791
1792
  // We need to bypass delayed-diagnostics because we might be called
1793
  // while the ParsingDeclarator is active.
1794
23
  EffectiveContext EC(CurContext);
1795
23
  switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1796
8
  case ::AR_accessible: return Sema::AR_accessible;
1797
13
  case ::AR_inaccessible: return Sema::AR_inaccessible;
1798
2
  case ::AR_dependent: return Sema::AR_dependent;
1799
0
  }
1800
0
  llvm_unreachable("invalid access result");
1801
0
}
1802
1803
Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1804
1.42k
                                                    DeclAccessPair Found) {
1805
1.42k
  if (!getLangOpts().AccessControl ||
1806
1.42k
      Found.getAccess() == AS_none ||
1807
290
      Found.getAccess() == AS_public)
1808
1.35k
    return AR_accessible;
1809
1810
69
  OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
1811
69
  CXXRecordDecl *NamingClass = Ovl->getNamingClass();
1812
1813
69
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1814
69
                      /*no instance context*/ QualType());
1815
69
  Entity.setDiag(diag::err_access)
1816
69
    << Ovl->getSourceRange();
1817
1818
69
  return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1819
69
}
1820
1821
/// Checks access for a hierarchy conversion.
1822
///
1823
/// \param ForceCheck true if this check should be performed even if access
1824
///     control is disabled;  some things rely on this for semantics
1825
/// \param ForceUnprivileged true if this check should proceed as if the
1826
///     context had no special privileges
1827
Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
1828
                                              QualType Base,
1829
                                              QualType Derived,
1830
                                              const CXXBasePath &Path,
1831
                                              unsigned DiagID,
1832
                                              bool ForceCheck,
1833
23.5k
                                              bool ForceUnprivileged) {
1834
23.5k
  if (!ForceCheck && 
!getLangOpts().AccessControl23.4k
)
1835
1.74k
    return AR_accessible;
1836
1837
21.7k
  if (Path.Access == AS_public)
1838
10.8k
    return AR_accessible;
1839
1840
10.9k
  CXXRecordDecl *BaseD, *DerivedD;
1841
10.9k
  BaseD = cast<CXXRecordDecl>(Base->castAs<RecordType>()->getDecl());
1842
10.9k
  DerivedD = cast<CXXRecordDecl>(Derived->castAs<RecordType>()->getDecl());
1843
1844
10.9k
  AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1845
10.9k
                      Path.Access);
1846
10.9k
  if (DiagID)
1847
10.8k
    Entity.setDiag(DiagID) << Derived << Base;
1848
1849
10.9k
  if (ForceUnprivileged) {
1850
15
    switch (CheckEffectiveAccess(*this, EffectiveContext(),
1851
15
                                 AccessLoc, Entity)) {
1852
0
    case ::AR_accessible: return Sema::AR_accessible;
1853
15
    case ::AR_inaccessible: return Sema::AR_inaccessible;
1854
0
    case ::AR_dependent: return Sema::AR_dependent;
1855
0
    }
1856
0
    llvm_unreachable("unexpected result from CheckEffectiveAccess");
1857
0
  }
1858
10.8k
  return CheckAccess(*this, AccessLoc, Entity);
1859
10.8k
}
1860
1861
/// Checks access to all the declarations in the given result set.
1862
4.37M
void Sema::CheckLookupAccess(const LookupResult &R) {
1863
4.37M
  assert(getLangOpts().AccessControl
1864
4.37M
         && "performing access check without access control");
1865
4.37M
  assert(R.getNamingClass() && "performing access check without naming class");
1866
1867
8.92M
  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; 
++I4.54M
) {
1868
4.54M
    if (I.getAccess() != AS_public) {
1869
836k
      AccessTarget Entity(Context, AccessedEntity::Member,
1870
836k
                          R.getNamingClass(), I.getPair(),
1871
836k
                          R.getBaseObjectType());
1872
836k
      Entity.setDiag(diag::err_access);
1873
836k
      CheckAccess(*this, R.getNameLoc(), Entity);
1874
836k
    }
1875
4.54M
  }
1876
4.37M
}
1877
1878
/// Checks access to Target from the given class. The check will take access
1879
/// specifiers into account, but no member access expressions and such.
1880
///
1881
/// \param Target the declaration to check if it can be accessed
1882
/// \param NamingClass the class in which the lookup was started.
1883
/// \param BaseType type of the left side of member access expression.
1884
///        \p BaseType and \p NamingClass are used for C++ access control.
1885
///        Depending on the lookup case, they should be set to the following:
1886
///        - lhs.target (member access without a qualifier):
1887
///          \p BaseType and \p NamingClass are both the type of 'lhs'.
1888
///        - lhs.X::target (member access with a qualifier):
1889
///          BaseType is the type of 'lhs', NamingClass is 'X'
1890
///        - X::target (qualified lookup without member access):
1891
///          BaseType is null, NamingClass is 'X'.
1892
///        - target (unqualified lookup).
1893
///          BaseType is null, NamingClass is the parent class of 'target'.
1894
/// \return true if the Target is accessible from the Class, false otherwise.
1895
bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
1896
16.9k
                              QualType BaseType) {
1897
  // Perform the C++ accessibility checks first.
1898
16.9k
  if (Target->isCXXClassMember() && 
NamingClass2.15k
) {
1899
2.12k
    if (!getLangOpts().CPlusPlus)
1900
0
      return false;
1901
    // The unprivileged access is AS_none as we don't know how the member was
1902
    // accessed, which is described by the access in DeclAccessPair.
1903
    // `IsAccessible` will examine the actual access of Target (i.e.
1904
    // Decl->getAccess()) when calculating the access.
1905
2.12k
    AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
1906
2.12k
                        DeclAccessPair::make(Target, AS_none), BaseType);
1907
2.12k
    EffectiveContext EC(CurContext);
1908
2.12k
    return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1909
2.12k
  }
1910
1911
14.7k
  if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
1912
    // @public and @package ivars are always accessible.
1913
76
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1914
66
        Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1915
10
      return true;
1916
1917
    // If we are inside a class or category implementation, determine the
1918
    // interface we're in.
1919
66
    ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1920
66
    if (ObjCMethodDecl *MD = getCurMethodDecl())
1921
56
      ClassOfMethodDecl =  MD->getClassInterface();
1922
10
    else if (FunctionDecl *FD = getCurFunctionDecl()) {
1923
10
      if (ObjCImplDecl *Impl
1924
0
            = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1925
0
        if (ObjCImplementationDecl *IMPD
1926
0
              = dyn_cast<ObjCImplementationDecl>(Impl))
1927
0
          ClassOfMethodDecl = IMPD->getClassInterface();
1928
0
        else if (ObjCCategoryImplDecl* CatImplClass
1929
0
                   = dyn_cast<ObjCCategoryImplDecl>(Impl))
1930
0
          ClassOfMethodDecl = CatImplClass->getClassInterface();
1931
0
      }
1932
10
    }
1933
1934
    // If we're not in an interface, this ivar is inaccessible.
1935
66
    if (!ClassOfMethodDecl)
1936
10
      return false;
1937
1938
    // If we're inside the same interface that owns the ivar, we're fine.
1939
56
    if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
1940
50
      return true;
1941
1942
    // If the ivar is private, it's inaccessible.
1943
6
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1944
3
      return false;
1945
1946
3
    return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1947
3
  }
1948
1949
14.7k
  return true;
1950
14.7k
}