Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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
81.9k
                                    AccessSpecifier LexicalAS) {
42
81.9k
  if (!PrevMemberDecl) {
43
80.0k
    // Use the lexical access specifier.
44
80.0k
    MemberDecl->setAccess(LexicalAS);
45
80.0k
    return false;
46
80.0k
  }
47
1.92k
48
1.92k
  // C++ [class.access.spec]p3: When a member is redeclared its access
49
1.92k
  // specifier must be same as its initial declaration.
50
1.92k
  if (LexicalAS != AS_none && 
LexicalAS != PrevMemberDecl->getAccess()110
) {
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.92k
61
1.92k
  MemberDecl->setAccess(PrevMemberDecl->getAccess());
62
1.92k
  return false;
63
1.92k
}
64
65
2.48M
static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66
2.48M
  DeclContext *DC = D->getDeclContext();
67
2.48M
68
2.48M
  // This can only happen at top: enum decls only "publish" their
69
2.48M
  // immediate members.
70
2.48M
  if (isa<EnumDecl>(DC))
71
35.1k
    DC = cast<EnumDecl>(DC)->getDeclContext();
72
2.48M
73
2.48M
  CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74
2.48M
  while (DeclaringClass->isAnonymousStructOrUnion())
75
0
    DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76
2.48M
  return DeclaringClass;
77
2.48M
}
78
79
namespace {
80
struct EffectiveContext {
81
15
  EffectiveContext() : Inner(nullptr), Dependent(false) {}
82
83
  explicit EffectiveContext(DeclContext *DC)
84
    : Inner(DC),
85
1.99M
      Dependent(DC->isDependentContext()) {
86
1.99M
87
1.99M
    // C++11 [class.access.nest]p1:
88
1.99M
    //   A nested class is a member and as such has the same access
89
1.99M
    //   rights as any other member.
90
1.99M
    // C++11 [class.access]p2:
91
1.99M
    //   A member of a class can also access all the names to which
92
1.99M
    //   the class has access.  A local class of a member function
93
1.99M
    //   may access the same names that the member function itself
94
1.99M
    //   may access.
95
1.99M
    // This almost implies that the privileges of nesting are transitive.
96
1.99M
    // Technically it says nothing about the local classes of non-member
97
1.99M
    // functions (which can gain privileges through friendship), but we
98
1.99M
    // take that as an oversight.
99
5.81M
    while (true) {
100
5.81M
      // We want to add canonical declarations to the EC lists for
101
5.81M
      // simplicity of checking, but we need to walk up through the
102
5.81M
      // actual current DC chain.  Otherwise, something like a local
103
5.81M
      // extern or friend which happens to be the canonical
104
5.81M
      // declaration will really mess us up.
105
5.81M
106
5.81M
      if (isa<CXXRecordDecl>(DC)) {
107
2.07M
        CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
108
2.07M
        Records.push_back(Record->getCanonicalDecl());
109
2.07M
        DC = Record->getDeclContext();
110
3.74M
      } else if (isa<FunctionDecl>(DC)) {
111
1.74M
        FunctionDecl *Function = cast<FunctionDecl>(DC);
112
1.74M
        Functions.push_back(Function->getCanonicalDecl());
113
1.74M
        if (Function->getFriendObjectKind())
114
3.97k
          DC = Function->getLexicalDeclContext();
115
1.73M
        else
116
1.73M
          DC = Function->getDeclContext();
117
1.99M
      } else if (DC->isFileContext()) {
118
1.99M
        break;
119
1.99M
      } else {
120
7.16k
        DC = DC->getParent();
121
7.16k
      }
122
5.81M
    }
123
1.99M
  }
124
125
156k
  bool isDependent() const { return Dependent; }
126
127
34.7k
  bool includesClass(const CXXRecordDecl *R) const {
128
34.7k
    R = R->getCanonicalDecl();
129
34.7k
    return llvm::find(Records, R) != Records.end();
130
34.7k
  }
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
523k
    : AccessedEntity(Entity) {
151
523k
    initialize();
152
523k
  }
153
154
  AccessTarget(ASTContext &Context,
155
               MemberNonce _,
156
               CXXRecordDecl *NamingClass,
157
               DeclAccessPair FoundDecl,
158
               QualType BaseObjectType)
159
    : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
160
1.95M
                     FoundDecl, BaseObjectType) {
161
1.95M
    initialize();
162
1.95M
  }
163
164
  AccessTarget(ASTContext &Context,
165
               BaseNonce _,
166
               CXXRecordDecl *BaseClass,
167
               CXXRecordDecl *DerivedClass,
168
               AccessSpecifier Access)
169
    : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
170
42.2k
                     Access) {
171
42.2k
    initialize();
172
42.2k
  }
173
174
174k
  bool isInstanceMember() const {
175
174k
    return (isMemberAccess() && 
getTargetDecl()->isCXXInstanceMember()174k
);
176
174k
  }
177
178
332k
  bool hasInstanceContext() const {
179
332k
    return HasInstanceContext;
180
332k
  }
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
105k
    ~SavedInstanceContext() {
189
105k
      if (Target)
190
105k
        Target->HasInstanceContext = Has;
191
105k
    }
192
193
  private:
194
    friend struct AccessTarget;
195
    explicit SavedInstanceContext(AccessTarget &Target)
196
105k
        : Target(&Target), Has(Target.HasInstanceContext) {}
197
    AccessTarget *Target;
198
    bool Has;
199
  };
200
201
105k
  SavedInstanceContext saveInstanceContext() {
202
105k
    return SavedInstanceContext(*this);
203
105k
  }
204
205
92.4k
  void suppressInstanceContext() {
206
92.4k
    HasInstanceContext = false;
207
92.4k
  }
208
209
161k
  const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
210
161k
    assert(HasInstanceContext);
211
161k
    if (CalculatedInstanceContext)
212
450
      return InstanceContext;
213
161k
214
161k
    CalculatedInstanceContext = true;
215
161k
    DeclContext *IC = S.computeDeclContext(getBaseObjectType());
216
161k
    InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
217
161k
                          : 
nullptr0
);
218
161k
    return InstanceContext;
219
161k
  }
220
221
108k
  const CXXRecordDecl *getDeclaringClass() const {
222
108k
    return DeclaringClass;
223
108k
  }
224
225
  /// The "effective" naming class is the canonical non-anonymous
226
  /// class containing the actual naming class.
227
1.99M
  const CXXRecordDecl *getEffectiveNamingClass() const {
228
1.99M
    const CXXRecordDecl *namingClass = getNamingClass();
229
1.99M
    while (namingClass->isAnonymousStructOrUnion())
230
0
      namingClass = cast<CXXRecordDecl>(namingClass->getParent());
231
1.99M
    return namingClass->getCanonicalDecl();
232
1.99M
  }
