Coverage Report

Created: 2020-02-15 09:57

/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
65.1k
                                    AccessSpecifier LexicalAS) {
42
65.1k
  if (!PrevMemberDecl) {
43
64.0k
    // Use the lexical access specifier.
44
64.0k
    MemberDecl->setAccess(LexicalAS);
45
64.0k
    return false;
46
64.0k
  }
47
1.09k
48
1.09k
  // C++ [class.access.spec]p3: When a member is redeclared its access
49
1.09k
  // specifier must be same as its initial declaration.
50
1.09k
  if (LexicalAS != AS_none && 
LexicalAS != PrevMemberDecl->getAccess()105
) {
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
4
57
4
    MemberDecl->setAccess(LexicalAS);
58
4
    return true;
59
4
  }
60
1.09k
61
1.09k
  MemberDecl->setAccess(PrevMemberDecl->getAccess());
62
1.09k
  return false;
63
1.09k
}
64
65
1.18M
static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66
1.18M
  DeclContext *DC = D->getDeclContext();
67
1.18M
68
1.18M
  // This can only happen at top: enum decls only "publish" their
69
1.18M
  // immediate members.
70
1.18M
  if (isa<EnumDecl>(DC))
71
9.47k
    DC = cast<EnumDecl>(DC)->getDeclContext();
72
1.18M
73
1.18M
  CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74
1.18M
  while (DeclaringClass->isAnonymousStructOrUnion())
75
0
    DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76
1.18M
  return DeclaringClass;
77
1.18M
}
78
79
namespace {
80
struct EffectiveContext {
81
15
  EffectiveContext() : Inner(nullptr), Dependent(false) {}
82
83
  explicit EffectiveContext(DeclContext *DC)
84
    : Inner(DC),
85
924k
      Dependent(DC->isDependentContext()) {
86
924k
87
924k
    // C++11 [class.access.nest]p1:
88
924k
    //   A nested class is a member and as such has the same access
89
924k
    //   rights as any other member.
90
924k
    // C++11 [class.access]p2:
91
924k
    //   A member of a class can also access all the names to which
92
924k
    //   the class has access.  A local class of a member function
93
924k
    //   may access the same names that the member function itself
94
924k
    //   may access.
95
924k
    // This almost implies that the privileges of nesting are transitive.
96
924k
    // Technically it says nothing about the local classes of non-member
97
924k
    // functions (which can gain privileges through friendship), but we
98
924k
    // take that as an oversight.
99
2.62M
    while (true) {
100
2.62M
      // We want to add canonical declarations to the EC lists for
101
2.62M
      // simplicity of checking, but we need to walk up through the
102
2.62M
      // actual current DC chain.  Otherwise, something like a local
103
2.62M
      // extern or friend which happens to be the canonical
104
2.62M
      // declaration will really mess us up.
105
2.62M
106
2.62M
      if (isa<CXXRecordDecl>(DC)) {
107
938k
        CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
108
938k
        Records.push_back(Record->getCanonicalDecl());
109
938k
        DC = Record->getDeclContext();
110
1.68M
      } else if (isa<FunctionDecl>(DC)) {
111
750k
        FunctionDecl *Function = cast<FunctionDecl>(DC);
112
750k
        Functions.push_back(Function->getCanonicalDecl());
113
750k
        if (Function->getFriendObjectKind())
114
3.99k
          DC = Function->getLexicalDeclContext();
115
746k
        else
116
746k
          DC = Function->getDeclContext();
117
934k
      } else if (DC->isFileContext()) {
118
924k
        break;
119
924k
      } else {
120
9.96k
        DC = DC->getParent();
121
9.96k
      }
122
2.62M
    }
123
924k
  }
124
125
88.6k
  bool isDependent() const { return Dependent; }
126
127
8.76k
  bool includesClass(const CXXRecordDecl *R) const {
128
8.76k
    R = R->getCanonicalDecl();
129
8.76k
    return llvm::find(Records, R) != Records.end();
130
8.76k
  }
131
132
  /// Retrieves the innermost "useful" context.  Can be null if we're
133
  /// doing access-control without privileges.
134
73
  DeclContext *getInnerContext() const {
135
73
    return Inner;
136
73
  }
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
260k
    : AccessedEntity(Entity) {
151
260k
    initialize();
152
260k
  }
153
154
  AccessTarget(ASTContext &Context,
155
               MemberNonce _,
156
               CXXRecordDecl *NamingClass,
157
               DeclAccessPair FoundDecl,
158
               QualType BaseObjectType)
159
    : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
160
924k
                     FoundDecl, BaseObjectType) {
161
924k
    initialize();
162
924k
  }
163
164
  AccessTarget(ASTContext &Context,
165
               BaseNonce _,
166
               CXXRecordDecl *BaseClass,
167
               CXXRecordDecl *DerivedClass,
168
               AccessSpecifier Access)
169
    : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
170
15.1k
                     Access) {
171
15.1k
    initialize();
172
15.1k
  }
173
174
184k
  bool isInstanceMember() const {
175
184k
    return (isMemberAccess() && 
getTargetDecl()->isCXXInstanceMember()184k
);
176
184k
  }
177
178
182k
  bool hasInstanceContext() const {
179
182k
    return HasInstanceContext;
180
182k
  }
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
60.3k
    ~SavedInstanceContext() {
189
60.3k
      if (Target)
190
60.3k
        Target->HasInstanceContext = Has;
191
60.3k
    }
192
193
  private:
194
    friend struct AccessTarget;
195
    explicit SavedInstanceContext(AccessTarget &Target)
196
60.3k
        : Target(&Target), Has(Target.HasInstanceContext) {}
197
    AccessTarget *Target;
198
    bool Has;
199
  };
200
201
60.3k
  SavedInstanceContext saveInstanceContext() {
202
60.3k
    return SavedInstanceContext(*this);
203
60.3k
  }
204
205
49.0k
  void suppressInstanceContext() {
206
49.0k
    HasInstanceContext = false;
207
49.0k
  }
208
209
53.8k
  const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
210
53.8k
    assert(HasInstanceContext);
211
53.8k
    if (CalculatedInstanceContext)
212
486
      return InstanceContext;
213
53.3k
214
53.3k
    CalculatedInstanceContext = true;
215
53.3k
    DeclContext *IC = S.computeDeclContext(getBaseObjectType());
216
53.3k
    InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
217
53.3k
                          : 
nullptr0
);
218
53.3k
    return InstanceContext;
219
53.3k
  }
220
221
64.4k
  const CXXRecordDecl *getDeclaringClass() const {
222
64.4k
    return DeclaringClass;
223
64.4k
  }
224
225
  /// The "effective" naming class is the canonical non-anonymous
226
  /// class containing the actual naming class.
227
925k
  const CXXRecordDecl *getEffectiveNamingClass() const {
228
925k
    const CXXRecordDecl *namingClass = getNamingClass();
229
925k
    while (namingClass->isAnonymousStructOrUnion())
230
0
      namingClass = cast<CXXRecordDecl>(namingClass->getParent());
231
925k
    return namingClass->getCanonicalDecl();
232
925k
  }
