blob: 9fbae2ca297f55fc83ea8bf5b4865774c899d207 [file] [log] [blame]
Anders Carlsson4742a9c2009-03-27 05:05:05 +00001//===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
Anders Carlsson8ed6f362009-03-27 04:43:36 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ access control semantics.
11//
12//===----------------------------------------------------------------------===//
Anders Carlsson17941122009-03-27 04:54:36 +000013
Eric Liu18b404a2018-07-19 13:32:00 +000014#include "clang/Basic/Specifiers.h"
John McCall83024632010-08-25 22:03:47 +000015#include "clang/Sema/SemaInternal.h"
Anders Carlsson733d77f2009-03-27 06:03:27 +000016#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000017#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/DeclCXX.h"
John McCall16927f62010-03-12 01:19:31 +000019#include "clang/AST/DeclFriend.h"
Douglas Gregor21ceb182011-11-03 19:00:24 +000020#include "clang/AST/DeclObjC.h"
John McCallc62bb642010-03-24 05:22:00 +000021#include "clang/AST/DependentDiagnostic.h"
John McCall58cc69d2010-01-27 01:50:18 +000022#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DelayedDiagnostic.h"
24#include "clang/Sema/Initialization.h"
25#include "clang/Sema/Lookup.h"
John McCall58cc69d2010-01-27 01:50:18 +000026
Anders Carlsson17941122009-03-27 04:54:36 +000027using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000028using namespace sema;
Anders Carlsson17941122009-03-27 04:54:36 +000029
John McCalla8ae2222010-04-06 21:38:20 +000030/// A copy of Sema's enum without AR_delayed.
31enum AccessResult {
32 AR_accessible,
33 AR_inaccessible,
34 AR_dependent
35};
36
Anders Carlsson4742a9c2009-03-27 05:05:05 +000037/// SetMemberAccessSpecifier - Set the access specifier of a member.
38/// Returns true on error (when the previous member decl access specifier
39/// is different from the new member decl access specifier).
Mike Stump11289f42009-09-09 15:08:12 +000040bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
Anders Carlsson17941122009-03-27 04:54:36 +000041 NamedDecl *PrevMemberDecl,
42 AccessSpecifier LexicalAS) {
43 if (!PrevMemberDecl) {
44 // Use the lexical access specifier.
45 MemberDecl->setAccess(LexicalAS);
46 return false;
47 }
Mike Stump11289f42009-09-09 15:08:12 +000048
Anders Carlsson17941122009-03-27 04:54:36 +000049 // C++ [class.access.spec]p3: When a member is redeclared its access
50 // specifier must be same as its initial declaration.
51 if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
Mike Stump11289f42009-09-09 15:08:12 +000052 Diag(MemberDecl->getLocation(),
53 diag::err_class_redeclared_with_different_access)
Anders Carlsson17941122009-03-27 04:54:36 +000054 << MemberDecl << LexicalAS;
55 Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
56 << PrevMemberDecl << PrevMemberDecl->getAccess();
John McCall0a4bb262009-12-23 00:37:40 +000057
58 MemberDecl->setAccess(LexicalAS);
Anders Carlsson17941122009-03-27 04:54:36 +000059 return true;
60 }
Mike Stump11289f42009-09-09 15:08:12 +000061
Anders Carlsson17941122009-03-27 04:54:36 +000062 MemberDecl->setAccess(PrevMemberDecl->getAccess());
63 return false;
64}
Anders Carlsson4742a9c2009-03-27 05:05:05 +000065
John McCalla8ae2222010-04-06 21:38:20 +000066static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
67 DeclContext *DC = D->getDeclContext();
68
69 // This can only happen at top: enum decls only "publish" their
70 // immediate members.
71 if (isa<EnumDecl>(DC))
72 DC = cast<EnumDecl>(DC)->getDeclContext();
73
74 CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
75 while (DeclaringClass->isAnonymousStructOrUnion())
76 DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
77 return DeclaringClass;
78}
79
John McCall5b0829a2010-02-10 09:31:12 +000080namespace {
81struct EffectiveContext {
Craig Topperc3ec1492014-05-26 06:22:03 +000082 EffectiveContext() : Inner(nullptr), Dependent(false) {}
Anders Carlsson733d77f2009-03-27 06:03:27 +000083
John McCall816d75b2010-03-24 07:46:06 +000084 explicit EffectiveContext(DeclContext *DC)
85 : Inner(DC),
86 Dependent(DC->isDependentContext()) {
John McCallc62bb642010-03-24 05:22:00 +000087
Richard Smithad5c1ca2013-04-29 10:13:55 +000088 // C++11 [class.access.nest]p1:
John McCallfb803d72010-03-17 04:58:56 +000089 // A nested class is a member and as such has the same access
90 // rights as any other member.
Richard Smithad5c1ca2013-04-29 10:13:55 +000091 // C++11 [class.access]p2:
John McCallfb803d72010-03-17 04:58:56 +000092 // A member of a class can also access all the names to which
John McCall3dc81f72010-03-27 06:55:49 +000093 // the class has access. A local class of a member function
94 // may access the same names that the member function itself
95 // may access.
96 // This almost implies that the privileges of nesting are transitive.
97 // Technically it says nothing about the local classes of non-member
98 // functions (which can gain privileges through friendship), but we
99 // take that as an oversight.
100 while (true) {
John McCalle91aec72012-08-24 22:54:02 +0000101 // We want to add canonical declarations to the EC lists for
102 // simplicity of checking, but we need to walk up through the
103 // actual current DC chain. Otherwise, something like a local
104 // extern or friend which happens to be the canonical
105 // declaration will really mess us up.
106
John McCall3dc81f72010-03-27 06:55:49 +0000107 if (isa<CXXRecordDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000108 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
109 Records.push_back(Record->getCanonicalDecl());
John McCall3dc81f72010-03-27 06:55:49 +0000110 DC = Record->getDeclContext();
111 } else if (isa<FunctionDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000112 FunctionDecl *Function = cast<FunctionDecl>(DC);
113 Functions.push_back(Function->getCanonicalDecl());
Douglas Gregor56636582011-10-09 22:38:36 +0000114 if (Function->getFriendObjectKind())
115 DC = Function->getLexicalDeclContext();
116 else
117 DC = Function->getDeclContext();
John McCall3dc81f72010-03-27 06:55:49 +0000118 } else if (DC->isFileContext()) {
119 break;
120 } else {
121 DC = DC->getParent();
122 }
John McCallfb803d72010-03-17 04:58:56 +0000123 }
Anders Carlsson733d77f2009-03-27 06:03:27 +0000124 }
Sebastian Redle644e192009-07-18 14:32:15 +0000125
John McCallc62bb642010-03-24 05:22:00 +0000126 bool isDependent() const { return Dependent; }
127
John McCallfb803d72010-03-17 04:58:56 +0000128 bool includesClass(const CXXRecordDecl *R) const {
129 R = R->getCanonicalDecl();
130 return std::find(Records.begin(), Records.end(), R)
131 != Records.end();
John McCall5b0829a2010-02-10 09:31:12 +0000132 }
133
John McCall816d75b2010-03-24 07:46:06 +0000134 /// Retrieves the innermost "useful" context. Can be null if we're
135 /// doing access-control without privileges.
136 DeclContext *getInnerContext() const {
137 return Inner;
John McCallc62bb642010-03-24 05:22:00 +0000138 }
139
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000140 typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
John McCallc62bb642010-03-24 05:22:00 +0000141
John McCall816d75b2010-03-24 07:46:06 +0000142 DeclContext *Inner;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000143 SmallVector<FunctionDecl*, 4> Functions;
144 SmallVector<CXXRecordDecl*, 4> Records;
John McCallc62bb642010-03-24 05:22:00 +0000145 bool Dependent;
John McCall5b0829a2010-02-10 09:31:12 +0000146};
John McCalla8ae2222010-04-06 21:38:20 +0000147
Nico Weber20c9f1d2010-11-28 22:53:37 +0000148/// Like sema::AccessedEntity, but kindly lets us scribble all over
John McCalla8ae2222010-04-06 21:38:20 +0000149/// it.
John McCallb45a1e72010-08-26 02:13:20 +0000150struct AccessTarget : public AccessedEntity {
151 AccessTarget(const AccessedEntity &Entity)
John McCalla8ae2222010-04-06 21:38:20 +0000152 : AccessedEntity(Entity) {
153 initialize();
154 }
155
156 AccessTarget(ASTContext &Context,
157 MemberNonce _,
158 CXXRecordDecl *NamingClass,
159 DeclAccessPair FoundDecl,
Erik Verbruggen631dfc62011-09-19 15:10:40 +0000160 QualType BaseObjectType)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000161 : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
162 FoundDecl, BaseObjectType) {
John McCalla8ae2222010-04-06 21:38:20 +0000163 initialize();
164 }
165
166 AccessTarget(ASTContext &Context,
167 BaseNonce _,
168 CXXRecordDecl *BaseClass,
169 CXXRecordDecl *DerivedClass,
170 AccessSpecifier Access)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000171 : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
172 Access) {
John McCalla8ae2222010-04-06 21:38:20 +0000173 initialize();
174 }
175
John McCall5dadb652012-04-07 03:04:20 +0000176 bool isInstanceMember() const {
177 return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
178 }
179
John McCalla8ae2222010-04-06 21:38:20 +0000180 bool hasInstanceContext() const {
181 return HasInstanceContext;
182 }
183
184 class SavedInstanceContext {
185 public:
David Blaikie8533e962015-08-12 22:58:10 +0000186 SavedInstanceContext(SavedInstanceContext &&S)
187 : Target(S.Target), Has(S.Has) {
188 S.Target = nullptr;
189 }
John McCalla8ae2222010-04-06 21:38:20 +0000190 ~SavedInstanceContext() {
David Blaikie8533e962015-08-12 22:58:10 +0000191 if (Target)
192 Target->HasInstanceContext = Has;
John McCalla8ae2222010-04-06 21:38:20 +0000193 }
194
195 private:
John McCall8e36d532010-04-07 00:41:46 +0000196 friend struct AccessTarget;
John McCalla8ae2222010-04-06 21:38:20 +0000197 explicit SavedInstanceContext(AccessTarget &Target)
David Blaikie8533e962015-08-12 22:58:10 +0000198 : Target(&Target), Has(Target.HasInstanceContext) {}
199 AccessTarget *Target;
John McCalla8ae2222010-04-06 21:38:20 +0000200 bool Has;
201 };
202
203 SavedInstanceContext saveInstanceContext() {
204 return SavedInstanceContext(*this);
205 }
206
207 void suppressInstanceContext() {
208 HasInstanceContext = false;
209 }
210
211 const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
212 assert(HasInstanceContext);
213 if (CalculatedInstanceContext)
214 return InstanceContext;
215
216 CalculatedInstanceContext = true;
217 DeclContext *IC = S.computeDeclContext(getBaseObjectType());
Craig Topperc3ec1492014-05-26 06:22:03 +0000218 InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
219 : nullptr);
John McCalla8ae2222010-04-06 21:38:20 +0000220 return InstanceContext;
221 }
222
223 const CXXRecordDecl *getDeclaringClass() const {
224 return DeclaringClass;
225 }
226
John McCalld010ac92013-02-27 00:08:19 +0000227 /// The "effective" naming class is the canonical non-anonymous
228 /// class containing the actual naming class.
229 const CXXRecordDecl *getEffectiveNamingClass() const {
230 const CXXRecordDecl *namingClass = getNamingClass();
231 while (namingClass->isAnonymousStructOrUnion())
232 namingClass = cast<CXXRecordDecl>(namingClass->getParent());
233 return namingClass->getCanonicalDecl();
234 }
235
John McCalla8ae2222010-04-06 21:38:20 +0000236private:
237 void initialize() {
238 HasInstanceContext = (isMemberAccess() &&
239 !getBaseObjectType().isNull() &&
240 getTargetDecl()->isCXXInstanceMember());
241 CalculatedInstanceContext = false;
Craig Topperc3ec1492014-05-26 06:22:03 +0000242 InstanceContext = nullptr;
John McCalla8ae2222010-04-06 21:38:20 +0000243
244 if (isMemberAccess())
245 DeclaringClass = FindDeclaringClass(getTargetDecl());
246 else
247 DeclaringClass = getBaseClass();
248 DeclaringClass = DeclaringClass->getCanonicalDecl();
249 }
250
251 bool HasInstanceContext : 1;
252 mutable bool CalculatedInstanceContext : 1;
253 mutable const CXXRecordDecl *InstanceContext;
254 const CXXRecordDecl *DeclaringClass;
255};
256
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000257}
John McCall553c0792010-01-23 00:46:32 +0000258
John McCall97205142010-05-04 05:11:27 +0000259/// Checks whether one class might instantiate to the other.
260static bool MightInstantiateTo(const CXXRecordDecl *From,
261 const CXXRecordDecl *To) {
262 // Declaration names are always preserved by instantiation.
263 if (From->getDeclName() != To->getDeclName())
264 return false;
265
266 const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
267 const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
268 if (FromDC == ToDC) return true;
269 if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
270
271 // Be conservative.
272 return true;
273}
274
John McCalla8ae2222010-04-06 21:38:20 +0000275/// Checks whether one class is derived from another, inclusively.
276/// Properly indicates when it couldn't be determined due to
277/// dependence.
278///
279/// This should probably be donated to AST or at least Sema.
280static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
281 const CXXRecordDecl *Target) {
282 assert(Derived->getCanonicalDecl() == Derived);
283 assert(Target->getCanonicalDecl() == Target);
John McCall69f75862010-03-24 09:04:37 +0000284
John McCalla8ae2222010-04-06 21:38:20 +0000285 if (Derived == Target) return AR_accessible;
John McCall69f75862010-03-24 09:04:37 +0000286
John McCall97205142010-05-04 05:11:27 +0000287 bool CheckDependent = Derived->isDependentContext();
288 if (CheckDependent && MightInstantiateTo(Derived, Target))
289 return AR_dependent;
290
John McCalla8ae2222010-04-06 21:38:20 +0000291 AccessResult OnFailure = AR_inaccessible;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000292 SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
John McCalla8ae2222010-04-06 21:38:20 +0000293
294 while (true) {
Richard Smithfd55fc82016-03-23 20:39:06 +0000295 if (Derived->isDependentContext() && !Derived->hasDefinition() &&
296 !Derived->isLambda())
Douglas Gregor0201a4c2011-11-14 23:00:43 +0000297 return AR_dependent;
Richard Smithfd55fc82016-03-23 20:39:06 +0000298
Aaron Ballman574705e2014-03-13 15:41:46 +0000299 for (const auto &I : Derived->bases()) {
John McCalla8ae2222010-04-06 21:38:20 +0000300 const CXXRecordDecl *RD;
301
Aaron Ballman574705e2014-03-13 15:41:46 +0000302 QualType T = I.getType();
John McCalla8ae2222010-04-06 21:38:20 +0000303 if (const RecordType *RT = T->getAs<RecordType>()) {
304 RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall97205142010-05-04 05:11:27 +0000305 } else if (const InjectedClassNameType *IT
306 = T->getAs<InjectedClassNameType>()) {
307 RD = IT->getDecl();
John McCalla8ae2222010-04-06 21:38:20 +0000308 } else {
John McCalla8ae2222010-04-06 21:38:20 +0000309 assert(T->isDependentType() && "non-dependent base wasn't a record?");
310 OnFailure = AR_dependent;
311 continue;
312 }
313
314 RD = RD->getCanonicalDecl();
315 if (RD == Target) return AR_accessible;
John McCall97205142010-05-04 05:11:27 +0000316 if (CheckDependent && MightInstantiateTo(RD, Target))
317 OnFailure = AR_dependent;
318
John McCalla8ae2222010-04-06 21:38:20 +0000319 Queue.push_back(RD);
320 }
321
322 if (Queue.empty()) break;
323
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000324 Derived = Queue.pop_back_val();
John McCalla8ae2222010-04-06 21:38:20 +0000325 }
326
327 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000328}
329
John McCalla8ae2222010-04-06 21:38:20 +0000330
John McCallc62bb642010-03-24 05:22:00 +0000331static bool MightInstantiateTo(Sema &S, DeclContext *Context,
332 DeclContext *Friend) {
333 if (Friend == Context)
334 return true;
335
336 assert(!Friend->isDependentContext() &&
337 "can't handle friends with dependent contexts here");
338
339 if (!Context->isDependentContext())
340 return false;
341
342 if (Friend->isFileContext())
343 return false;
344
345 // TODO: this is very conservative
346 return true;
347}
348
349// Asks whether the type in 'context' can ever instantiate to the type
350// in 'friend'.
351static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
352 if (Friend == Context)
353 return true;
354
355 if (!Friend->isDependentType() && !Context->isDependentType())
356 return false;
357
358 // TODO: this is very conservative.
359 return true;
360}
361
362static bool MightInstantiateTo(Sema &S,
363 FunctionDecl *Context,
364 FunctionDecl *Friend) {
365 if (Context->getDeclName() != Friend->getDeclName())
366 return false;
367
368 if (!MightInstantiateTo(S,
369 Context->getDeclContext(),
370 Friend->getDeclContext()))
371 return false;
372
373 CanQual<FunctionProtoType> FriendTy
374 = S.Context.getCanonicalType(Friend->getType())
375 ->getAs<FunctionProtoType>();
376 CanQual<FunctionProtoType> ContextTy
377 = S.Context.getCanonicalType(Context->getType())
378 ->getAs<FunctionProtoType>();
379
380 // There isn't any way that I know of to add qualifiers
381 // during instantiation.
382 if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
383 return false;
384
Alp Toker9cacbab2014-01-20 20:26:09 +0000385 if (FriendTy->getNumParams() != ContextTy->getNumParams())
John McCallc62bb642010-03-24 05:22:00 +0000386 return false;
387
Alp Toker314cc812014-01-25 16:55:45 +0000388 if (!MightInstantiateTo(S, ContextTy->getReturnType(),
389 FriendTy->getReturnType()))
John McCallc62bb642010-03-24 05:22:00 +0000390 return false;
391
Alp Toker9cacbab2014-01-20 20:26:09 +0000392 for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
393 if (!MightInstantiateTo(S, ContextTy->getParamType(I),
394 FriendTy->getParamType(I)))
John McCallc62bb642010-03-24 05:22:00 +0000395 return false;
396
397 return true;
398}
399
400static bool MightInstantiateTo(Sema &S,
401 FunctionTemplateDecl *Context,
402 FunctionTemplateDecl *Friend) {
403 return MightInstantiateTo(S,
404 Context->getTemplatedDecl(),
405 Friend->getTemplatedDecl());
406}
407
John McCalla8ae2222010-04-06 21:38:20 +0000408static AccessResult MatchesFriend(Sema &S,
409 const EffectiveContext &EC,
410 const CXXRecordDecl *Friend) {
John McCall39e82882010-03-17 20:01:29 +0000411 if (EC.includesClass(Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000412 return AR_accessible;
John McCall39e82882010-03-17 20:01:29 +0000413
John McCallc62bb642010-03-24 05:22:00 +0000414 if (EC.isDependent()) {
Richard Smithfd55fc82016-03-23 20:39:06 +0000415 for (const CXXRecordDecl *Context : EC.Records) {
416 if (MightInstantiateTo(Context, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000417 return AR_dependent;
John McCallc62bb642010-03-24 05:22:00 +0000418 }
419 }
420
John McCalla8ae2222010-04-06 21:38:20 +0000421 return AR_inaccessible;
John McCall39e82882010-03-17 20:01:29 +0000422}
423
John McCalla8ae2222010-04-06 21:38:20 +0000424static AccessResult MatchesFriend(Sema &S,
425 const EffectiveContext &EC,
426 CanQualType Friend) {
John McCallc62bb642010-03-24 05:22:00 +0000427 if (const RecordType *RT = Friend->getAs<RecordType>())
428 return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
John McCall39e82882010-03-17 20:01:29 +0000429
John McCallc62bb642010-03-24 05:22:00 +0000430 // TODO: we can do better than this
431 if (Friend->isDependentType())
John McCalla8ae2222010-04-06 21:38:20 +0000432 return AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000433
John McCalla8ae2222010-04-06 21:38:20 +0000434 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000435}
436
437/// Determines whether the given friend class template matches
438/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000439static AccessResult MatchesFriend(Sema &S,
440 const EffectiveContext &EC,
441 ClassTemplateDecl *Friend) {
442 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000443
John McCall598b4402010-03-25 06:39:04 +0000444 // Check whether the friend is the template of a class in the
445 // context chain.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000446 for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
John McCallc62bb642010-03-24 05:22:00 +0000447 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
448 CXXRecordDecl *Record = *I;
449
John McCall598b4402010-03-25 06:39:04 +0000450 // Figure out whether the current class has a template:
John McCallc62bb642010-03-24 05:22:00 +0000451 ClassTemplateDecl *CTD;
452
453 // A specialization of the template...
454 if (isa<ClassTemplateSpecializationDecl>(Record)) {
455 CTD = cast<ClassTemplateSpecializationDecl>(Record)
456 ->getSpecializedTemplate();
457
458 // ... or the template pattern itself.
459 } else {
460 CTD = Record->getDescribedClassTemplate();
461 if (!CTD) continue;
462 }
463
464 // It's a match.
465 if (Friend == CTD->getCanonicalDecl())
John McCalla8ae2222010-04-06 21:38:20 +0000466 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000467
John McCall598b4402010-03-25 06:39:04 +0000468 // If the context isn't dependent, it can't be a dependent match.
469 if (!EC.isDependent())
470 continue;
471
John McCallc62bb642010-03-24 05:22:00 +0000472 // If the template names don't match, it can't be a dependent
Richard Smith3f1b5d02011-05-05 21:57:07 +0000473 // match.
474 if (CTD->getDeclName() != Friend->getDeclName())
John McCallc62bb642010-03-24 05:22:00 +0000475 continue;
476
477 // If the class's context can't instantiate to the friend's
478 // context, it can't be a dependent match.
479 if (!MightInstantiateTo(S, CTD->getDeclContext(),
480 Friend->getDeclContext()))
481 continue;
482
483 // Otherwise, it's a dependent match.
John McCalla8ae2222010-04-06 21:38:20 +0000484 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000485 }
486
John McCallc62bb642010-03-24 05:22:00 +0000487 return OnFailure;
488}
489
490/// Determines whether the given friend function matches anything in
491/// the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000492static AccessResult MatchesFriend(Sema &S,
493 const EffectiveContext &EC,
494 FunctionDecl *Friend) {
495 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000496
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000497 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000498 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
499 if (Friend == *I)
John McCalla8ae2222010-04-06 21:38:20 +0000500 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000501
John McCall3dc81f72010-03-27 06:55:49 +0000502 if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000503 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000504 }
John McCallc62bb642010-03-24 05:22:00 +0000505
John McCall3dc81f72010-03-27 06:55:49 +0000506 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000507}
508
509/// Determines whether the given friend function template matches
510/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000511static AccessResult MatchesFriend(Sema &S,
512 const EffectiveContext &EC,
513 FunctionTemplateDecl *Friend) {
514 if (EC.Functions.empty()) return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000515
John McCalla8ae2222010-04-06 21:38:20 +0000516 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000517
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000518 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000519 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
John McCallc62bb642010-03-24 05:22:00 +0000520
John McCall3dc81f72010-03-27 06:55:49 +0000521 FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
522 if (!FTD)
523 FTD = (*I)->getDescribedFunctionTemplate();
524 if (!FTD)
525 continue;
John McCallc62bb642010-03-24 05:22:00 +0000526
John McCall3dc81f72010-03-27 06:55:49 +0000527 FTD = FTD->getCanonicalDecl();
528
529 if (Friend == FTD)
John McCalla8ae2222010-04-06 21:38:20 +0000530 return AR_accessible;
John McCall3dc81f72010-03-27 06:55:49 +0000531
532 if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000533 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000534 }
535
536 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000537}
538
539/// Determines whether the given friend declaration matches anything
540/// in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000541static AccessResult MatchesFriend(Sema &S,
542 const EffectiveContext &EC,
543 FriendDecl *FriendD) {
John McCall2c2eb122010-10-16 06:59:13 +0000544 // Whitelist accesses if there's an invalid or unsupported friend
545 // declaration.
546 if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
John McCallde3fd222010-10-12 23:13:28 +0000547 return AR_accessible;
548
John McCall15ad0962010-03-25 18:04:51 +0000549 if (TypeSourceInfo *T = FriendD->getFriendType())
550 return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
John McCallc62bb642010-03-24 05:22:00 +0000551
552 NamedDecl *Friend
553 = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
John McCall39e82882010-03-17 20:01:29 +0000554
555 // FIXME: declarations with dependent or templated scope.
556
John McCallc62bb642010-03-24 05:22:00 +0000557 if (isa<ClassTemplateDecl>(Friend))
558 return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000559
John McCallc62bb642010-03-24 05:22:00 +0000560 if (isa<FunctionTemplateDecl>(Friend))
561 return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000562
John McCallc62bb642010-03-24 05:22:00 +0000563 if (isa<CXXRecordDecl>(Friend))
564 return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000565
John McCallc62bb642010-03-24 05:22:00 +0000566 assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
567 return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000568}
569
John McCalla8ae2222010-04-06 21:38:20 +0000570static AccessResult GetFriendKind(Sema &S,
571 const EffectiveContext &EC,
572 const CXXRecordDecl *Class) {
573 AccessResult OnFailure = AR_inaccessible;
John McCallfb803d72010-03-17 04:58:56 +0000574
John McCall16927f62010-03-12 01:19:31 +0000575 // Okay, check friends.
Aaron Ballman522a6dd2014-03-13 17:00:06 +0000576 for (auto *Friend : Class->friends()) {
John McCall39e82882010-03-17 20:01:29 +0000577 switch (MatchesFriend(S, EC, Friend)) {
John McCalla8ae2222010-04-06 21:38:20 +0000578 case AR_accessible:
579 return AR_accessible;
John McCall16927f62010-03-12 01:19:31 +0000580
John McCalla8ae2222010-04-06 21:38:20 +0000581 case AR_inaccessible:
582 continue;
583
584 case AR_dependent:
585 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000586 break;
John McCall16927f62010-03-12 01:19:31 +0000587 }
John McCall16927f62010-03-12 01:19:31 +0000588 }
589
590 // That's it, give up.
John McCallfb803d72010-03-17 04:58:56 +0000591 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000592}
593
John McCall96329672010-08-28 07:56:00 +0000594namespace {
595
596/// A helper class for checking for a friend which will grant access
597/// to a protected instance member.
598struct ProtectedFriendContext {
599 Sema &S;
600 const EffectiveContext &EC;
601 const CXXRecordDecl *NamingClass;
602 bool CheckDependent;
603 bool EverDependent;
604
605 /// The path down to the current base class.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000606 SmallVector<const CXXRecordDecl*, 20> CurPath;
John McCall96329672010-08-28 07:56:00 +0000607
608 ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
609 const CXXRecordDecl *InstanceContext,
610 const CXXRecordDecl *NamingClass)
611 : S(S), EC(EC), NamingClass(NamingClass),
612 CheckDependent(InstanceContext->isDependentContext() ||
613 NamingClass->isDependentContext()),
614 EverDependent(false) {}
615
John McCall1177ff12010-08-28 08:47:21 +0000616 /// Check classes in the current path for friendship, starting at
617 /// the given index.
618 bool checkFriendshipAlongPath(unsigned I) {
619 assert(I < CurPath.size());
620 for (unsigned E = CurPath.size(); I != E; ++I) {
621 switch (GetFriendKind(S, EC, CurPath[I])) {
John McCall96329672010-08-28 07:56:00 +0000622 case AR_accessible: return true;
623 case AR_inaccessible: continue;
624 case AR_dependent: EverDependent = true; continue;
625 }
626 }
627 return false;
628 }
629
630 /// Perform a search starting at the given class.
John McCall1177ff12010-08-28 08:47:21 +0000631 ///
632 /// PrivateDepth is the index of the last (least derived) class
633 /// along the current path such that a notional public member of
634 /// the final class in the path would have access in that class.
635 bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
John McCall96329672010-08-28 07:56:00 +0000636 // If we ever reach the naming class, check the current path for
637 // friendship. We can also stop recursing because we obviously
638 // won't find the naming class there again.
John McCall1177ff12010-08-28 08:47:21 +0000639 if (Cur == NamingClass)
640 return checkFriendshipAlongPath(PrivateDepth);
John McCall96329672010-08-28 07:56:00 +0000641
642 if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
643 EverDependent = true;
644
645 // Recurse into the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000646 for (const auto &I : Cur->bases()) {
John McCall1177ff12010-08-28 08:47:21 +0000647 // If this is private inheritance, then a public member of the
648 // base will not have any access in classes derived from Cur.
649 unsigned BasePrivateDepth = PrivateDepth;
Aaron Ballman574705e2014-03-13 15:41:46 +0000650 if (I.getAccessSpecifier() == AS_private)
John McCall1177ff12010-08-28 08:47:21 +0000651 BasePrivateDepth = CurPath.size() - 1;
John McCall96329672010-08-28 07:56:00 +0000652
653 const CXXRecordDecl *RD;
654
Aaron Ballman574705e2014-03-13 15:41:46 +0000655 QualType T = I.getType();
John McCall96329672010-08-28 07:56:00 +0000656 if (const RecordType *RT = T->getAs<RecordType>()) {
657 RD = cast<CXXRecordDecl>(RT->getDecl());
658 } else if (const InjectedClassNameType *IT
659 = T->getAs<InjectedClassNameType>()) {
660 RD = IT->getDecl();
661 } else {
662 assert(T->isDependentType() && "non-dependent base wasn't a record?");
663 EverDependent = true;
664 continue;
665 }
666
667 // Recurse. We don't need to clean up if this returns true.
John McCall1177ff12010-08-28 08:47:21 +0000668 CurPath.push_back(RD);
669 if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
670 return true;
671 CurPath.pop_back();
John McCall96329672010-08-28 07:56:00 +0000672 }
673
John McCall96329672010-08-28 07:56:00 +0000674 return false;
675 }
John McCall1177ff12010-08-28 08:47:21 +0000676
677 bool findFriendship(const CXXRecordDecl *Cur) {
678 assert(CurPath.empty());
679 CurPath.push_back(Cur);
680 return findFriendship(Cur, 0);
681 }
John McCall96329672010-08-28 07:56:00 +0000682};
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000683}
John McCall96329672010-08-28 07:56:00 +0000684
685/// Search for a class P that EC is a friend of, under the constraint
John McCall5dadb652012-04-07 03:04:20 +0000686/// InstanceContext <= P
687/// if InstanceContext exists, or else
688/// NamingClass <= P
John McCall96329672010-08-28 07:56:00 +0000689/// and with the additional restriction that a protected member of
John McCall5dadb652012-04-07 03:04:20 +0000690/// NamingClass would have some natural access in P, which implicitly
691/// imposes the constraint that P <= NamingClass.
John McCall96329672010-08-28 07:56:00 +0000692///
John McCall5dadb652012-04-07 03:04:20 +0000693/// This isn't quite the condition laid out in the standard.
694/// Instead of saying that a notional protected member of NamingClass
695/// would have to have some natural access in P, it says the actual
696/// target has to have some natural access in P, which opens up the
697/// possibility that the target (which is not necessarily a member
698/// of NamingClass) might be more accessible along some path not
699/// passing through it. That's really a bad idea, though, because it
John McCall96329672010-08-28 07:56:00 +0000700/// introduces two problems:
John McCall5dadb652012-04-07 03:04:20 +0000701/// - Most importantly, it breaks encapsulation because you can
702/// access a forbidden base class's members by directly subclassing
703/// it elsewhere.
704/// - It also makes access substantially harder to compute because it
John McCall96329672010-08-28 07:56:00 +0000705/// breaks the hill-climbing algorithm: knowing that the target is
706/// accessible in some base class would no longer let you change
707/// the question solely to whether the base class is accessible,
708/// because the original target might have been more accessible
709/// because of crazy subclassing.
710/// So we don't implement that.
711static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
712 const CXXRecordDecl *InstanceContext,
713 const CXXRecordDecl *NamingClass) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000714 assert(InstanceContext == nullptr ||
John McCall5dadb652012-04-07 03:04:20 +0000715 InstanceContext->getCanonicalDecl() == InstanceContext);
John McCall96329672010-08-28 07:56:00 +0000716 assert(NamingClass->getCanonicalDecl() == NamingClass);
717
John McCall5dadb652012-04-07 03:04:20 +0000718 // If we don't have an instance context, our constraints give us
719 // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
720 // This is just the usual friendship check.
721 if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
722
John McCall96329672010-08-28 07:56:00 +0000723 ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
724 if (PRC.findFriendship(InstanceContext)) return AR_accessible;
725 if (PRC.EverDependent) return AR_dependent;
726 return AR_inaccessible;
727}
728
John McCalla8ae2222010-04-06 21:38:20 +0000729static AccessResult HasAccess(Sema &S,
730 const EffectiveContext &EC,
731 const CXXRecordDecl *NamingClass,
732 AccessSpecifier Access,
733 const AccessTarget &Target) {
John McCalld79b4d82010-04-02 00:03:43 +0000734 assert(NamingClass->getCanonicalDecl() == NamingClass &&
735 "declaration should be canonicalized before being passed here");
736
John McCalla8ae2222010-04-06 21:38:20 +0000737 if (Access == AS_public) return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000738 assert(Access == AS_private || Access == AS_protected);
739
John McCalla8ae2222010-04-06 21:38:20 +0000740 AccessResult OnFailure = AR_inaccessible;
741
John McCalld79b4d82010-04-02 00:03:43 +0000742 for (EffectiveContext::record_iterator
743 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
744 // All the declarations in EC have been canonicalized, so pointer
745 // equality from this point on will work fine.
746 const CXXRecordDecl *ECRecord = *I;
747
748 // [B2] and [M2]
John McCalla8ae2222010-04-06 21:38:20 +0000749 if (Access == AS_private) {
750 if (ECRecord == NamingClass)
751 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000752
John McCall97205142010-05-04 05:11:27 +0000753 if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
754 OnFailure = AR_dependent;
755
John McCalld79b4d82010-04-02 00:03:43 +0000756 // [B3] and [M3]
John McCalla8ae2222010-04-06 21:38:20 +0000757 } else {
758 assert(Access == AS_protected);
759 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
760 case AR_accessible: break;
761 case AR_inaccessible: continue;
762 case AR_dependent: OnFailure = AR_dependent; continue;
763 }
764
John McCalla8ae2222010-04-06 21:38:20 +0000765 // C++ [class.protected]p1:
766 // An additional access check beyond those described earlier in
767 // [class.access] is applied when a non-static data member or
768 // non-static member function is a protected member of its naming
769 // class. As described earlier, access to a protected member is
770 // granted because the reference occurs in a friend or member of
771 // some class C. If the access is to form a pointer to member,
772 // the nested-name-specifier shall name C or a class derived from
773 // C. All other accesses involve a (possibly implicit) object
774 // expression. In this case, the class of the object expression
775 // shall be C or a class derived from C.
776 //
John McCall5dadb652012-04-07 03:04:20 +0000777 // We interpret this as a restriction on [M3].
778
779 // In this part of the code, 'C' is just our context class ECRecord.
780
781 // These rules are different if we don't have an instance context.
782 if (!Target.hasInstanceContext()) {
783 // If it's not an instance member, these restrictions don't apply.
784 if (!Target.isInstanceMember()) return AR_accessible;
785
786 // If it's an instance member, use the pointer-to-member rule
787 // that the naming class has to be derived from the effective
788 // context.
789
Francois Picheta39371c2012-04-17 12:35:05 +0000790 // Emulate a MSVC bug where the creation of pointer-to-member
791 // to protected member of base class is allowed but only from
Francois Pichet52d38982012-04-19 07:48:57 +0000792 // static member functions.
Alp Tokerbfa39342014-01-14 12:51:41 +0000793 if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
Francois Pichet5b061f02012-04-18 03:24:38 +0000794 if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
795 if (MD->isStatic()) return AR_accessible;
Francois Picheta39371c2012-04-17 12:35:05 +0000796
John McCall5dadb652012-04-07 03:04:20 +0000797 // Despite the standard's confident wording, there is a case
798 // where you can have an instance member that's neither in a
799 // pointer-to-member expression nor in a member access: when
800 // it names a field in an unevaluated context that can't be an
801 // implicit member. Pending clarification, we just apply the
802 // same naming-class restriction here.
803 // FIXME: we're probably not correctly adding the
804 // protected-member restriction when we retroactively convert
805 // an expression to being evaluated.
806
807 // We know that ECRecord derives from NamingClass. The
808 // restriction says to check whether NamingClass derives from
809 // ECRecord, but that's not really necessary: two distinct
810 // classes can't be recursively derived from each other. So
811 // along this path, we just need to check whether the classes
812 // are equal.
813 if (NamingClass == ECRecord) return AR_accessible;
814
815 // Otherwise, this context class tells us nothing; on to the next.
816 continue;
817 }
818
819 assert(Target.isInstanceMember());
820
821 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
822 if (!InstanceContext) {
823 OnFailure = AR_dependent;
824 continue;
825 }
826
John McCalla8ae2222010-04-06 21:38:20 +0000827 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
828 case AR_accessible: return AR_accessible;
829 case AR_inaccessible: continue;
830 case AR_dependent: OnFailure = AR_dependent; continue;
831 }
832 }
John McCalld79b4d82010-04-02 00:03:43 +0000833 }
834
John McCall96329672010-08-28 07:56:00 +0000835 // [M3] and [B3] say that, if the target is protected in N, we grant
836 // access if the access occurs in a friend or member of some class P
837 // that's a subclass of N and where the target has some natural
838 // access in P. The 'member' aspect is easy to handle because P
839 // would necessarily be one of the effective-context records, and we
840 // address that above. The 'friend' aspect is completely ridiculous
841 // to implement because there are no restrictions at all on P
842 // *unless* the [class.protected] restriction applies. If it does,
843 // however, we should ignore whether the naming class is a friend,
844 // and instead rely on whether any potential P is a friend.
John McCall5dadb652012-04-07 03:04:20 +0000845 if (Access == AS_protected && Target.isInstanceMember()) {
846 // Compute the instance context if possible.
Craig Topperc3ec1492014-05-26 06:22:03 +0000847 const CXXRecordDecl *InstanceContext = nullptr;
John McCall5dadb652012-04-07 03:04:20 +0000848 if (Target.hasInstanceContext()) {
849 InstanceContext = Target.resolveInstanceContext(S);
850 if (!InstanceContext) return AR_dependent;
851 }
852
John McCall96329672010-08-28 07:56:00 +0000853 switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
854 case AR_accessible: return AR_accessible;
John McCalla8ae2222010-04-06 21:38:20 +0000855 case AR_inaccessible: return OnFailure;
856 case AR_dependent: return AR_dependent;
857 }
John McCallc6af8f42010-08-28 08:10:32 +0000858 llvm_unreachable("impossible friendship kind");
John McCalla8ae2222010-04-06 21:38:20 +0000859 }
860
861 switch (GetFriendKind(S, EC, NamingClass)) {
862 case AR_accessible: return AR_accessible;
863 case AR_inaccessible: return OnFailure;
864 case AR_dependent: return AR_dependent;
865 }
866
867 // Silence bogus warnings
868 llvm_unreachable("impossible friendship kind");
John McCalld79b4d82010-04-02 00:03:43 +0000869}
870
John McCall5b0829a2010-02-10 09:31:12 +0000871/// Finds the best path from the naming class to the declaring class,
872/// taking friend declarations into account.
873///
John McCalld79b4d82010-04-02 00:03:43 +0000874/// C++0x [class.access.base]p5:
875/// A member m is accessible at the point R when named in class N if
876/// [M1] m as a member of N is public, or
877/// [M2] m as a member of N is private, and R occurs in a member or
878/// friend of class N, or
879/// [M3] m as a member of N is protected, and R occurs in a member or
880/// friend of class N, or in a member or friend of a class P
881/// derived from N, where m as a member of P is public, private,
882/// or protected, or
883/// [M4] there exists a base class B of N that is accessible at R, and
884/// m is accessible at R when named in class B.
885///
886/// C++0x [class.access.base]p4:
887/// A base class B of N is accessible at R, if
888/// [B1] an invented public member of B would be a public member of N, or
889/// [B2] R occurs in a member or friend of class N, and an invented public
890/// member of B would be a private or protected member of N, or
891/// [B3] R occurs in a member or friend of a class P derived from N, and an
892/// invented public member of B would be a private or protected member
893/// of P, or
894/// [B4] there exists a class S such that B is a base class of S accessible
895/// at R and S is a base class of N accessible at R.
896///
897/// Along a single inheritance path we can restate both of these
898/// iteratively:
899///
900/// First, we note that M1-4 are equivalent to B1-4 if the member is
901/// treated as a notional base of its declaring class with inheritance
902/// access equivalent to the member's access. Therefore we need only
903/// ask whether a class B is accessible from a class N in context R.
904///
905/// Let B_1 .. B_n be the inheritance path in question (i.e. where
906/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
907/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
908/// closest accessible base in the path:
909/// Access(a, b) = (* access on the base specifier from a to b *)
910/// Merge(a, forbidden) = forbidden
911/// Merge(a, private) = forbidden
912/// Merge(a, b) = min(a,b)
913/// Accessible(c, forbidden) = false
914/// Accessible(c, private) = (R is c) || IsFriend(c, R)
915/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
916/// Accessible(c, public) = true
917/// ACAB(n) = public
918/// ACAB(i) =
919/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
920/// if Accessible(B_i, AccessToBase) then public else AccessToBase
921///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000922/// B is an accessible base of N at R iff ACAB(1) = public.
John McCalld79b4d82010-04-02 00:03:43 +0000923///
John McCalla8ae2222010-04-06 21:38:20 +0000924/// \param FinalAccess the access of the "final step", or AS_public if
John McCalla332b952010-03-18 23:49:19 +0000925/// there is no final step.
John McCall5b0829a2010-02-10 09:31:12 +0000926/// \return null if friendship is dependent
927static CXXBasePath *FindBestPath(Sema &S,
928 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +0000929 AccessTarget &Target,
John McCalla332b952010-03-18 23:49:19 +0000930 AccessSpecifier FinalAccess,
John McCall5b0829a2010-02-10 09:31:12 +0000931 CXXBasePaths &Paths) {
932 // Derive the paths to the desired base.
John McCalla8ae2222010-04-06 21:38:20 +0000933 const CXXRecordDecl *Derived = Target.getNamingClass();
934 const CXXRecordDecl *Base = Target.getDeclaringClass();
935
936 // FIXME: fail correctly when there are dependent paths.
937 bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
938 Paths);
John McCall5b0829a2010-02-10 09:31:12 +0000939 assert(isDerived && "derived class not actually derived from base");
940 (void) isDerived;
941
Craig Topperc3ec1492014-05-26 06:22:03 +0000942 CXXBasePath *BestPath = nullptr;
John McCall5b0829a2010-02-10 09:31:12 +0000943
John McCalla332b952010-03-18 23:49:19 +0000944 assert(FinalAccess != AS_none && "forbidden access after declaring class");
945
John McCallc62bb642010-03-24 05:22:00 +0000946 bool AnyDependent = false;
947
John McCall5b0829a2010-02-10 09:31:12 +0000948 // Derive the friend-modified access along each path.
949 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
950 PI != PE; ++PI) {
John McCalla8ae2222010-04-06 21:38:20 +0000951 AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +0000952
953 // Walk through the path backwards.
John McCalla332b952010-03-18 23:49:19 +0000954 AccessSpecifier PathAccess = FinalAccess;
John McCall5b0829a2010-02-10 09:31:12 +0000955 CXXBasePath::iterator I = PI->end(), E = PI->begin();
956 while (I != E) {
957 --I;
958
John McCalla332b952010-03-18 23:49:19 +0000959 assert(PathAccess != AS_none);
960
961 // If the declaration is a private member of a base class, there
962 // is no level of friendship in derived classes that can make it
963 // accessible.
964 if (PathAccess == AS_private) {
965 PathAccess = AS_none;
966 break;
967 }
968
John McCalla8ae2222010-04-06 21:38:20 +0000969 const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
970
John McCall5b0829a2010-02-10 09:31:12 +0000971 AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
John McCalld79b4d82010-04-02 00:03:43 +0000972 PathAccess = std::max(PathAccess, BaseAccess);
John McCalla8ae2222010-04-06 21:38:20 +0000973
974 switch (HasAccess(S, EC, NC, PathAccess, Target)) {
975 case AR_inaccessible: break;
976 case AR_accessible:
977 PathAccess = AS_public;
978
979 // Future tests are not against members and so do not have
980 // instance context.
981 Target.suppressInstanceContext();
982 break;
983 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +0000984 AnyDependent = true;
985 goto Next;
John McCall5b0829a2010-02-10 09:31:12 +0000986 }
John McCall5b0829a2010-02-10 09:31:12 +0000987 }
988
989 // Note that we modify the path's Access field to the
990 // friend-modified access.
Craig Topperc3ec1492014-05-26 06:22:03 +0000991 if (BestPath == nullptr || PathAccess < BestPath->Access) {
John McCall5b0829a2010-02-10 09:31:12 +0000992 BestPath = &*PI;
993 BestPath->Access = PathAccess;
John McCallc62bb642010-03-24 05:22:00 +0000994
995 // Short-circuit if we found a public path.
996 if (BestPath->Access == AS_public)
997 return BestPath;
John McCall5b0829a2010-02-10 09:31:12 +0000998 }
John McCallc62bb642010-03-24 05:22:00 +0000999
1000 Next: ;
John McCall5b0829a2010-02-10 09:31:12 +00001001 }
1002
John McCallc62bb642010-03-24 05:22:00 +00001003 assert((!BestPath || BestPath->Access != AS_public) &&
1004 "fell out of loop with public path");
1005
1006 // We didn't find a public path, but at least one path was subject
1007 // to dependent friendship, so delay the check.
1008 if (AnyDependent)
Craig Topperc3ec1492014-05-26 06:22:03 +00001009 return nullptr;
John McCallc62bb642010-03-24 05:22:00 +00001010
John McCall5b0829a2010-02-10 09:31:12 +00001011 return BestPath;
1012}
1013
John McCall417e7442010-09-03 04:56:05 +00001014/// Given that an entity has protected natural access, check whether
1015/// access might be denied because of the protected member access
1016/// restriction.
1017///
1018/// \return true if a note was emitted
1019static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1020 AccessTarget &Target) {
1021 // Only applies to instance accesses.
John McCall5dadb652012-04-07 03:04:20 +00001022 if (!Target.isInstanceMember())
John McCall417e7442010-09-03 04:56:05 +00001023 return false;
John McCall417e7442010-09-03 04:56:05 +00001024
John McCall5dadb652012-04-07 03:04:20 +00001025 assert(Target.isMemberAccess());
1026
John McCalld010ac92013-02-27 00:08:19 +00001027 const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
John McCall417e7442010-09-03 04:56:05 +00001028
1029 for (EffectiveContext::record_iterator
1030 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
1031 const CXXRecordDecl *ECRecord = *I;
John McCall5dadb652012-04-07 03:04:20 +00001032 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
John McCall417e7442010-09-03 04:56:05 +00001033 case AR_accessible: break;
1034 case AR_inaccessible: continue;
1035 case AR_dependent: continue;
1036 }
1037
1038 // The effective context is a subclass of the declaring class.
John McCall5dadb652012-04-07 03:04:20 +00001039 // Check whether the [class.protected] restriction is limiting
1040 // access.
John McCall417e7442010-09-03 04:56:05 +00001041
1042 // To get this exactly right, this might need to be checked more
1043 // holistically; it's not necessarily the case that gaining
1044 // access here would grant us access overall.
1045
John McCall5dadb652012-04-07 03:04:20 +00001046 NamedDecl *D = Target.getTargetDecl();
1047
1048 // If we don't have an instance context, [class.protected] says the
1049 // naming class has to equal the context class.
1050 if (!Target.hasInstanceContext()) {
1051 // If it does, the restriction doesn't apply.
1052 if (NamingClass == ECRecord) continue;
1053
1054 // TODO: it would be great to have a fixit here, since this is
1055 // such an obvious error.
1056 S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1057 << S.Context.getTypeDeclType(ECRecord);
1058 return true;
1059 }
1060
John McCall417e7442010-09-03 04:56:05 +00001061 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1062 assert(InstanceContext && "diagnosing dependent access");
1063
1064 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1065 case AR_accessible: continue;
1066 case AR_dependent: continue;
1067 case AR_inaccessible:
John McCall5dadb652012-04-07 03:04:20 +00001068 break;
1069 }
1070
1071 // Okay, the restriction seems to be what's limiting us.
1072
1073 // Use a special diagnostic for constructors and destructors.
1074 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
1075 (isa<FunctionTemplateDecl>(D) &&
1076 isa<CXXConstructorDecl>(
1077 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
Alp Tokera2794f92014-01-22 07:29:52 +00001078 return S.Diag(D->getLocation(),
1079 diag::note_access_protected_restricted_ctordtor)
1080 << isa<CXXDestructorDecl>(D->getAsFunction());
John McCall417e7442010-09-03 04:56:05 +00001081 }
John McCall5dadb652012-04-07 03:04:20 +00001082
1083 // Otherwise, use the generic diagnostic.
Alp Tokera2794f92014-01-22 07:29:52 +00001084 return S.Diag(D->getLocation(),
1085 diag::note_access_protected_restricted_object)
1086 << S.Context.getTypeDeclType(ECRecord);
John McCall417e7442010-09-03 04:56:05 +00001087 }
1088
1089 return false;
1090}
1091
John McCalld010ac92013-02-27 00:08:19 +00001092/// We are unable to access a given declaration due to its direct
1093/// access control; diagnose that.
1094static void diagnoseBadDirectAccess(Sema &S,
1095 const EffectiveContext &EC,
1096 AccessTarget &entity) {
1097 assert(entity.isMemberAccess());
1098 NamedDecl *D = entity.getTargetDecl();
1099
1100 if (D->getAccess() == AS_protected &&
1101 TryDiagnoseProtectedAccess(S, EC, entity))
1102 return;
1103
1104 // Find an original declaration.
1105 while (D->isOutOfLine()) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001106 NamedDecl *PrevDecl = nullptr;
John McCalld010ac92013-02-27 00:08:19 +00001107 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1108 PrevDecl = VD->getPreviousDecl();
1109 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1110 PrevDecl = FD->getPreviousDecl();
1111 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1112 PrevDecl = TND->getPreviousDecl();
1113 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1114 if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1115 break;
1116 PrevDecl = TD->getPreviousDecl();
1117 }
1118 if (!PrevDecl) break;
1119 D = PrevDecl;
1120 }
1121
1122 CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1123 Decl *ImmediateChild;
1124 if (D->getDeclContext() == DeclaringClass)
1125 ImmediateChild = D;
1126 else {
1127 DeclContext *DC = D->getDeclContext();
1128 while (DC->getParent() != DeclaringClass)
1129 DC = DC->getParent();
1130 ImmediateChild = cast<Decl>(DC);
1131 }
1132
1133 // Check whether there's an AccessSpecDecl preceding this in the
1134 // chain of the DeclContext.
1135 bool isImplicit = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00001136 for (const auto *I : DeclaringClass->decls()) {
1137 if (I == ImmediateChild) break;
1138 if (isa<AccessSpecDecl>(I)) {
John McCalld010ac92013-02-27 00:08:19 +00001139 isImplicit = false;
1140 break;
1141 }
1142 }
1143
1144 S.Diag(D->getLocation(), diag::note_access_natural)
1145 << (unsigned) (D->getAccess() == AS_protected)
1146 << isImplicit;
1147}
1148
John McCall5b0829a2010-02-10 09:31:12 +00001149/// Diagnose the path which caused the given declaration or base class
1150/// to become inaccessible.
1151static void DiagnoseAccessPath(Sema &S,
1152 const EffectiveContext &EC,
John McCalld010ac92013-02-27 00:08:19 +00001153 AccessTarget &entity) {
1154 // Save the instance context to preserve invariants.
1155 AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
John McCalld79b4d82010-04-02 00:03:43 +00001156
John McCalld010ac92013-02-27 00:08:19 +00001157 // This basically repeats the main algorithm but keeps some more
1158 // information.
John McCalld79b4d82010-04-02 00:03:43 +00001159
John McCalld010ac92013-02-27 00:08:19 +00001160 // The natural access so far.
1161 AccessSpecifier accessSoFar = AS_public;
John McCall417e7442010-09-03 04:56:05 +00001162
John McCalld010ac92013-02-27 00:08:19 +00001163 // Check whether we have special rights to the declaring class.
1164 if (entity.isMemberAccess()) {
1165 NamedDecl *D = entity.getTargetDecl();
1166 accessSoFar = D->getAccess();
1167 const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
John McCallf551aca2010-10-20 08:15:06 +00001168
John McCalld010ac92013-02-27 00:08:19 +00001169 switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1170 // If the declaration is accessible when named in its declaring
1171 // class, then we must be constrained by the path.
1172 case AR_accessible:
1173 accessSoFar = AS_public;
1174 entity.suppressInstanceContext();
1175 break;
John McCallf551aca2010-10-20 08:15:06 +00001176
John McCalld010ac92013-02-27 00:08:19 +00001177 case AR_inaccessible:
1178 if (accessSoFar == AS_private ||
1179 declaringClass == entity.getEffectiveNamingClass())
1180 return diagnoseBadDirectAccess(S, EC, entity);
1181 break;
John McCall5b0829a2010-02-10 09:31:12 +00001182
John McCalla8ae2222010-04-06 21:38:20 +00001183 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001184 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001185 }
1186 }
1187
John McCalld010ac92013-02-27 00:08:19 +00001188 CXXBasePaths paths;
1189 CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1190 assert(path.Access != AS_public);
John McCall5b0829a2010-02-10 09:31:12 +00001191
John McCalld010ac92013-02-27 00:08:19 +00001192 CXXBasePath::iterator i = path.end(), e = path.begin();
1193 CXXBasePath::iterator constrainingBase = i;
1194 while (i != e) {
1195 --i;
John McCall5b0829a2010-02-10 09:31:12 +00001196
John McCalld010ac92013-02-27 00:08:19 +00001197 assert(accessSoFar != AS_none && accessSoFar != AS_private);
John McCall5b0829a2010-02-10 09:31:12 +00001198
John McCalld010ac92013-02-27 00:08:19 +00001199 // Is the entity accessible when named in the deriving class, as
1200 // modified by the base specifier?
1201 const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1202 const CXXBaseSpecifier *base = i->Base;
John McCall5b0829a2010-02-10 09:31:12 +00001203
John McCalld010ac92013-02-27 00:08:19 +00001204 // If the access to this base is worse than the access we have to
1205 // the declaration, remember it.
1206 AccessSpecifier baseAccess = base->getAccessSpecifier();
1207 if (baseAccess > accessSoFar) {
1208 constrainingBase = i;
1209 accessSoFar = baseAccess;
1210 }
1211
1212 switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001213 case AR_inaccessible: break;
John McCalld010ac92013-02-27 00:08:19 +00001214 case AR_accessible:
1215 accessSoFar = AS_public;
1216 entity.suppressInstanceContext();
Craig Topperc3ec1492014-05-26 06:22:03 +00001217 constrainingBase = nullptr;
John McCalld010ac92013-02-27 00:08:19 +00001218 break;
John McCalla8ae2222010-04-06 21:38:20 +00001219 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001220 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001221 }
1222
John McCalld010ac92013-02-27 00:08:19 +00001223 // If this was private inheritance, but we don't have access to
1224 // the deriving class, we're done.
1225 if (accessSoFar == AS_private) {
1226 assert(baseAccess == AS_private);
1227 assert(constrainingBase == i);
1228 break;
John McCall5b0829a2010-02-10 09:31:12 +00001229 }
1230 }
1231
John McCalld010ac92013-02-27 00:08:19 +00001232 // If we don't have a constraining base, the access failure must be
1233 // due to the original declaration.
1234 if (constrainingBase == path.end())
1235 return diagnoseBadDirectAccess(S, EC, entity);
1236
1237 // We're constrained by inheritance, but we want to say
1238 // "declared private here" if we're diagnosing a hierarchy
1239 // conversion and this is the final step.
1240 unsigned diagnostic;
1241 if (entity.isMemberAccess() ||
1242 constrainingBase + 1 != path.end()) {
1243 diagnostic = diag::note_access_constrained_by_path;
1244 } else {
1245 diagnostic = diag::note_access_natural;
1246 }
1247
1248 const CXXBaseSpecifier *base = constrainingBase->Base;
1249
1250 S.Diag(base->getSourceRange().getBegin(), diagnostic)
1251 << base->getSourceRange()
1252 << (base->getAccessSpecifier() == AS_protected)
1253 << (base->getAccessSpecifierAsWritten() == AS_none);
1254
1255 if (entity.isMemberAccess())
Alp Toker2afa8782014-05-28 12:20:14 +00001256 S.Diag(entity.getTargetDecl()->getLocation(),
1257 diag::note_member_declared_at);
John McCall5b0829a2010-02-10 09:31:12 +00001258}
1259
John McCall1064d7e2010-03-16 05:22:47 +00001260static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
John McCall5b0829a2010-02-10 09:31:12 +00001261 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +00001262 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001263 const CXXRecordDecl *NamingClass = Entity.getNamingClass();
John McCalla8ae2222010-04-06 21:38:20 +00001264 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00001265 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : nullptr);
John McCalld79b4d82010-04-02 00:03:43 +00001266
1267 S.Diag(Loc, Entity.getDiag())
1268 << (Entity.getAccess() == AS_protected)
1269 << (D ? D->getDeclName() : DeclarationName())
1270 << S.Context.getTypeDeclType(NamingClass)
1271 << S.Context.getTypeDeclType(DeclaringClass);
1272 DiagnoseAccessPath(S, EC, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001273}
1274
Francois Pichetefb1af92011-05-23 03:43:44 +00001275/// MSVC has a bug where if during an using declaration name lookup,
1276/// the declaration found is unaccessible (private) and that declaration
1277/// was bring into scope via another using declaration whose target
1278/// declaration is accessible (public) then no error is generated.
1279/// Example:
1280/// class A {
1281/// public:
1282/// int f();
1283/// };
1284/// class B : public A {
1285/// private:
1286/// using A::f;
1287/// };
1288/// class C : public B {
1289/// private:
1290/// using B::f;
1291/// };
1292///
1293/// Here, B::f is private so this should fail in Standard C++, but
1294/// because B::f refers to A::f which is public MSVC accepts it.
1295static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1296 SourceLocation AccessLoc,
1297 AccessTarget &Entity) {
1298 if (UsingShadowDecl *Shadow =
1299 dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1300 const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1301 if (Entity.getTargetDecl()->getAccess() == AS_private &&
1302 (OrigDecl->getAccess() == AS_public ||
1303 OrigDecl->getAccess() == AS_protected)) {
Richard Smithe4345902011-12-29 21:57:33 +00001304 S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
Francois Pichetefb1af92011-05-23 03:43:44 +00001305 << Shadow->getUsingDecl()->getQualifiedNameAsString()
1306 << OrigDecl->getQualifiedNameAsString();
1307 return true;
1308 }
1309 }
1310 return false;
1311}
1312
John McCalld79b4d82010-04-02 00:03:43 +00001313/// Determines whether the accessed entity is accessible. Public members
1314/// have been weeded out by this point.
John McCalla8ae2222010-04-06 21:38:20 +00001315static AccessResult IsAccessible(Sema &S,
1316 const EffectiveContext &EC,
1317 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001318 // Determine the actual naming class.
John McCalld010ac92013-02-27 00:08:19 +00001319 const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
John McCall5b0829a2010-02-10 09:31:12 +00001320
John McCalld79b4d82010-04-02 00:03:43 +00001321 AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1322 assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1323
1324 // Before we try to recalculate access paths, try to white-list
1325 // accesses which just trade in on the final step, i.e. accesses
1326 // which don't require [M4] or [B4]. These are by far the most
John McCalla8ae2222010-04-06 21:38:20 +00001327 // common forms of privileged access.
John McCalld79b4d82010-04-02 00:03:43 +00001328 if (UnprivilegedAccess != AS_none) {
John McCalla8ae2222010-04-06 21:38:20 +00001329 switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1330 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +00001331 // This is actually an interesting policy decision. We don't
1332 // *have* to delay immediately here: we can do the full access
1333 // calculation in the hope that friendship on some intermediate
1334 // class will make the declaration accessible non-dependently.
1335 // But that's not cheap, and odds are very good (note: assertion
1336 // made without data) that the friend declaration will determine
1337 // access.
John McCalla8ae2222010-04-06 21:38:20 +00001338 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001339
John McCalla8ae2222010-04-06 21:38:20 +00001340 case AR_accessible: return AR_accessible;
1341 case AR_inaccessible: break;
John McCalld79b4d82010-04-02 00:03:43 +00001342 }
1343 }
1344
John McCalla8ae2222010-04-06 21:38:20 +00001345 AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +00001346
John McCalld79b4d82010-04-02 00:03:43 +00001347 // We lower member accesses to base accesses by pretending that the
1348 // member is a base class of its declaring class.
1349 AccessSpecifier FinalAccess;
1350
John McCall5b0829a2010-02-10 09:31:12 +00001351 if (Entity.isMemberAccess()) {
John McCalld79b4d82010-04-02 00:03:43 +00001352 // Determine if the declaration is accessible from EC when named
1353 // in its declaring class.
John McCall5b0829a2010-02-10 09:31:12 +00001354 NamedDecl *Target = Entity.getTargetDecl();
John McCalla8ae2222010-04-06 21:38:20 +00001355 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCall5b0829a2010-02-10 09:31:12 +00001356
John McCalld79b4d82010-04-02 00:03:43 +00001357 FinalAccess = Target->getAccess();
John McCalla8ae2222010-04-06 21:38:20 +00001358 switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1359 case AR_accessible:
John McCall5149fbf2013-02-22 03:52:55 +00001360 // Target is accessible at EC when named in its declaring class.
1361 // We can now hill-climb and simply check whether the declaring
1362 // class is accessible as a base of the naming class. This is
1363 // equivalent to checking the access of a notional public
1364 // member with no instance context.
John McCalla8ae2222010-04-06 21:38:20 +00001365 FinalAccess = AS_public;
John McCall5149fbf2013-02-22 03:52:55 +00001366 Entity.suppressInstanceContext();
John McCalla8ae2222010-04-06 21:38:20 +00001367 break;
1368 case AR_inaccessible: break;
1369 case AR_dependent: return AR_dependent; // see above
John McCall5b0829a2010-02-10 09:31:12 +00001370 }
1371
John McCalld79b4d82010-04-02 00:03:43 +00001372 if (DeclaringClass == NamingClass)
John McCalla8ae2222010-04-06 21:38:20 +00001373 return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
John McCalld79b4d82010-04-02 00:03:43 +00001374 } else {
1375 FinalAccess = AS_public;
John McCall5b0829a2010-02-10 09:31:12 +00001376 }
1377
John McCalla8ae2222010-04-06 21:38:20 +00001378 assert(Entity.getDeclaringClass() != NamingClass);
John McCall5b0829a2010-02-10 09:31:12 +00001379
1380 // Append the declaration's access if applicable.
1381 CXXBasePaths Paths;
John McCalla8ae2222010-04-06 21:38:20 +00001382 CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
John McCallc62bb642010-03-24 05:22:00 +00001383 if (!Path)
John McCalla8ae2222010-04-06 21:38:20 +00001384 return AR_dependent;
John McCall553c0792010-01-23 00:46:32 +00001385
John McCalld79b4d82010-04-02 00:03:43 +00001386 assert(Path->Access <= UnprivilegedAccess &&
1387 "access along best path worse than direct?");
1388 if (Path->Access == AS_public)
John McCalla8ae2222010-04-06 21:38:20 +00001389 return AR_accessible;
1390 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +00001391}
1392
John McCalla8ae2222010-04-06 21:38:20 +00001393static void DelayDependentAccess(Sema &S,
1394 const EffectiveContext &EC,
1395 SourceLocation Loc,
1396 const AccessTarget &Entity) {
John McCallc62bb642010-03-24 05:22:00 +00001397 assert(EC.isDependent() && "delaying non-dependent access");
John McCall816d75b2010-03-24 07:46:06 +00001398 DeclContext *DC = EC.getInnerContext();
John McCallc62bb642010-03-24 05:22:00 +00001399 assert(DC->isDependentContext() && "delaying non-dependent access");
1400 DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1401 Loc,
1402 Entity.isMemberAccess(),
1403 Entity.getAccess(),
1404 Entity.getTargetDecl(),
1405 Entity.getNamingClass(),
John McCalla8ae2222010-04-06 21:38:20 +00001406 Entity.getBaseObjectType(),
John McCallc62bb642010-03-24 05:22:00 +00001407 Entity.getDiag());
John McCall553c0792010-01-23 00:46:32 +00001408}
1409
John McCall5b0829a2010-02-10 09:31:12 +00001410/// Checks access to an entity from the given effective context.
John McCalla8ae2222010-04-06 21:38:20 +00001411static AccessResult CheckEffectiveAccess(Sema &S,
1412 const EffectiveContext &EC,
1413 SourceLocation Loc,
1414 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001415 assert(Entity.getAccess() != AS_public && "called for public access!");
John McCall553c0792010-01-23 00:46:32 +00001416
John McCalld79b4d82010-04-02 00:03:43 +00001417 switch (IsAccessible(S, EC, Entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001418 case AR_dependent:
1419 DelayDependentAccess(S, EC, Loc, Entity);
1420 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001421
John McCalla8ae2222010-04-06 21:38:20 +00001422 case AR_inaccessible:
Reid Kleckner42063b02014-02-08 02:40:20 +00001423 if (S.getLangOpts().MSVCCompat &&
1424 IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1425 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +00001426 if (!Entity.isQuiet())
1427 DiagnoseBadAccess(S, Loc, EC, Entity);
John McCalla8ae2222010-04-06 21:38:20 +00001428 return AR_inaccessible;
John McCalld79b4d82010-04-02 00:03:43 +00001429
John McCalla8ae2222010-04-06 21:38:20 +00001430 case AR_accessible:
1431 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +00001432 }
1433
John McCalla8ae2222010-04-06 21:38:20 +00001434 // silence unnecessary warning
1435 llvm_unreachable("invalid access result");
John McCall5b0829a2010-02-10 09:31:12 +00001436}
John McCall553c0792010-01-23 00:46:32 +00001437
John McCall5b0829a2010-02-10 09:31:12 +00001438static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
John McCalla8ae2222010-04-06 21:38:20 +00001439 AccessTarget &Entity) {
John McCall5b0829a2010-02-10 09:31:12 +00001440 // If the access path is public, it's accessible everywhere.
1441 if (Entity.getAccess() == AS_public)
1442 return Sema::AR_accessible;
John McCall553c0792010-01-23 00:46:32 +00001443
John McCallc1465822011-02-14 07:13:47 +00001444 // If we're currently parsing a declaration, we may need to delay
1445 // access control checking, because our effective context might be
1446 // different based on what the declaration comes out as.
1447 //
1448 // For example, we might be parsing a declaration with a scope
1449 // specifier, like this:
1450 // A::private_type A::foo() { ... }
1451 //
1452 // Or we might be parsing something that will turn out to be a friend:
1453 // void foo(A::private_type);
1454 // void B::foo(A::private_type);
1455 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1456 S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
John McCall5b0829a2010-02-10 09:31:12 +00001457 return Sema::AR_delayed;
John McCall553c0792010-01-23 00:46:32 +00001458 }
1459
John McCalla8ae2222010-04-06 21:38:20 +00001460 EffectiveContext EC(S.CurContext);
1461 switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1462 case AR_accessible: return Sema::AR_accessible;
1463 case AR_inaccessible: return Sema::AR_inaccessible;
1464 case AR_dependent: return Sema::AR_dependent;
1465 }
Davide Italiano24e89662015-05-17 02:27:10 +00001466 llvm_unreachable("invalid access result");
John McCall553c0792010-01-23 00:46:32 +00001467}
1468
Richard Smithad5c1ca2013-04-29 10:13:55 +00001469void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
John McCall9743e8d2011-02-15 22:51:53 +00001470 // Access control for names used in the declarations of functions
1471 // and function templates should normally be evaluated in the context
1472 // of the declaration, just in case it's a friend of something.
1473 // However, this does not apply to local extern declarations.
1474
Richard Smithad5c1ca2013-04-29 10:13:55 +00001475 DeclContext *DC = D->getDeclContext();
Richard Smith608da012013-12-11 03:35:27 +00001476 if (D->isLocalExternDecl()) {
1477 DC = D->getLexicalDeclContext();
1478 } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1479 DC = FN;
Richard Smithad5c1ca2013-04-29 10:13:55 +00001480 } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1481 DC = cast<DeclContext>(TD->getTemplatedDecl());
John McCall9743e8d2011-02-15 22:51:53 +00001482 }
1483
Chandler Carruthaad30072010-04-18 08:23:21 +00001484 EffectiveContext EC(DC);
John McCall86121512010-01-27 03:50:35 +00001485
John McCalla8ae2222010-04-06 21:38:20 +00001486 AccessTarget Target(DD.getAccessData());
1487
1488 if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
John McCall86121512010-01-27 03:50:35 +00001489 DD.Triggered = true;
1490}
1491
John McCallc62bb642010-03-24 05:22:00 +00001492void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1493 const MultiLevelTemplateArgumentList &TemplateArgs) {
1494 SourceLocation Loc = DD.getAccessLoc();
1495 AccessSpecifier Access = DD.getAccess();
1496
1497 Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1498 TemplateArgs);
1499 if (!NamingD) return;
1500 Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1501 TemplateArgs);
1502 if (!TargetD) return;
1503
1504 if (DD.isAccessToMember()) {
John McCalla8ae2222010-04-06 21:38:20 +00001505 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1506 NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1507 QualType BaseObjectType = DD.getAccessBaseObjectType();
1508 if (!BaseObjectType.isNull()) {
1509 BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1510 DeclarationName());
1511 if (BaseObjectType.isNull()) return;
1512 }
1513
1514 AccessTarget Entity(Context,
1515 AccessTarget::Member,
1516 NamingClass,
1517 DeclAccessPair::make(TargetDecl, Access),
1518 BaseObjectType);
John McCallc62bb642010-03-24 05:22:00 +00001519 Entity.setDiag(DD.getDiagnostic());
1520 CheckAccess(*this, Loc, Entity);
1521 } else {
John McCalla8ae2222010-04-06 21:38:20 +00001522 AccessTarget Entity(Context,
1523 AccessTarget::Base,
1524 cast<CXXRecordDecl>(TargetD),
1525 cast<CXXRecordDecl>(NamingD),
1526 Access);
John McCallc62bb642010-03-24 05:22:00 +00001527 Entity.setDiag(DD.getDiagnostic());
1528 CheckAccess(*this, Loc, Entity);
1529 }
1530}
1531
John McCall5b0829a2010-02-10 09:31:12 +00001532Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001533 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001534 if (!getLangOpts().AccessControl ||
John McCall1064d7e2010-03-16 05:22:47 +00001535 !E->getNamingClass() ||
John McCalla0296f72010-03-19 07:35:19 +00001536 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001537 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001538
John McCalla8ae2222010-04-06 21:38:20 +00001539 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1540 Found, QualType());
John McCall1064d7e2010-03-16 05:22:47 +00001541 Entity.setDiag(diag::err_access) << E->getSourceRange();
1542
1543 return CheckAccess(*this, E->getNameLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001544}
1545
1546/// Perform access-control checking on a previously-unresolved member
1547/// access which has now been resolved to a member.
John McCall5b0829a2010-02-10 09:31:12 +00001548Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001549 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001550 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001551 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001552 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001553
John McCalla8ae2222010-04-06 21:38:20 +00001554 QualType BaseType = E->getBaseType();
1555 if (E->isArrow())
1556 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1557
1558 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1559 Found, BaseType);
John McCall1064d7e2010-03-16 05:22:47 +00001560 Entity.setDiag(diag::err_access) << E->getSourceRange();
1561
1562 return CheckAccess(*this, E->getMemberLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001563}
1564
John McCalld4274212012-04-09 20:53:23 +00001565/// Is the given special member function accessible for the purposes of
1566/// deciding whether to define a special member function as deleted?
1567bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
1568 AccessSpecifier access,
1569 QualType objectType) {
1570 // Fast path.
1571 if (access == AS_public || !getLangOpts().AccessControl) return true;
1572
1573 AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
1574 DeclAccessPair::make(decl, access), objectType);
1575
1576 // Suppress diagnostics.
1577 entity.setDiag(PDiag());
1578
1579 switch (CheckAccess(*this, SourceLocation(), entity)) {
1580 case AR_accessible: return true;
1581 case AR_inaccessible: return false;
1582 case AR_dependent: llvm_unreachable("dependent for =delete computation");
1583 case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1584 }
1585 llvm_unreachable("bad access result");
1586}
1587
John McCall5b0829a2010-02-10 09:31:12 +00001588Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
John McCall1064d7e2010-03-16 05:22:47 +00001589 CXXDestructorDecl *Dtor,
John McCall5dadb652012-04-07 03:04:20 +00001590 const PartialDiagnostic &PDiag,
1591 QualType ObjectTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 if (!getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001593 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001594
John McCall1064d7e2010-03-16 05:22:47 +00001595 // There's never a path involved when checking implicit destructor access.
John McCall6781b052010-02-02 08:45:54 +00001596 AccessSpecifier Access = Dtor->getAccess();
1597 if (Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001598 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001599
John McCall1064d7e2010-03-16 05:22:47 +00001600 CXXRecordDecl *NamingClass = Dtor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001601 if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
1602
John McCalla8ae2222010-04-06 21:38:20 +00001603 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1604 DeclAccessPair::make(Dtor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001605 ObjectTy);
John McCall1064d7e2010-03-16 05:22:47 +00001606 Entity.setDiag(PDiag); // TODO: avoid copy
1607
1608 return CheckAccess(*this, Loc, Entity);
John McCall6781b052010-02-02 08:45:54 +00001609}
1610
John McCall760af172010-02-01 03:16:54 +00001611/// Checks access to a constructor.
John McCall5b0829a2010-02-10 09:31:12 +00001612Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001613 CXXConstructorDecl *Constructor,
Richard Smith5179eb72016-06-28 19:03:57 +00001614 DeclAccessPair Found,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001615 const InitializedEntity &Entity,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001616 bool IsCopyBindingRefToTemp) {
Richard Smith5179eb72016-06-28 19:03:57 +00001617 if (!getLangOpts().AccessControl || Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001618 return AR_accessible;
John McCall760af172010-02-01 03:16:54 +00001619
Alexis Hunteef8ee02011-06-10 03:50:41 +00001620 PartialDiagnostic PD(PDiag());
Anders Carlssona01874b2010-04-21 18:47:17 +00001621 switch (Entity.getKind()) {
1622 default:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001623 PD = PDiag(IsCopyBindingRefToTemp
1624 ? diag::ext_rvalue_to_reference_access_ctor
1625 : diag::err_access_ctor);
1626
Anders Carlssona01874b2010-04-21 18:47:17 +00001627 break;
John McCall1064d7e2010-03-16 05:22:47 +00001628
Anders Carlsson05bf0092010-04-22 05:40:53 +00001629 case InitializedEntity::EK_Base:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001630 PD = PDiag(diag::err_access_base_ctor);
1631 PD << Entity.isInheritedVirtualBase()
1632 << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
Anders Carlssona01874b2010-04-21 18:47:17 +00001633 break;
Anders Carlsson05bf0092010-04-22 05:40:53 +00001634
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001635 case InitializedEntity::EK_Member: {
1636 const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00001637 PD = PDiag(diag::err_access_field_ctor);
1638 PD << Field->getType() << getSpecialMember(Constructor);
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001639 break;
1640 }
Anders Carlssona01874b2010-04-21 18:47:17 +00001641
Douglas Gregor19666fb2012-02-15 16:57:26 +00001642 case InitializedEntity::EK_LambdaCapture: {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001643 StringRef VarName = Entity.getCapturedVarName();
Douglas Gregor19666fb2012-02-15 16:57:26 +00001644 PD = PDiag(diag::err_access_lambda_capture);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001645 PD << VarName << Entity.getType() << getSpecialMember(Constructor);
Douglas Gregor19666fb2012-02-15 16:57:26 +00001646 break;
1647 }
1648
Anders Carlsson43c64af2010-04-21 19:52:01 +00001649 }
1650
Richard Smith5179eb72016-06-28 19:03:57 +00001651 return CheckConstructorAccess(UseLoc, Constructor, Found, Entity, PD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00001652}
1653
1654/// Checks access to a constructor.
1655Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1656 CXXConstructorDecl *Constructor,
Richard Smith5179eb72016-06-28 19:03:57 +00001657 DeclAccessPair Found,
John McCall5dadb652012-04-07 03:04:20 +00001658 const InitializedEntity &Entity,
John McCall5dadb652012-04-07 03:04:20 +00001659 const PartialDiagnostic &PD) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (!getLangOpts().AccessControl ||
Richard Smith5179eb72016-06-28 19:03:57 +00001661 Found.getAccess() == AS_public)
Alexis Hunteef8ee02011-06-10 03:50:41 +00001662 return AR_accessible;
1663
1664 CXXRecordDecl *NamingClass = Constructor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001665
1666 // Initializing a base sub-object is an instance method call on an
1667 // object of the derived class. Otherwise, we have an instance method
1668 // call on an object of the constructed type.
Richard Smithbbbe6182016-03-08 23:17:35 +00001669 //
1670 // FIXME: If we have a parent, we're initializing the base class subobject
1671 // in aggregate initialization. It's not clear whether the object class
1672 // should be the base class or the derived class in that case.
John McCall5dadb652012-04-07 03:04:20 +00001673 CXXRecordDecl *ObjectClass;
Richard Smith5179eb72016-06-28 19:03:57 +00001674 if ((Entity.getKind() == InitializedEntity::EK_Base ||
1675 Entity.getKind() == InitializedEntity::EK_Delegating) &&
1676 !Entity.getParent()) {
John McCall5dadb652012-04-07 03:04:20 +00001677 ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
Richard Smith5179eb72016-06-28 19:03:57 +00001678 } else if (auto *Shadow =
1679 dyn_cast<ConstructorUsingShadowDecl>(Found.getDecl())) {
1680 // If we're using an inheriting constructor to construct an object,
1681 // the object class is the derived class, not the base class.
1682 ObjectClass = Shadow->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001683 } else {
1684 ObjectClass = NamingClass;
1685 }
1686
Richard Smith5179eb72016-06-28 19:03:57 +00001687 AccessTarget AccessEntity(
1688 Context, AccessTarget::Member, NamingClass,
1689 DeclAccessPair::make(Constructor, Found.getAccess()),
1690 Context.getTypeDeclType(ObjectClass));
Alexis Hunteef8ee02011-06-10 03:50:41 +00001691 AccessEntity.setDiag(PD);
1692
Anders Carlssona01874b2010-04-21 18:47:17 +00001693 return CheckAccess(*this, UseLoc, AccessEntity);
John McCall5dadb652012-04-07 03:04:20 +00001694}
John McCall760af172010-02-01 03:16:54 +00001695
John McCallfb6f5262010-03-18 08:19:33 +00001696/// Checks access to an overloaded operator new or delete.
1697Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1698 SourceRange PlacementRange,
1699 CXXRecordDecl *NamingClass,
Alexis Huntf91729462011-05-12 22:46:25 +00001700 DeclAccessPair Found,
1701 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001702 if (!getLangOpts().AccessControl ||
John McCallfb6f5262010-03-18 08:19:33 +00001703 !NamingClass ||
John McCalla0296f72010-03-19 07:35:19 +00001704 Found.getAccess() == AS_public)
John McCallfb6f5262010-03-18 08:19:33 +00001705 return AR_accessible;
1706
John McCalla8ae2222010-04-06 21:38:20 +00001707 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1708 QualType());
Alexis Huntf91729462011-05-12 22:46:25 +00001709 if (Diagnose)
1710 Entity.setDiag(diag::err_access)
1711 << PlacementRange;
John McCallfb6f5262010-03-18 08:19:33 +00001712
1713 return CheckAccess(*this, OpLoc, Entity);
1714}
1715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001716/// Checks access to a member.
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001717Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1718 CXXRecordDecl *NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001719 DeclAccessPair Found) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001720 if (!getLangOpts().AccessControl ||
1721 !NamingClass ||
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001722 Found.getAccess() == AS_public)
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001723 return AR_accessible;
1724
1725 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001726 Found, QualType());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001727
1728 return CheckAccess(*this, UseLoc, Entity);
1729}
1730
John McCall760af172010-02-01 03:16:54 +00001731/// Checks access to an overloaded member operator, including
1732/// conversion operators.
John McCall5b0829a2010-02-10 09:31:12 +00001733Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1734 Expr *ObjectExpr,
John McCall1064d7e2010-03-16 05:22:47 +00001735 Expr *ArgExpr,
John McCalla0296f72010-03-19 07:35:19 +00001736 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001737 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001738 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001739 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001740
John McCall30909032011-09-21 08:36:56 +00001741 const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
John McCallb3a44002010-01-28 01:42:12 +00001742 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1743
John McCalla8ae2222010-04-06 21:38:20 +00001744 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1745 ObjectExpr->getType());
John McCall1064d7e2010-03-16 05:22:47 +00001746 Entity.setDiag(diag::err_access)
1747 << ObjectExpr->getSourceRange()
1748 << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
1749
1750 return CheckAccess(*this, OpLoc, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001751}
John McCallb3a44002010-01-28 01:42:12 +00001752
John McCalla0a96892012-08-10 03:15:35 +00001753/// Checks access to the target of a friend declaration.
1754Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
Alp Tokera2794f92014-01-22 07:29:52 +00001755 assert(isa<CXXMethodDecl>(target->getAsFunction()));
John McCalla0a96892012-08-10 03:15:35 +00001756
1757 // Friendship lookup is a redeclaration lookup, so there's never an
1758 // inheritance path modifying access.
1759 AccessSpecifier access = target->getAccess();
1760
1761 if (!getLangOpts().AccessControl || access == AS_public)
1762 return AR_accessible;
1763
Alp Toker2bd4a282014-01-22 07:53:08 +00001764 CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
John McCalla0a96892012-08-10 03:15:35 +00001765
1766 AccessTarget entity(Context, AccessTarget::Member,
1767 cast<CXXRecordDecl>(target->getDeclContext()),
1768 DeclAccessPair::make(target, access),
1769 /*no instance context*/ QualType());
1770 entity.setDiag(diag::err_access_friend_function)
Reid Kleckneraf9bf592014-12-17 23:40:46 +00001771 << (method->getQualifier() ? method->getQualifierLoc().getSourceRange()
1772 : method->getNameInfo().getSourceRange());
John McCalla0a96892012-08-10 03:15:35 +00001773
1774 // We need to bypass delayed-diagnostics because we might be called
1775 // while the ParsingDeclarator is active.
1776 EffectiveContext EC(CurContext);
1777 switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
Etienne Bergeron47533022016-06-01 21:17:32 +00001778 case ::AR_accessible: return Sema::AR_accessible;
1779 case ::AR_inaccessible: return Sema::AR_inaccessible;
1780 case ::AR_dependent: return Sema::AR_dependent;
John McCalla0a96892012-08-10 03:15:35 +00001781 }
Davide Italiano9b950d82015-07-29 20:55:04 +00001782 llvm_unreachable("invalid access result");
John McCalla0a96892012-08-10 03:15:35 +00001783}
1784
John McCall16df1e52010-03-30 21:47:33 +00001785Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1786 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001787 if (!getLangOpts().AccessControl ||
John McCallb493d532010-03-30 22:20:00 +00001788 Found.getAccess() == AS_none ||
John McCall16df1e52010-03-30 21:47:33 +00001789 Found.getAccess() == AS_public)
1790 return AR_accessible;
1791
John McCall8d08b9b2010-08-27 09:08:28 +00001792 OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
John McCall8c12dc42010-04-22 18:44:12 +00001793 CXXRecordDecl *NamingClass = Ovl->getNamingClass();
John McCall16df1e52010-03-30 21:47:33 +00001794
John McCalla8ae2222010-04-06 21:38:20 +00001795 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
John McCall5dadb652012-04-07 03:04:20 +00001796 /*no instance context*/ QualType());
John McCall16df1e52010-03-30 21:47:33 +00001797 Entity.setDiag(diag::err_access)
1798 << Ovl->getSourceRange();
1799
1800 return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1801}
1802
John McCall5b0829a2010-02-10 09:31:12 +00001803/// Checks access for a hierarchy conversion.
1804///
John McCall5b0829a2010-02-10 09:31:12 +00001805/// \param ForceCheck true if this check should be performed even if access
1806/// control is disabled; some things rely on this for semantics
1807/// \param ForceUnprivileged true if this check should proceed as if the
1808/// context had no special privileges
John McCall5b0829a2010-02-10 09:31:12 +00001809Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
John McCall5b0829a2010-02-10 09:31:12 +00001810 QualType Base,
1811 QualType Derived,
1812 const CXXBasePath &Path,
John McCall1064d7e2010-03-16 05:22:47 +00001813 unsigned DiagID,
John McCall5b0829a2010-02-10 09:31:12 +00001814 bool ForceCheck,
John McCall1064d7e2010-03-16 05:22:47 +00001815 bool ForceUnprivileged) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001816 if (!ForceCheck && !getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001817 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001818
John McCall5b0829a2010-02-10 09:31:12 +00001819 if (Path.Access == AS_public)
1820 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001821
John McCall5b0829a2010-02-10 09:31:12 +00001822 CXXRecordDecl *BaseD, *DerivedD;
1823 BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1824 DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
John McCall1064d7e2010-03-16 05:22:47 +00001825
John McCalla8ae2222010-04-06 21:38:20 +00001826 AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1827 Path.Access);
John McCall1064d7e2010-03-16 05:22:47 +00001828 if (DiagID)
1829 Entity.setDiag(DiagID) << Derived << Base;
John McCall5b0829a2010-02-10 09:31:12 +00001830
John McCalla8ae2222010-04-06 21:38:20 +00001831 if (ForceUnprivileged) {
1832 switch (CheckEffectiveAccess(*this, EffectiveContext(),
1833 AccessLoc, Entity)) {
1834 case ::AR_accessible: return Sema::AR_accessible;
1835 case ::AR_inaccessible: return Sema::AR_inaccessible;
1836 case ::AR_dependent: return Sema::AR_dependent;
1837 }
1838 llvm_unreachable("unexpected result from CheckEffectiveAccess");
1839 }
John McCall1064d7e2010-03-16 05:22:47 +00001840 return CheckAccess(*this, AccessLoc, Entity);
John McCallb3a44002010-01-28 01:42:12 +00001841}
1842
John McCall553c0792010-01-23 00:46:32 +00001843/// Checks access to all the declarations in the given result set.
John McCall5b0829a2010-02-10 09:31:12 +00001844void Sema::CheckLookupAccess(const LookupResult &R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001845 assert(getLangOpts().AccessControl
John McCall5b0829a2010-02-10 09:31:12 +00001846 && "performing access check without access control");
1847 assert(R.getNamingClass() && "performing access check without naming class");
1848
John McCall1064d7e2010-03-16 05:22:47 +00001849 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1850 if (I.getAccess() != AS_public) {
John McCalla8ae2222010-04-06 21:38:20 +00001851 AccessTarget Entity(Context, AccessedEntity::Member,
1852 R.getNamingClass(), I.getPair(),
Erik Verbruggen631dfc62011-09-19 15:10:40 +00001853 R.getBaseObjectType());
John McCall1064d7e2010-03-16 05:22:47 +00001854 Entity.setDiag(diag::err_access);
John McCall1064d7e2010-03-16 05:22:47 +00001855 CheckAccess(*this, R.getNameLoc(), Entity);
1856 }
1857 }
John McCall553c0792010-01-23 00:46:32 +00001858}
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001859
Eric Liu18b404a2018-07-19 13:32:00 +00001860/// Checks access to Target from the given class. The check will take access
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001861/// specifiers into account, but no member access expressions and such.
1862///
Eric Liu18b404a2018-07-19 13:32:00 +00001863/// \param Target the declaration to check if it can be accessed
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001864/// \param Ctx the class/context from which to start the search
Eric Liu18b404a2018-07-19 13:32:00 +00001865/// \return true if the Target is accessible from the Class, false otherwise.
1866bool Sema::IsSimplyAccessible(NamedDecl *Target, DeclContext *Ctx) {
Douglas Gregor03ba1882011-11-03 16:51:37 +00001867 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) {
Eric Liu18b404a2018-07-19 13:32:00 +00001868 if (!Target->isCXXClassMember())
Douglas Gregor03ba1882011-11-03 16:51:37 +00001869 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001870
Eric Liu18b404a2018-07-19 13:32:00 +00001871 if (Target->getAccess() == AS_public)
1872 return true;
Douglas Gregor03ba1882011-11-03 16:51:37 +00001873 QualType qType = Class->getTypeForDecl()->getCanonicalTypeInternal();
Eric Liu18b404a2018-07-19 13:32:00 +00001874 // The unprivileged access is AS_none as we don't know how the member was
1875 // accessed, which is described by the access in DeclAccessPair.
1876 // `IsAccessible` will examine the actual access of Target (i.e.
1877 // Decl->getAccess()) when calculating the access.
Douglas Gregor03ba1882011-11-03 16:51:37 +00001878 AccessTarget Entity(Context, AccessedEntity::Member, Class,
Eric Liu18b404a2018-07-19 13:32:00 +00001879 DeclAccessPair::make(Target, AS_none), qType);
Douglas Gregor03ba1882011-11-03 16:51:37 +00001880 EffectiveContext EC(CurContext);
1881 return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1882 }
Eric Liu18b404a2018-07-19 13:32:00 +00001883
1884 if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Target)) {
Douglas Gregor21ceb182011-11-03 19:00:24 +00001885 // @public and @package ivars are always accessible.
1886 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1887 Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1888 return true;
Serge Pavlov64bc7032013-05-07 16:56:03 +00001889
Douglas Gregor21ceb182011-11-03 19:00:24 +00001890 // If we are inside a class or category implementation, determine the
1891 // interface we're in.
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Douglas Gregor21ceb182011-11-03 19:00:24 +00001893 if (ObjCMethodDecl *MD = getCurMethodDecl())
1894 ClassOfMethodDecl = MD->getClassInterface();
1895 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1896 if (ObjCImplDecl *Impl
1897 = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1898 if (ObjCImplementationDecl *IMPD
1899 = dyn_cast<ObjCImplementationDecl>(Impl))
1900 ClassOfMethodDecl = IMPD->getClassInterface();
1901 else if (ObjCCategoryImplDecl* CatImplClass
1902 = dyn_cast<ObjCCategoryImplDecl>(Impl))
1903 ClassOfMethodDecl = CatImplClass->getClassInterface();
1904 }
1905 }
1906
1907 // If we're not in an interface, this ivar is inaccessible.
1908 if (!ClassOfMethodDecl)
1909 return false;
1910
1911 // If we're inside the same interface that owns the ivar, we're fine.
Douglas Gregor0b144e12011-12-15 00:29:59 +00001912 if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
Douglas Gregor21ceb182011-11-03 19:00:24 +00001913 return true;
1914
1915 // If the ivar is private, it's inaccessible.
1916 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1917 return false;
1918
1919 return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1920 }
1921
Douglas Gregor03ba1882011-11-03 16:51:37 +00001922 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001923}