233
234
private:
235
2.52M
  void initialize() {
236
2.52M
    HasInstanceContext = (isMemberAccess() &&
237
2.52M
                          
!getBaseObjectType().isNull()2.47M
&&
238
2.52M
                          
getTargetDecl()->isCXXInstanceMember()1.39M
);
239
2.52M
    CalculatedInstanceContext = false;
240
2.52M
    InstanceContext = nullptr;
241
2.52M
242
2.52M
    if (isMemberAccess())
243
2.47M
      DeclaringClass = FindDeclaringClass(getTargetDecl());
244
42.2k
    else
245
42.2k
      DeclaringClass = getBaseClass();
246
2.52M
    DeclaringClass = DeclaringClass->getCanonicalDecl();
247
2.52M
  }
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
16.1k
                               const CXXRecordDecl *To) {
260
16.1k
  // Declaration names are always preserved by instantiation.
261
16.1k
  if (From->getDeclName() != To->getDeclName())
262
16.0k
    return false;
263
32
264
32
  const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
265
32
  const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
266
32
  if (FromDC == ToDC) 
return true24
;
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
496k
                                           const CXXRecordDecl *Target) {
280
496k
  assert(Derived->getCanonicalDecl() == Derived);
281
496k
  assert(Target->getCanonicalDecl() == Target);
282
496k
283
496k
  if (Derived == Target) 
return AR_accessible410k
;
284
85.2k
285
85.2k
  bool CheckDependent = Derived->isDependentContext();
286
85.2k
  if (CheckDependent && 
MightInstantiateTo(Derived, Target)3.88k
)
287
12
    return AR_dependent;
288
85.2k
289
85.2k
  AccessResult OnFailure = AR_inaccessible;
290
85.2k
  SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
291
85.2k
292
85.8k
  while (true) {
293
85.8k
    if (Derived->isDependentContext() && 
!Derived->hasDefinition()3.87k
&&
294
85.8k
        
!Derived->isLambda()1
)
295
1
      return AR_dependent;
296
85.8k
297
85.8k
    for (const auto &I : Derived->bases()) {
298
83.5k
      const CXXRecordDecl *RD;
299
83.5k
300
83.5k
      QualType T = I.getType();
301
83.5k
      if (const RecordType *RT = T->getAs<RecordType>()) {
302
83.5k
        RD = cast<CXXRecordDecl>(RT->getDecl());
303
83.5k
      } 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
83.5k
312
83.5k
      RD = RD->getCanonicalDecl();
313
83.5k
      if (RD == Target) 
return AR_accessible82.0k
;
314
1.46k
      if (CheckDependent && 
MightInstantiateTo(RD, Target)425
)
315
0
        OnFailure = AR_dependent;
316
1.46k
317
1.46k
      Queue.push_back(RD);
318
1.46k
    }
319
85.8k
320
85.8k
    
if (3.80k
Queue.empty()3.80k
)
break3.12k
;
321
685
322
685
    Derived = Queue.pop_back_val();
323
685
  }
324
85.2k
325
85.2k
  
return OnFailure3.12k
;
326
85.2k
}
327
328
329
static bool MightInstantiateTo(Sema &S, DeclContext *Context,
330
83
                               DeclContext *Friend) {
331
83
  if (Friend == Context)
332
71
    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
184
static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
350
184
  if (Friend == Context)
351
110
    return true;
352
74
353
74
  if (!Friend->isDependentType() && !Context->isDependentType())
354
0
    return false;
355
74
356
74
  // TODO: this is very conservative.
357
74
  return true;
358
74
}
359
360
static bool MightInstantiateTo(Sema &S,
361
                               FunctionDecl *Context,
362
445
                               FunctionDecl *Friend) {
363
445
  if (Context->getDeclName() != Friend->getDeclName())
364
365
    return false;
365
80
366
80
  if (!MightInstantiateTo(S,
367
80
                          Context->getDeclContext(),
368
80
                          Friend->getDeclContext()))
369
7
    return false;
370
73
371
73
  CanQual<FunctionProtoType> FriendTy
372
73
    = S.Context.getCanonicalType(Friend->getType())
373
73
         ->getAs<FunctionProtoType>();
374
73
  CanQual<FunctionProtoType> ContextTy
375
73
    = S.Context.getCanonicalType(Context->getType())
376
73
         ->getAs<FunctionProtoType>();
377
73
378
73
  // There isn't any way that I know of to add qualifiers
379
73
  // during instantiation.
380
73
  if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
381
0
    return false;
382
73
383
73
  if (FriendTy->getNumParams() != ContextTy->getNumParams())
384
0
    return false;
385
73
386
73
  if (!MightInstantiateTo(S, ContextTy->getReturnType(),
387
73
                          FriendTy->getReturnType()))
388
0
    return false;
389
73
390
184
  
for (unsigned I = 0, E = FriendTy->getNumParams(); 73
I != E;
++I111
)
391
111
    if (!MightInstantiateTo(S, ContextTy->getParamType(I),
392
111
                            FriendTy->getParamType(I)))
393
0
      return false;
394
73
395
73
  return true;
396
73
}
397
398
static bool MightInstantiateTo(Sema &S,
399
                               FunctionTemplateDecl *Context,
400
272
                               FunctionTemplateDecl *Friend) {
401
272
  return MightInstantiateTo(S,
402
272
                            Context->getTemplatedDecl(),
403
272
                            Friend->getTemplatedDecl());
404
272
}
405
406
static AccessResult MatchesFriend(Sema &S,
407
                                  const EffectiveContext &EC,
408
34.7k
                                  const CXXRecordDecl *Friend) {
409
34.7k
  if (EC.includesClass(Friend))
410
25.4k
    return AR_accessible;
411
9.25k
412
9.25k
  if (EC.isDependent()) {
413
46
    for (const CXXRecordDecl *Context : EC.Records) {
414
29
      if (MightInstantiateTo(Context, Friend))
415
10
        return AR_dependent;
416
29
    }
417
46
  }
418
9.25k
419
9.25k
  
return AR_inaccessible9.24k
;
420
9.25k
}
421
422
static AccessResult MatchesFriend(Sema &S,
423
                                  const EffectiveContext &EC,
424
34.7k
                                  CanQualType Friend) {
425
34.7k
  if (const RecordType *RT = Friend->getAs<RecordType>())
426
34.7k
    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
15.4k
                                  ClassTemplateDecl *Friend) {
440
15.4k
  AccessResult OnFailure = AR_inaccessible;
441
15.4k
442
15.4k
  // Check whether the friend is the template of a class in the
443
15.4k
  // context chain.
444
15.4k
  for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
445
23.5k
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I8.16k
) {
446
15.3k
    CXXRecordDecl *Record = *I;
447
15.3k
448
15.3k
    // Figure out whether the current class has a template:
449
15.3k
    ClassTemplateDecl *CTD;
450
15.3k
451
15.3k
    // A specialization of the template...
452
15.3k
    if (isa<ClassTemplateSpecializationDecl>(Record)) {
453
10.5k
      CTD = cast<ClassTemplateSpecializationDecl>(Record)
454
10.5k
        ->getSpecializedTemplate();
455
10.5k
456
10.5k
    // ... or the template pattern itself.
457
10.5k
    } else {
458
4.86k
      CTD = Record->getDescribedClassTemplate();
459
4.86k
      if (!CTD) 
continue24
;
460
15.3k
    }
461
15.3k
462
15.3k
    // It's a match.
463
15.3k
    if (Friend == CTD->getCanonicalDecl())
464
7.22k
      return AR_accessible;
465
8.13k
466
8.13k
    // If the context isn't dependent, it can't be a dependent match.
467
8.13k
    if (!EC.isDependent())
468
8.11k
      continue;
469
25
470
25
    // If the template names don't match, it can't be a dependent
471
25
    // match.
472
25
    if (CTD->getDeclName() != Friend->getDeclName())
473
22
      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
15.4k
485
15.4k
  
return OnFailure8.18k
;
486
15.4k
}
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
6.01k
                                  FunctionDecl *Friend) {
493
6.01k
  AccessResult OnFailure = AR_inaccessible;
494
6.01k
495
6.01k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
496
10.3k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I4.29k
) {
497
6.00k
    if (Friend == *I)
498
1.71k
      return AR_accessible;
499
4.29k
500
4.29k
    if (EC.isDependent() && 
MightInstantiateTo(S, *I, Friend)173
)
501
73
      OnFailure = AR_dependent;
502
4.29k
  }
503
6.01k
504
6.01k
  