233
234
private:
235
1.19M
  void initialize() {
236
1.19M
    HasInstanceContext = (isMemberAccess() &&
237
1.19M
                          
!getBaseObjectType().isNull()1.18M
&&
238
1.19M
                          
getTargetDecl()->isCXXInstanceMember()503k
);
239
1.19M
    CalculatedInstanceContext = false;
240
1.19M
    InstanceContext = nullptr;
241
1.19M
242
1.19M
    if (isMemberAccess())
243
1.18M
      DeclaringClass = FindDeclaringClass(getTargetDecl());
244
15.2k
    else
245
15.2k
      DeclaringClass = getBaseClass();
246
1.19M
    DeclaringClass = DeclaringClass->getCanonicalDecl();
247
1.19M
  }
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
6.17k
                               const CXXRecordDecl *To) {
260
6.17k
  // Declaration names are always preserved by instantiation.
261
6.17k
  if (From->getDeclName() != To->getDeclName())
262
6.07k
    return false;
263
104
264
104
  const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
265
104
  const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
266
104
  if (FromDC == ToDC) 
return true96
;
267
8
  if (FromDC->isFileContext() || ToDC->isFileContext()) 
return false0
;
268
8
269
8
  // 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
237k
                                           const CXXRecordDecl *Target) {
280
237k
  assert(Derived->getCanonicalDecl() == Derived);
281
237k
  assert(Target->getCanonicalDecl() == Target);
282
237k
283
237k
  if (Derived == Target) 
return AR_accessible179k
;
284
57.5k
285
57.5k
  bool CheckDependent = Derived->isDependentContext();
286
57.5k
  if (CheckDependent && 
MightInstantiateTo(Derived, Target)1.64k
)
287
12
    return AR_dependent;
288
57.5k
289
57.5k
  AccessResult OnFailure = AR_inaccessible;
290
57.5k
  SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
291
57.5k
292
58.1k
  while (true) {
293
58.1k
    if (Derived->isDependentContext() && 
!Derived->hasDefinition()1.63k
&&
294
58.1k
        
!Derived->isLambda()1
)
295
1
      return AR_dependent;
296
58.1k
297
58.1k
    for (const auto &I : Derived->bases()) {
298
56.8k
      const CXXRecordDecl *RD;
299
56.8k
300
56.8k
      QualType T = I.getType();
301
56.8k
      if (const RecordType *RT = T->getAs<RecordType>()) {
302
56.8k
        RD = cast<CXXRecordDecl>(RT->getDecl());
303
56.8k
      } else 
if (const InjectedClassNameType *6
IT6
304
0
                   = T->getAs<InjectedClassNameType>()) {
305
0
        RD = IT->getDecl();
306
6
      } else {
307
6
        assert(T->isDependentType() && "non-dependent base wasn't a record?");
308
6
        OnFailure = AR_dependent;
309
6
        continue;
310
6
      }
311
56.8k
312
56.8k
      RD = RD->getCanonicalDecl();
313
56.8k
      if (RD == Target) 
return AR_accessible55.6k
;
314
1.13k
      if (CheckDependent && 
MightInstantiateTo(RD, Target)179
)
315
0
        OnFailure = AR_dependent;
316
1.13k
317
1.13k
      Queue.push_back(RD);
318
1.13k
    }
319
58.1k
320
58.1k
    
if (2.50k
Queue.empty()2.50k
)
break1.81k
;
321
683
322
683
    Derived = Queue.pop_back_val();
323
683
  }
324
57.5k
325
57.5k
  
return OnFailure1.81k
;
326
57.5k
}
327
328
329
static bool MightInstantiateTo(Sema &S, DeclContext *Context,
330
45
                               DeclContext *Friend) {
331
45
  if (Friend == Context)
332
33
    return true;
333
12
334
12
  assert(!Friend->isDependentContext() &&
335
12
         "can't handle friends with dependent contexts here");
336
12
337
12
  if (!Context->isDependentContext())
338
10
    return false;
339
2
340
2
  if (Friend->isFileContext())
341
0
    return false;
342
2
343
2
  // 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
36
353
36
  if (!Friend->isDependentType() && !Context->isDependentType())
354
0
    return false;
355
36
356
36
  // TODO: this is very conservative.
357
36
  return true;
358
36
}
359
360
static bool MightInstantiateTo(Sema &S,
361
                               FunctionDecl *Context,
362
2.84k
                               FunctionDecl *Friend) {
363
2.84k
  if (Context->getDeclName() != Friend->getDeclName())
364
2.80k
    return false;
365
42
366
42
  if (!MightInstantiateTo(S,
367
42
                          Context->getDeclContext(),
368
42
                          Friend->getDeclContext()))
369
7
    return false;
370
35
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
35
378
35
  // There isn't any way that I know of to add qualifiers
379
35
  // during instantiation.
380
35
  if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
381
0
    return false;
382
35
383
35
  if (FriendTy->getNumParams() != ContextTy->getNumParams())
384
0
    return false;
385
35
386
35
  if (!MightInstantiateTo(S, ContextTy->getReturnType(),
387
35
                          FriendTy->getReturnType()))
388
0
    return false;
389
35
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
35
395
35
  return true;
396
35
}
397
398
static bool MightInstantiateTo(Sema &S,
399
                               FunctionTemplateDecl *Context,
400
2.54k
                               FunctionTemplateDecl *Friend) {
401
2.54k
  return MightInstantiateTo(S,
402
2.54k
                            Context->getTemplatedDecl(),
403
2.54k
                            Friend->getTemplatedDecl());
404
2.54k
}
405
406
static AccessResult MatchesFriend(Sema &S,
407
                                  const EffectiveContext &EC,
408
8.76k
                                  const CXXRecordDecl *Friend) {
409
8.76k
  if (EC.includesClass(Friend))
410
3.31k
    return AR_accessible;
411
5.44k
412
5.44k
  if (EC.isDependent()) {
413
380
    for (const CXXRecordDecl *Context : EC.Records) {
414
29
      if (MightInstantiateTo(Context, Friend))
415
10
        return AR_dependent;
416
29
    }
417
380
  }
418
5.44k
419
5.44k
  
return AR_inaccessible5.43k
;
420
5.44k
}
421
422
static AccessResult MatchesFriend(Sema &S,
423
                                  const EffectiveContext &EC,
424
8.76k
                                  CanQualType Friend) {
425
8.76k
  if (const RecordType *RT = Friend->getAs<RecordType>())
426
8.76k
    return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
427
0
428
0
  // TODO: we can do better than this
429
0
  if (Friend->isDependentType())
430
0
    return AR_dependent;
431
0
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
9.23k
                                  ClassTemplateDecl *Friend) {
440
9.23k
  AccessResult OnFailure = AR_inaccessible;
441
9.23k
442
9.23k
  // Check whether the friend is the template of a class in the
443
9.23k
  // context chain.
444
9.23k
  for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
445
16.8k
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I7.65k
) {
446
9.74k
    CXXRecordDecl *Record = *I;
447
9.74k
448
9.74k
    // Figure out whether the current class has a template:
449
9.74k
    ClassTemplateDecl *CTD;
450
9.74k
451
9.74k
    // A specialization of the template...
452
9.74k
    if (isa<ClassTemplateSpecializationDecl>(Record)) {
453
3.15k
      CTD = cast<ClassTemplateSpecializationDecl>(Record)
454
3.15k
        ->getSpecializedTemplate();
455
3.15k
456
3.15k
    // ... or the template pattern itself.
457
6.59k
    } else {
458
6.59k
      CTD = Record->getDescribedClassTemplate();
459
6.59k
      if (!CTD) 
continue552
;
460
9.19k
    }
461
9.19k
462
9.19k
    // It's a match.
463
9.19k
    if (Friend == CTD->getCanonicalDecl())
464
2.08k
      return AR_accessible;
465
7.10k
466
7.10k
    // If the context isn't dependent, it can't be a dependent match.
467
7.10k
    if (!EC.isDependent())
468
2.22k
      continue;
469
4.88k
470
4.88k
    // If the template names don't match, it can't be a dependent
471
4.88k
    // match.
472
4.88k
    if (CTD->getDeclName() != Friend->getDeclName())
473
4.87k
      continue;
474
3
475
3
    // If the class's context can't instantiate to the friend's
476
3
    // context, it can't be a dependent match.
477
3
    if (!MightInstantiateTo(S, CTD->getDeclContext(),
478
3
                            Friend->getDeclContext()))
479
3
      continue;
480
0
481
0
    // Otherwise, it's a dependent match.
482
0
    OnFailure = AR_dependent;
483
0
  }
484
9.23k
485
9.23k
  
return OnFailure7.14k
;
486
9.23k
}
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.24k
                                  FunctionDecl *Friend) {
493
5.24k
  AccessResult OnFailure = AR_inaccessible;
494
5.24k
495
5.24k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
496
9.44k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I4.20k
) {
497
5.23k
    if (Friend == *I)
498
1.02k
      return AR_accessible;
499
4.20k
500
4.20k
    if (EC.isDependent() && 
MightInstantiateTo(S, *I, Friend)302
)
501
35
      OnFailure = AR_dependent;
502
4.20k
  }
503
5.24k
504
5.24k
  
return OnFailure4.21k
;
505
5.24k
}
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
25.6k
                                  FunctionTemplateDecl *Friend) {
512
25.6k
  if (EC.Functions.empty()) 
return AR_inaccessible46
;
513
25.5k
514
25.5k
  AccessResult OnFailure = AR_inaccessible;
515
25.5k
516
25.5k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
517
48.7k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I23.2k
) {
518
25.5k
519
25.5k
    FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
520
25.5k
    if (!FTD)
521
13.8k
      FTD = (*I)->getDescribedFunctionTemplate();
522
25.5k
    if (!FTD)
523
10.5k
      continue;
524
14.9k
525
14.9k
    FTD = FTD->getCanonicalDecl();
526
14.9k
527
14.9k
    if (Friend == FTD)
528
2.35k
      return AR_accessible;
529
12.6k
530
12.6k
    if (EC.isDependent() && 
MightInstantiateTo(S, FTD, Friend)2.54k
)
531
0
      OnFailure = AR_dependent;
532
12.6k
  }
533
25.5k
534
25.5k
  
