blob: f7806d25161255d5b18a9148f151a44d1566d801 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Anders Carlsson733d77f2009-03-27 06:03:27 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclCXX.h"
John McCall16927f62010-03-12 01:19:31 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregor21ceb182011-11-03 19:00:24 +000019#include "clang/AST/DeclObjC.h"
John McCallc62bb642010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
John McCall58cc69d2010-01-27 01:50:18 +000021#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/DelayedDiagnostic.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
John McCall58cc69d2010-01-27 01:50:18 +000025
Anders Carlsson17941122009-03-27 04:54:36 +000026using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000027using namespace sema;
Anders Carlsson17941122009-03-27 04:54:36 +000028
John McCalla8ae2222010-04-06 21:38:20 +000029/// A copy of Sema's enum without AR_delayed.
30enum AccessResult {
31 AR_accessible,
32 AR_inaccessible,
33 AR_dependent
34};
35
Anders Carlsson4742a9c2009-03-27 05:05:05 +000036/// SetMemberAccessSpecifier - Set the access specifier of a member.
37/// Returns true on error (when the previous member decl access specifier
38/// is different from the new member decl access specifier).
Mike Stump11289f42009-09-09 15:08:12 +000039bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
Anders Carlsson17941122009-03-27 04:54:36 +000040 NamedDecl *PrevMemberDecl,
41 AccessSpecifier LexicalAS) {
42 if (!PrevMemberDecl) {
43 // Use the lexical access specifier.
44 MemberDecl->setAccess(LexicalAS);
45 return false;
46 }
Mike Stump11289f42009-09-09 15:08:12 +000047
Anders Carlsson17941122009-03-27 04:54:36 +000048 // C++ [class.access.spec]p3: When a member is redeclared its access
49 // specifier must be same as its initial declaration.
50 if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
Mike Stump11289f42009-09-09 15:08:12 +000051 Diag(MemberDecl->getLocation(),
52 diag::err_class_redeclared_with_different_access)
Anders Carlsson17941122009-03-27 04:54:36 +000053 << MemberDecl << LexicalAS;
54 Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
55 << PrevMemberDecl << PrevMemberDecl->getAccess();
John McCall0a4bb262009-12-23 00:37:40 +000056
57 MemberDecl->setAccess(LexicalAS);
Anders Carlsson17941122009-03-27 04:54:36 +000058 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Anders Carlsson17941122009-03-27 04:54:36 +000061 MemberDecl->setAccess(PrevMemberDecl->getAccess());
62 return false;
63}
Anders Carlsson4742a9c2009-03-27 05:05:05 +000064
John McCalla8ae2222010-04-06 21:38:20 +000065static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66 DeclContext *DC = D->getDeclContext();
67
68 // This can only happen at top: enum decls only "publish" their
69 // immediate members.
70 if (isa<EnumDecl>(DC))
71 DC = cast<EnumDecl>(DC)->getDeclContext();
72
73 CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74 while (DeclaringClass->isAnonymousStructOrUnion())
75 DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76 return DeclaringClass;
77}
78
John McCall5b0829a2010-02-10 09:31:12 +000079namespace {
80struct EffectiveContext {
John McCall3dc81f72010-03-27 06:55:49 +000081 EffectiveContext() : Inner(0), Dependent(false) {}
Anders Carlsson733d77f2009-03-27 06:03:27 +000082
John McCall816d75b2010-03-24 07:46:06 +000083 explicit EffectiveContext(DeclContext *DC)
84 : Inner(DC),
85 Dependent(DC->isDependentContext()) {
John McCallc62bb642010-03-24 05:22:00 +000086
Richard Smithad5c1ca2013-04-29 10:13:55 +000087 // C++11 [class.access.nest]p1:
John McCallfb803d72010-03-17 04:58:56 +000088 // A nested class is a member and as such has the same access
89 // rights as any other member.
Richard Smithad5c1ca2013-04-29 10:13:55 +000090 // C++11 [class.access]p2:
John McCallfb803d72010-03-17 04:58:56 +000091 // A member of a class can also access all the names to which
John McCall3dc81f72010-03-27 06:55:49 +000092 // the class has access. A local class of a member function
93 // may access the same names that the member function itself
94 // may access.
95 // This almost implies that the privileges of nesting are transitive.
96 // Technically it says nothing about the local classes of non-member
97 // functions (which can gain privileges through friendship), but we
98 // take that as an oversight.
99 while (true) {
John McCalle91aec72012-08-24 22:54:02 +0000100 // We want to add canonical declarations to the EC lists for
101 // simplicity of checking, but we need to walk up through the
102 // actual current DC chain. Otherwise, something like a local
103 // extern or friend which happens to be the canonical
104 // declaration will really mess us up.
105
John McCall3dc81f72010-03-27 06:55:49 +0000106 if (isa<CXXRecordDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000107 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
108 Records.push_back(Record->getCanonicalDecl());
John McCall3dc81f72010-03-27 06:55:49 +0000109 DC = Record->getDeclContext();
110 } else if (isa<FunctionDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000111 FunctionDecl *Function = cast<FunctionDecl>(DC);
112 Functions.push_back(Function->getCanonicalDecl());
Douglas Gregor56636582011-10-09 22:38:36 +0000113 if (Function->getFriendObjectKind())
114 DC = Function->getLexicalDeclContext();
115 else
116 DC = Function->getDeclContext();
John McCall3dc81f72010-03-27 06:55:49 +0000117 } else if (DC->isFileContext()) {
118 break;
119 } else {
120 DC = DC->getParent();
121 }
John McCallfb803d72010-03-17 04:58:56 +0000122 }
Anders Carlsson733d77f2009-03-27 06:03:27 +0000123 }
Sebastian Redle644e192009-07-18 14:32:15 +0000124
John McCallc62bb642010-03-24 05:22:00 +0000125 bool isDependent() const { return Dependent; }
126
John McCallfb803d72010-03-17 04:58:56 +0000127 bool includesClass(const CXXRecordDecl *R) const {
128 R = R->getCanonicalDecl();
129 return std::find(Records.begin(), Records.end(), R)
130 != Records.end();
John McCall5b0829a2010-02-10 09:31:12 +0000131 }
132
John McCall816d75b2010-03-24 07:46:06 +0000133 /// Retrieves the innermost "useful" context. Can be null if we're
134 /// doing access-control without privileges.
135 DeclContext *getInnerContext() const {
136 return Inner;
John McCallc62bb642010-03-24 05:22:00 +0000137 }
138
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000139 typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
John McCallc62bb642010-03-24 05:22:00 +0000140
John McCall816d75b2010-03-24 07:46:06 +0000141 DeclContext *Inner;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000142 SmallVector<FunctionDecl*, 4> Functions;
143 SmallVector<CXXRecordDecl*, 4> Records;
John McCallc62bb642010-03-24 05:22:00 +0000144 bool Dependent;
John McCall5b0829a2010-02-10 09:31:12 +0000145};
John McCalla8ae2222010-04-06 21:38:20 +0000146
Nico Weber20c9f1d2010-11-28 22:53:37 +0000147/// Like sema::AccessedEntity, but kindly lets us scribble all over
John McCalla8ae2222010-04-06 21:38:20 +0000148/// it.
John McCallb45a1e72010-08-26 02:13:20 +0000149struct AccessTarget : public AccessedEntity {
150 AccessTarget(const AccessedEntity &Entity)
John McCalla8ae2222010-04-06 21:38:20 +0000151 : AccessedEntity(Entity) {
152 initialize();
153 }
154
155 AccessTarget(ASTContext &Context,
156 MemberNonce _,
157 CXXRecordDecl *NamingClass,
158 DeclAccessPair FoundDecl,
Erik Verbruggen631dfc62011-09-19 15:10:40 +0000159 QualType BaseObjectType)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000160 : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
161 FoundDecl, BaseObjectType) {
John McCalla8ae2222010-04-06 21:38:20 +0000162 initialize();
163 }
164
165 AccessTarget(ASTContext &Context,
166 BaseNonce _,
167 CXXRecordDecl *BaseClass,
168 CXXRecordDecl *DerivedClass,
169 AccessSpecifier Access)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000170 : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
171 Access) {
John McCalla8ae2222010-04-06 21:38:20 +0000172 initialize();
173 }
174
John McCall5dadb652012-04-07 03:04:20 +0000175 bool isInstanceMember() const {
176 return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
177 }
178
John McCalla8ae2222010-04-06 21:38:20 +0000179 bool hasInstanceContext() const {
180 return HasInstanceContext;
181 }
182
183 class SavedInstanceContext {
184 public:
185 ~SavedInstanceContext() {
186 Target.HasInstanceContext = Has;
187 }
188
189 private:
John McCall8e36d532010-04-07 00:41:46 +0000190 friend struct AccessTarget;
John McCalla8ae2222010-04-06 21:38:20 +0000191 explicit SavedInstanceContext(AccessTarget &Target)
192 : Target(Target), Has(Target.HasInstanceContext) {}
193 AccessTarget &Target;
194 bool Has;
195 };
196
197 SavedInstanceContext saveInstanceContext() {
198 return SavedInstanceContext(*this);
199 }
200
201 void suppressInstanceContext() {
202 HasInstanceContext = false;
203 }
204
205 const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
206 assert(HasInstanceContext);
207 if (CalculatedInstanceContext)
208 return InstanceContext;
209
210 CalculatedInstanceContext = true;
211 DeclContext *IC = S.computeDeclContext(getBaseObjectType());
212 InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl() : 0);
213 return InstanceContext;
214 }
215
216 const CXXRecordDecl *getDeclaringClass() const {
217 return DeclaringClass;
218 }
219
John McCalld010ac92013-02-27 00:08:19 +0000220 /// The "effective" naming class is the canonical non-anonymous
221 /// class containing the actual naming class.
222 const CXXRecordDecl *getEffectiveNamingClass() const {
223 const CXXRecordDecl *namingClass = getNamingClass();
224 while (namingClass->isAnonymousStructOrUnion())
225 namingClass = cast<CXXRecordDecl>(namingClass->getParent());
226 return namingClass->getCanonicalDecl();
227 }
228
John McCalla8ae2222010-04-06 21:38:20 +0000229private:
230 void initialize() {
231 HasInstanceContext = (isMemberAccess() &&
232 !getBaseObjectType().isNull() &&
233 getTargetDecl()->isCXXInstanceMember());
234 CalculatedInstanceContext = false;
235 InstanceContext = 0;
236
237 if (isMemberAccess())
238 DeclaringClass = FindDeclaringClass(getTargetDecl());
239 else
240 DeclaringClass = getBaseClass();
241 DeclaringClass = DeclaringClass->getCanonicalDecl();
242 }
243
244 bool HasInstanceContext : 1;
245 mutable bool CalculatedInstanceContext : 1;
246 mutable const CXXRecordDecl *InstanceContext;
247 const CXXRecordDecl *DeclaringClass;
248};
249
Anders Carlsson4742a9c2009-03-27 05:05:05 +0000250}
John McCall553c0792010-01-23 00:46:32 +0000251
John McCall97205142010-05-04 05:11:27 +0000252/// Checks whether one class might instantiate to the other.
253static bool MightInstantiateTo(const CXXRecordDecl *From,
254 const CXXRecordDecl *To) {
255 // Declaration names are always preserved by instantiation.
256 if (From->getDeclName() != To->getDeclName())
257 return false;
258
259 const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
260 const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
261 if (FromDC == ToDC) return true;
262 if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
263
264 // Be conservative.
265 return true;
266}
267
John McCalla8ae2222010-04-06 21:38:20 +0000268/// Checks whether one class is derived from another, inclusively.
269/// Properly indicates when it couldn't be determined due to
270/// dependence.
271///
272/// This should probably be donated to AST or at least Sema.
273static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
274 const CXXRecordDecl *Target) {
275 assert(Derived->getCanonicalDecl() == Derived);
276 assert(Target->getCanonicalDecl() == Target);
John McCall69f75862010-03-24 09:04:37 +0000277
John McCalla8ae2222010-04-06 21:38:20 +0000278 if (Derived == Target) return AR_accessible;
John McCall69f75862010-03-24 09:04:37 +0000279
John McCall97205142010-05-04 05:11:27 +0000280 bool CheckDependent = Derived->isDependentContext();
281 if (CheckDependent && MightInstantiateTo(Derived, Target))
282 return AR_dependent;
283
John McCalla8ae2222010-04-06 21:38:20 +0000284 AccessResult OnFailure = AR_inaccessible;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000285 SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
John McCalla8ae2222010-04-06 21:38:20 +0000286
287 while (true) {
Douglas Gregor0201a4c2011-11-14 23:00:43 +0000288 if (Derived->isDependentContext() && !Derived->hasDefinition())
289 return AR_dependent;
290
Aaron Ballman574705e2014-03-13 15:41:46 +0000291 for (const auto &I : Derived->bases()) {
John McCalla8ae2222010-04-06 21:38:20 +0000292 const CXXRecordDecl *RD;
293
Aaron Ballman574705e2014-03-13 15:41:46 +0000294 QualType T = I.getType();
John McCalla8ae2222010-04-06 21:38:20 +0000295 if (const RecordType *RT = T->getAs<RecordType>()) {
296 RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall97205142010-05-04 05:11:27 +0000297 } else if (const InjectedClassNameType *IT
298 = T->getAs<InjectedClassNameType>()) {
299 RD = IT->getDecl();
John McCalla8ae2222010-04-06 21:38:20 +0000300 } else {
John McCalla8ae2222010-04-06 21:38:20 +0000301 assert(T->isDependentType() && "non-dependent base wasn't a record?");
302 OnFailure = AR_dependent;
303 continue;
304 }
305
306 RD = RD->getCanonicalDecl();
307 if (RD == Target) return AR_accessible;
John McCall97205142010-05-04 05:11:27 +0000308 if (CheckDependent && MightInstantiateTo(RD, Target))
309 OnFailure = AR_dependent;
310
John McCalla8ae2222010-04-06 21:38:20 +0000311 Queue.push_back(RD);
312 }
313
314 if (Queue.empty()) break;
315
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000316 Derived = Queue.pop_back_val();
John McCalla8ae2222010-04-06 21:38:20 +0000317 }
318
319 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000320}
321
John McCalla8ae2222010-04-06 21:38:20 +0000322
John McCallc62bb642010-03-24 05:22:00 +0000323static bool MightInstantiateTo(Sema &S, DeclContext *Context,
324 DeclContext *Friend) {
325 if (Friend == Context)
326 return true;
327
328 assert(!Friend->isDependentContext() &&
329 "can't handle friends with dependent contexts here");
330
331 if (!Context->isDependentContext())
332 return false;
333
334 if (Friend->isFileContext())
335 return false;
336
337 // TODO: this is very conservative
338 return true;
339}
340
341// Asks whether the type in 'context' can ever instantiate to the type
342// in 'friend'.
343static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
344 if (Friend == Context)
345 return true;
346
347 if (!Friend->isDependentType() && !Context->isDependentType())
348 return false;
349
350 // TODO: this is very conservative.
351 return true;
352}
353
354static bool MightInstantiateTo(Sema &S,
355 FunctionDecl *Context,
356 FunctionDecl *Friend) {
357 if (Context->getDeclName() != Friend->getDeclName())
358 return false;
359
360 if (!MightInstantiateTo(S,
361 Context->getDeclContext(),
362 Friend->getDeclContext()))
363 return false;
364
365 CanQual<FunctionProtoType> FriendTy
366 = S.Context.getCanonicalType(Friend->getType())
367 ->getAs<FunctionProtoType>();
368 CanQual<FunctionProtoType> ContextTy
369 = S.Context.getCanonicalType(Context->getType())
370 ->getAs<FunctionProtoType>();
371
372 // There isn't any way that I know of to add qualifiers
373 // during instantiation.
374 if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
375 return false;
376
Alp Toker9cacbab2014-01-20 20:26:09 +0000377 if (FriendTy->getNumParams() != ContextTy->getNumParams())
John McCallc62bb642010-03-24 05:22:00 +0000378 return false;
379
Alp Toker314cc812014-01-25 16:55:45 +0000380 if (!MightInstantiateTo(S, ContextTy->getReturnType(),
381 FriendTy->getReturnType()))
John McCallc62bb642010-03-24 05:22:00 +0000382 return false;
383
Alp Toker9cacbab2014-01-20 20:26:09 +0000384 for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
385 if (!MightInstantiateTo(S, ContextTy->getParamType(I),
386 FriendTy->getParamType(I)))
John McCallc62bb642010-03-24 05:22:00 +0000387 return false;
388
389 return true;
390}
391
392static bool MightInstantiateTo(Sema &S,
393 FunctionTemplateDecl *Context,
394 FunctionTemplateDecl *Friend) {
395 return MightInstantiateTo(S,
396 Context->getTemplatedDecl(),
397 Friend->getTemplatedDecl());
398}
399
John McCalla8ae2222010-04-06 21:38:20 +0000400static AccessResult MatchesFriend(Sema &S,
401 const EffectiveContext &EC,
402 const CXXRecordDecl *Friend) {
John McCall39e82882010-03-17 20:01:29 +0000403 if (EC.includesClass(Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000404 return AR_accessible;
John McCall39e82882010-03-17 20:01:29 +0000405
John McCallc62bb642010-03-24 05:22:00 +0000406 if (EC.isDependent()) {
407 CanQualType FriendTy
408 = S.Context.getCanonicalType(S.Context.getTypeDeclType(Friend));
409
410 for (EffectiveContext::record_iterator
411 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
412 CanQualType ContextTy
413 = S.Context.getCanonicalType(S.Context.getTypeDeclType(*I));
414 if (MightInstantiateTo(S, ContextTy, FriendTy))
John McCalla8ae2222010-04-06 21:38:20 +0000415 return AR_dependent;
John McCallc62bb642010-03-24 05:22:00 +0000416 }
417 }
418
John McCalla8ae2222010-04-06 21:38:20 +0000419 return AR_inaccessible;
John McCall39e82882010-03-17 20:01:29 +0000420}
421
John McCalla8ae2222010-04-06 21:38:20 +0000422static AccessResult MatchesFriend(Sema &S,
423 const EffectiveContext &EC,
424 CanQualType Friend) {
John McCallc62bb642010-03-24 05:22:00 +0000425 if (const RecordType *RT = Friend->getAs<RecordType>())
426 return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
John McCall39e82882010-03-17 20:01:29 +0000427
John McCallc62bb642010-03-24 05:22:00 +0000428 // TODO: we can do better than this
429 if (Friend->isDependentType())
John McCalla8ae2222010-04-06 21:38:20 +0000430 return AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000431
John McCalla8ae2222010-04-06 21:38:20 +0000432 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000433}
434
435/// Determines whether the given friend class template matches
436/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000437static AccessResult MatchesFriend(Sema &S,
438 const EffectiveContext &EC,
439 ClassTemplateDecl *Friend) {
440 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000441
John McCall598b4402010-03-25 06:39:04 +0000442 // Check whether the friend is the template of a class in the
443 // context chain.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444 for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
John McCallc62bb642010-03-24 05:22:00 +0000445 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
446 CXXRecordDecl *Record = *I;
447
John McCall598b4402010-03-25 06:39:04 +0000448 // Figure out whether the current class has a template:
John McCallc62bb642010-03-24 05:22:00 +0000449 ClassTemplateDecl *CTD;
450
451 // A specialization of the template...
452 if (isa<ClassTemplateSpecializationDecl>(Record)) {
453 CTD = cast<ClassTemplateSpecializationDecl>(Record)
454 ->getSpecializedTemplate();
455
456 // ... or the template pattern itself.
457 } else {
458 CTD = Record->getDescribedClassTemplate();
459 if (!CTD) continue;
460 }
461
462 // It's a match.
463 if (Friend == CTD->getCanonicalDecl())
John McCalla8ae2222010-04-06 21:38:20 +0000464 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000465
John McCall598b4402010-03-25 06:39:04 +0000466 // If the context isn't dependent, it can't be a dependent match.
467 if (!EC.isDependent())
468 continue;
469
John McCallc62bb642010-03-24 05:22:00 +0000470 // If the template names don't match, it can't be a dependent
Richard Smith3f1b5d02011-05-05 21:57:07 +0000471 // match.
472 if (CTD->getDeclName() != Friend->getDeclName())
John McCallc62bb642010-03-24 05:22:00 +0000473 continue;
474
475 // If the class's context can't instantiate to the friend's
476 // context, it can't be a dependent match.
477 if (!MightInstantiateTo(S, CTD->getDeclContext(),
478 Friend->getDeclContext()))
479 continue;
480
481 // Otherwise, it's a dependent match.
John McCalla8ae2222010-04-06 21:38:20 +0000482 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000483 }
484
John McCallc62bb642010-03-24 05:22:00 +0000485 return OnFailure;
486}
487
488/// Determines whether the given friend function matches anything in
489/// the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000490static AccessResult MatchesFriend(Sema &S,
491 const EffectiveContext &EC,
492 FunctionDecl *Friend) {
493 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000494
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000496 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
497 if (Friend == *I)
John McCalla8ae2222010-04-06 21:38:20 +0000498 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000499
John McCall3dc81f72010-03-27 06:55:49 +0000500 if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000501 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000502 }
John McCallc62bb642010-03-24 05:22:00 +0000503
John McCall3dc81f72010-03-27 06:55:49 +0000504 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000505}
506
507/// Determines whether the given friend function template matches
508/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000509static AccessResult MatchesFriend(Sema &S,
510 const EffectiveContext &EC,
511 FunctionTemplateDecl *Friend) {
512 if (EC.Functions.empty()) return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000513
John McCalla8ae2222010-04-06 21:38:20 +0000514 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000515
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000517 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
John McCallc62bb642010-03-24 05:22:00 +0000518
John McCall3dc81f72010-03-27 06:55:49 +0000519 FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
520 if (!FTD)
521 FTD = (*I)->getDescribedFunctionTemplate();
522 if (!FTD)
523 continue;
John McCallc62bb642010-03-24 05:22:00 +0000524
John McCall3dc81f72010-03-27 06:55:49 +0000525 FTD = FTD->getCanonicalDecl();
526
527 if (Friend == FTD)
John McCalla8ae2222010-04-06 21:38:20 +0000528 return AR_accessible;
John McCall3dc81f72010-03-27 06:55:49 +0000529
530 if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000531 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000532 }
533
534 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000535}
536
537/// Determines whether the given friend declaration matches anything
538/// in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000539static AccessResult MatchesFriend(Sema &S,
540 const EffectiveContext &EC,
541 FriendDecl *FriendD) {
John McCall2c2eb122010-10-16 06:59:13 +0000542 // Whitelist accesses if there's an invalid or unsupported friend
543 // declaration.
544 if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
John McCallde3fd222010-10-12 23:13:28 +0000545 return AR_accessible;
546
John McCall15ad0962010-03-25 18:04:51 +0000547 if (TypeSourceInfo *T = FriendD->getFriendType())
548 return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
John McCallc62bb642010-03-24 05:22:00 +0000549
550 NamedDecl *Friend
551 = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
John McCall39e82882010-03-17 20:01:29 +0000552
553 // FIXME: declarations with dependent or templated scope.
554
John McCallc62bb642010-03-24 05:22:00 +0000555 if (isa<ClassTemplateDecl>(Friend))
556 return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000557
John McCallc62bb642010-03-24 05:22:00 +0000558 if (isa<FunctionTemplateDecl>(Friend))
559 return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000560
John McCallc62bb642010-03-24 05:22:00 +0000561 if (isa<CXXRecordDecl>(Friend))
562 return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000563
John McCallc62bb642010-03-24 05:22:00 +0000564 assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
565 return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000566}
567
John McCalla8ae2222010-04-06 21:38:20 +0000568static AccessResult GetFriendKind(Sema &S,
569 const EffectiveContext &EC,
570 const CXXRecordDecl *Class) {
571 AccessResult OnFailure = AR_inaccessible;
John McCallfb803d72010-03-17 04:58:56 +0000572
John McCall16927f62010-03-12 01:19:31 +0000573 // Okay, check friends.
Aaron Ballman522a6dd2014-03-13 17:00:06 +0000574 for (auto *Friend : Class->friends()) {
John McCall39e82882010-03-17 20:01:29 +0000575 switch (MatchesFriend(S, EC, Friend)) {
John McCalla8ae2222010-04-06 21:38:20 +0000576 case AR_accessible:
577 return AR_accessible;
John McCall16927f62010-03-12 01:19:31 +0000578
John McCalla8ae2222010-04-06 21:38:20 +0000579 case AR_inaccessible:
580 continue;
581
582 case AR_dependent:
583 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000584 break;
John McCall16927f62010-03-12 01:19:31 +0000585 }
John McCall16927f62010-03-12 01:19:31 +0000586 }
587
588 // That's it, give up.
John McCallfb803d72010-03-17 04:58:56 +0000589 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000590}
591
John McCall96329672010-08-28 07:56:00 +0000592namespace {
593
594/// A helper class for checking for a friend which will grant access
595/// to a protected instance member.
596struct ProtectedFriendContext {
597 Sema &S;
598 const EffectiveContext &EC;
599 const CXXRecordDecl *NamingClass;
600 bool CheckDependent;
601 bool EverDependent;
602
603 /// The path down to the current base class.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000604 SmallVector<const CXXRecordDecl*, 20> CurPath;
John McCall96329672010-08-28 07:56:00 +0000605
606 ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
607 const CXXRecordDecl *InstanceContext,
608 const CXXRecordDecl *NamingClass)
609 : S(S), EC(EC), NamingClass(NamingClass),
610 CheckDependent(InstanceContext->isDependentContext() ||
611 NamingClass->isDependentContext()),
612 EverDependent(false) {}
613
John McCall1177ff12010-08-28 08:47:21 +0000614 /// Check classes in the current path for friendship, starting at
615 /// the given index.
616 bool checkFriendshipAlongPath(unsigned I) {
617 assert(I < CurPath.size());
618 for (unsigned E = CurPath.size(); I != E; ++I) {
619 switch (GetFriendKind(S, EC, CurPath[I])) {
John McCall96329672010-08-28 07:56:00 +0000620 case AR_accessible: return true;
621 case AR_inaccessible: continue;
622 case AR_dependent: EverDependent = true; continue;
623 }
624 }
625 return false;
626 }
627
628 /// Perform a search starting at the given class.
John McCall1177ff12010-08-28 08:47:21 +0000629 ///
630 /// PrivateDepth is the index of the last (least derived) class
631 /// along the current path such that a notional public member of
632 /// the final class in the path would have access in that class.
633 bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
John McCall96329672010-08-28 07:56:00 +0000634 // If we ever reach the naming class, check the current path for
635 // friendship. We can also stop recursing because we obviously
636 // won't find the naming class there again.
John McCall1177ff12010-08-28 08:47:21 +0000637 if (Cur == NamingClass)
638 return checkFriendshipAlongPath(PrivateDepth);
John McCall96329672010-08-28 07:56:00 +0000639
640 if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
641 EverDependent = true;
642
643 // Recurse into the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000644 for (const auto &I : Cur->bases()) {
John McCall1177ff12010-08-28 08:47:21 +0000645 // If this is private inheritance, then a public member of the
646 // base will not have any access in classes derived from Cur.
647 unsigned BasePrivateDepth = PrivateDepth;
Aaron Ballman574705e2014-03-13 15:41:46 +0000648 if (I.getAccessSpecifier() == AS_private)
John McCall1177ff12010-08-28 08:47:21 +0000649 BasePrivateDepth = CurPath.size() - 1;
John McCall96329672010-08-28 07:56:00 +0000650
651 const CXXRecordDecl *RD;
652
Aaron Ballman574705e2014-03-13 15:41:46 +0000653 QualType T = I.getType();
John McCall96329672010-08-28 07:56:00 +0000654 if (const RecordType *RT = T->getAs<RecordType>()) {
655 RD = cast<CXXRecordDecl>(RT->getDecl());
656 } else if (const InjectedClassNameType *IT
657 = T->getAs<InjectedClassNameType>()) {
658 RD = IT->getDecl();
659 } else {
660 assert(T->isDependentType() && "non-dependent base wasn't a record?");
661 EverDependent = true;
662 continue;
663 }
664
665 // Recurse. We don't need to clean up if this returns true.
John McCall1177ff12010-08-28 08:47:21 +0000666 CurPath.push_back(RD);
667 if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
668 return true;
669 CurPath.pop_back();
John McCall96329672010-08-28 07:56:00 +0000670 }
671
John McCall96329672010-08-28 07:56:00 +0000672 return false;
673 }
John McCall1177ff12010-08-28 08:47:21 +0000674
675 bool findFriendship(const CXXRecordDecl *Cur) {
676 assert(CurPath.empty());
677 CurPath.push_back(Cur);
678 return findFriendship(Cur, 0);
679 }
John McCall96329672010-08-28 07:56:00 +0000680};
681}
682
683/// Search for a class P that EC is a friend of, under the constraint
John McCall5dadb652012-04-07 03:04:20 +0000684/// InstanceContext <= P
685/// if InstanceContext exists, or else
686/// NamingClass <= P
John McCall96329672010-08-28 07:56:00 +0000687/// and with the additional restriction that a protected member of
John McCall5dadb652012-04-07 03:04:20 +0000688/// NamingClass would have some natural access in P, which implicitly
689/// imposes the constraint that P <= NamingClass.
John McCall96329672010-08-28 07:56:00 +0000690///
John McCall5dadb652012-04-07 03:04:20 +0000691/// This isn't quite the condition laid out in the standard.
692/// Instead of saying that a notional protected member of NamingClass
693/// would have to have some natural access in P, it says the actual
694/// target has to have some natural access in P, which opens up the
695/// possibility that the target (which is not necessarily a member
696/// of NamingClass) might be more accessible along some path not
697/// passing through it. That's really a bad idea, though, because it
John McCall96329672010-08-28 07:56:00 +0000698/// introduces two problems:
John McCall5dadb652012-04-07 03:04:20 +0000699/// - Most importantly, it breaks encapsulation because you can
700/// access a forbidden base class's members by directly subclassing
701/// it elsewhere.
702/// - It also makes access substantially harder to compute because it
John McCall96329672010-08-28 07:56:00 +0000703/// breaks the hill-climbing algorithm: knowing that the target is
704/// accessible in some base class would no longer let you change
705/// the question solely to whether the base class is accessible,
706/// because the original target might have been more accessible
707/// because of crazy subclassing.
708/// So we don't implement that.
709static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
710 const CXXRecordDecl *InstanceContext,
711 const CXXRecordDecl *NamingClass) {
John McCall5dadb652012-04-07 03:04:20 +0000712 assert(InstanceContext == 0 ||
713 InstanceContext->getCanonicalDecl() == InstanceContext);
John McCall96329672010-08-28 07:56:00 +0000714 assert(NamingClass->getCanonicalDecl() == NamingClass);
715
John McCall5dadb652012-04-07 03:04:20 +0000716 // If we don't have an instance context, our constraints give us
717 // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
718 // This is just the usual friendship check.
719 if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
720
John McCall96329672010-08-28 07:56:00 +0000721 ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
722 if (PRC.findFriendship(InstanceContext)) return AR_accessible;
723 if (PRC.EverDependent) return AR_dependent;
724 return AR_inaccessible;
725}
726
John McCalla8ae2222010-04-06 21:38:20 +0000727static AccessResult HasAccess(Sema &S,
728 const EffectiveContext &EC,
729 const CXXRecordDecl *NamingClass,
730 AccessSpecifier Access,
731 const AccessTarget &Target) {
John McCalld79b4d82010-04-02 00:03:43 +0000732 assert(NamingClass->getCanonicalDecl() == NamingClass &&
733 "declaration should be canonicalized before being passed here");
734
John McCalla8ae2222010-04-06 21:38:20 +0000735 if (Access == AS_public) return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000736 assert(Access == AS_private || Access == AS_protected);
737
John McCalla8ae2222010-04-06 21:38:20 +0000738 AccessResult OnFailure = AR_inaccessible;
739
John McCalld79b4d82010-04-02 00:03:43 +0000740 for (EffectiveContext::record_iterator
741 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
742 // All the declarations in EC have been canonicalized, so pointer
743 // equality from this point on will work fine.
744 const CXXRecordDecl *ECRecord = *I;
745
746 // [B2] and [M2]
John McCalla8ae2222010-04-06 21:38:20 +0000747 if (Access == AS_private) {
748 if (ECRecord == NamingClass)
749 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000750
John McCall97205142010-05-04 05:11:27 +0000751 if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
752 OnFailure = AR_dependent;
753
John McCalld79b4d82010-04-02 00:03:43 +0000754 // [B3] and [M3]
John McCalla8ae2222010-04-06 21:38:20 +0000755 } else {
756 assert(Access == AS_protected);
757 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
758 case AR_accessible: break;
759 case AR_inaccessible: continue;
760 case AR_dependent: OnFailure = AR_dependent; continue;
761 }
762
John McCalla8ae2222010-04-06 21:38:20 +0000763 // C++ [class.protected]p1:
764 // An additional access check beyond those described earlier in
765 // [class.access] is applied when a non-static data member or
766 // non-static member function is a protected member of its naming
767 // class. As described earlier, access to a protected member is
768 // granted because the reference occurs in a friend or member of
769 // some class C. If the access is to form a pointer to member,
770 // the nested-name-specifier shall name C or a class derived from
771 // C. All other accesses involve a (possibly implicit) object
772 // expression. In this case, the class of the object expression
773 // shall be C or a class derived from C.
774 //
John McCall5dadb652012-04-07 03:04:20 +0000775 // We interpret this as a restriction on [M3].
776
777 // In this part of the code, 'C' is just our context class ECRecord.
778
779 // These rules are different if we don't have an instance context.
780 if (!Target.hasInstanceContext()) {
781 // If it's not an instance member, these restrictions don't apply.
782 if (!Target.isInstanceMember()) return AR_accessible;
783
784 // If it's an instance member, use the pointer-to-member rule
785 // that the naming class has to be derived from the effective
786 // context.
787
Francois Picheta39371c2012-04-17 12:35:05 +0000788 // Emulate a MSVC bug where the creation of pointer-to-member
789 // to protected member of base class is allowed but only from
Francois Pichet52d38982012-04-19 07:48:57 +0000790 // static member functions.
Alp Tokerbfa39342014-01-14 12:51:41 +0000791 if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
Francois Pichet5b061f02012-04-18 03:24:38 +0000792 if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
793 if (MD->isStatic()) return AR_accessible;
Francois Picheta39371c2012-04-17 12:35:05 +0000794
John McCall5dadb652012-04-07 03:04:20 +0000795 // Despite the standard's confident wording, there is a case
796 // where you can have an instance member that's neither in a
797 // pointer-to-member expression nor in a member access: when
798 // it names a field in an unevaluated context that can't be an
799 // implicit member. Pending clarification, we just apply the
800 // same naming-class restriction here.
801 // FIXME: we're probably not correctly adding the
802 // protected-member restriction when we retroactively convert
803 // an expression to being evaluated.
804
805 // We know that ECRecord derives from NamingClass. The
806 // restriction says to check whether NamingClass derives from
807 // ECRecord, but that's not really necessary: two distinct
808 // classes can't be recursively derived from each other. So
809 // along this path, we just need to check whether the classes
810 // are equal.
811 if (NamingClass == ECRecord) return AR_accessible;
812
813 // Otherwise, this context class tells us nothing; on to the next.
814 continue;
815 }
816
817 assert(Target.isInstanceMember());
818
819 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
820 if (!InstanceContext) {
821 OnFailure = AR_dependent;
822 continue;
823 }
824
John McCalla8ae2222010-04-06 21:38:20 +0000825 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
826 case AR_accessible: return AR_accessible;
827 case AR_inaccessible: continue;
828 case AR_dependent: OnFailure = AR_dependent; continue;
829 }
830 }
John McCalld79b4d82010-04-02 00:03:43 +0000831 }
832
John McCall96329672010-08-28 07:56:00 +0000833 // [M3] and [B3] say that, if the target is protected in N, we grant
834 // access if the access occurs in a friend or member of some class P
835 // that's a subclass of N and where the target has some natural
836 // access in P. The 'member' aspect is easy to handle because P
837 // would necessarily be one of the effective-context records, and we
838 // address that above. The 'friend' aspect is completely ridiculous
839 // to implement because there are no restrictions at all on P
840 // *unless* the [class.protected] restriction applies. If it does,
841 // however, we should ignore whether the naming class is a friend,
842 // and instead rely on whether any potential P is a friend.
John McCall5dadb652012-04-07 03:04:20 +0000843 if (Access == AS_protected && Target.isInstanceMember()) {
844 // Compute the instance context if possible.
845 const CXXRecordDecl *InstanceContext = 0;
846 if (Target.hasInstanceContext()) {
847 InstanceContext = Target.resolveInstanceContext(S);
848 if (!InstanceContext) return AR_dependent;
849 }
850
John McCall96329672010-08-28 07:56:00 +0000851 switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
852 case AR_accessible: return AR_accessible;
John McCalla8ae2222010-04-06 21:38:20 +0000853 case AR_inaccessible: return OnFailure;
854 case AR_dependent: return AR_dependent;
855 }
John McCallc6af8f42010-08-28 08:10:32 +0000856 llvm_unreachable("impossible friendship kind");
John McCalla8ae2222010-04-06 21:38:20 +0000857 }
858
859 switch (GetFriendKind(S, EC, NamingClass)) {
860 case AR_accessible: return AR_accessible;
861 case AR_inaccessible: return OnFailure;
862 case AR_dependent: return AR_dependent;
863 }
864
865 // Silence bogus warnings
866 llvm_unreachable("impossible friendship kind");
John McCalld79b4d82010-04-02 00:03:43 +0000867}
868
John McCall5b0829a2010-02-10 09:31:12 +0000869/// Finds the best path from the naming class to the declaring class,
870/// taking friend declarations into account.
871///
John McCalld79b4d82010-04-02 00:03:43 +0000872/// C++0x [class.access.base]p5:
873/// A member m is accessible at the point R when named in class N if
874/// [M1] m as a member of N is public, or
875/// [M2] m as a member of N is private, and R occurs in a member or
876/// friend of class N, or
877/// [M3] m as a member of N is protected, and R occurs in a member or
878/// friend of class N, or in a member or friend of a class P
879/// derived from N, where m as a member of P is public, private,
880/// or protected, or
881/// [M4] there exists a base class B of N that is accessible at R, and
882/// m is accessible at R when named in class B.
883///
884/// C++0x [class.access.base]p4:
885/// A base class B of N is accessible at R, if
886/// [B1] an invented public member of B would be a public member of N, or
887/// [B2] R occurs in a member or friend of class N, and an invented public
888/// member of B would be a private or protected member of N, or
889/// [B3] R occurs in a member or friend of a class P derived from N, and an
890/// invented public member of B would be a private or protected member
891/// of P, or
892/// [B4] there exists a class S such that B is a base class of S accessible
893/// at R and S is a base class of N accessible at R.
894///
895/// Along a single inheritance path we can restate both of these
896/// iteratively:
897///
898/// First, we note that M1-4 are equivalent to B1-4 if the member is
899/// treated as a notional base of its declaring class with inheritance
900/// access equivalent to the member's access. Therefore we need only
901/// ask whether a class B is accessible from a class N in context R.
902///
903/// Let B_1 .. B_n be the inheritance path in question (i.e. where
904/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
905/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
906/// closest accessible base in the path:
907/// Access(a, b) = (* access on the base specifier from a to b *)
908/// Merge(a, forbidden) = forbidden
909/// Merge(a, private) = forbidden
910/// Merge(a, b) = min(a,b)
911/// Accessible(c, forbidden) = false
912/// Accessible(c, private) = (R is c) || IsFriend(c, R)
913/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
914/// Accessible(c, public) = true
915/// ACAB(n) = public
916/// ACAB(i) =
917/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
918/// if Accessible(B_i, AccessToBase) then public else AccessToBase
919///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000920/// B is an accessible base of N at R iff ACAB(1) = public.
John McCalld79b4d82010-04-02 00:03:43 +0000921///
John McCalla8ae2222010-04-06 21:38:20 +0000922/// \param FinalAccess the access of the "final step", or AS_public if
John McCalla332b952010-03-18 23:49:19 +0000923/// there is no final step.
John McCall5b0829a2010-02-10 09:31:12 +0000924/// \return null if friendship is dependent
925static CXXBasePath *FindBestPath(Sema &S,
926 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +0000927 AccessTarget &Target,
John McCalla332b952010-03-18 23:49:19 +0000928 AccessSpecifier FinalAccess,
John McCall5b0829a2010-02-10 09:31:12 +0000929 CXXBasePaths &Paths) {
930 // Derive the paths to the desired base.
John McCalla8ae2222010-04-06 21:38:20 +0000931 const CXXRecordDecl *Derived = Target.getNamingClass();
932 const CXXRecordDecl *Base = Target.getDeclaringClass();
933
934 // FIXME: fail correctly when there are dependent paths.
935 bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
936 Paths);
John McCall5b0829a2010-02-10 09:31:12 +0000937 assert(isDerived && "derived class not actually derived from base");
938 (void) isDerived;
939
940 CXXBasePath *BestPath = 0;
941
John McCalla332b952010-03-18 23:49:19 +0000942 assert(FinalAccess != AS_none && "forbidden access after declaring class");
943
John McCallc62bb642010-03-24 05:22:00 +0000944 bool AnyDependent = false;
945
John McCall5b0829a2010-02-10 09:31:12 +0000946 // Derive the friend-modified access along each path.
947 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
948 PI != PE; ++PI) {
John McCalla8ae2222010-04-06 21:38:20 +0000949 AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +0000950
951 // Walk through the path backwards.
John McCalla332b952010-03-18 23:49:19 +0000952 AccessSpecifier PathAccess = FinalAccess;
John McCall5b0829a2010-02-10 09:31:12 +0000953 CXXBasePath::iterator I = PI->end(), E = PI->begin();
954 while (I != E) {
955 --I;
956
John McCalla332b952010-03-18 23:49:19 +0000957 assert(PathAccess != AS_none);
958
959 // If the declaration is a private member of a base class, there
960 // is no level of friendship in derived classes that can make it
961 // accessible.
962 if (PathAccess == AS_private) {
963 PathAccess = AS_none;
964 break;
965 }
966
John McCalla8ae2222010-04-06 21:38:20 +0000967 const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
968
John McCall5b0829a2010-02-10 09:31:12 +0000969 AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
John McCalld79b4d82010-04-02 00:03:43 +0000970 PathAccess = std::max(PathAccess, BaseAccess);
John McCalla8ae2222010-04-06 21:38:20 +0000971
972 switch (HasAccess(S, EC, NC, PathAccess, Target)) {
973 case AR_inaccessible: break;
974 case AR_accessible:
975 PathAccess = AS_public;
976
977 // Future tests are not against members and so do not have
978 // instance context.
979 Target.suppressInstanceContext();
980 break;
981 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +0000982 AnyDependent = true;
983 goto Next;
John McCall5b0829a2010-02-10 09:31:12 +0000984 }
John McCall5b0829a2010-02-10 09:31:12 +0000985 }
986
987 // Note that we modify the path's Access field to the
988 // friend-modified access.
989 if (BestPath == 0 || PathAccess < BestPath->Access) {
990 BestPath = &*PI;
991 BestPath->Access = PathAccess;
John McCallc62bb642010-03-24 05:22:00 +0000992
993 // Short-circuit if we found a public path.
994 if (BestPath->Access == AS_public)
995 return BestPath;
John McCall5b0829a2010-02-10 09:31:12 +0000996 }
John McCallc62bb642010-03-24 05:22:00 +0000997
998 Next: ;
John McCall5b0829a2010-02-10 09:31:12 +0000999 }
1000
John McCallc62bb642010-03-24 05:22:00 +00001001 assert((!BestPath || BestPath->Access != AS_public) &&
1002 "fell out of loop with public path");
1003
1004 // We didn't find a public path, but at least one path was subject
1005 // to dependent friendship, so delay the check.
1006 if (AnyDependent)
1007 return 0;
1008
John McCall5b0829a2010-02-10 09:31:12 +00001009 return BestPath;
1010}
1011
John McCall417e7442010-09-03 04:56:05 +00001012/// Given that an entity has protected natural access, check whether
1013/// access might be denied because of the protected member access
1014/// restriction.
1015///
1016/// \return true if a note was emitted
1017static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1018 AccessTarget &Target) {
1019 // Only applies to instance accesses.
John McCall5dadb652012-04-07 03:04:20 +00001020 if (!Target.isInstanceMember())
John McCall417e7442010-09-03 04:56:05 +00001021 return false;
John McCall417e7442010-09-03 04:56:05 +00001022
John McCall5dadb652012-04-07 03:04:20 +00001023 assert(Target.isMemberAccess());
1024
John McCalld010ac92013-02-27 00:08:19 +00001025 const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
John McCall417e7442010-09-03 04:56:05 +00001026
1027 for (EffectiveContext::record_iterator
1028 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
1029 const CXXRecordDecl *ECRecord = *I;
John McCall5dadb652012-04-07 03:04:20 +00001030 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
John McCall417e7442010-09-03 04:56:05 +00001031 case AR_accessible: break;
1032 case AR_inaccessible: continue;
1033 case AR_dependent: continue;
1034 }
1035
1036 // The effective context is a subclass of the declaring class.
John McCall5dadb652012-04-07 03:04:20 +00001037 // Check whether the [class.protected] restriction is limiting
1038 // access.
John McCall417e7442010-09-03 04:56:05 +00001039
1040 // To get this exactly right, this might need to be checked more
1041 // holistically; it's not necessarily the case that gaining
1042 // access here would grant us access overall.
1043
John McCall5dadb652012-04-07 03:04:20 +00001044 NamedDecl *D = Target.getTargetDecl();
1045
1046 // If we don't have an instance context, [class.protected] says the
1047 // naming class has to equal the context class.
1048 if (!Target.hasInstanceContext()) {
1049 // If it does, the restriction doesn't apply.
1050 if (NamingClass == ECRecord) continue;
1051
1052 // TODO: it would be great to have a fixit here, since this is
1053 // such an obvious error.
1054 S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1055 << S.Context.getTypeDeclType(ECRecord);
1056 return true;
1057 }
1058
John McCall417e7442010-09-03 04:56:05 +00001059 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1060 assert(InstanceContext && "diagnosing dependent access");
1061
1062 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1063 case AR_accessible: continue;
1064 case AR_dependent: continue;
1065 case AR_inaccessible:
John McCall5dadb652012-04-07 03:04:20 +00001066 break;
1067 }
1068
1069 // Okay, the restriction seems to be what's limiting us.
1070
1071 // Use a special diagnostic for constructors and destructors.
1072 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
1073 (isa<FunctionTemplateDecl>(D) &&
1074 isa<CXXConstructorDecl>(
1075 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
Alp Tokera2794f92014-01-22 07:29:52 +00001076 return S.Diag(D->getLocation(),
1077 diag::note_access_protected_restricted_ctordtor)
1078 << isa<CXXDestructorDecl>(D->getAsFunction());
John McCall417e7442010-09-03 04:56:05 +00001079 }
John McCall5dadb652012-04-07 03:04:20 +00001080
1081 // Otherwise, use the generic diagnostic.
Alp Tokera2794f92014-01-22 07:29:52 +00001082 return S.Diag(D->getLocation(),
1083 diag::note_access_protected_restricted_object)
1084 << S.Context.getTypeDeclType(ECRecord);
John McCall417e7442010-09-03 04:56:05 +00001085 }
1086
1087 return false;
1088}
1089
John McCalld010ac92013-02-27 00:08:19 +00001090/// We are unable to access a given declaration due to its direct
1091/// access control; diagnose that.
1092static void diagnoseBadDirectAccess(Sema &S,
1093 const EffectiveContext &EC,
1094 AccessTarget &entity) {
1095 assert(entity.isMemberAccess());
1096 NamedDecl *D = entity.getTargetDecl();
1097
1098 if (D->getAccess() == AS_protected &&
1099 TryDiagnoseProtectedAccess(S, EC, entity))
1100 return;
1101
1102 // Find an original declaration.
1103 while (D->isOutOfLine()) {
1104 NamedDecl *PrevDecl = 0;
1105 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1106 PrevDecl = VD->getPreviousDecl();
1107 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1108 PrevDecl = FD->getPreviousDecl();
1109 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1110 PrevDecl = TND->getPreviousDecl();
1111 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1112 if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1113 break;
1114 PrevDecl = TD->getPreviousDecl();
1115 }
1116 if (!PrevDecl) break;
1117 D = PrevDecl;
1118 }
1119
1120 CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1121 Decl *ImmediateChild;
1122 if (D->getDeclContext() == DeclaringClass)
1123 ImmediateChild = D;
1124 else {
1125 DeclContext *DC = D->getDeclContext();
1126 while (DC->getParent() != DeclaringClass)
1127 DC = DC->getParent();
1128 ImmediateChild = cast<Decl>(DC);
1129 }
1130
1131 // Check whether there's an AccessSpecDecl preceding this in the
1132 // chain of the DeclContext.
1133 bool isImplicit = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00001134 for (const auto *I : DeclaringClass->decls()) {
1135 if (I == ImmediateChild) break;
1136 if (isa<AccessSpecDecl>(I)) {
John McCalld010ac92013-02-27 00:08:19 +00001137 isImplicit = false;
1138 break;
1139 }
1140 }
1141
1142 S.Diag(D->getLocation(), diag::note_access_natural)
1143 << (unsigned) (D->getAccess() == AS_protected)
1144 << isImplicit;
1145}
1146
John McCall5b0829a2010-02-10 09:31:12 +00001147/// Diagnose the path which caused the given declaration or base class
1148/// to become inaccessible.
1149static void DiagnoseAccessPath(Sema &S,
1150 const EffectiveContext &EC,
John McCalld010ac92013-02-27 00:08:19 +00001151 AccessTarget &entity) {
1152 // Save the instance context to preserve invariants.
1153 AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
John McCalld79b4d82010-04-02 00:03:43 +00001154
John McCalld010ac92013-02-27 00:08:19 +00001155 // This basically repeats the main algorithm but keeps some more
1156 // information.
John McCalld79b4d82010-04-02 00:03:43 +00001157
John McCalld010ac92013-02-27 00:08:19 +00001158 // The natural access so far.
1159 AccessSpecifier accessSoFar = AS_public;
John McCall417e7442010-09-03 04:56:05 +00001160
John McCalld010ac92013-02-27 00:08:19 +00001161 // Check whether we have special rights to the declaring class.
1162 if (entity.isMemberAccess()) {
1163 NamedDecl *D = entity.getTargetDecl();
1164 accessSoFar = D->getAccess();
1165 const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
John McCallf551aca2010-10-20 08:15:06 +00001166
John McCalld010ac92013-02-27 00:08:19 +00001167 switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1168 // If the declaration is accessible when named in its declaring
1169 // class, then we must be constrained by the path.
1170 case AR_accessible:
1171 accessSoFar = AS_public;
1172 entity.suppressInstanceContext();
1173 break;
John McCallf551aca2010-10-20 08:15:06 +00001174
John McCalld010ac92013-02-27 00:08:19 +00001175 case AR_inaccessible:
1176 if (accessSoFar == AS_private ||
1177 declaringClass == entity.getEffectiveNamingClass())
1178 return diagnoseBadDirectAccess(S, EC, entity);
1179 break;
John McCall5b0829a2010-02-10 09:31:12 +00001180
John McCalla8ae2222010-04-06 21:38:20 +00001181 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001182 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001183 }
1184 }
1185
John McCalld010ac92013-02-27 00:08:19 +00001186 CXXBasePaths paths;
1187 CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1188 assert(path.Access != AS_public);
John McCall5b0829a2010-02-10 09:31:12 +00001189
John McCalld010ac92013-02-27 00:08:19 +00001190 CXXBasePath::iterator i = path.end(), e = path.begin();
1191 CXXBasePath::iterator constrainingBase = i;
1192 while (i != e) {
1193 --i;
John McCall5b0829a2010-02-10 09:31:12 +00001194
John McCalld010ac92013-02-27 00:08:19 +00001195 assert(accessSoFar != AS_none && accessSoFar != AS_private);
John McCall5b0829a2010-02-10 09:31:12 +00001196
John McCalld010ac92013-02-27 00:08:19 +00001197 // Is the entity accessible when named in the deriving class, as
1198 // modified by the base specifier?
1199 const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1200 const CXXBaseSpecifier *base = i->Base;
John McCall5b0829a2010-02-10 09:31:12 +00001201
John McCalld010ac92013-02-27 00:08:19 +00001202 // If the access to this base is worse than the access we have to
1203 // the declaration, remember it.
1204 AccessSpecifier baseAccess = base->getAccessSpecifier();
1205 if (baseAccess > accessSoFar) {
1206 constrainingBase = i;
1207 accessSoFar = baseAccess;
1208 }
1209
1210 switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001211 case AR_inaccessible: break;
John McCalld010ac92013-02-27 00:08:19 +00001212 case AR_accessible:
1213 accessSoFar = AS_public;
1214 entity.suppressInstanceContext();
1215 constrainingBase = 0;
1216 break;
John McCalla8ae2222010-04-06 21:38:20 +00001217 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001218 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001219 }
1220
John McCalld010ac92013-02-27 00:08:19 +00001221 // If this was private inheritance, but we don't have access to
1222 // the deriving class, we're done.
1223 if (accessSoFar == AS_private) {
1224 assert(baseAccess == AS_private);
1225 assert(constrainingBase == i);
1226 break;
John McCall5b0829a2010-02-10 09:31:12 +00001227 }
1228 }
1229
John McCalld010ac92013-02-27 00:08:19 +00001230 // If we don't have a constraining base, the access failure must be
1231 // due to the original declaration.
1232 if (constrainingBase == path.end())
1233 return diagnoseBadDirectAccess(S, EC, entity);
1234
1235 // We're constrained by inheritance, but we want to say
1236 // "declared private here" if we're diagnosing a hierarchy
1237 // conversion and this is the final step.
1238 unsigned diagnostic;
1239 if (entity.isMemberAccess() ||
1240 constrainingBase + 1 != path.end()) {
1241 diagnostic = diag::note_access_constrained_by_path;
1242 } else {
1243 diagnostic = diag::note_access_natural;
1244 }
1245
1246 const CXXBaseSpecifier *base = constrainingBase->Base;
1247
1248 S.Diag(base->getSourceRange().getBegin(), diagnostic)
1249 << base->getSourceRange()
1250 << (base->getAccessSpecifier() == AS_protected)
1251 << (base->getAccessSpecifierAsWritten() == AS_none);
1252
1253 if (entity.isMemberAccess())
1254 S.Diag(entity.getTargetDecl()->getLocation(), diag::note_field_decl);
John McCall5b0829a2010-02-10 09:31:12 +00001255}
1256
John McCall1064d7e2010-03-16 05:22:47 +00001257static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
John McCall5b0829a2010-02-10 09:31:12 +00001258 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +00001259 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001260 const CXXRecordDecl *NamingClass = Entity.getNamingClass();
John McCalla8ae2222010-04-06 21:38:20 +00001261 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1262 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
John McCalld79b4d82010-04-02 00:03:43 +00001263
1264 S.Diag(Loc, Entity.getDiag())
1265 << (Entity.getAccess() == AS_protected)
1266 << (D ? D->getDeclName() : DeclarationName())
1267 << S.Context.getTypeDeclType(NamingClass)
1268 << S.Context.getTypeDeclType(DeclaringClass);
1269 DiagnoseAccessPath(S, EC, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001270}
1271
Francois Pichetefb1af92011-05-23 03:43:44 +00001272/// MSVC has a bug where if during an using declaration name lookup,
1273/// the declaration found is unaccessible (private) and that declaration
1274/// was bring into scope via another using declaration whose target
1275/// declaration is accessible (public) then no error is generated.
1276/// Example:
1277/// class A {
1278/// public:
1279/// int f();
1280/// };
1281/// class B : public A {
1282/// private:
1283/// using A::f;
1284/// };
1285/// class C : public B {
1286/// private:
1287/// using B::f;
1288/// };
1289///
1290/// Here, B::f is private so this should fail in Standard C++, but
1291/// because B::f refers to A::f which is public MSVC accepts it.
1292static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1293 SourceLocation AccessLoc,
1294 AccessTarget &Entity) {
1295 if (UsingShadowDecl *Shadow =
1296 dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1297 const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1298 if (Entity.getTargetDecl()->getAccess() == AS_private &&
1299 (OrigDecl->getAccess() == AS_public ||
1300 OrigDecl->getAccess() == AS_protected)) {
Richard Smithe4345902011-12-29 21:57:33 +00001301 S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
Francois Pichetefb1af92011-05-23 03:43:44 +00001302 << Shadow->getUsingDecl()->getQualifiedNameAsString()
1303 << OrigDecl->getQualifiedNameAsString();
1304 return true;
1305 }
1306 }
1307 return false;
1308}
1309
John McCalld79b4d82010-04-02 00:03:43 +00001310/// Determines whether the accessed entity is accessible. Public members
1311/// have been weeded out by this point.
John McCalla8ae2222010-04-06 21:38:20 +00001312static AccessResult IsAccessible(Sema &S,
1313 const EffectiveContext &EC,
1314 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001315 // Determine the actual naming class.
John McCalld010ac92013-02-27 00:08:19 +00001316 const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
John McCall5b0829a2010-02-10 09:31:12 +00001317
John McCalld79b4d82010-04-02 00:03:43 +00001318 AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1319 assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1320
1321 // Before we try to recalculate access paths, try to white-list
1322 // accesses which just trade in on the final step, i.e. accesses
1323 // which don't require [M4] or [B4]. These are by far the most
John McCalla8ae2222010-04-06 21:38:20 +00001324 // common forms of privileged access.
John McCalld79b4d82010-04-02 00:03:43 +00001325 if (UnprivilegedAccess != AS_none) {
John McCalla8ae2222010-04-06 21:38:20 +00001326 switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1327 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +00001328 // This is actually an interesting policy decision. We don't
1329 // *have* to delay immediately here: we can do the full access
1330 // calculation in the hope that friendship on some intermediate
1331 // class will make the declaration accessible non-dependently.
1332 // But that's not cheap, and odds are very good (note: assertion
1333 // made without data) that the friend declaration will determine
1334 // access.
John McCalla8ae2222010-04-06 21:38:20 +00001335 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001336
John McCalla8ae2222010-04-06 21:38:20 +00001337 case AR_accessible: return AR_accessible;
1338 case AR_inaccessible: break;
John McCalld79b4d82010-04-02 00:03:43 +00001339 }
1340 }
1341
John McCalla8ae2222010-04-06 21:38:20 +00001342 AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +00001343
John McCalld79b4d82010-04-02 00:03:43 +00001344 // We lower member accesses to base accesses by pretending that the
1345 // member is a base class of its declaring class.
1346 AccessSpecifier FinalAccess;
1347
John McCall5b0829a2010-02-10 09:31:12 +00001348 if (Entity.isMemberAccess()) {
John McCalld79b4d82010-04-02 00:03:43 +00001349 // Determine if the declaration is accessible from EC when named
1350 // in its declaring class.
John McCall5b0829a2010-02-10 09:31:12 +00001351 NamedDecl *Target = Entity.getTargetDecl();
John McCalla8ae2222010-04-06 21:38:20 +00001352 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCall5b0829a2010-02-10 09:31:12 +00001353
John McCalld79b4d82010-04-02 00:03:43 +00001354 FinalAccess = Target->getAccess();
John McCalla8ae2222010-04-06 21:38:20 +00001355 switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1356 case AR_accessible:
John McCall5149fbf2013-02-22 03:52:55 +00001357 // Target is accessible at EC when named in its declaring class.
1358 // We can now hill-climb and simply check whether the declaring
1359 // class is accessible as a base of the naming class. This is
1360 // equivalent to checking the access of a notional public
1361 // member with no instance context.
John McCalla8ae2222010-04-06 21:38:20 +00001362 FinalAccess = AS_public;
John McCall5149fbf2013-02-22 03:52:55 +00001363 Entity.suppressInstanceContext();
John McCalla8ae2222010-04-06 21:38:20 +00001364 break;
1365 case AR_inaccessible: break;
1366 case AR_dependent: return AR_dependent; // see above
John McCall5b0829a2010-02-10 09:31:12 +00001367 }
1368
John McCalld79b4d82010-04-02 00:03:43 +00001369 if (DeclaringClass == NamingClass)
John McCalla8ae2222010-04-06 21:38:20 +00001370 return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
John McCalld79b4d82010-04-02 00:03:43 +00001371 } else {
1372 FinalAccess = AS_public;
John McCall5b0829a2010-02-10 09:31:12 +00001373 }
1374
John McCalla8ae2222010-04-06 21:38:20 +00001375 assert(Entity.getDeclaringClass() != NamingClass);
John McCall5b0829a2010-02-10 09:31:12 +00001376
1377 // Append the declaration's access if applicable.
1378 CXXBasePaths Paths;
John McCalla8ae2222010-04-06 21:38:20 +00001379 CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
John McCallc62bb642010-03-24 05:22:00 +00001380 if (!Path)
John McCalla8ae2222010-04-06 21:38:20 +00001381 return AR_dependent;
John McCall553c0792010-01-23 00:46:32 +00001382
John McCalld79b4d82010-04-02 00:03:43 +00001383 assert(Path->Access <= UnprivilegedAccess &&
1384 "access along best path worse than direct?");
1385 if (Path->Access == AS_public)
John McCalla8ae2222010-04-06 21:38:20 +00001386 return AR_accessible;
1387 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +00001388}
1389
John McCalla8ae2222010-04-06 21:38:20 +00001390static void DelayDependentAccess(Sema &S,
1391 const EffectiveContext &EC,
1392 SourceLocation Loc,
1393 const AccessTarget &Entity) {
John McCallc62bb642010-03-24 05:22:00 +00001394 assert(EC.isDependent() && "delaying non-dependent access");
John McCall816d75b2010-03-24 07:46:06 +00001395 DeclContext *DC = EC.getInnerContext();
John McCallc62bb642010-03-24 05:22:00 +00001396 assert(DC->isDependentContext() && "delaying non-dependent access");
1397 DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1398 Loc,
1399 Entity.isMemberAccess(),
1400 Entity.getAccess(),
1401 Entity.getTargetDecl(),
1402 Entity.getNamingClass(),
John McCalla8ae2222010-04-06 21:38:20 +00001403 Entity.getBaseObjectType(),
John McCallc62bb642010-03-24 05:22:00 +00001404 Entity.getDiag());
John McCall553c0792010-01-23 00:46:32 +00001405}
1406
John McCall5b0829a2010-02-10 09:31:12 +00001407/// Checks access to an entity from the given effective context.
John McCalla8ae2222010-04-06 21:38:20 +00001408static AccessResult CheckEffectiveAccess(Sema &S,
1409 const EffectiveContext &EC,
1410 SourceLocation Loc,
1411 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001412 assert(Entity.getAccess() != AS_public && "called for public access!");
John McCall553c0792010-01-23 00:46:32 +00001413
John McCalld79b4d82010-04-02 00:03:43 +00001414 switch (IsAccessible(S, EC, Entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001415 case AR_dependent:
1416 DelayDependentAccess(S, EC, Loc, Entity);
1417 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001418
John McCalla8ae2222010-04-06 21:38:20 +00001419 case AR_inaccessible:
Reid Kleckner42063b02014-02-08 02:40:20 +00001420 if (S.getLangOpts().MSVCCompat &&
1421 IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1422 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +00001423 if (!Entity.isQuiet())
1424 DiagnoseBadAccess(S, Loc, EC, Entity);
John McCalla8ae2222010-04-06 21:38:20 +00001425 return AR_inaccessible;
John McCalld79b4d82010-04-02 00:03:43 +00001426
John McCalla8ae2222010-04-06 21:38:20 +00001427 case AR_accessible:
1428 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +00001429 }
1430
John McCalla8ae2222010-04-06 21:38:20 +00001431 // silence unnecessary warning
1432 llvm_unreachable("invalid access result");
John McCall5b0829a2010-02-10 09:31:12 +00001433}
John McCall553c0792010-01-23 00:46:32 +00001434
John McCall5b0829a2010-02-10 09:31:12 +00001435static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
John McCalla8ae2222010-04-06 21:38:20 +00001436 AccessTarget &Entity) {
John McCall5b0829a2010-02-10 09:31:12 +00001437 // If the access path is public, it's accessible everywhere.
1438 if (Entity.getAccess() == AS_public)
1439 return Sema::AR_accessible;
John McCall553c0792010-01-23 00:46:32 +00001440
John McCallc1465822011-02-14 07:13:47 +00001441 // If we're currently parsing a declaration, we may need to delay
1442 // access control checking, because our effective context might be
1443 // different based on what the declaration comes out as.
1444 //
1445 // For example, we might be parsing a declaration with a scope
1446 // specifier, like this:
1447 // A::private_type A::foo() { ... }
1448 //
1449 // Or we might be parsing something that will turn out to be a friend:
1450 // void foo(A::private_type);
1451 // void B::foo(A::private_type);
1452 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1453 S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
John McCall5b0829a2010-02-10 09:31:12 +00001454 return Sema::AR_delayed;
John McCall553c0792010-01-23 00:46:32 +00001455 }
1456
John McCalla8ae2222010-04-06 21:38:20 +00001457 EffectiveContext EC(S.CurContext);
1458 switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1459 case AR_accessible: return Sema::AR_accessible;
1460 case AR_inaccessible: return Sema::AR_inaccessible;
1461 case AR_dependent: return Sema::AR_dependent;
1462 }
1463 llvm_unreachable("falling off end");
John McCall553c0792010-01-23 00:46:32 +00001464}
1465
Richard Smithad5c1ca2013-04-29 10:13:55 +00001466void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
John McCall9743e8d2011-02-15 22:51:53 +00001467 // Access control for names used in the declarations of functions
1468 // and function templates should normally be evaluated in the context
1469 // of the declaration, just in case it's a friend of something.
1470 // However, this does not apply to local extern declarations.
1471
Richard Smithad5c1ca2013-04-29 10:13:55 +00001472 DeclContext *DC = D->getDeclContext();
Richard Smith608da012013-12-11 03:35:27 +00001473 if (D->isLocalExternDecl()) {
1474 DC = D->getLexicalDeclContext();
1475 } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1476 DC = FN;
Richard Smithad5c1ca2013-04-29 10:13:55 +00001477 } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1478 DC = cast<DeclContext>(TD->getTemplatedDecl());
John McCall9743e8d2011-02-15 22:51:53 +00001479 }
1480
Chandler Carruthaad30072010-04-18 08:23:21 +00001481 EffectiveContext EC(DC);
John McCall86121512010-01-27 03:50:35 +00001482
John McCalla8ae2222010-04-06 21:38:20 +00001483 AccessTarget Target(DD.getAccessData());
1484
1485 if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
John McCall86121512010-01-27 03:50:35 +00001486 DD.Triggered = true;
1487}
1488
John McCallc62bb642010-03-24 05:22:00 +00001489void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1490 const MultiLevelTemplateArgumentList &TemplateArgs) {
1491 SourceLocation Loc = DD.getAccessLoc();
1492 AccessSpecifier Access = DD.getAccess();
1493
1494 Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1495 TemplateArgs);
1496 if (!NamingD) return;
1497 Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1498 TemplateArgs);
1499 if (!TargetD) return;
1500
1501 if (DD.isAccessToMember()) {
John McCalla8ae2222010-04-06 21:38:20 +00001502 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1503 NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1504 QualType BaseObjectType = DD.getAccessBaseObjectType();
1505 if (!BaseObjectType.isNull()) {
1506 BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1507 DeclarationName());
1508 if (BaseObjectType.isNull()) return;
1509 }
1510
1511 AccessTarget Entity(Context,
1512 AccessTarget::Member,
1513 NamingClass,
1514 DeclAccessPair::make(TargetDecl, Access),
1515 BaseObjectType);
John McCallc62bb642010-03-24 05:22:00 +00001516 Entity.setDiag(DD.getDiagnostic());
1517 CheckAccess(*this, Loc, Entity);
1518 } else {
John McCalla8ae2222010-04-06 21:38:20 +00001519 AccessTarget Entity(Context,
1520 AccessTarget::Base,
1521 cast<CXXRecordDecl>(TargetD),
1522 cast<CXXRecordDecl>(NamingD),
1523 Access);
John McCallc62bb642010-03-24 05:22:00 +00001524 Entity.setDiag(DD.getDiagnostic());
1525 CheckAccess(*this, Loc, Entity);
1526 }
1527}
1528
John McCall5b0829a2010-02-10 09:31:12 +00001529Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001530 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001531 if (!getLangOpts().AccessControl ||
John McCall1064d7e2010-03-16 05:22:47 +00001532 !E->getNamingClass() ||
John McCalla0296f72010-03-19 07:35:19 +00001533 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001534 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001535
John McCalla8ae2222010-04-06 21:38:20 +00001536 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1537 Found, QualType());
John McCall1064d7e2010-03-16 05:22:47 +00001538 Entity.setDiag(diag::err_access) << E->getSourceRange();
1539
1540 return CheckAccess(*this, E->getNameLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001541}
1542
1543/// Perform access-control checking on a previously-unresolved member
1544/// access which has now been resolved to a member.
John McCall5b0829a2010-02-10 09:31:12 +00001545Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001546 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001547 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001548 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001549 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001550
John McCalla8ae2222010-04-06 21:38:20 +00001551 QualType BaseType = E->getBaseType();
1552 if (E->isArrow())
1553 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1554
1555 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1556 Found, BaseType);
John McCall1064d7e2010-03-16 05:22:47 +00001557 Entity.setDiag(diag::err_access) << E->getSourceRange();
1558
1559 return CheckAccess(*this, E->getMemberLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001560}
1561
John McCalld4274212012-04-09 20:53:23 +00001562/// Is the given special member function accessible for the purposes of
1563/// deciding whether to define a special member function as deleted?
1564bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
1565 AccessSpecifier access,
1566 QualType objectType) {
1567 // Fast path.
1568 if (access == AS_public || !getLangOpts().AccessControl) return true;
1569
1570 AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
1571 DeclAccessPair::make(decl, access), objectType);
1572
1573 // Suppress diagnostics.
1574 entity.setDiag(PDiag());
1575
1576 switch (CheckAccess(*this, SourceLocation(), entity)) {
1577 case AR_accessible: return true;
1578 case AR_inaccessible: return false;
1579 case AR_dependent: llvm_unreachable("dependent for =delete computation");
1580 case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1581 }
1582 llvm_unreachable("bad access result");
1583}
1584
John McCall5b0829a2010-02-10 09:31:12 +00001585Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
John McCall1064d7e2010-03-16 05:22:47 +00001586 CXXDestructorDecl *Dtor,
John McCall5dadb652012-04-07 03:04:20 +00001587 const PartialDiagnostic &PDiag,
1588 QualType ObjectTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001589 if (!getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001590 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001591
John McCall1064d7e2010-03-16 05:22:47 +00001592 // There's never a path involved when checking implicit destructor access.
John McCall6781b052010-02-02 08:45:54 +00001593 AccessSpecifier Access = Dtor->getAccess();
1594 if (Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001595 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001596
John McCall1064d7e2010-03-16 05:22:47 +00001597 CXXRecordDecl *NamingClass = Dtor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001598 if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
1599
John McCalla8ae2222010-04-06 21:38:20 +00001600 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1601 DeclAccessPair::make(Dtor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001602 ObjectTy);
John McCall1064d7e2010-03-16 05:22:47 +00001603 Entity.setDiag(PDiag); // TODO: avoid copy
1604
1605 return CheckAccess(*this, Loc, Entity);
John McCall6781b052010-02-02 08:45:54 +00001606}
1607
John McCall760af172010-02-01 03:16:54 +00001608/// Checks access to a constructor.
John McCall5b0829a2010-02-10 09:31:12 +00001609Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001610 CXXConstructorDecl *Constructor,
1611 const InitializedEntity &Entity,
1612 AccessSpecifier Access,
1613 bool IsCopyBindingRefToTemp) {
John McCall5dadb652012-04-07 03:04:20 +00001614 if (!getLangOpts().AccessControl || Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001615 return AR_accessible;
John McCall760af172010-02-01 03:16:54 +00001616
Alexis Hunteef8ee02011-06-10 03:50:41 +00001617 PartialDiagnostic PD(PDiag());
Anders Carlssona01874b2010-04-21 18:47:17 +00001618 switch (Entity.getKind()) {
1619 default:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001620 PD = PDiag(IsCopyBindingRefToTemp
1621 ? diag::ext_rvalue_to_reference_access_ctor
1622 : diag::err_access_ctor);
1623
Anders Carlssona01874b2010-04-21 18:47:17 +00001624 break;
John McCall1064d7e2010-03-16 05:22:47 +00001625
Anders Carlsson05bf0092010-04-22 05:40:53 +00001626 case InitializedEntity::EK_Base:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001627 PD = PDiag(diag::err_access_base_ctor);
1628 PD << Entity.isInheritedVirtualBase()
1629 << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
Anders Carlssona01874b2010-04-21 18:47:17 +00001630 break;
Anders Carlsson05bf0092010-04-22 05:40:53 +00001631
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001632 case InitializedEntity::EK_Member: {
1633 const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00001634 PD = PDiag(diag::err_access_field_ctor);
1635 PD << Field->getType() << getSpecialMember(Constructor);
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001636 break;
1637 }
Anders Carlssona01874b2010-04-21 18:47:17 +00001638
Douglas Gregor19666fb2012-02-15 16:57:26 +00001639 case InitializedEntity::EK_LambdaCapture: {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001640 StringRef VarName = Entity.getCapturedVarName();
Douglas Gregor19666fb2012-02-15 16:57:26 +00001641 PD = PDiag(diag::err_access_lambda_capture);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001642 PD << VarName << Entity.getType() << getSpecialMember(Constructor);
Douglas Gregor19666fb2012-02-15 16:57:26 +00001643 break;
1644 }
1645
Anders Carlsson43c64af2010-04-21 19:52:01 +00001646 }
1647
John McCall5dadb652012-04-07 03:04:20 +00001648 return CheckConstructorAccess(UseLoc, Constructor, Entity, Access, PD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00001649}
1650
1651/// Checks access to a constructor.
1652Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1653 CXXConstructorDecl *Constructor,
John McCall5dadb652012-04-07 03:04:20 +00001654 const InitializedEntity &Entity,
Alexis Hunteef8ee02011-06-10 03:50:41 +00001655 AccessSpecifier Access,
John McCall5dadb652012-04-07 03:04:20 +00001656 const PartialDiagnostic &PD) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001657 if (!getLangOpts().AccessControl ||
Alexis Hunteef8ee02011-06-10 03:50:41 +00001658 Access == AS_public)
1659 return AR_accessible;
1660
1661 CXXRecordDecl *NamingClass = Constructor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001662
1663 // Initializing a base sub-object is an instance method call on an
1664 // object of the derived class. Otherwise, we have an instance method
1665 // call on an object of the constructed type.
1666 CXXRecordDecl *ObjectClass;
1667 if (Entity.getKind() == InitializedEntity::EK_Base) {
1668 ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1669 } else {
1670 ObjectClass = NamingClass;
1671 }
1672
Alexis Hunteef8ee02011-06-10 03:50:41 +00001673 AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
1674 DeclAccessPair::make(Constructor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001675 Context.getTypeDeclType(ObjectClass));
Alexis Hunteef8ee02011-06-10 03:50:41 +00001676 AccessEntity.setDiag(PD);
1677
Anders Carlssona01874b2010-04-21 18:47:17 +00001678 return CheckAccess(*this, UseLoc, AccessEntity);
John McCall5dadb652012-04-07 03:04:20 +00001679}
John McCall760af172010-02-01 03:16:54 +00001680
John McCallfb6f5262010-03-18 08:19:33 +00001681/// Checks access to an overloaded operator new or delete.
1682Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1683 SourceRange PlacementRange,
1684 CXXRecordDecl *NamingClass,
Alexis Huntf91729462011-05-12 22:46:25 +00001685 DeclAccessPair Found,
1686 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001687 if (!getLangOpts().AccessControl ||
John McCallfb6f5262010-03-18 08:19:33 +00001688 !NamingClass ||
John McCalla0296f72010-03-19 07:35:19 +00001689 Found.getAccess() == AS_public)
John McCallfb6f5262010-03-18 08:19:33 +00001690 return AR_accessible;
1691
John McCalla8ae2222010-04-06 21:38:20 +00001692 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1693 QualType());
Alexis Huntf91729462011-05-12 22:46:25 +00001694 if (Diagnose)
1695 Entity.setDiag(diag::err_access)
1696 << PlacementRange;
John McCallfb6f5262010-03-18 08:19:33 +00001697
1698 return CheckAccess(*this, OpLoc, Entity);
1699}
1700
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001701/// \brief Checks access to a member.
1702Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1703 CXXRecordDecl *NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001704 DeclAccessPair Found) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001705 if (!getLangOpts().AccessControl ||
1706 !NamingClass ||
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001707 Found.getAccess() == AS_public)
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001708 return AR_accessible;
1709
1710 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001711 Found, QualType());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001712
1713 return CheckAccess(*this, UseLoc, Entity);
1714}
1715
John McCall760af172010-02-01 03:16:54 +00001716/// Checks access to an overloaded member operator, including
1717/// conversion operators.
John McCall5b0829a2010-02-10 09:31:12 +00001718Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1719 Expr *ObjectExpr,
John McCall1064d7e2010-03-16 05:22:47 +00001720 Expr *ArgExpr,
John McCalla0296f72010-03-19 07:35:19 +00001721 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001722 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001723 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001724 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001725
John McCall30909032011-09-21 08:36:56 +00001726 const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
John McCallb3a44002010-01-28 01:42:12 +00001727 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1728
John McCalla8ae2222010-04-06 21:38:20 +00001729 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1730 ObjectExpr->getType());
John McCall1064d7e2010-03-16 05:22:47 +00001731 Entity.setDiag(diag::err_access)
1732 << ObjectExpr->getSourceRange()
1733 << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
1734
1735 return CheckAccess(*this, OpLoc, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001736}
John McCallb3a44002010-01-28 01:42:12 +00001737
John McCalla0a96892012-08-10 03:15:35 +00001738/// Checks access to the target of a friend declaration.
1739Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
Alp Tokera2794f92014-01-22 07:29:52 +00001740 assert(isa<CXXMethodDecl>(target->getAsFunction()));
John McCalla0a96892012-08-10 03:15:35 +00001741
1742 // Friendship lookup is a redeclaration lookup, so there's never an
1743 // inheritance path modifying access.
1744 AccessSpecifier access = target->getAccess();
1745
1746 if (!getLangOpts().AccessControl || access == AS_public)
1747 return AR_accessible;
1748
Alp Toker2bd4a282014-01-22 07:53:08 +00001749 CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
John McCalla0a96892012-08-10 03:15:35 +00001750 assert(method->getQualifier());
1751
1752 AccessTarget entity(Context, AccessTarget::Member,
1753 cast<CXXRecordDecl>(target->getDeclContext()),
1754 DeclAccessPair::make(target, access),
1755 /*no instance context*/ QualType());
1756 entity.setDiag(diag::err_access_friend_function)
1757 << method->getQualifierLoc().getSourceRange();
1758
1759 // We need to bypass delayed-diagnostics because we might be called
1760 // while the ParsingDeclarator is active.
1761 EffectiveContext EC(CurContext);
1762 switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1763 case AR_accessible: return Sema::AR_accessible;
1764 case AR_inaccessible: return Sema::AR_inaccessible;
1765 case AR_dependent: return Sema::AR_dependent;
1766 }
1767 llvm_unreachable("falling off end");
1768}
1769
John McCall16df1e52010-03-30 21:47:33 +00001770Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1771 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001772 if (!getLangOpts().AccessControl ||
John McCallb493d532010-03-30 22:20:00 +00001773 Found.getAccess() == AS_none ||
John McCall16df1e52010-03-30 21:47:33 +00001774 Found.getAccess() == AS_public)
1775 return AR_accessible;
1776
John McCall8d08b9b2010-08-27 09:08:28 +00001777 OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
John McCall8c12dc42010-04-22 18:44:12 +00001778 CXXRecordDecl *NamingClass = Ovl->getNamingClass();
John McCall16df1e52010-03-30 21:47:33 +00001779
John McCalla8ae2222010-04-06 21:38:20 +00001780 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
John McCall5dadb652012-04-07 03:04:20 +00001781 /*no instance context*/ QualType());
John McCall16df1e52010-03-30 21:47:33 +00001782 Entity.setDiag(diag::err_access)
1783 << Ovl->getSourceRange();
1784
1785 return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1786}
1787
John McCall5b0829a2010-02-10 09:31:12 +00001788/// Checks access for a hierarchy conversion.
1789///
John McCall5b0829a2010-02-10 09:31:12 +00001790/// \param ForceCheck true if this check should be performed even if access
1791/// control is disabled; some things rely on this for semantics
1792/// \param ForceUnprivileged true if this check should proceed as if the
1793/// context had no special privileges
John McCall5b0829a2010-02-10 09:31:12 +00001794Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
John McCall5b0829a2010-02-10 09:31:12 +00001795 QualType Base,
1796 QualType Derived,
1797 const CXXBasePath &Path,
John McCall1064d7e2010-03-16 05:22:47 +00001798 unsigned DiagID,
John McCall5b0829a2010-02-10 09:31:12 +00001799 bool ForceCheck,
John McCall1064d7e2010-03-16 05:22:47 +00001800 bool ForceUnprivileged) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001801 if (!ForceCheck && !getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001802 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001803
John McCall5b0829a2010-02-10 09:31:12 +00001804 if (Path.Access == AS_public)
1805 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001806
John McCall5b0829a2010-02-10 09:31:12 +00001807 CXXRecordDecl *BaseD, *DerivedD;
1808 BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1809 DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
John McCall1064d7e2010-03-16 05:22:47 +00001810
John McCalla8ae2222010-04-06 21:38:20 +00001811 AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1812 Path.Access);
John McCall1064d7e2010-03-16 05:22:47 +00001813 if (DiagID)
1814 Entity.setDiag(DiagID) << Derived << Base;
John McCall5b0829a2010-02-10 09:31:12 +00001815
John McCalla8ae2222010-04-06 21:38:20 +00001816 if (ForceUnprivileged) {
1817 switch (CheckEffectiveAccess(*this, EffectiveContext(),
1818 AccessLoc, Entity)) {
1819 case ::AR_accessible: return Sema::AR_accessible;
1820 case ::AR_inaccessible: return Sema::AR_inaccessible;
1821 case ::AR_dependent: return Sema::AR_dependent;
1822 }
1823 llvm_unreachable("unexpected result from CheckEffectiveAccess");
1824 }
John McCall1064d7e2010-03-16 05:22:47 +00001825 return CheckAccess(*this, AccessLoc, Entity);
John McCallb3a44002010-01-28 01:42:12 +00001826}
1827
John McCall553c0792010-01-23 00:46:32 +00001828/// Checks access to all the declarations in the given result set.
John McCall5b0829a2010-02-10 09:31:12 +00001829void Sema::CheckLookupAccess(const LookupResult &R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001830 assert(getLangOpts().AccessControl
John McCall5b0829a2010-02-10 09:31:12 +00001831 && "performing access check without access control");
1832 assert(R.getNamingClass() && "performing access check without naming class");
1833
John McCall1064d7e2010-03-16 05:22:47 +00001834 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1835 if (I.getAccess() != AS_public) {
John McCalla8ae2222010-04-06 21:38:20 +00001836 AccessTarget Entity(Context, AccessedEntity::Member,
1837 R.getNamingClass(), I.getPair(),
Erik Verbruggen631dfc62011-09-19 15:10:40 +00001838 R.getBaseObjectType());
John McCall1064d7e2010-03-16 05:22:47 +00001839 Entity.setDiag(diag::err_access);
John McCall1064d7e2010-03-16 05:22:47 +00001840 CheckAccess(*this, R.getNameLoc(), Entity);
1841 }
1842 }
John McCall553c0792010-01-23 00:46:32 +00001843}
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001844
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001845/// Checks access to Decl from the given class. The check will take access
1846/// specifiers into account, but no member access expressions and such.
1847///
1848/// \param Decl the declaration to check if it can be accessed
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001849/// \param Ctx the class/context from which to start the search
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001850/// \return true if the Decl is accessible from the Class, false otherwise.
Douglas Gregor03ba1882011-11-03 16:51:37 +00001851bool Sema::IsSimplyAccessible(NamedDecl *Decl, DeclContext *Ctx) {
1852 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) {
Douglas Gregor3b52b692011-11-03 17:41:55 +00001853 if (!Decl->isCXXClassMember())
Douglas Gregor03ba1882011-11-03 16:51:37 +00001854 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001855
Douglas Gregor03ba1882011-11-03 16:51:37 +00001856 QualType qType = Class->getTypeForDecl()->getCanonicalTypeInternal();
1857 AccessTarget Entity(Context, AccessedEntity::Member, Class,
1858 DeclAccessPair::make(Decl, Decl->getAccess()),
1859 qType);
1860 if (Entity.getAccess() == AS_public)
1861 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001862
Douglas Gregor03ba1882011-11-03 16:51:37 +00001863 EffectiveContext EC(CurContext);
1864 return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1865 }
1866
Douglas Gregor21ceb182011-11-03 19:00:24 +00001867 if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Decl)) {
1868 // @public and @package ivars are always accessible.
1869 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1870 Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1871 return true;
Serge Pavlov64bc7032013-05-07 16:56:03 +00001872
Douglas Gregor21ceb182011-11-03 19:00:24 +00001873 // If we are inside a class or category implementation, determine the
1874 // interface we're in.
1875 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1876 if (ObjCMethodDecl *MD = getCurMethodDecl())
1877 ClassOfMethodDecl = MD->getClassInterface();
1878 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1879 if (ObjCImplDecl *Impl
1880 = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1881 if (ObjCImplementationDecl *IMPD
1882 = dyn_cast<ObjCImplementationDecl>(Impl))
1883 ClassOfMethodDecl = IMPD->getClassInterface();
1884 else if (ObjCCategoryImplDecl* CatImplClass
1885 = dyn_cast<ObjCCategoryImplDecl>(Impl))
1886 ClassOfMethodDecl = CatImplClass->getClassInterface();
1887 }
1888 }
1889
1890 // If we're not in an interface, this ivar is inaccessible.
1891 if (!ClassOfMethodDecl)
1892 return false;
1893
1894 // If we're inside the same interface that owns the ivar, we're fine.
Douglas Gregor0b144e12011-12-15 00:29:59 +00001895 if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
Douglas Gregor21ceb182011-11-03 19:00:24 +00001896 return true;
1897
1898 // If the ivar is private, it's inaccessible.
1899 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1900 return false;
1901
1902 return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1903 }
1904
Douglas Gregor03ba1882011-11-03 16:51:37 +00001905 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001906}