return OnFailure4.30k
;
505
6.01k
}
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
33.4k
                                  FunctionTemplateDecl *Friend) {
512
33.4k
  if (EC.Functions.empty()) 
return AR_inaccessible46
;
513
33.3k
514
33.3k
  AccessResult OnFailure = AR_inaccessible;
515
33.3k
516
33.3k
  for (SmallVectorImpl<FunctionDecl*>::const_iterator
517
63.2k
         I = EC.Functions.begin(), E = EC.Functions.end(); I != E; 
++I29.8k
) {
518
33.3k
519
33.3k
    FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
520
33.3k
    if (!FTD)
521
16.8k
      FTD = (*I)->getDescribedFunctionTemplate();
522
33.3k
    if (!FTD)
523
15.6k
      continue;
524
17.6k
525
17.6k
    FTD = FTD->getCanonicalDecl();
526
17.6k
527
17.6k
    if (Friend == FTD)
528
3.47k
      return AR_accessible;
529
14.2k
530
14.2k
    if (EC.isDependent() && 
MightInstantiateTo(S, FTD, Friend)272
)
531
0
      OnFailure = AR_dependent;
532
14.2k
  }
533
33.3k
534
33.3k
  
return OnFailure29.8k
;
535
33.3k
}
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
89.5k
                                  FriendDecl *FriendD) {
542
89.5k
  // Whitelist accesses if there's an invalid or unsupported friend
543
89.5k
  // declaration.
544
89.5k
  if (FriendD->isInvalidDecl() || 
FriendD->isUnsupportedFriend()89.5k
)
545
37
    return AR_accessible;
546
89.5k
547
89.5k
  if (TypeSourceInfo *T = FriendD->getFriendType())
548
34.7k
    return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
549
54.8k
550
54.8k
  NamedDecl *Friend
551
54.8k
    = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
552
54.8k
553
54.8k
  // FIXME: declarations with dependent or templated scope.
554
54.8k
555
54.8k
  if (isa<ClassTemplateDecl>(Friend))
556
15.4k
    return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
557
39.4k
558
39.4k
  if (isa<FunctionTemplateDecl>(Friend))
559
33.4k
    return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
560
6.01k
561
6.01k
  if (isa<CXXRecordDecl>(Friend))
562
0
    return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
563
6.01k
564
6.01k
  assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
565
6.01k
  return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
566
6.01k
}
567
568
static AccessResult GetFriendKind(Sema &S,
569
                                  const EffectiveContext &EC,
570
128k
                                  const CXXRecordDecl *Class) {
571
128k
  AccessResult OnFailure = AR_inaccessible;
572
128k
573
128k
  // Okay, check friends.
574
128k
  for (auto *Friend : Class->friends()) {
575
89.5k
    switch (MatchesFriend(S, EC, Friend)) {
576
89.5k
    case AR_accessible:
577
37.9k
      return AR_accessible;
578
89.5k
579
89.5k
    case AR_inaccessible:
580
51.5k
      continue;
581
89.5k
582
89.5k
    case AR_dependent:
583
83
      OnFailure = AR_dependent;
584
83
      break;
585
89.5k
    }
586
89.5k
  }
587
128k
588
128k
  // That's it, give up.
589
128k
  
return OnFailure90.2k
;
590
128k
}
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
585
      EverDependent(false) {}
613
614
  /// Check classes in the current path for friendship, starting at
615
  /// the given index.
616
567
  bool checkFriendshipAlongPath(unsigned I) {
617
567
    assert(I < CurPath.size());
618
1.10k
    for (unsigned E = CurPath.size(); I != E; 
++I539
) {
619
686
      switch (GetFriendKind(S, EC, CurPath[I])) {
620
686
      
case AR_accessible: return true147
;
621
686
      
case AR_inaccessible: continue539
;
622
686
      
case AR_dependent: EverDependent = true; continue0
;
623
686
      }
624
686
    }
625
567
    
return false420
;
626
567
  }
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
736
  bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
634
736
    // If we ever reach the naming class, check the current path for
635
736
    // friendship.  We can also stop recursing because we obviously
636
736
    // won't find the naming class there again.
637
736
    if (Cur == NamingClass)
638
567
      return checkFriendshipAlongPath(PrivateDepth);
639
169
640
169
    if (CheckDependent && 
MightInstantiateTo(Cur, NamingClass)0
)
641
0
      EverDependent = true;
642
169
643
169
    // Recurse into the base classes.
644
169
    for (const auto &I : Cur->bases()) {
645
151
      // If this is private inheritance, then a public member of the
646
151
      // base will not have any access in classes derived from Cur.
647
151
      unsigned BasePrivateDepth = PrivateDepth;
648
151
      if (I.getAccessSpecifier() == AS_private)
649
33
        BasePrivateDepth = CurPath.size() - 1;
650
151
651
151
      const CXXRecordDecl *RD;
652
151
653
151
      QualType T = I.getType();
654
151
      if (const RecordType *RT = T->getAs<RecordType>()) {
655
151
        RD = cast<CXXRecordDecl>(RT->getDecl());
656
151
      } 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
151
665
151
      // Recurse.  We don't need to clean up if this returns true.
666
151
      CurPath.push_back(RD);
667
151
      if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
668
53
        return true;
669
98
      CurPath.pop_back();
670
98
    }
671
169
672
169
    
return false116
;
673
169
  }
674
675
585
  bool findFriendship(const CXXRecordDecl *Cur) {
676
585
    assert(CurPath.empty());
677
585
    CurPath.push_back(Cur);
678
585
    return findFriendship(Cur, 0);
679
585
  }
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
776
                                           const CXXRecordDecl *NamingClass) {
712
776
  assert(InstanceContext == nullptr ||
713
776
         InstanceContext->getCanonicalDecl() == InstanceContext);
714
776
  assert(NamingClass->getCanonicalDecl() == NamingClass);
715
776
716
776
  // If we don't have an instance context, our constraints give us
717
776
  // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
718
776
  // This is just the usual friendship check.
719
776
  if (!InstanceContext) 
return GetFriendKind(S, EC, NamingClass)191
;
720
585
721
585
  ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
722
585
  if (PRC.findFriendship(InstanceContext)) 
return AR_accessible147
;
723
438
  if (PRC.EverDependent) 
return AR_dependent0
;
724
438
  return AR_inaccessible;
725
438
}
726
727
static AccessResult HasAccess(Sema &S,
728
                              const EffectiveContext &EC,
729
                              const CXXRecordDecl *NamingClass,
730
                              AccessSpecifier Access,
731
2.08M
                              const AccessTarget &Target) {
732
2.08M
  assert(NamingClass->getCanonicalDecl() == NamingClass &&
733
2.08M
         "declaration should be canonicalized before being passed here");
734
2.08M
735
2.08M
  if (Access == AS_public) 
return AR_accessible81.3k
;
736
1.99M
  assert(Access == AS_private || Access == AS_protected);
737
1.99M
738
1.99M
  AccessResult OnFailure = AR_inaccessible;
739
1.99M
740
1.99M
  for (EffectiveContext::record_iterator
741
2.12M
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I124k
) {
742
1.99M
    // All the declarations in EC have been canonicalized, so pointer
743
1.99M
    // equality from this point on will work fine.
744
1.99M
    const CXXRecordDecl *ECRecord = *I;
745
1.99M
746
1.99M
    // [B2] and [M2]
747
1.99M
    if (Access == AS_private) {
748
1.66M
      if (ECRecord == NamingClass)
749
1.54M
        return AR_accessible;
750
121k
751
121k
      if (EC.isDependent() && 
MightInstantiateTo(ECRecord, NamingClass)11.7k
)
752
10
        OnFailure = AR_dependent;
753
121k
754
121k
    // [B3] and [M3]
755
334k
    } else {
756
334k
      assert(Access == AS_protected);
757
334k
      switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
758
334k
      
case AR_accessible: break331k
;
759
334k
      
case AR_inaccessible: continue2.96k
;
760
334k
      
case AR_dependent: OnFailure = AR_dependent; continue19
;
761
331k
      }
762
331k
763
331k
      // C++ [class.protected]p1:
764
331k
      //   An additional access check beyond those described earlier in
765
331k
      //   [class.access] is applied when a non-static data member or
766
331k
      //   non-static member function is a protected member of its naming
767
331k
      //   class.  As described earlier, access to a protected member is
768
331k
      //   granted because the reference occurs in a friend or member of
769
331k
      //   some class C.  If the access is to form a pointer to member,
770
331k
      //   the nested-name-specifier shall name C or a class derived from
771
331k
      //   C. All other accesses involve a (possibly implicit) object
772
331k
      //   expression. In this case, the class of the object expression
773
331k
      //   shall be C or a class derived from C.
774
331k
      //
775
331k
      // We interpret this as a restriction on [M3].
776
331k
777
331k
      // In this part of the code, 'C' is just our context class ECRecord.
778
331k
779
331k
      // These rules are different if we don't have an instance context.
780
331k
      if (!Target.hasInstanceContext()) {
781
170k
        // If it's not an instance member, these restrictions don't apply.
782
170k
        if (!Target.isInstanceMember()) 
return AR_accessible170k
;
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
161k
817
161k
      assert(Target.isInstanceMember());
818
161k
819
161k
      const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
820
161k
      if (!InstanceContext) {
821
0
        OnFailure = AR_dependent;
822
0
        continue;
823
0
      }
824
161k
825
161k
      switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
826
161k
      
case AR_accessible: return AR_accessible161k
;
827
161k
      
case AR_inaccessible: continue104
;
828
161k
      
case AR_dependent: OnFailure = AR_dependent; continue0
;
829
161k
      }
830
161k
    }
831
1.99M
  }