return OnFailure23.2k
;
535
25.5k
}
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
48.8k
                                  FriendDecl *FriendD) {
542
48.8k
  // Whitelist accesses if there's an invalid or unsupported friend
543
48.8k
  // declaration.
544
48.8k
  if (FriendD->isInvalidDecl() || 
FriendD->isUnsupportedFriend()48.8k
)
545
38
    return AR_accessible;
546
48.8k
547
48.8k
  if (TypeSourceInfo *T = FriendD->getFriendType())
548
8.76k
    return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
549
40.0k
550
40.0k
  NamedDecl *Friend
551
40.0k
    = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
552
40.0k
553
40.0k
  // FIXME: declarations with dependent or templated scope.
554
40.0k
555
40.0k
  if (isa<ClassTemplateDecl>(Friend))
556
9.23k
    return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
557
30.8k
558
30.8k
  if (isa<FunctionTemplateDecl>(Friend))
559
25.6k
    return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
560
5.24k
561
5.24k
  if (isa<CXXRecordDecl>(Friend))
562
0
    return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
563
5.24k
564
5.24k
  assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
565
5.24k
  return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
566
5.24k
}
567
568
static AccessResult GetFriendKind(Sema &S,
569
                                  const EffectiveContext &EC,
570
69.6k
                                  const CXXRecordDecl *Class) {
571
69.6k
  AccessResult OnFailure = AR_inaccessible;
572
69.6k
573
69.6k
  // Okay, check friends.
574
69.6k
  for (auto *Friend : Class->friends()) {
575
48.8k
    switch (MatchesFriend(S, EC, Friend)) {
576
8.82k
    case AR_accessible:
577
8.82k
      return AR_accessible;
578
0
579
40.0k
    case AR_inaccessible:
580
40.0k
      continue;
581
0
582
45
    case AR_dependent:
583
45
      OnFailure = AR_dependent;
584
45
      break;
585
48.8k
    }
586
48.8k
  }
587
69.6k
588
69.6k
  // That's it, give up.
589
69.6k
  
return OnFailure60.7k
;
590
69.6k
}
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
573
      EverDependent(false) {}
613
614
  /// Check classes in the current path for friendship, starting at
615
  /// the given index.
616
555
  bool checkFriendshipAlongPath(unsigned I) {
617
555
    assert(I < CurPath.size());
618
1.29k
    for (unsigned E = CurPath.size(); I != E; 
++I738
) {
619
830
      switch (GetFriendKind(S, EC, CurPath[I])) {
620
92
      case AR_accessible:   return true;
621
738
      case AR_inaccessible: continue;
622
0
      case AR_dependent:    EverDependent = true; continue;
623
830
      }
624
830
    }
625
555
    
return false463
;
626
555
  }
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
880
  bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
634
880
    // If we ever reach the naming class, check the current path for
635
880
    // friendship.  We can also stop recursing because we obviously
636
880
    // won't find the naming class there again.
637
880
    if (Cur == NamingClass)
638
555
      return checkFriendshipAlongPath(PrivateDepth);
639
325
640
325
    if (CheckDependent && 
MightInstantiateTo(Cur, NamingClass)0
)
641
0
      EverDependent = true;
642
325
643
325
    // Recurse into the base classes.
644
325
    for (const auto &I : Cur->bases()) {
645
307
      // If this is private inheritance, then a public member of the
646
307
      // base will not have any access in classes derived from Cur.
647
307
      unsigned BasePrivateDepth = PrivateDepth;
648
307
      if (I.getAccessSpecifier() == AS_private)
649
33
        BasePrivateDepth = CurPath.size() - 1;
650
307
651
307
      const CXXRecordDecl *RD;
652
307
653
307
      QualType T = I.getType();
654
307
      if (const RecordType *RT = T->getAs<RecordType>()) {
655
307
        RD = cast<CXXRecordDecl>(RT->getDecl());
656
307
      } else 
if (const InjectedClassNameType *0
IT0
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
307
665
307
      // Recurse.  We don't need to clean up if this returns true.
666
307
      CurPath.push_back(RD);
667
307
      if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
668
209
        return true;
669
98
      CurPath.pop_back();
670
98
    }
671
325
672
325
    
return false116
;
673
325
  }
674
675
573
  bool findFriendship(const CXXRecordDecl *Cur) {
676
573
    assert(CurPath.empty());
677
573
    CurPath.push_back(Cur);
678
573
    return findFriendship(Cur, 0);
679
573
  }
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
764
                                           const CXXRecordDecl *NamingClass) {
712
764
  assert(InstanceContext == nullptr ||
713
764
         InstanceContext->getCanonicalDecl() == InstanceContext);
714
764
  assert(NamingClass->getCanonicalDecl() == NamingClass);
715
764
716
764
  // If we don't have an instance context, our constraints give us
717
764
  // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
718
764
  // This is just the usual friendship check.
719
764
  if (!InstanceContext) 
return GetFriendKind(S, EC, NamingClass)191
;
720
573
721
573
  ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
722
573
  if (PRC.findFriendship(InstanceContext)) 
return AR_accessible92
;
723
481
  if (PRC.EverDependent) 
return AR_dependent0
;
724
481
  return AR_inaccessible;
725
481
}
726
727
static AccessResult HasAccess(Sema &S,
728
                              const EffectiveContext &EC,
729
                              const CXXRecordDecl *NamingClass,
730
                              AccessSpecifier Access,
731
978k
                              const AccessTarget &Target) {
732
978k
  assert(NamingClass->getCanonicalDecl() == NamingClass &&
733
978k
         "declaration should be canonicalized before being passed here");
734
978k
735
978k
  if (Access == AS_public) 
return AR_accessible47.9k
;
736
930k
  assert(Access == AS_private || Access == AS_protected);
737
930k
738
930k
  AccessResult OnFailure = AR_inaccessible;
739
930k
740
930k
  for (EffectiveContext::record_iterator
741
992k
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I61.0k
) {
742
922k
    // All the declarations in EC have been canonicalized, so pointer
743
922k
    // equality from this point on will work fine.
744
922k
    const CXXRecordDecl *ECRecord = *I;
745
922k
746
922k
    // [B2] and [M2]
747
922k
    if (Access == AS_private) {
748
738k
      if (ECRecord == NamingClass)
749
679k
        return AR_accessible;
750
59.2k
751
59.2k
      if (EC.isDependent() && 
MightInstantiateTo(ECRecord, NamingClass)4.32k
)
752
82
        OnFailure = AR_dependent;
753
59.2k
754
59.2k
    // [B3] and [M3]
755
183k
    } else {
756
183k
      assert(Access == AS_protected);
757
183k
      switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
758
182k
      case AR_accessible: break;
759
1.65k
      case AR_inaccessible: continue;
760
19
      case AR_dependent: OnFailure = AR_dependent; continue;
761
182k
      }
762
182k
763
182k
      // C++ [class.protected]p1:
764
182k
      //   An additional access check beyond those described earlier in
765
182k
      //   [class.access] is applied when a non-static data member or
766
182k
      //   non-static member function is a protected member of its naming
767
182k
      //   class.  As described earlier, access to a protected member is
768
182k
      //   granted because the reference occurs in a friend or member of
769
182k
      //   some class C.  If the access is to form a pointer to member,
770
182k
      //   the nested-name-specifier shall name C or a class derived from
771
182k
      //   C. All other accesses involve a (possibly implicit) object
772
182k
      //   expression. In this case, the class of the object expression
773
182k
      //   shall be C or a class derived from C.
774
182k
      //
775
182k
      // We interpret this as a restriction on [M3].
776
182k
777
182k
      // In this part of the code, 'C' is just our context class ECRecord.
778
182k
779
182k
      // These rules are different if we don't have an instance context.
780
182k
      if (!Target.hasInstanceContext()) {
781
128k
        // If it's not an instance member, these restrictions don't apply.
782
128k
        if (!Target.isInstanceMember()) 
return AR_accessible128k
;
783
82
784
82
        // If it's an instance member, use the pointer-to-member rule
785
82
        // that the naming class has to be derived from the effective
786
82
        // context.
787
82
788
82
        // Emulate a MSVC bug where the creation of pointer-to-member
789
82
        // to protected member of base class is allowed but only from
790
82
        // 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
81
795
81
        // Despite the standard's confident wording, there is a case
796
81
        // where you can have an instance member that's neither in a
797
81
        // pointer-to-member expression nor in a member access:  when
798
81
        // it names a field in an unevaluated context that can't be an
799
81
        // implicit member.  Pending clarification, we just apply the
800
81
        // same naming-class restriction here.
801
81
        //   FIXME: we're probably not correctly adding the
802
81
        //   protected-member restriction when we retroactively convert
803
81
        //   an expression to being evaluated.
804
81
805
81
        // We know that ECRecord derives from NamingClass.  The
806
81
        // restriction says to check whether NamingClass derives from
807
81
        // ECRecord, but that's not really necessary: two distinct
808
81
        // classes can't be recursively derived from each other.  So
809
81
        // along this path, we just need to check whether the classes
810
81
        // are equal.
811
81
        if (NamingClass == ECRecord) 
return AR_accessible25
;
812
56
813
56
        // Otherwise, this context class tells us nothing;  on to the next.
814
56
        continue;
815
56
      }
816
53.2k
817
53.2k
      assert(Target.isInstanceMember());
818
53.2k
819
53.2k
      const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
820
53.2k
      if (!InstanceContext) {
821
0
        OnFailure = AR_dependent;
822
0
        continue;
823
0
      }
824
53.2k
825
53.2k
      switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
826
53.1k
      case AR_accessible: return AR_accessible;
827
104
      case AR_inaccessible: continue;
828
0
      case AR_dependent: OnFailure = AR_dependent; continue;
829
53.2k
      }
830
53.2k
    }