832
1.99M
833
1.99M
  // [M3] and [B3] say that, if the target is protected in N, we grant
834
1.99M
  // access if the access occurs in a friend or member of some class P
835
1.99M
  // that's a subclass of N and where the target has some natural
836
1.99M
  // access in P.  The 'member' aspect is easy to handle because P
837
1.99M
  // would necessarily be one of the effective-context records, and we
838
1.99M
  // address that above.  The 'friend' aspect is completely ridiculous
839
1.99M
  // to implement because there are no restrictions at all on P
840
1.99M
  // *unless* the [class.protected] restriction applies.  If it does,
841
1.99M
  // however, we should ignore whether the naming class is a friend,
842
1.99M
  // and instead rely on whether any potential P is a friend.
843
1.99M
  
if (128k
Access == AS_protected128k
&&
Target.isInstanceMember()3.73k
) {
844
776
    // Compute the instance context if possible.
845
776
    const CXXRecordDecl *InstanceContext = nullptr;
846
776
    if (Target.hasInstanceContext()) {
847
585
      InstanceContext = Target.resolveInstanceContext(S);
848
585
      if (!InstanceContext) 
return AR_dependent0
;
849
776
    }
850
776
851
776
    switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
852
776
    
case AR_accessible: return AR_accessible150
;
853
776
    
case AR_inaccessible: return OnFailure626
;
854
776
    
case AR_dependent: return AR_dependent0
;
855
0
    }
856
0
    llvm_unreachable("impossible friendship kind");
857
0
  }
858
127k
859
127k
  switch (GetFriendKind(S, EC, NamingClass)) {
860
127k
  
case AR_accessible: return AR_accessible37.7k
;
861
127k
  
case AR_inaccessible: return OnFailure89.4k
;
862
127k
  
case AR_dependent: return AR_dependent45
;
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
11.1k
                                 CXXBasePaths &Paths) {
930
11.1k
  // Derive the paths to the desired base.
931
11.1k
  const CXXRecordDecl *Derived = Target.getNamingClass();
932
11.1k
  const CXXRecordDecl *Base = Target.getDeclaringClass();
933
11.1k
934
11.1k
  // FIXME: fail correctly when there are dependent paths.
935
11.1k
  bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
936
11.1k
                                          Paths);
937
11.1k
  assert(isDerived && "derived class not actually derived from base");
938
11.1k
  (void) isDerived;
939
11.1k
940
11.1k
  CXXBasePath *BestPath = nullptr;
941
11.1k
942
11.1k
  assert(FinalAccess != AS_none && "forbidden access after declaring class");
943
11.1k
944
11.1k
  bool AnyDependent = false;
945
11.1k
946
11.1k
  // Derive the friend-modified access along each path.
947
11.1k
  for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
948
11.9k
         PI != PE; 
++PI784
) {
949
11.1k
    AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
950
11.1k
951
11.1k
    // Walk through the path backwards.
952
11.1k
    AccessSpecifier PathAccess = FinalAccess;
953
11.1k
    CXXBasePath::iterator I = PI->end(), E = PI->begin();
954
22.4k
    while (I != E) {
955
11.5k
      --I;
956
11.5k
957
11.5k
      assert(PathAccess != AS_none);
958
11.5k
959
11.5k
      // If the declaration is a private member of a base class, there
960
11.5k
      // is no level of friendship in derived classes that can make it
961
11.5k
      // accessible.
962
11.5k
      if (PathAccess == AS_private) {
963
268
        PathAccess = AS_none;
964
268
        break;
965
268
      }
966
11.2k
967
11.2k
      const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
968
11.2k
969
11.2k
      AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
970
11.2k
      PathAccess = std::max(PathAccess, BaseAccess);
971
11.2k
972
11.2k
      switch (HasAccess(S, EC, NC, PathAccess, Target)) {
973
11.2k
      
case AR_inaccessible: break739
;
974
11.2k
      case AR_accessible:
975
10.5k
        PathAccess = AS_public;
976
10.5k
977
10.5k
        // Future tests are not against members and so do not have
978
10.5k
        // instance context.
979
10.5k
        Target.suppressInstanceContext();
980
10.5k
        break;
981
11.2k
      case AR_dependent:
982
0
        AnyDependent = true;
983
0
        goto Next;
984
11.2k
      }
985
11.2k
    }
986
11.1k
987
11.1k
    // Note that we modify the path's Access field to the
988
11.1k
    // friend-modified access.
989
11.1k
    if (BestPath == nullptr || 
PathAccess < BestPath->Access6
) {
990
11.1k
      BestPath = &*PI;
991
11.1k
      BestPath->Access = PathAccess;
992
11.1k
993
11.1k
      // Short-circuit if we found a public path.
994
11.1k
      if (BestPath->Access == AS_public)
995
10.3k
        return BestPath;
996
784
    }
997
784
998
784
  Next: ;
999
784
  }
1000
11.1k
1001
11.1k
  assert((!BestPath || BestPath->Access != AS_public) &&
1002
778
         "fell out of loop with public path");
1003
778
1004
778
  // We didn't find a public path, but at least one path was subject
1005
778
  // to dependent friendship, so delay the check.
1006
778
  if (AnyDependent)
1007
0
    return nullptr;
1008
778
1009
778
  return BestPath;
1010
778
}
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
164
                                       AccessTarget &Target) {
1019
164
  // Only applies to instance accesses.
1020
164
  if (!Target.isInstanceMember())
1021
50
    return false;
1022
114
1023
114
  assert(Target.isMemberAccess());
1024
114
1025
114
  const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
1026
114
1027
114
  for (EffectiveContext::record_iterator
1028
141
         I = EC.Records.begin(), E = EC.Records.end(); I != E; 
++I27
) {
1029
59
    const CXXRecordDecl *ECRecord = *I;
1030
59
    switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
1031
59
    
case AR_accessible: break32
;
1032
59
    
case AR_inaccessible: continue27
;
1033
59
    
case AR_dependent: continue0
;
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
20
    
case AR_accessible: continue0
;
1064
20
    
case AR_dependent: continue0
;
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
114
1087
114
  
return false82
;
1088
114
}
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
2.48k
                                    AccessTarget &entity) {
1095
2.48k
  assert(entity.isMemberAccess());
1096
2.48k
  NamedDecl *D = entity.getTargetDecl();
1097
2.48k
1098
2.48k
  if (D->getAccess() == AS_protected &&
1099
2.48k
      
TryDiagnoseProtectedAccess(S, EC, entity)164
)
1100
32
    return;
1101
2.45k
1102
2.45k
  // Find an original declaration.
1103
2.47k
  
while (2.45k
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
2.45k
1120
2.45k
  CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1121
2.45k
  Decl *ImmediateChild;
1122
2.45k
  if (D->getDeclContext() == DeclaringClass)
1123
2.45k
    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
2.45k
1131
2.45k
  // Check whether there's an AccessSpecDecl preceding this in the
1132
2.45k
  // chain of the DeclContext.
1133
2.45k
  bool isImplicit = true;
1134
7.21k
  for (const auto *I : DeclaringClass->decls()) {
1135
7.21k
    if (I == ImmediateChild) 
break2.05k
;
1136
5.15k
    if (isa<AccessSpecDecl>(I)) {
1137
396
      isImplicit = false;
1138
396
      break;
1139
396
    }
1140
5.15k
  }
1141
2.45k
1142
2.45k
  S.Diag(D->getLocation(), diag::note_access_natural)
1143
2.45k
    << (unsigned) (D->getAccess() == AS_protected)
1144
2.45k
    << isImplicit;
1145
2.45k
}
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
2.76k
                               AccessTarget &entity) {
1152
2.76k
  // Save the instance context to preserve invariants.
1153
2.76k
  AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
1154
2.76k
1155
2.76k
  // This basically repeats the main algorithm but keeps some more
1156
2.76k
  // information.
1157
2.76k
1158
2.76k
  // The natural access so far.
1159
2.76k
  AccessSpecifier accessSoFar = AS_public;
1160
2.76k
1161
2.76k
  // Check whether we have special rights to the declaring class.
1162
2.76k
  if (entity.isMemberAccess()) {
1163
2.60k
    NamedDecl *D = entity.getTargetDecl();
1164
2.60k
    accessSoFar = D->getAccess();
1165
2.60k
    const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
1166
2.60k
1167
2.60k
    switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1168
2.60k
    // If the declaration is accessible when named in its declaring
1169
2.60k
    // class, then we must be constrained by the path.
1170
2.60k
    case AR_accessible:
1171
116
      accessSoFar = AS_public;
1172
116
      entity.suppressInstanceContext();
1173
116
      break;
1174
2.60k
1175
2.60k
    case AR_inaccessible:
1176
2.49k
      if (accessSoFar == AS_private ||
1177
2.49k
          
declaringClass == entity.getEffectiveNamingClass()169
)
1178
2.44k
        return diagnoseBadDirectAccess(S, EC, entity);
1179
47
      break;
1180
47
1181
47
    case AR_dependent:
1182
0
      llvm_unreachable("cannot diagnose dependent access");
1183
324
    }
1184
324
  }
1185
324
1186
324
  CXXBasePaths paths;
1187
324
  CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1188
324
  assert(path.Access != AS_public);
1189
324
1190
324
  CXXBasePath::iterator i = path.end(), e = path.begin();
1191
324
  CXXBasePath::iterator constrainingBase = i;
1192
447
  while (i != e) {
1193
351
    --i;
1194
351
1195
351
    assert(accessSoFar != AS_none && accessSoFar != AS_private);
1196
351
1197
351
    // Is the entity accessible when named in the deriving class, as
1198
351
    // modified by the base specifier?
1199
351
    const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1200
351
    const CXXBaseSpecifier *base = i->Base;
1201
351
1202
351
    // If the access to this base is worse than the access we have to
1203
351
    // the declaration, remember it.
1204
351
    AccessSpecifier baseAccess = base->getAccessSpecifier();
1205
351
    if (baseAccess > accessSoFar) {
1206
282
      constrainingBase = i;
1207
282
      accessSoFar = baseAccess;
1208
282
    }
1209
351
1210
351
    switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
1211
351
    
case AR_inaccessible: break332
;
1212
351
    case AR_accessible:
1213
19
      accessSoFar = AS_public;
1214
19
      entity.suppressInstanceContext();
1215
19
      constrainingBase = nullptr;
1216
19
      break;
1217
351
    case AR_dependent:
1218
0
      llvm_unreachable("cannot diagnose dependent access");
1219
351
    }
1220
351
1221
351
    // If this was private inheritance, but we don't have access to
1222
351
    // the deriving class, we're done.
1223
351
    if (accessSoFar == AS_private) {
1224
228
      assert(baseAccess == AS_private);
1225
228
      assert(constrainingBase == i);
1226
228
      break;
1227
228
    }
1228
351
  }
1229
324
1230
324
  // If we don't have a constraining base, the access failure must be
1231
324
  // due to the original declaration.
1232
324
  if (constrainingBase == path.end())
1233
42
    return diagnoseBadDirectAccess(S, EC, entity);
1234
282
1235
282
  // We're constrained by inheritance, but we want to say
1236
282
  // "declared private here" if we're diagnosing a hierarchy
1237
282
  // conversion and this is the final step.
1238
282
  unsigned diagnostic;
1239
282
  if (entity.isMemberAccess() ||
1240
282
      
constrainingBase + 1 != path.end()161
) {
1241
129
    diagnostic = diag::note_access_constrained_by_path;
1242
153
  } else {
1243
153
    diagnostic = diag::note_access_natural;
1244
153
  }
1245
282
1246
282
  const CXXBaseSpecifier *base = constrainingBase->Base;
1247
282
1248
282
  S.Diag(base->getSourceRange().getBegin(), diagnostic)
1249
282
    << base->getSourceRange()
1250
282
    << (base->getAccessSpecifier() == AS_protected)
1251
282
    << (base->getAccessSpecifierAsWritten() == AS_none);
1252
282
1253
282
  if (entity.isMemberAccess())
1254
121
    S.Diag(entity.getTargetDecl()->getLocation(),
1255
121
           diag::note_member_declared_at);
1256
282
}
1257
1258
static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
1259
                              const EffectiveContext &EC,
1260
2.76k
                              AccessTarget &Entity) {
1261
2.76k
  const CXXRecordDecl *NamingClass = Entity.getNamingClass();
1262
2.76k
  const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1263
2.76k
  NamedDecl *D = (Entity.isMemberAccess() ? 
Entity.getTargetDecl()2.60k
:
nullptr161
);
1264
2.76k
1265
2.76k
  S.Diag(Loc, Entity.getDiag())
1266
2.76k
    << (Entity.getAccess() == AS_protected)
1267
2.76k
    << (D ? 
D->getDeclName()2.60k
:
DeclarationName()161
)
1268
2.76k
    << S.Context.getTypeDeclType(NamingClass)
1269
2.76k
    << S.Context.getTypeDeclType(DeclaringClass);
1270
2.76k
  DiagnoseAccessPath(S, EC, Entity);
1271
2.76k
}
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
13
                                                 AccessTarget &Entity) {
1296
13
  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
11
  }
1308
11
  return false;
1309
11
}
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
1.99M
                                 AccessTarget &Entity) {
1316
1.99M
  // Determine the actual naming class.
1317
1.99M
  const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
1318
1.99M
1319
1.99M
  AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1320
1.99M
  assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1321
1.99M
1322
1.99M
  // Before we try to recalculate access paths, try to white-list
1323
1.99M
  // accesses which just trade in on the final step, i.e. accesses
1324
1.99M
  // which don't require [M4] or [B4]. These are by far the most
1325
1.99M
  // common forms of privileged access.
1326
1.99M
  if (UnprivilegedAccess != AS_none) {
1327
1.97M
    switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1328
1.97M
    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
1.97M
1338
1.97M
    
case AR_accessible: return AR_accessible1.89M
;
1339
1.97M
    
case AR_inaccessible: break76.4k
;
1340
91.9k
    }
1341
91.9k
  }
1342
91.9k
1343
91.9k
  AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
1344
91.9k
1345
91.9k
  // We lower member accesses to base accesses by pretending that the
1346
91.9k
  // member is a base class of its declaring class.
1347
91.9k
  AccessSpecifier FinalAccess;
1348
91.9k
1349
91.9k
  if (Entity.isMemberAccess()) {
1350
91.8k
    // Determine if the declaration is accessible from EC when named
1351
91.8k
    // in its declaring class.
1352
91.8k
    NamedDecl *Target = Entity.getTargetDecl();
1353
91.8k
    const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1354
91.8k
1355
91.8k
    FinalAccess = Target->getAccess();
1356
91.8k
    switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1357
91.8k
    case AR_accessible:
1358
81.7k
      // Target is accessible at EC when named in its declaring class.
1359
81.7k
      // We can now hill-climb and simply check whether the declaring
1360
81.7k
      // class is accessible as a base of the naming class.  This is
1361
81.7k
      // equivalent to checking the access of a notional public
1362
81.7k
      // member with no instance context.
1363
81.7k
      FinalAccess = AS_public;
1364
81.7k
      Entity.suppressInstanceContext();
1365
81.7k
      break;
1366
91.8k
    
case AR_inaccessible: break10.0k
;
1367
91.8k
    
case AR_dependent: return AR_dependent0
; // see above
1368
91.8k
    }