831
922k
  }
832
930k
833
930k
  // [M3] and [B3] say that, if the target is protected in N, we grant
834
930k
  // access if the access occurs in a friend or member of some class P
835
930k
  // that's a subclass of N and where the target has some natural
836
930k
  // access in P.  The 'member' aspect is easy to handle because P
837
930k
  // would necessarily be one of the effective-context records, and we
838
930k
  // address that above.  The 'friend' aspect is completely ridiculous
839
930k
  // to implement because there are no restrictions at all on P
840
930k
  // *unless* the [class.protected] restriction applies.  If it does,
841
930k
  // however, we should ignore whether the naming class is a friend,
842
930k
  // and instead rely on whether any potential P is a friend.
843
930k
  
if (69.3k
Access == AS_protected69.3k
&&
Target.isInstanceMember()2.36k
) {
844
764
    // Compute the instance context if possible.
845
764
    const CXXRecordDecl *InstanceContext = nullptr;
846
764
    if (Target.hasInstanceContext()) {
847
573
      InstanceContext = Target.resolveInstanceContext(S);
848
573
      if (!InstanceContext) 
return AR_dependent0
;
849
764
    }
850
764
851
764
    switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
852
95
    case AR_accessible: return AR_accessible;
853
669
    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
68.5k
859
68.5k
  switch (GetFriendKind(S, EC, NamingClass)) {
860
8.72k
  case AR_accessible: return AR_accessible;
861
59.8k
  case AR_inaccessible: return OnFailure;
862
45
  case AR_dependent: return AR_dependent;
863
0
  }
864
0
865
0
  // 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.21k
                                 CXXBasePaths &Paths) {
930
1.21k
  // Derive the paths to the desired base.
931
1.21k
  const CXXRecordDecl *Derived = Target.getNamingClass();
932
1.21k
  const CXXRecordDecl *Base = Target.getDeclaringClass();
933
1.21k
934
1.21k
  // FIXME: fail correctly when there are dependent paths.
935
1.21k
  bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
936
1.21k
                                          Paths);
937
1.21k
  assert(isDerived && "derived class not actually derived from base");
938
1.21k
  (void) isDerived;
939
1.21k
940
1.21k
  CXXBasePath *BestPath = nullptr;
941
1.21k
942
1.21k
  assert(FinalAccess != AS_none && "forbidden access after declaring class");
943
1.21k
944
1.21k
  bool AnyDependent = false;
945
1.21k
946
1.21k
  // Derive the friend-modified access along each path.
947
1.21k
  for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
948
2.01k
         PI != PE; 
++PI797
) {
949
1.22k
    AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
950
1.22k
951
1.22k
    // Walk through the path backwards.
952
1.22k
    AccessSpecifier PathAccess = FinalAccess;
953
1.22k
    CXXBasePath::iterator I = PI->end(), E = PI->begin();
954
2.66k
    while (I != E) {
955
1.71k
      --I;
956
1.71k
957
1.71k
      assert(PathAccess != AS_none);
958
1.71k
959
1.71k
      // If the declaration is a private member of a base class, there
960
1.71k
      // is no level of friendship in derived classes that can make it
961
1.71k
      // accessible.
962
1.71k
      if (PathAccess == AS_private) {
963
270
        PathAccess = AS_none;
964
270
        break;
965
270
      }
966
1.44k
967
1.44k
      const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
968
1.44k
969
1.44k
      AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
970
1.44k
      PathAccess = std::max(PathAccess, BaseAccess);
971
1.44k
972
1.44k
      switch (HasAccess(S, EC, NC, PathAccess, Target)) {
973
750
      case AR_inaccessible: break;
974
691
      case AR_accessible:
975
691
        PathAccess = AS_public;
976
691
977
691
        // Future tests are not against members and so do not have
978
691
        // instance context.
979
691
        Target.suppressInstanceContext();
980
691
        break;
981
0
      case AR_dependent:
982
0
        AnyDependent = true;
983
0
        goto Next;
984
1.44k
      }
985
1.44k
    }
986
1.22k
987
1.22k
    // Note that we modify the path's Access field to the
988
1.22k
    // friend-modified access.
989
1.22k
    if (BestPath == nullptr || 
PathAccess < BestPath->Access6
) {
990
1.22k
      BestPath = &*PI;
991
1.22k
      BestPath->Access = PathAccess;
992
1.22k
993
1.22k
      // Short-circuit if we found a public path.
994
1.22k
      if (BestPath->Access == AS_public)
995
424
        return BestPath;
996
797
    }
997
797
998
797
  Next: ;
999
797
  }
1000
1.21k
1001
1.21k
  assert((!BestPath || BestPath->Access != AS_public) &&
1002
791
         "fell out of loop with public path");
1003
791
1004
791
  // We didn't find a public path, but at least one path was subject
1005
791
  // to dependent friendship, so delay the check.
1006
791
  if (AnyDependent)
1007
0
    return nullptr;
1008
791
1009
791
  return BestPath;
1010
791
}
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
169
                                       AccessTarget &Target) {
1019
169
  // Only applies to instance accesses.
1020
169
  if (!Target.isInstanceMember())
1021
50
    return false;
1022
119
1023
119
  assert(Target.isMemberAccess());
1024
119
1025
119
  const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
1026
119
1027
119
  for (EffectiveContext::record_iterator
1028
148
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I29
) {
1029
61
    const CXXRecordDecl *ECRecord = *I;
1030
61
    switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
1031
32
    case AR_accessible: break;
1032
29
    case AR_inaccessible: continue;
1033
0
    case AR_dependent: continue;
1034
32
    }
1035
32
1036
32
    // The effective context is a subclass of the declaring class.
1037
32
    // Check whether the [class.protected] restriction is limiting
1038
32
    // access.
1039
32
1040
32
    // To get this exactly right, this might need to be checked more
1041
32
    // holistically;  it's not necessarily the case that gaining
1042
32
    // access here would grant us access overall.
1043
32
1044
32
    NamedDecl *D = Target.getTargetDecl();
1045
32
1046
32
    // If we don't have an instance context, [class.protected] says the
1047
32
    // naming class has to equal the context class.
1048
32
    if (!Target.hasInstanceContext()) {
1049
12
      // If it does, the restriction doesn't apply.
1050
12
      if (NamingClass == ECRecord) 
continue0
;
1051
12
1052
12
      // TODO: it would be great to have a fixit here, since this is
1053
12
      // 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
20
1059
20
    const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1060
20
    assert(InstanceContext && "diagnosing dependent access");
1061
20
1062
20
    switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1063
0
    case AR_accessible: continue;
1064
0
    case AR_dependent: continue;
1065
20
    case AR_inaccessible:
1066
20
      break;
1067
20
    }
1068
20
1069
20
    // Okay, the restriction seems to be what's limiting us.
1070
20
1071
20
    // Use a special diagnostic for constructors and destructors.
1072
20
    if (isa<CXXConstructorDecl>(D) || 
isa<CXXDestructorDecl>(D)17
||
1073
20
        
(14
isa<FunctionTemplateDecl>(D)14
&&
1074
14
         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
14
1081
14
    // Otherwise, use the generic diagnostic.
1082
14
    return S.Diag(D->getLocation(),
1083
14
                  diag::note_access_protected_restricted_object)
1084
14
           << S.Context.getTypeDeclType(ECRecord);
1085
14
  }
1086
119
1087
119
  
return false87
;
1088
119
}
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
3.30k
                                    AccessTarget &entity) {
1095
3.30k
  assert(entity.isMemberAccess());
1096
3.30k
  NamedDecl *D = entity.getTargetDecl();
1097
3.30k
1098
3.30k
  if (D->getAccess() == AS_protected &&
1099
3.30k
      
TryDiagnoseProtectedAccess(S, EC, entity)169
)
1100
32
    return;
1101
3.27k
1102
3.27k
  // Find an original declaration.
1103
3.29k
  
while (3.27k
D->isOutOfLine()) {
1104
25
    NamedDecl *PrevDecl = nullptr;
1105
25
    if (VarDecl *VD = dyn_cast<VarDecl>(D))
1106
4
      PrevDecl = VD->getPreviousDecl();
1107
21
    else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1108
17
      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
25
    if (!PrevDecl) 
break0
;
1117
25
    D = PrevDecl;
1118
25
  }
1119
3.27k
1120
3.27k
  CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1121
3.27k
  Decl *ImmediateChild;
1122
3.27k
  if (D->getDeclContext() == DeclaringClass)
1123
3.26k
    ImmediateChild = D;
1124
3
  else {
1125
3
    DeclContext *DC = D->getDeclContext();
1126
3
    while (DC->getParent() != DeclaringClass)
1127
0
      DC = DC->getParent();
1128
3
    ImmediateChild = cast<Decl>(DC);
1129
3
  }
1130
3.27k
1131
3.27k
  // Check whether there's an AccessSpecDecl preceding this in the
1132
3.27k
  // chain of the DeclContext.
1133
3.27k
  bool isImplicit = true;
1134
9.67k
  for (const auto *I : DeclaringClass->decls()) {
1135
9.67k
    if (I == ImmediateChild) 
break2.86k
;
1136
6.81k
    if (isa<AccessSpecDecl>(I)) {
1137
405
      isImplicit = false;
1138
405
      break;
1139
405
    }
1140
6.81k
  }
1141
3.27k
1142
3.27k
  S.Diag(D->getLocation(), diag::note_access_natural)
1143
3.27k
    << (unsigned) (D->getAccess() == AS_protected)
1144
3.27k
    << isImplicit;
1145
3.27k
}
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
3.58k
                               AccessTarget &entity) {
1152
3.58k
  // Save the instance context to preserve invariants.
1153
3.58k
  AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
1154
3.58k
1155
3.58k
  // This basically repeats the main algorithm but keeps some more
1156
3.58k
  // information.
1157
3.58k
1158
3.58k
  // The natural access so far.
1159
3.58k
  AccessSpecifier accessSoFar = AS_public;
1160
3.58k
1161
3.58k
  // Check whether we have special rights to the declaring class.
1162
3.58k
  if (entity.isMemberAccess()) {
1163
3.42k
    NamedDecl *D = entity.getTargetDecl();
1164
3.42k
    accessSoFar = D->getAccess();
1165
3.42k
    const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
1166
3.42k
1167
3.42k
    switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1168
0
    // If the declaration is accessible when named in its declaring
1169
0
    // class, then we must be constrained by the path.
1170
116
    case AR_accessible:
1171
116
      accessSoFar = AS_public;
1172
116
      entity.suppressInstanceContext();
1173
116
      break;
1174
0
1175
3.30k
    case AR_inaccessible:
1176
3.30k
      if (accessSoFar == AS_private ||
1177
3.30k
          
declaringClass == entity.getEffectiveNamingClass()174
)
1178
3.26k
        return diagnoseBadDirectAccess(S, EC, entity);
1179
47
      break;
1180
47
1181
47
    case AR_dependent:
1182
0
      llvm_unreachable("cannot diagnose dependent access");
1183
325
    }
1184
325
  }
1185
325
1186
325
  CXXBasePaths paths;
1187
325
  CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1188
325
  assert(path.Access != AS_public);
1189
325
1190
325
  CXXBasePath::iterator i = path.end(), e = path.begin();
1191
325
  CXXBasePath::iterator constrainingBase = i;
1192
448
  while (i != e) {
1193
352
    --i;
1194
352
1195
352
    assert(accessSoFar != AS_none && accessSoFar != AS_private);
1196
352
1197
352
    // Is the entity accessible when named in the deriving class, as
1198
352
    // modified by the base specifier?
1199
352
    const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1200
352
    const CXXBaseSpecifier *base = i->Base;
1201
352
1202
352
    // If the access to this base is worse than the access we have to
1203
352
    // the declaration, remember it.
1204
352
    AccessSpecifier baseAccess = base->getAccessSpecifier();
1205
352
    if (baseAccess > accessSoFar) {
1206
283
      constrainingBase = i;
1207
283
      accessSoFar = baseAccess;
1208
283
    }
1209
352
1210
352
    switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
1211
333
    case AR_inaccessible: break;
1212
19
    case AR_accessible:
1213
19
      accessSoFar = AS_public;
1214
19
      entity.suppressInstanceContext();
1215
19
      constrainingBase = nullptr;
1216
19
      break;
1217
0
    case AR_dependent:
1218
0
      llvm_unreachable("cannot diagnose dependent access");
1219
352
    }
1220
352
1221
352
    // If this was private inheritance, but we don't have access to
1222
352
    // the deriving class, we're done.
1223
352
    if (accessSoFar == AS_private) {
1224
229
      assert(baseAccess == AS_private);
1225
229
      assert(constrainingBase == i);
1226
229
      break;
1227
229
    }
1228
352
  }
1229
325
1230
325
  // If we don't have a constraining base, the access failure must be
1231
325
  // due to the original declaration.
1232
325
  if (constrainingBase == path.end())
1233
42
    return diagnoseBadDirectAccess(S, EC, entity);
1234
283
1235
283
  // We're constrained by inheritance, but we want to say
1236
283
  // "declared private here" if we're diagnosing a hierarchy
1237
283
  // conversion and this is the final step.
1238
283
  unsigned diagnostic;
1239
283
  if (entity.isMemberAccess() ||
1240
283
      
constrainingBase + 1 != path.end()162
) {
1241
129
    diagnostic = diag::note_access_constrained_by_path;
1242
154
  } else {
1243
154
    diagnostic = diag::note_access_natural;
1244
154
  }
1245
283
1246
283
  const CXXBaseSpecifier *base = constrainingBase->Base;
1247
283
1248
283
  S.Diag(base->getSourceRange().getBegin(), diagnostic)
1249
283
    << base->getSourceRange()
1250
283
    << (base->getAccessSpecifier() == AS_protected)
1251
283
    << (base->getAccessSpecifierAsWritten() == AS_none);
1252
283
1253
283
  if (entity.isMemberAccess())
1254
121
    S.Diag(entity.getTargetDecl()->getLocation(),
1255
121
           diag::note_member_declared_at);
1256
283
}
1257
1258
static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
1259
                              const EffectiveContext &EC,
1260
3.58k
                              AccessTarget &Entity) {
1261
3.58k
  const CXXRecordDecl *NamingClass = Entity.getNamingClass();
1262
3.58k
  const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1263
3.58k
  NamedDecl *D = (Entity.isMemberAccess() ? 
Entity.getTargetDecl()3.42k
:
nullptr162
);
1264
3.58k
1265
3.58k
  S.Diag(Loc, Entity.getDiag())
1266
3.58k
    << (Entity.getAccess() == AS_protected)
1267
3.58k
    << (D ? 
D->getDeclName()3.42k
:
DeclarationName()162
)
1268
3.58k
    << S.Context.getTypeDeclType(NamingClass)
1269
3.58k
    << S.Context.getTypeDeclType(DeclaringClass);
1270
3.58k
  DiagnoseAccessPath(S, EC, Entity);
1271
3.58k
}
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
924k
                                 AccessTarget &Entity) {
1316
924k
  // Determine the actual naming class.
1317
924k
  const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
1318
924k
1319
924k
  AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1320
924k
  assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1321
924k
1322
924k
  // Before we try to recalculate access paths, try to white-list
1323
924k
  // accesses which just trade in on the final step, i.e. accesses
1324
924k
  // which don't require [M4] or [B4]. These are by far the most
1325
924k
  // common forms of privileged access.
1326
924k
  if (UnprivilegedAccess != AS_none) {
1327
918k
    switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1328
73
    case AR_dependent:
1329
73
      // This is actually an interesting policy decision.  We don't
1330
73
      // *have* to delay immediately here: we can do the full access
1331
73
      // calculation in the hope that friendship on some intermediate
1332
73
      // class will make the declaration accessible non-dependently.
1333
73
      // But that's not cheap, and odds are very good (note: assertion
1334
73
      // made without data) that the friend declaration will determine
1335
73
      // access.
1336
73
      return AR_dependent;
1337
0
1338
869k
    case AR_accessible: return AR_accessible;
1339
48.9k
    case AR_inaccessible: break;
1340
55.5k
    }
1341
55.5k
  }
1342
55.5k
1343
55.5k
  AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
1344
55.5k
1345
55.5k
  // We lower member accesses to base accesses by pretending that the
1346
55.5k
  // member is a base class of its declaring class.
1347
55.5k
  AccessSpecifier FinalAccess;
1348
55.5k
1349
55.5k
  if (Entity.isMemberAccess()) {
1350
55.3k
    // Determine if the declaration is accessible from EC when named
1351
55.3k
    // in its declaring class.
1352
55.3k
    NamedDecl *Target = Entity.getTargetDecl();
1353
55.3k
    const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1354
55.3k
1355
55.3k
    FinalAccess = Target->getAccess();
1356
55.3k
    switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1357
48.2k
    case AR_accessible:
1358
48.2k
      // Target is accessible at EC when named in its declaring class.
1359
48.2k
      // We can now hill-climb and simply check whether the declaring
1360
48.2k
      // class is accessible as a base of the naming class.  This is
1361
48.2k
      // equivalent to checking the access of a notional public
1362
48.2k
      // member with no instance context.
1363
48.2k
      FinalAccess = AS_public;
1364
48.2k
      Entity.suppressInstanceContext();
1365
48.2k
      break;
1366
7.13k
    case AR_inaccessible: break;
1367
0
    case AR_dependent: return AR_dependent; // see above
1368
55.3k
    }