1369
91.8k
1370
91.8k
    if (DeclaringClass == NamingClass)
1371
81.1k
      return (FinalAccess == AS_public ? 
AR_accessible71.2k
:
AR_inaccessible9.89k
);
1372
191
  } else {
1373
191
    FinalAccess = AS_public;
1374
191
  }
1375
91.9k
1376
91.9k
  assert(Entity.getDeclaringClass() != NamingClass);
1377
10.8k
1378
10.8k
  // Append the declaration's access if applicable.
1379
10.8k
  CXXBasePaths Paths;
1380
10.8k
  CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
1381
10.8k
  if (!Path)
1382
0
    return AR_dependent;
1383
10.8k
1384
10.8k
  assert(Path->Access <= UnprivilegedAccess &&
1385
10.8k
         "access along best path worse than direct?");
1386
10.8k
  if (Path->Access == AS_public)
1387
10.3k
    return AR_accessible;
1388
454
  return AR_inaccessible;
1389
454
}
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
1.98M
                                         AccessTarget &Entity) {
1413
1.98M
  assert(Entity.getAccess() != AS_public && "called for public access!");
1414
1.98M
1415
1.98M
  switch (IsAccessible(S, EC, Entity)) {
1416
1.98M
  case AR_dependent:
1417
73
    DelayDependentAccess(S, EC, Loc, Entity);
1418
73
    return AR_dependent;
1419
1.98M
1420
1.98M
  case AR_inaccessible:
1421
10.2k
    if (S.getLangOpts().MSVCCompat &&
1422
10.2k
        
IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity)13
)
1423
2
      return AR_accessible;
1424
10.2k
    if (!Entity.isQuiet())
1425
2.76k
      DiagnoseBadAccess(S, Loc, EC, Entity);
1426
10.2k
    return AR_inaccessible;
1427
10.2k
1428
1.97M
  case AR_accessible:
1429
1.97M
    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
1.99M
                                      AccessTarget &Entity) {
1438
1.99M
  // If the access path is public, it's accessible everywhere.
1439
1.99M
  if (Entity.getAccess() == AS_public)
1440
0
    return Sema::AR_accessible;
1441
1.99M
1442
1.99M
  // If we're currently parsing a declaration, we may need to delay
1443
1.99M
  // access control checking, because our effective context might be
1444
1.99M
  // different based on what the declaration comes out as.
1445
1.99M
  //
1446
1.99M
  // For example, we might be parsing a declaration with a scope
1447
1.99M
  // specifier, like this:
1448
1.99M
  //   A::private_type A::foo() { ... }
1449
1.99M
  //
1450
1.99M
  // Or we might be parsing something that will turn out to be a friend:
1451
1.99M
  //   void foo(A::private_type);
1452
1.99M
  //   void B::foo(A::private_type);
1453
1.99M
  if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1454
530k
    S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
1455
530k
    return Sema::AR_delayed;
1456
530k
  }
1457
1.46M
1458
1.46M
  EffectiveContext EC(S.CurContext);
1459
1.46M
  switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1460
1.46M
  
case AR_accessible: return Sema::AR_accessible1.45M
;
1461
1.46M
  
case AR_inaccessible: return Sema::AR_inaccessible9.88k
;
1462
1.46M
  
case AR_dependent: return Sema::AR_dependent62
;
1463
0
  }
1464
0
  llvm_unreachable("invalid access result");
1465
0
}
1466
1467
523k
void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
1468
523k
  // Access control for names used in the declarations of functions
1469
523k
  // and function templates should normally be evaluated in the context
1470
523k
  // of the declaration, just in case it's a friend of something.
1471
523k
  // However, this does not apply to local extern declarations.
1472
523k
1473
523k
  DeclContext *DC = D->getDeclContext();
1474
523k
  if (D->isLocalExternDecl()) {
1475
10
    DC = D->getLexicalDeclContext();
1476
523k
  } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1477
114k
    DC = FN;
1478
408k
  } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1479
33.9k
    DC = cast<DeclContext>(TD->getTemplatedDecl());
1480
33.9k
  }
1481
523k
1482
523k
  EffectiveContext EC(DC);
1483
523k
1484
523k
  AccessTarget Target(DD.getAccessData());
1485
523k
1486
523k
  if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
1487
367
    DD.Triggered = true;
1488
523k
}
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
899k
                                                     DeclAccessPair Found) {
1532
899k
  if (!getLangOpts().AccessControl ||
1533
899k
      
!E->getNamingClass()899k
||
1534
899k
      
Found.getAccess() == AS_public71.8k
)
1535
886k
    return AR_accessible;
1536
12.9k
1537
12.9k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1538
12.9k
                      Found, QualType());
1539
12.9k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1540
12.9k
1541
12.9k
  return CheckAccess(*this, E->getNameLoc(), Entity);
1542
12.9k
}
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
163k
                                                     DeclAccessPair Found) {
1548
163k
  if (!getLangOpts().AccessControl ||
1549
163k
      Found.getAccess() == AS_public)
1550
134k
    return AR_accessible;
1551
29.3k
1552
29.3k
  QualType BaseType = E->getBaseType();
1553
29.3k
  if (E->isArrow())
1554
28.1k
    BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1555
29.3k
1556
29.3k
  AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1557
29.3k
                      Found, BaseType);
1558
29.3k
  Entity.setDiag(diag::err_access) << E->getSourceRange();
1559
29.3k
1560
29.3k
  return CheckAccess(*this, E->getMemberLoc(), Entity);
1561
29.3k
}
1562
1563
/// Is the given special member function accessible for the purposes of
1564
/// deciding whether to define a special member function as deleted?
1565
bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
1566
                                                AccessSpecifier access,
1567
553k
                                                QualType objectType) {
1568
553k
  // Fast path.
1569
553k
  if (access == AS_public || 
!getLangOpts().AccessControl90.5k
)
return true463k
;
1570
90.5k
1571
90.5k
  AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
1572
90.5k
                      DeclAccessPair::make(decl, access), objectType);
1573
90.5k
1574
90.5k
  // Suppress diagnostics.
1575
90.5k
  entity.setDiag(PDiag());
1576
90.5k
1577
90.5k
  switch (CheckAccess(*this, SourceLocation(), entity)) {
1578
90.5k
  
case AR_accessible: return true83.2k
;
1579
90.5k
  
case AR_inaccessible: return false7.34k
;
1580
90.5k
  
case AR_dependent: 0
llvm_unreachable0
("dependent for =delete computation");
1581
90.5k
  
case AR_delayed: 0
llvm_unreachable0
("cannot delay =delete computation");
1582
0
  }
1583
0
  llvm_unreachable("bad access result");
1584
0
}
1585
1586
Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
1587
                                               CXXDestructorDecl *Dtor,
1588
                                               const PartialDiagnostic &PDiag,
1589
345k
                                               QualType ObjectTy) {
1590
345k
  if (!getLangOpts().AccessControl)
1591
19
    return AR_accessible;
1592
345k
1593
345k
  // There's never a path involved when checking implicit destructor access.
1594
345k
  AccessSpecifier Access = Dtor->getAccess();
1595
345k
  if (Access == AS_public)
1596
339k
    return AR_accessible;
1597
5.86k
1598
5.86k
  CXXRecordDecl *NamingClass = Dtor->getParent();
1599
5.86k
  if (ObjectTy.isNull()) 
ObjectTy = Context.getTypeDeclType(NamingClass)139
;
1600
5.86k
1601
5.86k
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1602
5.86k
                      DeclAccessPair::make(Dtor, Access),
1603
5.86k
                      ObjectTy);
1604
5.86k
  Entity.setDiag(PDiag); // TODO: avoid copy
1605
5.86k
1606
5.86k
  return CheckAccess(*this, Loc, Entity);
1607
5.86k
}
1608
1609
/// Checks access to a constructor.
1610
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1611
                                                CXXConstructorDecl *Constructor,
1612
                                                DeclAccessPair Found,
1613
                                                const InitializedEntity &Entity,
1614
444k
                                                bool IsCopyBindingRefToTemp) {
1615
444k
  if (!getLangOpts().AccessControl || 
Found.getAccess() == AS_public444k
)
1616
430k
    return AR_accessible;
1617
14.2k
1618
14.2k
  PartialDiagnostic PD(PDiag());
1619
14.2k
  switch (Entity.getKind()) {
1620
14.2k
  default:
1621
4.39k
    PD = PDiag(IsCopyBindingRefToTemp
1622
4.39k
                 ? 
diag::ext_rvalue_to_reference_access_ctor7
1623
4.39k
                 : 
diag::err_access_ctor4.38k
);
1624
4.39k
1625
4.39k
    break;
1626
14.2k
1627
14.2k
  case InitializedEntity::EK_Base:
1628
9.82k
    PD = PDiag(diag::err_access_base_ctor);
1629
9.82k
    PD << Entity.isInheritedVirtualBase()
1630
9.82k
       << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
1631
9.82k
    break;
1632
14.2k
1633
14.2k
  case InitializedEntity::EK_Member: {
1634
10
    const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
1635
10
    PD = PDiag(diag::err_access_field_ctor);
1636
10
    PD << Field->getType() << getSpecialMember(Constructor);
1637
10
    break;
1638
14.2k
  }
1639
14.2k
1640
14.2k
  case InitializedEntity::EK_LambdaCapture: {
1641
2
    StringRef VarName = Entity.getCapturedVarName();
1642
2
    PD = PDiag(diag::err_access_lambda_capture);
1643
2
    PD << VarName << Entity.getType() << getSpecialMember(Constructor);
1644
2
    break;
1645
14.2k
  }
1646
14.2k
1647
14.2k
  }
1648
14.2k
1649
14.2k
  return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
1650
14.2k
}
1651
1652
/// Checks access to a constructor.
1653
Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1654
                                                CXXConstructorDecl *Constructor,
1655
                                                DeclAccessPair Found,
1656
                                                const InitializedEntity &Entity,
1657
14.2k
                                                const PartialDiagnostic &PD) {
1658
14.2k
  if (!getLangOpts().AccessControl ||
1659
14.2k
      Found.getAccess() == AS_public)
1660
34
    return AR_accessible;
1661
14.2k
1662
14.2k
  CXXRecordDecl *NamingClass = Constructor->getParent();
1663
14.2k
1664
14.2k
  // Initializing a base sub-object is an instance method call on an
1665
14.2k
  // object of the derived class.  Otherwise, we have an instance method
1666
14.2k
  // call on an object of the constructed type.
1667
14.2k
  //
1668
14.2k
  // FIXME: If we have a parent, we're initializing the base class subobject
1669
14.2k
  // in aggregate initialization. It's not clear whether the object class
1670
14.2k
  // should be the base class or the derived class in that case.
1671
14.2k
  CXXRecordDecl *ObjectClass;
1672
14.2k
  if ((Entity.getKind() == InitializedEntity::EK_Base ||
1673
14.2k
       
Entity.getKind() == InitializedEntity::EK_Delegating4.41k
) &&
1674
14.2k
      
!Entity.getParent()10.2k
) {
1675
10.2k
    ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1676
10.2k
  } else 
if (auto *3.94k
Shadow3.94k
=
1677
12
                 dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
1678
12
    // If we're using an inheriting constructor to construct an object,
1679
12
    // the object class is the derived class, not the base class.
1680
12
    ObjectClass = Shadow->getParent();
1681
3.93k
  } else {
1682
3.93k
    ObjectClass = NamingClass;
1683
3.93k
  }
1684
14.2k
1685
14.2k
  AccessTarget AccessEntity(
1686
14.2k
      Context, AccessTarget::Member, NamingClass,
1687
14.2k
      DeclAccessPair::make(Constructor, Found.getAccess()),
1688
14.2k
      Context.getTypeDeclType(ObjectClass));
1689
14.2k
  AccessEntity.setDiag(PD);
1690
14.2k
1691
14.2k
  return CheckAccess(*this, UseLoc, AccessEntity);
1692
14.2k
}
1693
1694
/// Checks access to an overloaded operator new or delete.
1695
Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1696
                                               SourceRange PlacementRange,
1697
                                               CXXRecordDecl *NamingClass,
1698
                                               DeclAccessPair Found,
1699
14.1k
                                               bool Diagnose) {
1700
14.1k
  if (!getLangOpts().AccessControl ||
1701
14.1k
      
!NamingClass14.0k
||
1702
14.1k
      
Found.getAccess() == AS_public911
)
1703
14.0k
    return AR_accessible;
1704
22
1705
22
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1706
22
                      QualType());
1707
22
  if (Diagnose)
1708
16
    Entity.setDiag(diag::err_access)
1709
16
      << PlacementRange;
1710
22
1711
22
  return CheckAccess(*this, OpLoc, Entity);
1712
22
}
1713
1714
/// Checks access to a member.
1715
Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1716
                                           CXXRecordDecl *NamingClass,
1717
1.83k
                                           DeclAccessPair Found) {
1718
1.83k
  if (!getLangOpts().AccessControl ||
1719
1.83k
      !NamingClass ||
1720
1.83k
      
Found.getAccess() == AS_public789
)
1721
1.66k
    return AR_accessible;
1722
166
1723
166
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1724
166
                      Found, QualType());
1725
166
1726
166
  return CheckAccess(*this, UseLoc, Entity);
1727
166
}
1728
1729
/// Checks implicit access to a member in a structured binding.
1730
Sema::AccessResult
1731
Sema::CheckStructuredBindingMemberAccess(SourceLocation UseLoc,
1732
                                         CXXRecordDecl *DecomposedClass,
1733
283
                                         DeclAccessPair Field) {
1734
283
  if (!getLangOpts().AccessControl ||
1735
283
      Field.getAccess() == AS_public)
1736
268
    return AR_accessible;
1737
15
1738
15
  AccessTarget Entity(Context, AccessTarget::Member, DecomposedClass, Field,
1739
15
                      Context.getRecordType(DecomposedClass));
1740
15
  Entity.setDiag(diag::err_decomp_decl_inaccessible_field);
1741
15
1742
15
  return CheckAccess(*this, UseLoc, Entity);
1743
15
}
1744
1745
/// Checks access to an overloaded member operator, including
1746
/// conversion operators.
1747
Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1748
                                                   Expr *ObjectExpr,
1749
                                                   Expr *ArgExpr,
1750
148k
                                                   DeclAccessPair Found) {
1751
148k
  if (!getLangOpts().AccessControl ||
1752
148k
      
Found.getAccess() == AS_public148k
)
1753
147k
    return AR_accessible;
1754
775
1755
775
  const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
1756
775
  CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1757
775
1758
775
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1759
775
                      ObjectExpr->getType());
1760
775
  Entity.setDiag(diag::err_access)
1761
775
    << ObjectExpr->getSourceRange()
1762
775
    << (ArgExpr ? 
ArgExpr->getSourceRange()719
:
SourceRange()56
);
1763
775
1764
775
  return CheckAccess(*this, OpLoc, Entity);
1765
775
}
1766
1767
/// Checks access to the target of a friend declaration.
1768
347
Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
1769
347
  assert(isa<CXXMethodDecl>(target->getAsFunction()));
1770
347
1771
347
  // Friendship lookup is a redeclaration lookup, so there's never an
1772
347
  // inheritance path modifying access.
1773
347
  AccessSpecifier access = target->getAccess();
1774
347
1775
347
  if (!getLangOpts().AccessControl || access == AS_public)
1776
324
    return AR_accessible;
1777
23
1778
23
  CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
1779
23
1780
23
  AccessTarget entity(Context, AccessTarget::Member,
1781
23
                      cast<CXXRecordDecl>(target->getDeclContext()),
1782
23
                      DeclAccessPair::make(target, access),
1783
23
                      /*no instance context*/ QualType());