1369
55.3k
1370
55.3k
    if (DeclaringClass == NamingClass)
1371
54.6k
      return (FinalAccess == AS_public ? 
AR_accessible47.6k
:
AR_inaccessible7.01k
);
1372
192
  } else {
1373
192
    FinalAccess = AS_public;
1374
192
  }
1375
55.5k
1376
55.5k
  assert(Entity.getDeclaringClass() != NamingClass);
1377
890
1378
890
  // Append the declaration's access if applicable.
1379
890
  CXXBasePaths Paths;
1380
890
  CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
1381
890
  if (!Path)
1382
0
    return AR_dependent;
1383
890
1384
890
  assert(Path->Access <= UnprivilegedAccess &&
1385
890
         "access along best path worse than direct?");
1386
890
  if (Path->Access == AS_public)
1387
424
    return AR_accessible;
1388
466
  return AR_inaccessible;
1389
466
}
1390
1391
static void DelayDependentAccess(Sema &S,
1392
                                 const EffectiveContext &EC,
1393
                                 SourceLocation Loc,
1394
73
                                 const AccessTarget &Entity) {
1395
73
  assert(EC.isDependent() && "delaying non-dependent access");
1396
73
  DeclContext *DC = EC.getInnerContext();
1397
73
  assert(DC->isDependentContext() && "delaying non-dependent access");
1398
73
  DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1399
73
                              Loc,
1400
73
                              Entity.isMemberAccess(),
1401
73
                              Entity.getAccess(),
1402
73
                              Entity.getTargetDecl(),
1403
73
                              Entity.getNamingClass(),
1404
73
                              Entity.getBaseObjectType(),
1405
73
                              Entity.getDiag());
1406
73
}
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
922k
                                         AccessTarget &Entity) {
1413
922k
  assert(Entity.getAccess() != AS_public && "called for public access!");
1414
922k
1415
922k
  switch (IsAccessible(S, EC, Entity)) {
1416
73
  case AR_dependent:
1417
73
    DelayDependentAccess(S, EC, Loc, Entity);
1418
73
    return AR_dependent;
1419
0
1420
7.41k
  case AR_inaccessible:
1421
7.41k
    if (S.getLangOpts().MSVCCompat &&
1422
7.41k
        
IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity)15
)
1423
2
      return AR_accessible;
1424
7.40k
    if (!Entity.isQuiet())
1425
3.58k
      DiagnoseBadAccess(S, Loc, EC, Entity);
1426
7.40k
    return AR_inaccessible;
1427
7.40k
1428
915k
  case AR_accessible:
1429
915k
    return AR_accessible;
1430
0
  }
1431
0
1432
0
  // silence unnecessary warning
1433
0
  llvm_unreachable("invalid access result");
1434
0
}
1435
1436
static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
1437
937k
                                      AccessTarget &Entity) {
1438
937k
  // If the access path is public, it's accessible everywhere.
1439
937k
  if (Entity.getAccess() == AS_public)
1440
0
    return Sema::AR_accessible;
1441
937k
1442
937k
  // If we're currently parsing a declaration, we may need to delay
1443
937k
  // access control checking, because our effective context might be
1444
937k
  // different based on what the declaration comes out as.
1445
937k
  //
1446
937k
  // For example, we might be parsing a declaration with a scope
1447
937k
  // specifier, like this:
1448
937k
  //   A::private_type A::foo() { ... }
1449
937k
  //
1450
937k
  // Or we might be parsing something that will turn out to be a friend:
1451
937k
  //   void foo(A::private_type);
1452
937k
  //   void B::foo(A::private_type);
1453
937k
  if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1454
274k
    S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
1455
274k
    return Sema::AR_delayed;
1456
274k
  }
1457
662k
1458
662k
  EffectiveContext EC(S.CurContext);
1459
662k
  switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1460
655k
  case AR_accessible: return Sema::AR_accessible;
1461
7.01k
  case AR_inaccessible: return Sema::AR_inaccessible;
1462
62
  case AR_dependent: return Sema::AR_dependent;
1463
0
  }
1464
0
  llvm_unreachable("invalid access result");
1465
0
}
1466
1467
260k
void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
1468
260k
  // Access control for names used in the declarations of functions
1469
260k
  // and function templates should normally be evaluated in the context
1470
260k
  // of the declaration, just in case it's a friend of something.
1471
260k
  // However, this does not apply to local extern declarations.
1472
260k
1473
260k
  DeclContext *DC = D->getDeclContext();
1474
260k
  if (D->isLocalExternDecl()) {
1475
10
    DC = D->getLexicalDeclContext();
1476
260k
  } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1477
67.9k
    DC = FN;
1478
192k
  } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1479
41.9k
    DC = cast<DeclContext>(TD->getTemplatedDecl());
1480
41.9k
  }
1481
260k
1482
260k
  EffectiveContext EC(DC);
1483
260k
1484
260k
  AccessTarget Target(DD.getAccessData());
1485
260k
1486
260k
  if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
1487
370
    DD.Triggered = true;
1488
260k
}
1489
1490
void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1491
92
                        const MultiLevelTemplateArgumentList &TemplateArgs) {
1492
92
  SourceLocation Loc = DD.getAccessLoc();
1493
92
  AccessSpecifier Access = DD.getAccess();
1494
92
1495
92
  Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1496
92
                                       TemplateArgs);
1497
92
  if (!NamingD) 
return0
;
1498
92
  Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1499
92
                                       TemplateArgs);
1500
92
  if (!TargetD) 
return0
;
1501
92
1502
92
  if (DD.isAccessToMember()) {
1503
92
    CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1504
92
    NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1505
92
    QualType BaseObjectType = DD.getAccessBaseObjectType();
1506
92
    if (!BaseObjectType.isNull()) {
1507
83
      BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1508
83
                                 DeclarationName());
1509
83
      if (BaseObjectType.isNull()) 
return0
;
1510
92
    }
1511
92
1512
92
    AccessTarget Entity(Context,
1513
92
                        AccessTarget::Member,
1514
92
                        NamingClass,
1515
92
                        DeclAccessPair::make(TargetDecl, Access),
1516
92
                        BaseObjectType);
1517
92
    Entity.setDiag(DD.getDiagnostic());
1518
92
    CheckAccess(*this, Loc, Entity);
1519
92
  } else {
1520
0
    AccessTarget Entity(Context,
1521
0
                        AccessTarget::Base,
1522
0
                        cast<CXXRecordDecl>(TargetD),
1523
0
                        cast<CXXRecordDecl>(NamingD),
1524
0
                        Access);
1525
0
    Entity.setDiag(DD.getDiagnostic());
1526
0
    CheckAccess(*this, Loc, Entity);
1527
0
  }
1528
92
}
1529
1530
Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
1531
560k
                                                     DeclAccessPair Found) {
1532
560k
  if (!getLangOpts().AccessControl ||
1533
560k
      
!E->getNamingClass()524k
||
1534
560k
      
Found.getAccess() == AS_public56.5k
)
1535
552k
    return AR_accessible;
1536
7.92k
1537
7.92k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1538
7.92k
                      Found, QualType());
1539
7.92k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1540
7.92k
1541
7.92k
  return CheckAccess(*this, E->getNameLoc(), Entity);
1542
7.92k
}
1543
1544
/// Perform access-control checking on a previously-unresolved member
1545
/// access which has now been resolved to a member.
1546
Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
1547
63.6k
                                                     DeclAccessPair Found) {
1548
63.6k
  if (!getLangOpts().AccessControl ||
1549
63.6k
      
Found.getAccess() == AS_public60.0k
)
1550
53.9k
    return AR_accessible;
1551
9.68k
1552
9.68k
  QualType BaseType = E->getBaseType();
1553
9.68k
  if (E->isArrow())
1554
9.40k
    BaseType = BaseType->castAs<PointerType>()->getPointeeType();
1555
9.68k
1556
9.68k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1557
9.68k
                      Found, BaseType);
1558
9.68k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1559
9.68k
1560
9.68k
  return CheckAccess(*this, E->getMemberLoc(), Entity);
1561
9.68k
}
1562
1563
/// Is the given member accessible for the purposes of deciding whether to
1564
/// define a special member function as deleted?
1565
bool Sema::isMemberAccessibleForDeletion(CXXRecordDecl *NamingClass,
1566
                                         DeclAccessPair Found,
1567
                                         QualType ObjectType,
1568
                                         SourceLocation Loc,
1569
225k
                                         const PartialDiagnostic &Diag) {
1570
225k
  // Fast path.
1571
225k
  if (Found.getAccess() == AS_public || 
!getLangOpts().AccessControl52.8k
)
1572
174k
    return true;
1573
51.2k
1574
51.2k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1575
51.2k
                      ObjectType);