1784
23
  entity.setDiag(diag::err_access_friend_function)
1785
23
      << (method->getQualifier() ? 
method->getQualifierLoc().getSourceRange()21
1786
23
                                 : 
method->getNameInfo().getSourceRange()2
);
1787
23
1788
23
  // We need to bypass delayed-diagnostics because we might be called
1789
23
  // while the ParsingDeclarator is active.
1790
23
  EffectiveContext EC(CurContext);
1791
23
  switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1792
23
  
case ::AR_accessible: return Sema::AR_accessible8
;
1793
23
  
case ::AR_inaccessible: return Sema::AR_inaccessible13
;
1794
23
  
case ::AR_dependent: return Sema::AR_dependent2
;
1795
0
  }
1796
0
  llvm_unreachable("invalid access result");
1797
0
}
1798
1799
Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1800
2.63k
                                                    DeclAccessPair Found) {
1801
2.63k
  if (!getLangOpts().AccessControl ||
1802
2.63k
      Found.getAccess() == AS_none ||
1803
2.63k
      
Found.getAccess() == AS_public264
)
1804
2.57k
    return AR_accessible;
1805
62
1806
62
  OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
1807
62
  CXXRecordDecl *NamingClass = Ovl->getNamingClass();
1808
62
1809
62
  AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1810
62
                      /*no instance context*/ QualType());
1811
62
  Entity.setDiag(diag::err_access)
1812
62
    << Ovl->getSourceRange();
1813
62
1814
62
  return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1815
62
}
1816
1817
/// Checks access for a hierarchy conversion.
1818
///
1819
/// \param ForceCheck true if this check should be performed even if access
1820
///     control is disabled;  some things rely on this for semantics
1821
/// \param ForceUnprivileged true if this check should proceed as if the
1822
///     context had no special privileges
1823
Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
1824
                                              QualType Base,
1825
                                              QualType Derived,
1826
                                              const CXXBasePath &Path,
1827
                                              unsigned DiagID,
1828
                                              bool ForceCheck,
1829
180k
                                              bool ForceUnprivileged) {
1830
180k
  if (!ForceCheck && 
!getLangOpts().AccessControl180k
)
1831
2
    return AR_accessible;
1832
180k
1833
180k
  if (Path.Access == AS_public)
1834
138k
    return AR_accessible;
1835
42.2k
1836
42.2k
  CXXRecordDecl *BaseD, *DerivedD;
1837
42.2k
  BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1838
42.2k
  DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
1839
42.2k
1840
42.2k
  AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1841
42.2k
                      Path.Access);
1842
42.2k
  if (DiagID)
1843
42.2k
    Entity.setDiag(DiagID) << Derived << Base;
1844
42.2k
1845
42.2k
  if (ForceUnprivileged) {
1846
15
    switch (CheckEffectiveAccess(*this, EffectiveContext(),
1847
15
                                 AccessLoc, Entity)) {
1848
15
    
case ::AR_accessible: return Sema::AR_accessible0
;
1849
15
    case ::AR_inaccessible: return Sema::AR_inaccessible;
1850
15
    
case ::AR_dependent: return Sema::AR_dependent0
;
1851
0
    }
1852
0
    llvm_unreachable("unexpected result from CheckEffectiveAccess");
1853
0
  }
1854
42.2k
  return CheckAccess(*this, AccessLoc, Entity);
1855
42.2k
}
1856
1857
/// Checks access to all the declarations in the given result set.
1858
7.31M
void Sema::CheckLookupAccess(const LookupResult &R) {
1859
7.31M
  assert(getLangOpts().AccessControl
1860
7.31M
         && "performing access check without access control");
1861
7.31M
  assert(R.getNamingClass() && "performing access check without naming class");
1862
7.31M
1863
14.6M
  for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; 
++I7.29M
) {
1864
7.29M
    if (I.getAccess() != AS_public) {
1865
1.79M
      AccessTarget Entity(Context, AccessedEntity::Member,
1866
1.79M
                          R.getNamingClass(), I.getPair(),
1867
1.79M
                          R.getBaseObjectType());
1868
1.79M
      Entity.setDiag(diag::err_access);
1869
1.79M
      CheckAccess(*this, R.getNameLoc(), Entity);
1870
1.79M
    }
1871
7.29M
  }
1872
7.31M
}
1873
1874
/// Checks access to Target from the given class. The check will take access
1875
/// specifiers into account, but no member access expressions and such.
1876
///
1877
/// \param Target the declaration to check if it can be accessed
1878
/// \param NamingClass the class in which the lookup was started.
1879
/// \param BaseType type of the left side of member access expression.
1880
///        \p BaseType and \p NamingClass are used for C++ access control.
1881
///        Depending on the lookup case, they should be set to the following:
1882
///        - lhs.target (member access without a qualifier):
1883
///          \p BaseType and \p NamingClass are both the type of 'lhs'.
1884
///        - lhs.X::target (member access with a qualifier):
1885
///          BaseType is the type of 'lhs', NamingClass is 'X'
1886
///        - X::target (qualified lookup without member access):
1887
///          BaseType is null, NamingClass is 'X'.
1888
///        - target (unqualified lookup).
1889
///          BaseType is null, NamingClass is the parent class of 'target'.
1890
/// \return true if the Target is accessible from the Class, false otherwise.
1891
bool Sema::IsSimplyAccessible(NamedDecl *Target, CXXRecordDecl *NamingClass,
1892
13.5k
                              QualType BaseType) {
1893
13.5k
  // Perform the C++ accessibility checks first.
1894
13.5k
  if (Target->isCXXClassMember() && 
NamingClass1.53k
) {
1895
1.49k
    if (!getLangOpts().CPlusPlus)
1896
0
      return false;
1897
1.49k
    // The unprivileged access is AS_none as we don't know how the member was
1898
1.49k
    // accessed, which is described by the access in DeclAccessPair.
1899
1.49k
    // `IsAccessible` will examine the actual access of Target (i.e.
1900
1.49k
    // Decl->getAccess()) when calculating the access.
1901
1.49k
    AccessTarget Entity(Context, AccessedEntity::Member, NamingClass,
1902
1.49k
                        DeclAccessPair::make(Target, AS_none), BaseType);
1903
1.49k
    EffectiveContext EC(CurContext);
1904
1.49k
    return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1905
1.49k
  }
1906
12.0k
1907
12.0k
  if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
1908
76
    // @public and @package ivars are always accessible.
1909
76
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1910
76
        
Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package66
)
1911
10
      return true;
1912
66
1913
66
    // If we are inside a class or category implementation, determine the
1914
66
    // interface we're in.
1915
66
    ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1916
66
    if (ObjCMethodDecl *MD = getCurMethodDecl())
1917
56
      ClassOfMethodDecl =  MD->getClassInterface();
1918
10
    else if (FunctionDecl *FD = getCurFunctionDecl()) {
1919
10
      if (ObjCImplDecl *Impl
1920
0
            = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1921
0
        if (ObjCImplementationDecl *IMPD
1922
0
              = dyn_cast<ObjCImplementationDecl>(Impl))
1923
0
          ClassOfMethodDecl = IMPD->getClassInterface();
1924
0
        else if (ObjCCategoryImplDecl* CatImplClass
1925
0
                   = dyn_cast<ObjCCategoryImplDecl>(Impl))
1926
0
          ClassOfMethodDecl = CatImplClass->getClassInterface();
1927
0
      }
1928
10
    }
1929
66
1930
66
    // If we're not in an interface, this ivar is inaccessible.
1931
66
    if (!ClassOfMethodDecl)
1932
10
      return false;
1933
56
1934
56
    // If we're inside the same interface that owns the ivar, we're fine.
1935
56
    if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
1936
50
      return true;
1937
6
1938
6
    // If the ivar is private, it's inaccessible.
1939
6
    if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1940
3
      return false;
1941
3
1942
3
    return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1943
3
  }
1944
11.9k
1945
11.9k
  return true;
1946
11.9k
}