1576
51.2k
1577
51.2k
  // Suppress diagnostics.
1578
51.2k
  Entity.setDiag(Diag);
1579
51.2k
1580
51.2k
  switch (CheckAccess(*this, Loc, Entity)) {
1581
47.5k
  case AR_accessible: return true;
1582
3.65k
  case AR_inaccessible: return false;
1583
0
  case AR_dependent: llvm_unreachable("dependent for =delete computation");
1584
0
  case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1585
0
  }
1586
0
  llvm_unreachable("bad access result");
1587
0
}
1588
1589
Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
1590
                                               CXXDestructorDecl *Dtor,
1591
                                               const PartialDiagnostic &PDiag,
1592
233k
                                               QualType ObjectTy) {
1593
233k
  if (!getLangOpts().AccessControl)
1594
2.44k
    return AR_accessible;
1595
231k
1596
231k
  // There's never a path involved when checking implicit destructor access.
1597
231k
  AccessSpecifier Access = Dtor->getAccess();
1598
231k
  if (Access == AS_public)
1599
228k
    return AR_accessible;
1600
2.66k
1601
2.66k
  CXXRecordDecl *NamingClass = Dtor->getParent();
1602
2.66k
  if (ObjectTy.isNull()) 
ObjectTy = Context.getTypeDeclType(NamingClass)140
;
1603
2.66k
1604
2.66k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1605
2.66k
                      DeclAccessPair::make(Dtor, Access),
1606
2.66k
                      ObjectTy);
1607
2.66k
  Entity.setDiag(PDiag); // TODO: avoid copy
1608
2.66k
1609
2.66k
  return CheckAccess(*this, Loc, Entity);
1610
2.66k
}
1611
1612
/// Checks access to a constructor.
1613
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1614
                                                CXXConstructorDecl *Constructor,
1615
                                                DeclAccessPair Found,
1616
                                                const InitializedEntity &Entity,
1617
286k
                                                bool IsCopyBindingRefToTemp) {
1618
286k
  if (!getLangOpts().AccessControl || 
Found.getAccess() == AS_public284k
)
1619
280k
    return AR_accessible;
1620
6.49k
1621
6.49k
  PartialDiagnostic PD(PDiag());
1622
6.49k
  switch (Entity.getKind()) {
1623
3.40k
  default:
1624
3.40k
    PD = PDiag(IsCopyBindingRefToTemp
1625
3.40k
                 ? 
diag::ext_rvalue_to_reference_access_ctor7
1626
3.40k
                 : 
diag::err_access_ctor3.39k
);
1627
3.40k
1628
3.40k
    break;
1629
0
1630
3.06k
  case InitializedEntity::EK_Base:
1631
3.06k
    PD = PDiag(diag::err_access_base_ctor);
1632
3.06k
    PD << Entity.isInheritedVirtualBase()
1633
3.06k
       << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
1634
3.06k
    break;
1635
0
1636
30
  case InitializedEntity::EK_Member: {
1637
30
    const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
1638
30
    PD = PDiag(diag::err_access_field_ctor);
1639
30
    PD << Field->getType() << getSpecialMember(Constructor);
1640
30
    break;
1641
0
  }
1642
0
1643
2
  case InitializedEntity::EK_LambdaCapture: {
1644
2
    StringRef VarName = Entity.getCapturedVarName();
1645
2
    PD = PDiag(diag::err_access_lambda_capture);
1646
2
    PD << VarName << Entity.getType() << getSpecialMember(Constructor);
1647
2
    break;
1648
6.49k
  }
1649
6.49k
1650
6.49k
  }
1651
6.49k
1652
6.49k
  return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
1653
6.49k
}
1654
1655
/// Checks access to a constructor.
1656
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1657
                                                CXXConstructorDecl *Constructor,
1658
                                                DeclAccessPair Found,
1659
                                                const InitializedEntity &Entity,
1660
6.53k
                                                const PartialDiagnostic &PD) {
1661
6.53k
  if (!getLangOpts().AccessControl ||
1662
6.53k
      Found.getAccess() == AS_public)
1663
34
    return AR_accessible;
1664
6.50k
1665
6.50k
  CXXRecordDecl *NamingClass = Constructor->getParent();
1666
6.50k
1667
6.50k
  // Initializing a base sub-object is an instance method call on an
1668
6.50k
  // object of the derived class.  Otherwise, we have an instance method
1669
6.50k
  // call on an object of the constructed type.
1670
6.50k
  //
1671
6.50k
  // FIXME: If we have a parent, we're initializing the base class subobject
1672
6.50k
  // in aggregate initialization. It's not clear whether the object class
1673
6.50k
  // should be the base class or the derived class in that case.
1674
6.50k
  CXXRecordDecl *ObjectClass;
1675
6.50k
  if ((Entity.getKind() == InitializedEntity::EK_Base ||
1676
6.50k
       
Entity.getKind() == InitializedEntity::EK_Delegating3.44k
) &&
1677
6.50k
      
!Entity.getParent()3.31k
) {
1678
3.30k
    ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1679
3.30k
  } else 
if (auto *3.19k
Shadow3.19k
=
1680
12
                 dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
1681
12
    // If we're using an inheriting constructor to construct an object,
1682
12
    // the object class is the derived class, not the base class.
1683
12
    ObjectClass = Shadow->getParent();
1684
3.18k
  } else {
1685
3.18k
    ObjectClass = NamingClass;
1686
3.18k
  }
1687
6.50k
1688
6.50k
  AccessTarget AccessEntity(
1689
6.50k
      Context, AccessTarget::Member, NamingClass,
1690
6.50k
      DeclAccessPair::make(Constructor, Found.getAccess()),
1691
6.50k
      Context.getTypeDeclType(ObjectClass));
1692
6.50k
  AccessEntity.setDiag(PD);
1693
6.50k
1694
6.50k
  return CheckAccess(*this, UseLoc, AccessEntity);
1695
6.50k
}
1696
1697
/// Checks access to an overloaded operator new or delete.
1698
Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1699
                                               SourceRange PlacementRange,
1700
                                               CXXRecordDecl *NamingClass,
1701
                                               DeclAccessPair Found,
1702
7.26k
                                               bool Diagnose) {
1703
7.26k
  if (!getLangOpts().AccessControl ||
1704
7.26k
      
!NamingClass7.16k
||
1705
7.26k
      
Found.getAccess() == AS_public550
)
1706
7.24k
    return AR_accessible;
1707
22
1708
22
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1709
22
                      QualType());
1710
22
  if (Diagnose)
1711
16
    Entity.setDiag(diag::err_access)
1712
16
      << PlacementRange;
1713
22
1714
22
  return CheckAccess(*this, OpLoc, Entity);
1715
22
}
1716
1717
/// Checks access to a member.
1718
Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1719
                                           CXXRecordDecl *NamingClass,
1720
1.89k
                                           DeclAccessPair Found) {
1721
1.89k
  if (!getLangOpts().AccessControl ||
1722
1.89k
      !NamingClass ||
1723
1.89k
      
Found.getAccess() == AS_public802
)
1724
1.72k
    return AR_accessible;
1725
164
1726
164
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1727
164
                      Found, QualType());
1728
164
1729
164
  return CheckAccess(*this, UseLoc, Entity);
1730
164
}
1731
1732
/// Checks implicit access to a member in a structured binding.
1733
Sema::AccessResult
1734
Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1735
                                         CXXRecordDecl *DecomposedClass,
1736
311
                                         DeclAccessPair Field) {
1737
311
  if (!getLangOpts().AccessControl ||
1738
311
      Field.getAccess() == AS_public)
1739
296
    return AR_accessible;
1740
15
1741
15
  AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
1742
15
                      Context.getRecordType(DecomposedClass));
1743
15
  Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
1744
15
1745
15
  return CheckAccess(*this, UseLoc, Entity);
1746
15
}
1747
1748
/// Checks access to an overloaded member operator, including
1749
/// conversion operators.
1750
Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1751
                                                   Expr *ObjectExpr,
1752
                                                   Expr *ArgExpr,
1753
73.5k
                                                   DeclAccessPair Found) {
1754
73.5k
  if (!getLangOpts().AccessControl ||
1755
73.5k
      
Found.getAccess() == AS_public72.2k
)
1756
72.5k
    return AR_accessible;
1757
1.01k
1758
1.01k
  const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
1759
1.01k
  CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1760
1.01k
1761
1.01k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1762
1.01k
                      ObjectExpr->getType());
1763
1.01k
  Entity.setDiag(diag::err_access)
1764
1.01k
    << ObjectExpr->getSourceRange()
1765
1.01k
    << (ArgExpr ? 
ArgExpr->getSourceRange()957
:
SourceRange()56
);
1766
1.01k
1767
1.01k
  return CheckAccess(*this, OpLoc, Entity);
1768
1.01k
}
1769
1770
/// Checks access to the target of a friend declaration.
1771
356
Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
1772
356
  assert(isa<CXXMethodDecl>(target->getAsFunction()));
1773
356
1774
356
  // Friendship lookup is a redeclaration lookup, so there's never an
1775
356
  // inheritance path modifying access.
1776
356
  AccessSpecifier access = target->getAccess();
1777
356
1778
356
  if (!getLangOpts().AccessControl || access == AS_public)
1779
333
    return AR_accessible;
1780
23
1781
23
  CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
1782
23
1783
23
  AccessTarget entity(Context, AccessTarget::Member,
1784
23
                      cast<CXXRecordDecl>(target->getDeclContext()),
1785
23
                      DeclAccessPair::make(target, access),
1786
23
                      /*no instance context*/ QualType());
1787
23
  entity.setDiag(diag::err_access_friend_function)
1788
23
      << (method->getQualifier() ? 
method->getQualifierLoc().getSourceRange()21
1789
23
                                 : 
method->getNameInfo().getSourceRange()2
);
1790
23
1791
23
  // We need to bypass delayed-diagnostics because we might be called
1792
23
  // while the ParsingDeclarator is active.
1793
23
  EffectiveContext EC(CurContext);
1794
23
  switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1795
8
  case ::AR_accessible: return Sema::AR_accessible;
1796
13
  case ::AR_inaccessible: return Sema::AR_inaccessible;
1797
2
  case ::AR_dependent: return Sema::AR_dependent;
1798
0
  }
1799
0
  llvm_unreachable("invalid access result");
1800
0
}
1801
1802
Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1803
1.39k
                                                    DeclAccessPair Found) {
1804
1.39k
  if (!getLangOpts().AccessControl ||
1805
1.39k
      Found.getAccess() == AS_none ||
1806
1.39k
      
Found.getAccess() == AS_public272
)
1807
1.33k
    return AR_accessible;
1808
62
1809
62
  OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
1810
62
  CXXRecordDecl *NamingClass = Ovl->getNamingClass();
1811
62
1812
62
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1813
62
                      /*no instance context*/ QualType());
1814
62
  Entity.setDiag(diag::err_access)
1815
62
    << Ovl->getSourceRange();
1816
62
1817
62
  return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1818
62
}
1819
1820
/// Checks access for a hierarchy conversion.
1821
///
1822
/// \param ForceCheck true if this check should be performed even if access
1823
///     control is disabled;  some things rely on this for semantics
1824
/// \param ForceUnprivileged true if this check should proceed as if the
1825
///     context had no special privileges
1826
Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
1827
                                              QualType Base,
1828
                                              QualType Derived,
1829
                                              const CXXBasePath &Path,
1830
                                              unsigned DiagID,
1831
                                              bool ForceCheck,
1832
35.4k
                                              bool ForceUnprivileged) {
1833
35.4k
  if (!ForceCheck && 
!getLangOpts().AccessControl35.4k
)
1834
2.35k
    return AR_accessible;
1835
33.1k
1836
33.1k
  if (Path.Access == AS_public)
1837
17.9k
    return AR_accessible;
1838
15.1k
1839
15.1k
  CXXRecordDecl *BaseD, *DerivedD;
1840
15.1k
  BaseD = cast<CXXRecordDecl>(Base->castAs<RecordType>()->getDecl());
1841
15.1k
  DerivedD = cast<CXXRecordDecl>(Derived->castAs<RecordType>()->getDecl());
1842
15.1k
1843
15.1k
  AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1844
15.1k
                      Path.Access);
1845
15.1k
  if (DiagID)
1846
15.1k
    Entity.setDiag(DiagID) << Derived << Base;
1847
15.1k
1848
15.1k
  if (ForceUnprivileged) {
1849
15
    switch (CheckEffectiveAccess(*this, EffectiveContext(),
1850
15
                                 AccessLoc, Entity)) {
1851
0
    case ::AR_accessible: return Sema::AR_accessible;
1852
15
    case ::AR_inaccessible: return Sema::AR_inaccessible;
1853
0
    case ::AR_dependent: return Sema::AR_dependent;
1854
0
    }
1855
0
    llvm_unreachable("unexpected result from CheckEffectiveAccess");
1856
0
  }
1857
15.1k
  return CheckAccess(*this, AccessLoc, Entity);
1858
15.1k
}
1859
1860
/// Checks access to all the declarations in the given result set.
1861
4.19M
void Sema::CheckLookupAccess(const LookupResult &R) {
1862
4.19M
  assert(getLangOpts().AccessControl
1863
4.19M
         && "performing access check without access control");
1864
4.19M
  assert(R.getNamingClass() && "performing access check without naming class");
1865
4.19M
1866
8.54M
  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; 
++I4.35M
) {
1867
4.35M
    if (I.getAccess() != AS_public) {
1868
842k
      AccessTarget Entity(Context, AccessedEntity::Member,
1869
842k
                          R.getNamingClass(), I.getPair(),
1870
842k
                          R.getBaseObjectType());
1871
842k
      Entity.setDiag(diag::err_access);
1872
842k
      CheckAccess(*this, R.getNameLoc(), Entity);
1873
842k
    }
1874
4.35M
  }
1875
4.19M
}
1876
1877
/// Checks access to Target from the given class. The check will take access
1878
/// specifiers into account, but no member access expressions and such.
1879
///
1880
/// \param Target the declaration to check if it can be accessed
1881
/// \param NamingClass the class in which the lookup was started.
1882
/// \param BaseType type of the left side of member access expression.
1883
///        \p BaseType and \p NamingClass are used for C++ access control.
1884
///        Depending on the lookup case, they should be set to the following:
1885
///        - lhs.target (member access without a qualifier):
1886
///          \p BaseType and \p NamingClass are both the type of 'lhs'.
1887
///        - lhs.X::target (member access with a qualifier):
1888
///          BaseType is the type of 'lhs', NamingClass is 'X'
1889
///        - X::target (qualified lookup without member access):
1890
///          BaseType is null, NamingClass is 'X'.
1891
///        - target (unqualified lookup).
1892
///          BaseType is null, NamingClass is the parent class of 'target'.
1893
/// \return true if the Target is accessible from the Class, false otherwise.
1894
bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
1895
16.6k
                              QualType BaseType) {
1896
16.6k
  // Perform the C++ accessibility checks first.
1897
16.6k
  if (Target->isCXXClassMember() && 
NamingClass2.13k
) {
1898
2.09k
    if (!getLangOpts().CPlusPlus)
1899
0
      return false;
1900
2.09k
    // The unprivileged access is AS_none as we don't know how the member was
1901
2.09k
    // accessed, which is described by the access in DeclAccessPair.
1902
2.09k
    // `IsAccessible` will examine the actual access of Target (i.e.
1903
2.09k
    // Decl->getAccess()) when calculating the access.
1904
2.09k
    AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
1905
2.09k
                        DeclAccessPair::make(Target, AS_none), BaseType);
1906
2.09k
    EffectiveContext EC(CurContext);
1907
2.09k
    return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1908
2.09k
  }
1909
14.5k
1910
14.5k
  if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
1911
76
    // @public and @package ivars are always accessible.
1912
76
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1913
76
        
Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package66
)
1914
10
      return true;
1915
66
1916
66
    // If we are inside a class or category implementation, determine the
1917
66
    // interface we're in.
1918
66
    ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1919
66
    if (ObjCMethodDecl *MD = getCurMethodDecl())
1920
56
      ClassOfMethodDecl =  MD->getClassInterface();
1921
10
    else if (FunctionDecl *FD = getCurFunctionDecl()) {
1922
10
      if (ObjCImplDecl *Impl
1923
0
            = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1924
0
        if (ObjCImplementationDecl *IMPD
1925
0
              = dyn_cast<ObjCImplementationDecl>(Impl))
1926
0
          ClassOfMethodDecl = IMPD->getClassInterface();
1927
0
        else if (ObjCCategoryImplDecl* CatImplClass
1928
0
                   = dyn_cast<ObjCCategoryImplDecl>(Impl))
1929
0
          ClassOfMethodDecl = CatImplClass->getClassInterface();
1930
0
      }
1931
10
    }
1932
66
1933
66
    // If we're not in an interface, this ivar is inaccessible.
1934
66
    if (!ClassOfMethodDecl)
1935
10
      return false;
1936
56
1937
56
    // If we're inside the same interface that owns the ivar, we're fine.
1938
56
    if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
1939
50
      return true;
1940
6
1941
6
    // If the ivar is private, it's inaccessible.
1942
6
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1943
3
      return false;
1944
3
1945
3
    return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1946
3
  }
1947
14.4k
1948
14.4k
  return true;
1949
14.4k
}