blob: 0f1df58e6d105d37edc1c148bc048dc6bd9c95c8 [file] [log] [blame]
John McCall526ab472011-10-25 17:37:35 +00001//===--- SemaPseudoObject.cpp - Semantic Analysis for Pseudo-Objects ------===//
2//
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 implements semantic analysis for expressions involving
11// pseudo-object references. Pseudo-objects are conceptual objects
12// whose storage is entirely abstract and all accesses to which are
13// translated through some sort of abstraction barrier.
14//
15// For example, Objective-C objects can have "properties", either
16// declared or undeclared. A property may be accessed by writing
17// expr.prop
18// where 'expr' is an r-value of Objective-C pointer type and 'prop'
19// is the name of the property. If this expression is used in a context
20// needing an r-value, it is treated as if it were a message-send
21// of the associated 'getter' selector, typically:
22// [expr prop]
23// If it is used as the LHS of a simple assignment, it is treated
24// as a message-send of the associated 'setter' selector, typically:
25// [expr setProp: RHS]
26// If it is used as the LHS of a compound assignment, or the operand
27// of a unary increment or decrement, both are required; for example,
28// 'expr.prop *= 100' would be translated to:
29// [expr setProp: [expr prop] * 100]
30//
31//===----------------------------------------------------------------------===//
32
33#include "clang/Sema/SemaInternal.h"
John McCall526ab472011-10-25 17:37:35 +000034#include "clang/AST/ExprObjC.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000035#include "clang/Basic/CharInfo.h"
John McCall526ab472011-10-25 17:37:35 +000036#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Sema/Initialization.h"
38#include "clang/Sema/ScopeInfo.h"
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +000039#include "llvm/ADT/SmallString.h"
John McCall526ab472011-10-25 17:37:35 +000040
41using namespace clang;
42using namespace sema;
43
John McCallfe96e0b2011-11-06 09:01:30 +000044namespace {
45 // Basically just a very focused copy of TreeTransform.
46 template <class T> struct Rebuilder {
47 Sema &S;
48 Rebuilder(Sema &S) : S(S) {}
49
50 T &getDerived() { return static_cast<T&>(*this); }
51
52 Expr *rebuild(Expr *e) {
53 // Fast path: nothing to look through.
54 if (typename T::specific_type *specific
55 = dyn_cast<typename T::specific_type>(e))
56 return getDerived().rebuildSpecific(specific);
57
58 // Otherwise, we should look through and rebuild anything that
59 // IgnoreParens would.
60
61 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
62 e = rebuild(parens->getSubExpr());
63 return new (S.Context) ParenExpr(parens->getLParen(),
64 parens->getRParen(),
65 e);
66 }
67
68 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
69 assert(uop->getOpcode() == UO_Extension);
70 e = rebuild(uop->getSubExpr());
71 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
72 uop->getType(),
73 uop->getValueKind(),
74 uop->getObjectKind(),
75 uop->getOperatorLoc());
76 }
77
78 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
79 assert(!gse->isResultDependent());
80 unsigned resultIndex = gse->getResultIndex();
81 unsigned numAssocs = gse->getNumAssocs();
82
83 SmallVector<Expr*, 8> assocs(numAssocs);
84 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
85
86 for (unsigned i = 0; i != numAssocs; ++i) {
87 Expr *assoc = gse->getAssocExpr(i);
88 if (i == resultIndex) assoc = rebuild(assoc);
89 assocs[i] = assoc;
90 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
91 }
92
93 return new (S.Context) GenericSelectionExpr(S.Context,
94 gse->getGenericLoc(),
95 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000096 assocTypes,
97 assocs,
John McCallfe96e0b2011-11-06 09:01:30 +000098 gse->getDefaultLoc(),
99 gse->getRParenLoc(),
100 gse->containsUnexpandedParameterPack(),
101 resultIndex);
102 }
103
Eli Friedman75807f22013-07-20 00:40:58 +0000104 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
105 assert(!ce->isConditionDependent());
106
107 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
108 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
109 rebuiltExpr = rebuild(rebuiltExpr);
110
111 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
112 ce->getCond(),
113 LHS, RHS,
114 rebuiltExpr->getType(),
115 rebuiltExpr->getValueKind(),
116 rebuiltExpr->getObjectKind(),
117 ce->getRParenLoc(),
118 ce->isConditionTrue(),
119 rebuiltExpr->isTypeDependent(),
120 rebuiltExpr->isValueDependent());
121 }
122
John McCallfe96e0b2011-11-06 09:01:30 +0000123 llvm_unreachable("bad expression to rebuild!");
124 }
125 };
126
127 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
128 Expr *NewBase;
129 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Kramer5c29d692011-11-06 09:50:13 +0000130 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000131
132 typedef ObjCPropertyRefExpr specific_type;
133 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
134 // Fortunately, the constraint that we're rebuilding something
135 // with a base limits the number of cases here.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000136 assert(refExpr->isObjectReceiver());
John McCallfe96e0b2011-11-06 09:01:30 +0000137
138 if (refExpr->isExplicitProperty()) {
139 return new (S.Context)
140 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
141 refExpr->getType(), refExpr->getValueKind(),
142 refExpr->getObjectKind(), refExpr->getLocation(),
143 NewBase);
144 }
145 return new (S.Context)
146 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
147 refExpr->getImplicitPropertySetter(),
148 refExpr->getType(), refExpr->getValueKind(),
149 refExpr->getObjectKind(),refExpr->getLocation(),
150 NewBase);
151 }
152 };
153
Ted Kremeneke65b0862012-03-06 20:05:56 +0000154 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
155 Expr *NewBase;
156 Expr *NewKeyExpr;
157 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
158 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
159 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
160
161 typedef ObjCSubscriptRefExpr specific_type;
162 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
163 assert(refExpr->getBaseExpr());
164 assert(refExpr->getKeyExpr());
165
166 return new (S.Context)
167 ObjCSubscriptRefExpr(NewBase,
168 NewKeyExpr,
169 refExpr->getType(), refExpr->getValueKind(),
170 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
171 refExpr->setAtIndexMethodDecl(),
172 refExpr->getRBracket());
173 }
174 };
John McCall5e77d762013-04-16 07:28:30 +0000175
176 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
177 Expr *NewBase;
178 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
179 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
180
181 typedef MSPropertyRefExpr specific_type;
182 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
183 assert(refExpr->getBaseExpr());
184
185 return new (S.Context)
186 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
187 refExpr->isArrow(), refExpr->getType(),
188 refExpr->getValueKind(), refExpr->getQualifierLoc(),
189 refExpr->getMemberLoc());
190 }
191 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000192
John McCallfe96e0b2011-11-06 09:01:30 +0000193 class PseudoOpBuilder {
194 public:
195 Sema &S;
196 unsigned ResultIndex;
197 SourceLocation GenericLoc;
198 SmallVector<Expr *, 4> Semantics;
199
200 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
201 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
202 GenericLoc(genericLoc) {}
203
Matt Beaumont-Gayfb3cb9a2011-11-08 01:53:17 +0000204 virtual ~PseudoOpBuilder() {}
205
John McCallfe96e0b2011-11-06 09:01:30 +0000206 /// Add a normal semantic expression.
207 void addSemanticExpr(Expr *semantic) {
208 Semantics.push_back(semantic);
209 }
210
211 /// Add the 'result' semantic expression.
212 void addResultSemanticExpr(Expr *resultExpr) {
213 assert(ResultIndex == PseudoObjectExpr::NoResult);
214 ResultIndex = Semantics.size();
215 Semantics.push_back(resultExpr);
216 }
217
218 ExprResult buildRValueOperation(Expr *op);
219 ExprResult buildAssignmentOperation(Scope *Sc,
220 SourceLocation opLoc,
221 BinaryOperatorKind opcode,
222 Expr *LHS, Expr *RHS);
223 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
224 UnaryOperatorKind opcode,
225 Expr *op);
226
Jordan Rosed3934582012-09-28 22:21:30 +0000227 virtual ExprResult complete(Expr *syntacticForm);
John McCallfe96e0b2011-11-06 09:01:30 +0000228
229 OpaqueValueExpr *capture(Expr *op);
230 OpaqueValueExpr *captureValueAsResult(Expr *op);
231
232 void setResultToLastSemantic() {
233 assert(ResultIndex == PseudoObjectExpr::NoResult);
234 ResultIndex = Semantics.size() - 1;
235 }
236
237 /// Return true if assignments have a non-void result.
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000238 bool CanCaptureValue(Expr *exp) {
239 if (exp->isGLValue())
240 return true;
241 QualType ty = exp->getType();
Eli Friedman00fa4292012-11-13 23:16:33 +0000242 assert(!ty->isIncompleteType());
243 assert(!ty->isDependentType());
244
245 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
246 return ClassDecl->isTriviallyCopyable();
247 return true;
248 }
John McCallfe96e0b2011-11-06 09:01:30 +0000249
250 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
251 virtual ExprResult buildGet() = 0;
252 virtual ExprResult buildSet(Expr *, SourceLocation,
253 bool captureSetValueAsResult) = 0;
254 };
255
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000256 /// A PseudoOpBuilder for Objective-C \@properties.
John McCallfe96e0b2011-11-06 09:01:30 +0000257 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
258 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000259 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCallfe96e0b2011-11-06 09:01:30 +0000260 OpaqueValueExpr *InstanceReceiver;
261 ObjCMethodDecl *Getter;
262
263 ObjCMethodDecl *Setter;
264 Selector SetterSelector;
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000265 Selector GetterSelector;
John McCallfe96e0b2011-11-06 09:01:30 +0000266
267 public:
268 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
269 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000270 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) {
John McCallfe96e0b2011-11-06 09:01:30 +0000271 }
272
273 ExprResult buildRValueOperation(Expr *op);
274 ExprResult buildAssignmentOperation(Scope *Sc,
275 SourceLocation opLoc,
276 BinaryOperatorKind opcode,
277 Expr *LHS, Expr *RHS);
278 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
279 UnaryOperatorKind opcode,
280 Expr *op);
281
282 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000283 bool findSetter(bool warn=true);
John McCallfe96e0b2011-11-06 09:01:30 +0000284 bool findGetter();
285
286 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
287 ExprResult buildGet();
288 ExprResult buildSet(Expr *op, SourceLocation, bool);
Jordan Rosed3934582012-09-28 22:21:30 +0000289 ExprResult complete(Expr *SyntacticForm);
290
291 bool isWeakProperty() const;
John McCallfe96e0b2011-11-06 09:01:30 +0000292 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000293
294 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
295 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
296 ObjCSubscriptRefExpr *RefExpr;
297 OpaqueValueExpr *InstanceBase;
298 OpaqueValueExpr *InstanceKey;
299 ObjCMethodDecl *AtIndexGetter;
300 Selector AtIndexGetterSelector;
301
302 ObjCMethodDecl *AtIndexSetter;
303 Selector AtIndexSetterSelector;
304
305 public:
306 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
307 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
308 RefExpr(refExpr),
309 InstanceBase(0), InstanceKey(0),
310 AtIndexGetter(0), AtIndexSetter(0) { }
311
312 ExprResult buildRValueOperation(Expr *op);
313 ExprResult buildAssignmentOperation(Scope *Sc,
314 SourceLocation opLoc,
315 BinaryOperatorKind opcode,
316 Expr *LHS, Expr *RHS);
317 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
318
319 bool findAtIndexGetter();
320 bool findAtIndexSetter();
321
322 ExprResult buildGet();
323 ExprResult buildSet(Expr *op, SourceLocation, bool);
324 };
325
John McCall5e77d762013-04-16 07:28:30 +0000326 class MSPropertyOpBuilder : public PseudoOpBuilder {
327 MSPropertyRefExpr *RefExpr;
328
329 public:
330 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
331 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
332 RefExpr(refExpr) {}
333
334 Expr *rebuildAndCaptureObject(Expr *);
335 ExprResult buildGet();
336 ExprResult buildSet(Expr *op, SourceLocation, bool);
337 };
John McCallfe96e0b2011-11-06 09:01:30 +0000338}
339
340/// Capture the given expression in an OpaqueValueExpr.
341OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
342 // Make a new OVE whose source is the given expression.
343 OpaqueValueExpr *captured =
344 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +0000345 e->getValueKind(), e->getObjectKind(),
346 e);
John McCallfe96e0b2011-11-06 09:01:30 +0000347
348 // Make sure we bind that in the semantics.
349 addSemanticExpr(captured);
350 return captured;
351}
352
353/// Capture the given expression as the result of this pseudo-object
354/// operation. This routine is safe against expressions which may
355/// already be captured.
356///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000357/// \returns the captured expression, which will be the
John McCallfe96e0b2011-11-06 09:01:30 +0000358/// same as the input if the input was already captured
359OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
360 assert(ResultIndex == PseudoObjectExpr::NoResult);
361
362 // If the expression hasn't already been captured, just capture it
363 // and set the new semantic
364 if (!isa<OpaqueValueExpr>(e)) {
365 OpaqueValueExpr *cap = capture(e);
366 setResultToLastSemantic();
367 return cap;
368 }
369
370 // Otherwise, it must already be one of our semantic expressions;
371 // set ResultIndex to its index.
372 unsigned index = 0;
373 for (;; ++index) {
374 assert(index < Semantics.size() &&
375 "captured expression not found in semantics!");
376 if (e == Semantics[index]) break;
377 }
378 ResultIndex = index;
379 return cast<OpaqueValueExpr>(e);
380}
381
382/// The routine which creates the final PseudoObjectExpr.
383ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
384 return PseudoObjectExpr::Create(S.Context, syntactic,
385 Semantics, ResultIndex);
386}
387
388/// The main skeleton for building an r-value operation.
389ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
390 Expr *syntacticBase = rebuildAndCaptureObject(op);
391
392 ExprResult getExpr = buildGet();
393 if (getExpr.isInvalid()) return ExprError();
394 addResultSemanticExpr(getExpr.take());
395
396 return complete(syntacticBase);
397}
398
399/// The basic skeleton for building a simple or compound
400/// assignment operation.
401ExprResult
402PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
403 BinaryOperatorKind opcode,
404 Expr *LHS, Expr *RHS) {
405 assert(BinaryOperator::isAssignmentOp(opcode));
406
407 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
408 OpaqueValueExpr *capturedRHS = capture(RHS);
409
410 Expr *syntactic;
411
412 ExprResult result;
413 if (opcode == BO_Assign) {
414 result = capturedRHS;
415 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
416 opcode, capturedRHS->getType(),
417 capturedRHS->getValueKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000418 OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000419 } else {
420 ExprResult opLHS = buildGet();
421 if (opLHS.isInvalid()) return ExprError();
422
423 // Build an ordinary, non-compound operation.
424 BinaryOperatorKind nonCompound =
425 BinaryOperator::getOpForCompoundAssignment(opcode);
426 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
427 opLHS.take(), capturedRHS);
428 if (result.isInvalid()) return ExprError();
429
430 syntactic =
431 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
432 result.get()->getType(),
433 result.get()->getValueKind(),
434 OK_Ordinary,
435 opLHS.get()->getType(),
436 result.get()->getType(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000437 opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000438 }
439
440 // The result of the assignment, if not void, is the value set into
441 // the l-value.
Eli Friedman00fa4292012-11-13 23:16:33 +0000442 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true);
John McCallfe96e0b2011-11-06 09:01:30 +0000443 if (result.isInvalid()) return ExprError();
444 addSemanticExpr(result.take());
445
446 return complete(syntactic);
447}
448
449/// The basic skeleton for building an increment or decrement
450/// operation.
451ExprResult
452PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
453 UnaryOperatorKind opcode,
454 Expr *op) {
455 assert(UnaryOperator::isIncrementDecrementOp(opcode));
456
457 Expr *syntacticOp = rebuildAndCaptureObject(op);
458
459 // Load the value.
460 ExprResult result = buildGet();
461 if (result.isInvalid()) return ExprError();
462
463 QualType resultType = result.get()->getType();
464
465 // That's the postfix result.
John McCall0d9dd732013-04-16 22:32:04 +0000466 if (UnaryOperator::isPostfix(opcode) &&
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000467 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
John McCallfe96e0b2011-11-06 09:01:30 +0000468 result = capture(result.take());
469 setResultToLastSemantic();
470 }
471
472 // Add or subtract a literal 1.
473 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
474 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
475 GenericLoc);
476
477 if (UnaryOperator::isIncrementOp(opcode)) {
478 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
479 } else {
480 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
481 }
482 if (result.isInvalid()) return ExprError();
483
484 // Store that back into the result. The value stored is the result
485 // of a prefix operation.
Eli Friedman00fa4292012-11-13 23:16:33 +0000486 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode));
John McCallfe96e0b2011-11-06 09:01:30 +0000487 if (result.isInvalid()) return ExprError();
488 addSemanticExpr(result.take());
489
490 UnaryOperator *syntactic =
491 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
492 VK_LValue, OK_Ordinary, opcLoc);
493 return complete(syntactic);
494}
495
496
497//===----------------------------------------------------------------------===//
498// Objective-C @property and implicit property references
499//===----------------------------------------------------------------------===//
500
501/// Look up a method in the receiver type of an Objective-C property
502/// reference.
John McCall526ab472011-10-25 17:37:35 +0000503static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
504 const ObjCPropertyRefExpr *PRE) {
John McCall526ab472011-10-25 17:37:35 +0000505 if (PRE->isObjectReceiver()) {
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000506 const ObjCObjectPointerType *PT =
507 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +0000508
509 // Special case for 'self' in class method implementations.
510 if (PT->isObjCClassType() &&
511 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
512 // This cast is safe because isSelfExpr is only true within
513 // methods.
514 ObjCMethodDecl *method =
515 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
516 return S.LookupMethodInObjectType(sel,
517 S.Context.getObjCInterfaceType(method->getClassInterface()),
518 /*instance*/ false);
519 }
520
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000521 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall526ab472011-10-25 17:37:35 +0000522 }
523
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000524 if (PRE->isSuperReceiver()) {
525 if (const ObjCObjectPointerType *PT =
526 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
527 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
528
529 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
530 }
531
532 assert(PRE->isClassReceiver() && "Invalid expression");
533 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
534 return S.LookupMethodInObjectType(sel, IT, false);
John McCall526ab472011-10-25 17:37:35 +0000535}
536
Jordan Rosed3934582012-09-28 22:21:30 +0000537bool ObjCPropertyOpBuilder::isWeakProperty() const {
538 QualType T;
539 if (RefExpr->isExplicitProperty()) {
540 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
541 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
542 return true;
543
544 T = Prop->getType();
545 } else if (Getter) {
Alp Toker314cc812014-01-25 16:55:45 +0000546 T = Getter->getReturnType();
Jordan Rosed3934582012-09-28 22:21:30 +0000547 } else {
548 return false;
549 }
550
551 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
552}
553
John McCallfe96e0b2011-11-06 09:01:30 +0000554bool ObjCPropertyOpBuilder::findGetter() {
555 if (Getter) return true;
John McCall526ab472011-10-25 17:37:35 +0000556
John McCallcfef5462011-11-07 22:49:50 +0000557 // For implicit properties, just trust the lookup we already did.
558 if (RefExpr->isImplicitProperty()) {
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000559 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
560 GetterSelector = Getter->getSelector();
561 return true;
562 }
563 else {
564 // Must build the getter selector the hard way.
565 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
566 assert(setter && "both setter and getter are null - cannot happen");
567 IdentifierInfo *setterName =
568 setter->getSelector().getIdentifierInfoForSlot(0);
569 const char *compStr = setterName->getNameStart();
570 compStr += 3;
571 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
572 GetterSelector =
573 S.PP.getSelectorTable().getNullarySelector(getterName);
574 return false;
575
576 }
John McCallcfef5462011-11-07 22:49:50 +0000577 }
578
579 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
580 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
John McCallfe96e0b2011-11-06 09:01:30 +0000581 return (Getter != 0);
582}
583
584/// Try to find the most accurate setter declaration for the property
585/// reference.
586///
587/// \return true if a setter was found, in which case Setter
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000588bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCallfe96e0b2011-11-06 09:01:30 +0000589 // For implicit properties, just trust the lookup we already did.
590 if (RefExpr->isImplicitProperty()) {
591 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
592 Setter = setter;
593 SetterSelector = setter->getSelector();
594 return true;
John McCall526ab472011-10-25 17:37:35 +0000595 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000596 IdentifierInfo *getterName =
597 RefExpr->getImplicitPropertyGetter()->getSelector()
598 .getIdentifierInfoForSlot(0);
599 SetterSelector =
Adrian Prantla4ce9062013-06-07 22:29:12 +0000600 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
601 S.PP.getSelectorTable(),
602 getterName);
John McCallfe96e0b2011-11-06 09:01:30 +0000603 return false;
John McCall526ab472011-10-25 17:37:35 +0000604 }
John McCallfe96e0b2011-11-06 09:01:30 +0000605 }
606
607 // For explicit properties, this is more involved.
608 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
609 SetterSelector = prop->getSetterName();
610
611 // Do a normal method lookup first.
612 if (ObjCMethodDecl *setter =
613 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Jordan Rosed01e83a2012-10-10 16:42:25 +0000614 if (setter->isPropertyAccessor() && warn)
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000615 if (const ObjCInterfaceDecl *IFace =
616 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
617 const StringRef thisPropertyName(prop->getName());
Jordan Rosea7d03842013-02-08 22:30:41 +0000618 // Try flipping the case of the first character.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000619 char front = thisPropertyName.front();
Jordan Rosea7d03842013-02-08 22:30:41 +0000620 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000621 SmallString<100> PropertyName = thisPropertyName;
622 PropertyName[0] = front;
623 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
624 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
625 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
Fariborz Jahanianf3b76812012-05-26 16:10:06 +0000626 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Aaron Ballman1fb39552014-01-03 14:23:03 +0000627 << prop << prop1 << setter->getSelector();
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000628 S.Diag(prop->getLocation(), diag::note_property_declare);
629 S.Diag(prop1->getLocation(), diag::note_property_declare);
630 }
631 }
John McCallfe96e0b2011-11-06 09:01:30 +0000632 Setter = setter;
633 return true;
634 }
635
636 // That can fail in the somewhat crazy situation that we're
637 // type-checking a message send within the @interface declaration
638 // that declared the @property. But it's not clear that that's
639 // valuable to support.
640
641 return false;
642}
643
644/// Capture the base object of an Objective-C property expression.
645Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
646 assert(InstanceReceiver == 0);
647
648 // If we have a base, capture it in an OVE and rebuild the syntactic
649 // form to use the OVE as its base.
650 if (RefExpr->isObjectReceiver()) {
651 InstanceReceiver = capture(RefExpr->getBase());
652
653 syntacticBase =
654 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
655 }
656
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000657 if (ObjCPropertyRefExpr *
658 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
659 SyntacticRefExpr = refE;
660
John McCallfe96e0b2011-11-06 09:01:30 +0000661 return syntacticBase;
662}
663
664/// Load from an Objective-C property reference.
665ExprResult ObjCPropertyOpBuilder::buildGet() {
666 findGetter();
667 assert(Getter);
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000668
669 if (SyntacticRefExpr)
670 SyntacticRefExpr->setIsMessagingGetter();
671
John McCallfe96e0b2011-11-06 09:01:30 +0000672 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000673 if (RefExpr->isClassReceiver()) {
674 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
675 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000676 receiverType = RefExpr->getSuperReceiverType();
John McCall526ab472011-10-25 17:37:35 +0000677 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000678 assert(InstanceReceiver);
679 receiverType = InstanceReceiver->getType();
680 }
John McCall526ab472011-10-25 17:37:35 +0000681
John McCallfe96e0b2011-11-06 09:01:30 +0000682 // Build a message-send.
683 ExprResult msg;
684 if (Getter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
685 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000686 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
687 GenericLoc, Getter->getSelector(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000688 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000689 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000690 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000691 GenericLoc, Getter->getSelector(),
692 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000693 }
694 return msg;
695}
John McCall526ab472011-10-25 17:37:35 +0000696
John McCallfe96e0b2011-11-06 09:01:30 +0000697/// Store to an Objective-C property reference.
698///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000699/// \param captureSetValueAsResult If true, capture the actual
John McCallfe96e0b2011-11-06 09:01:30 +0000700/// value being set as the value of the property operation.
701ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
702 bool captureSetValueAsResult) {
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000703 bool hasSetter = findSetter(false);
John McCallfe96e0b2011-11-06 09:01:30 +0000704 assert(hasSetter); (void) hasSetter;
705
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000706 if (SyntacticRefExpr)
707 SyntacticRefExpr->setIsMessagingSetter();
708
John McCallfe96e0b2011-11-06 09:01:30 +0000709 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000710 if (RefExpr->isClassReceiver()) {
711 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
712 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000713 receiverType = RefExpr->getSuperReceiverType();
714 } else {
715 assert(InstanceReceiver);
716 receiverType = InstanceReceiver->getType();
717 }
718
719 // Use assignment constraints when possible; they give us better
720 // diagnostics. "When possible" basically means anything except a
721 // C++ class type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000722 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000723 QualType paramType = (*Setter->param_begin())->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000725 ExprResult opResult = op;
726 Sema::AssignConvertType assignResult
727 = S.CheckSingleAssignmentConstraints(paramType, opResult);
728 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
729 op->getType(), opResult.get(),
730 Sema::AA_Assigning))
731 return ExprError();
732
733 op = opResult.take();
734 assert(op && "successful assignment left argument invalid?");
John McCall526ab472011-10-25 17:37:35 +0000735 }
Fariborz Jahanian2eaec612013-10-16 17:51:43 +0000736 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
737 Expr *Initializer = OVE->getSourceExpr();
738 // passing C++11 style initialized temporaries to objc++ properties
739 // requires special treatment by removing OpaqueValueExpr so type
740 // conversion takes place and adding the OpaqueValueExpr later on.
741 if (isa<InitListExpr>(Initializer) &&
742 Initializer->getType()->isVoidType()) {
743 op = Initializer;
744 }
745 }
John McCall526ab472011-10-25 17:37:35 +0000746 }
747
John McCallfe96e0b2011-11-06 09:01:30 +0000748 // Arguments.
749 Expr *args[] = { op };
John McCall526ab472011-10-25 17:37:35 +0000750
John McCallfe96e0b2011-11-06 09:01:30 +0000751 // Build a message-send.
752 ExprResult msg;
753 if (Setter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000754 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
755 GenericLoc, SetterSelector, Setter,
756 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000757 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000758 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
759 GenericLoc,
760 SetterSelector, Setter,
761 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000762 }
763
764 if (!msg.isInvalid() && captureSetValueAsResult) {
765 ObjCMessageExpr *msgExpr =
766 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
767 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000768 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +0000769 msgExpr->setArg(0, captureValueAsResult(arg));
John McCallfe96e0b2011-11-06 09:01:30 +0000770 }
771
772 return msg;
John McCall526ab472011-10-25 17:37:35 +0000773}
774
John McCallfe96e0b2011-11-06 09:01:30 +0000775/// @property-specific behavior for doing lvalue-to-rvalue conversion.
776ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
777 // Explicit properties always have getters, but implicit ones don't.
778 // Check that before proceeding.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000779 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000780 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000781 << RefExpr->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +0000782 return ExprError();
783 }
784
John McCallfe96e0b2011-11-06 09:01:30 +0000785 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall526ab472011-10-25 17:37:35 +0000786 if (result.isInvalid()) return ExprError();
787
John McCallfe96e0b2011-11-06 09:01:30 +0000788 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
789 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
790 Getter, RefExpr->getLocation());
791
792 // As a special case, if the method returns 'id', try to get
793 // a better type from the property.
794 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
795 result.get()->getType()->isObjCIdType()) {
796 QualType propType = RefExpr->getExplicitProperty()->getType();
797 if (const ObjCObjectPointerType *ptr
798 = propType->getAs<ObjCObjectPointerType>()) {
799 if (!ptr->isObjCIdType())
800 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
801 }
802 }
803
John McCall526ab472011-10-25 17:37:35 +0000804 return result;
805}
806
John McCallfe96e0b2011-11-06 09:01:30 +0000807/// Try to build this as a call to a getter that returns a reference.
808///
809/// \return true if it was possible, whether or not it actually
810/// succeeded
811bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
812 ExprResult &result) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000813 if (!S.getLangOpts().CPlusPlus) return false;
John McCallfe96e0b2011-11-06 09:01:30 +0000814
815 findGetter();
816 assert(Getter && "property has no setter and no getter!");
817
818 // Only do this if the getter returns an l-value reference type.
Alp Toker314cc812014-01-25 16:55:45 +0000819 QualType resultType = Getter->getReturnType();
John McCallfe96e0b2011-11-06 09:01:30 +0000820 if (!resultType->isLValueReferenceType()) return false;
821
822 result = buildRValueOperation(op);
823 return true;
824}
825
826/// @property-specific behavior for doing assignments.
827ExprResult
828ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
829 SourceLocation opcLoc,
830 BinaryOperatorKind opcode,
831 Expr *LHS, Expr *RHS) {
John McCall526ab472011-10-25 17:37:35 +0000832 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall526ab472011-10-25 17:37:35 +0000833
834 // If there's no setter, we have no choice but to try to assign to
835 // the result of the getter.
John McCallfe96e0b2011-11-06 09:01:30 +0000836 if (!findSetter()) {
837 ExprResult result;
838 if (tryBuildGetOfReference(LHS, result)) {
839 if (result.isInvalid()) return ExprError();
840 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall526ab472011-10-25 17:37:35 +0000841 }
842
843 // Otherwise, it's an error.
John McCallfe96e0b2011-11-06 09:01:30 +0000844 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
845 << unsigned(RefExpr->isImplicitProperty())
846 << SetterSelector
John McCall526ab472011-10-25 17:37:35 +0000847 << LHS->getSourceRange() << RHS->getSourceRange();
848 return ExprError();
849 }
850
851 // If there is a setter, we definitely want to use it.
852
John McCallfe96e0b2011-11-06 09:01:30 +0000853 // Verify that we can do a compound assignment.
854 if (opcode != BO_Assign && !findGetter()) {
855 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall526ab472011-10-25 17:37:35 +0000856 << LHS->getSourceRange() << RHS->getSourceRange();
857 return ExprError();
858 }
859
John McCallfe96e0b2011-11-06 09:01:30 +0000860 ExprResult result =
861 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall526ab472011-10-25 17:37:35 +0000862 if (result.isInvalid()) return ExprError();
863
John McCallfe96e0b2011-11-06 09:01:30 +0000864 // Various warnings about property assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000865 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCallfe96e0b2011-11-06 09:01:30 +0000866 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
867 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
868 }
869
John McCall526ab472011-10-25 17:37:35 +0000870 return result;
871}
John McCallfe96e0b2011-11-06 09:01:30 +0000872
873/// @property-specific behavior for doing increments and decrements.
874ExprResult
875ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
876 UnaryOperatorKind opcode,
877 Expr *op) {
878 // If there's no setter, we have no choice but to try to assign to
879 // the result of the getter.
880 if (!findSetter()) {
881 ExprResult result;
882 if (tryBuildGetOfReference(op, result)) {
883 if (result.isInvalid()) return ExprError();
884 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
885 }
886
887 // Otherwise, it's an error.
888 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
889 << unsigned(RefExpr->isImplicitProperty())
890 << unsigned(UnaryOperator::isDecrementOp(opcode))
891 << SetterSelector
892 << op->getSourceRange();
893 return ExprError();
894 }
895
896 // If there is a setter, we definitely want to use it.
897
898 // We also need a getter.
899 if (!findGetter()) {
900 assert(RefExpr->isImplicitProperty());
901 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
902 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000903 << GetterSelector
John McCallfe96e0b2011-11-06 09:01:30 +0000904 << op->getSourceRange();
905 return ExprError();
906 }
907
908 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
909}
910
Jordan Rosed3934582012-09-28 22:21:30 +0000911ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
912 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
913 DiagnosticsEngine::Level Level =
914 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
915 SyntacticForm->getLocStart());
916 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +0000917 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
918 SyntacticRefExpr->isMessagingGetter());
Jordan Rosed3934582012-09-28 22:21:30 +0000919 }
920
921 return PseudoOpBuilder::complete(SyntacticForm);
922}
923
Ted Kremeneke65b0862012-03-06 20:05:56 +0000924// ObjCSubscript build stuff.
925//
926
927/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
928/// conversion.
929/// FIXME. Remove this routine if it is proven that no additional
930/// specifity is needed.
931ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
932 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
933 if (result.isInvalid()) return ExprError();
934 return result;
935}
936
937/// objective-c subscripting-specific behavior for doing assignments.
938ExprResult
939ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
940 SourceLocation opcLoc,
941 BinaryOperatorKind opcode,
942 Expr *LHS, Expr *RHS) {
943 assert(BinaryOperator::isAssignmentOp(opcode));
944 // There must be a method to do the Index'ed assignment.
945 if (!findAtIndexSetter())
946 return ExprError();
947
948 // Verify that we can do a compound assignment.
949 if (opcode != BO_Assign && !findAtIndexGetter())
950 return ExprError();
951
952 ExprResult result =
953 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
954 if (result.isInvalid()) return ExprError();
955
956 // Various warnings about objc Index'ed assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000957 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000958 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
959 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
960 }
961
962 return result;
963}
964
965/// Capture the base object of an Objective-C Index'ed expression.
966Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
967 assert(InstanceBase == 0);
968
969 // Capture base expression in an OVE and rebuild the syntactic
970 // form to use the OVE as its base expression.
971 InstanceBase = capture(RefExpr->getBaseExpr());
972 InstanceKey = capture(RefExpr->getKeyExpr());
973
974 syntacticBase =
975 ObjCSubscriptRefRebuilder(S, InstanceBase,
976 InstanceKey).rebuild(syntacticBase);
977
978 return syntacticBase;
979}
980
981/// CheckSubscriptingKind - This routine decide what type
982/// of indexing represented by "FromE" is being done.
983Sema::ObjCSubscriptKind
984 Sema::CheckSubscriptingKind(Expr *FromE) {
985 // If the expression already has integral or enumeration type, we're golden.
986 QualType T = FromE->getType();
987 if (T->isIntegralOrEnumerationType())
988 return OS_Array;
989
990 // If we don't have a class type in C++, there's no way we can get an
991 // expression of integral or enumeration type.
992 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000993 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremeneke65b0862012-03-06 20:05:56 +0000994 // All other scalar cases are assumed to be dictionary indexing which
995 // caller handles, with diagnostics if needed.
996 return OS_Dictionary;
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000997 if (!getLangOpts().CPlusPlus ||
998 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000999 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001000 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1001 if (isa<StringLiteral>(IndexExpr))
1002 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1003 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1004 else
1005 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1006 << T;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001007 return OS_Error;
1008 }
1009
1010 // We must have a complete class type.
1011 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001012 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001013 return OS_Error;
1014
1015 // Look for a conversion to an integral, enumeration type, or
1016 // objective-C pointer type.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001017 std::pair<CXXRecordDecl::conversion_iterator,
1018 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremeneke65b0862012-03-06 20:05:56 +00001019 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1020
1021 int NoIntegrals=0, NoObjCIdPointers=0;
1022 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1023
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001024 for (CXXRecordDecl::conversion_iterator
1025 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001026 if (CXXConversionDecl *Conversion
1027 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1028 QualType CT = Conversion->getConversionType().getNonReferenceType();
1029 if (CT->isIntegralOrEnumerationType()) {
1030 ++NoIntegrals;
1031 ConversionDecls.push_back(Conversion);
1032 }
1033 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1034 ++NoObjCIdPointers;
1035 ConversionDecls.push_back(Conversion);
1036 }
1037 }
1038 }
1039 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1040 return OS_Array;
1041 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1042 return OS_Dictionary;
1043 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1044 // No conversion function was found. Issue diagnostic and return.
1045 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1046 << FromE->getType();
1047 return OS_Error;
1048 }
1049 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1050 << FromE->getType();
1051 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1052 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1053
1054 return OS_Error;
1055}
1056
Fariborz Jahanian90804912012-08-02 18:03:58 +00001057/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1058/// objects used as dictionary subscript key objects.
1059static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1060 Expr *Key) {
1061 if (ContainerT.isNull())
1062 return;
1063 // dictionary subscripting.
1064 // - (id)objectForKeyedSubscript:(id)key;
1065 IdentifierInfo *KeyIdents[] = {
1066 &S.Context.Idents.get("objectForKeyedSubscript")
1067 };
1068 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1069 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1070 true /*instance*/);
1071 if (!Getter)
1072 return;
1073 QualType T = Getter->param_begin()[0]->getType();
1074 S.CheckObjCARCConversion(Key->getSourceRange(),
1075 T, Key, Sema::CCK_ImplicitConversion);
1076}
1077
Ted Kremeneke65b0862012-03-06 20:05:56 +00001078bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1079 if (AtIndexGetter)
1080 return true;
1081
1082 Expr *BaseExpr = RefExpr->getBaseExpr();
1083 QualType BaseT = BaseExpr->getType();
1084
1085 QualType ResultType;
1086 if (const ObjCObjectPointerType *PTy =
1087 BaseT->getAs<ObjCObjectPointerType>()) {
1088 ResultType = PTy->getPointeeType();
1089 if (const ObjCObjectType *iQFaceTy =
1090 ResultType->getAsObjCQualifiedInterfaceType())
1091 ResultType = iQFaceTy->getBaseType();
1092 }
1093 Sema::ObjCSubscriptKind Res =
1094 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001095 if (Res == Sema::OS_Error) {
1096 if (S.getLangOpts().ObjCAutoRefCount)
1097 CheckKeyForObjCARCConversion(S, ResultType,
1098 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001099 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001100 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001101 bool arrayRef = (Res == Sema::OS_Array);
1102
1103 if (ResultType.isNull()) {
1104 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1105 << BaseExpr->getType() << arrayRef;
1106 return false;
1107 }
1108 if (!arrayRef) {
1109 // dictionary subscripting.
1110 // - (id)objectForKeyedSubscript:(id)key;
1111 IdentifierInfo *KeyIdents[] = {
1112 &S.Context.Idents.get("objectForKeyedSubscript")
1113 };
1114 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1115 }
1116 else {
1117 // - (id)objectAtIndexedSubscript:(size_t)index;
1118 IdentifierInfo *KeyIdents[] = {
1119 &S.Context.Idents.get("objectAtIndexedSubscript")
1120 };
1121
1122 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1123 }
1124
1125 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1126 true /*instance*/);
1127 bool receiverIdType = (BaseT->isObjCIdType() ||
1128 BaseT->isObjCQualifiedIdType());
1129
David Blaikiebbafb8a2012-03-11 07:00:24 +00001130 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001131 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1132 SourceLocation(), AtIndexGetterSelector,
1133 S.Context.getObjCIdType() /*ReturnType*/,
1134 0 /*TypeSourceInfo */,
1135 S.Context.getTranslationUnitDecl(),
1136 true /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +00001137 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001138 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1139 ObjCMethodDecl::Required,
1140 false);
1141 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1142 SourceLocation(), SourceLocation(),
1143 arrayRef ? &S.Context.Idents.get("index")
1144 : &S.Context.Idents.get("key"),
1145 arrayRef ? S.Context.UnsignedLongTy
1146 : S.Context.getObjCIdType(),
1147 /*TInfo=*/0,
1148 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001149 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001150 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001151 }
1152
1153 if (!AtIndexGetter) {
1154 if (!receiverIdType) {
1155 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1156 << BaseExpr->getType() << 0 << arrayRef;
1157 return false;
1158 }
1159 AtIndexGetter =
1160 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1161 RefExpr->getSourceRange(),
1162 true, false);
1163 }
1164
1165 if (AtIndexGetter) {
1166 QualType T = AtIndexGetter->param_begin()[0]->getType();
1167 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1168 (!arrayRef && !T->isObjCObjectPointerType())) {
1169 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1170 arrayRef ? diag::err_objc_subscript_index_type
1171 : diag::err_objc_subscript_key_type) << T;
1172 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1173 diag::note_parameter_type) << T;
1174 return false;
1175 }
Alp Toker314cc812014-01-25 16:55:45 +00001176 QualType R = AtIndexGetter->getReturnType();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001177 if (!R->isObjCObjectPointerType()) {
1178 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1179 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1180 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1181 AtIndexGetter->getDeclName();
1182 }
1183 }
1184 return true;
1185}
1186
1187bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1188 if (AtIndexSetter)
1189 return true;
1190
1191 Expr *BaseExpr = RefExpr->getBaseExpr();
1192 QualType BaseT = BaseExpr->getType();
1193
1194 QualType ResultType;
1195 if (const ObjCObjectPointerType *PTy =
1196 BaseT->getAs<ObjCObjectPointerType>()) {
1197 ResultType = PTy->getPointeeType();
1198 if (const ObjCObjectType *iQFaceTy =
1199 ResultType->getAsObjCQualifiedInterfaceType())
1200 ResultType = iQFaceTy->getBaseType();
1201 }
1202
1203 Sema::ObjCSubscriptKind Res =
1204 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001205 if (Res == Sema::OS_Error) {
1206 if (S.getLangOpts().ObjCAutoRefCount)
1207 CheckKeyForObjCARCConversion(S, ResultType,
1208 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001209 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001210 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001211 bool arrayRef = (Res == Sema::OS_Array);
1212
1213 if (ResultType.isNull()) {
1214 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1215 << BaseExpr->getType() << arrayRef;
1216 return false;
1217 }
1218
1219 if (!arrayRef) {
1220 // dictionary subscripting.
1221 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1222 IdentifierInfo *KeyIdents[] = {
1223 &S.Context.Idents.get("setObject"),
1224 &S.Context.Idents.get("forKeyedSubscript")
1225 };
1226 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1227 }
1228 else {
1229 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1230 IdentifierInfo *KeyIdents[] = {
1231 &S.Context.Idents.get("setObject"),
1232 &S.Context.Idents.get("atIndexedSubscript")
1233 };
1234 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1235 }
1236 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1237 true /*instance*/);
1238
1239 bool receiverIdType = (BaseT->isObjCIdType() ||
1240 BaseT->isObjCQualifiedIdType());
1241
David Blaikiebbafb8a2012-03-11 07:00:24 +00001242 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Alp Toker314cc812014-01-25 16:55:45 +00001243 TypeSourceInfo *ReturnTInfo = 0;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001244 QualType ReturnType = S.Context.VoidTy;
Alp Toker314cc812014-01-25 16:55:45 +00001245 AtIndexSetter = ObjCMethodDecl::Create(
1246 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1247 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1248 true /*Instance*/, false /*isVariadic*/,
1249 /*isPropertyAccessor=*/false,
1250 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1251 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001252 SmallVector<ParmVarDecl *, 2> Params;
1253 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1254 SourceLocation(), SourceLocation(),
1255 &S.Context.Idents.get("object"),
1256 S.Context.getObjCIdType(),
1257 /*TInfo=*/0,
1258 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001259 0);
1260 Params.push_back(object);
1261 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1262 SourceLocation(), SourceLocation(),
1263 arrayRef ? &S.Context.Idents.get("index")
1264 : &S.Context.Idents.get("key"),
1265 arrayRef ? S.Context.UnsignedLongTy
1266 : S.Context.getObjCIdType(),
1267 /*TInfo=*/0,
1268 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001269 0);
1270 Params.push_back(key);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001271 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001272 }
1273
1274 if (!AtIndexSetter) {
1275 if (!receiverIdType) {
1276 S.Diag(BaseExpr->getExprLoc(),
1277 diag::err_objc_subscript_method_not_found)
1278 << BaseExpr->getType() << 1 << arrayRef;
1279 return false;
1280 }
1281 AtIndexSetter =
1282 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1283 RefExpr->getSourceRange(),
1284 true, false);
1285 }
1286
1287 bool err = false;
1288 if (AtIndexSetter && arrayRef) {
1289 QualType T = AtIndexSetter->param_begin()[1]->getType();
1290 if (!T->isIntegralOrEnumerationType()) {
1291 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1292 diag::err_objc_subscript_index_type) << T;
1293 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1294 diag::note_parameter_type) << T;
1295 err = true;
1296 }
1297 T = AtIndexSetter->param_begin()[0]->getType();
1298 if (!T->isObjCObjectPointerType()) {
1299 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1300 diag::err_objc_subscript_object_type) << T << arrayRef;
1301 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1302 diag::note_parameter_type) << T;
1303 err = true;
1304 }
1305 }
1306 else if (AtIndexSetter && !arrayRef)
1307 for (unsigned i=0; i <2; i++) {
1308 QualType T = AtIndexSetter->param_begin()[i]->getType();
1309 if (!T->isObjCObjectPointerType()) {
1310 if (i == 1)
1311 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1312 diag::err_objc_subscript_key_type) << T;
1313 else
1314 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1315 diag::err_objc_subscript_dic_object_type) << T;
1316 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1317 diag::note_parameter_type) << T;
1318 err = true;
1319 }
1320 }
1321
1322 return !err;
1323}
1324
1325// Get the object at "Index" position in the container.
1326// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1327ExprResult ObjCSubscriptOpBuilder::buildGet() {
1328 if (!findAtIndexGetter())
1329 return ExprError();
1330
1331 QualType receiverType = InstanceBase->getType();
1332
1333 // Build a message-send.
1334 ExprResult msg;
1335 Expr *Index = InstanceKey;
1336
1337 // Arguments.
1338 Expr *args[] = { Index };
1339 assert(InstanceBase);
1340 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1341 GenericLoc,
1342 AtIndexGetterSelector, AtIndexGetter,
1343 MultiExprArg(args, 1));
1344 return msg;
1345}
1346
1347/// Store into the container the "op" object at "Index"'ed location
1348/// by building this messaging expression:
1349/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001350/// \param captureSetValueAsResult If true, capture the actual
Ted Kremeneke65b0862012-03-06 20:05:56 +00001351/// value being set as the value of the property operation.
1352ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1353 bool captureSetValueAsResult) {
1354 if (!findAtIndexSetter())
1355 return ExprError();
1356
1357 QualType receiverType = InstanceBase->getType();
1358 Expr *Index = InstanceKey;
1359
1360 // Arguments.
1361 Expr *args[] = { op, Index };
1362
1363 // Build a message-send.
1364 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1365 GenericLoc,
1366 AtIndexSetterSelector,
1367 AtIndexSetter,
1368 MultiExprArg(args, 2));
1369
1370 if (!msg.isInvalid() && captureSetValueAsResult) {
1371 ObjCMessageExpr *msgExpr =
1372 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1373 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +00001374 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +00001375 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremeneke65b0862012-03-06 20:05:56 +00001376 }
1377
1378 return msg;
1379}
1380
John McCallfe96e0b2011-11-06 09:01:30 +00001381//===----------------------------------------------------------------------===//
John McCall5e77d762013-04-16 07:28:30 +00001382// MSVC __declspec(property) references
1383//===----------------------------------------------------------------------===//
1384
1385Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1386 Expr *NewBase = capture(RefExpr->getBaseExpr());
1387
1388 syntacticBase =
1389 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1390
1391 return syntacticBase;
1392}
1393
1394ExprResult MSPropertyOpBuilder::buildGet() {
1395 if (!RefExpr->getPropertyDecl()->hasGetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001396 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001397 << 0 /* getter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001398 return ExprError();
1399 }
1400
1401 UnqualifiedId GetterName;
1402 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1403 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1404 CXXScopeSpec SS;
1405 SS.Adopt(RefExpr->getQualifierLoc());
1406 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1407 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1408 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1409 GetterName, 0, true);
1410 if (GetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001411 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001412 diag::error_cannot_find_suitable_accessor) << 0 /* getter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001413 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001414 return ExprError();
1415 }
1416
1417 MultiExprArg ArgExprs;
1418 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1419 RefExpr->getSourceRange().getBegin(), ArgExprs,
1420 RefExpr->getSourceRange().getEnd());
1421}
1422
1423ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1424 bool captureSetValueAsResult) {
1425 if (!RefExpr->getPropertyDecl()->hasSetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001426 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001427 << 1 /* setter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001428 return ExprError();
1429 }
1430
1431 UnqualifiedId SetterName;
1432 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1433 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1434 CXXScopeSpec SS;
1435 SS.Adopt(RefExpr->getQualifierLoc());
1436 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1437 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1438 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1439 SetterName, 0, true);
1440 if (SetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001441 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001442 diag::error_cannot_find_suitable_accessor) << 1 /* setter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001443 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001444 return ExprError();
1445 }
1446
1447 SmallVector<Expr*, 1> ArgExprs;
1448 ArgExprs.push_back(op);
1449 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(),
1450 RefExpr->getSourceRange().getBegin(), ArgExprs,
1451 op->getSourceRange().getEnd());
1452}
1453
1454//===----------------------------------------------------------------------===//
John McCallfe96e0b2011-11-06 09:01:30 +00001455// General Sema routines.
1456//===----------------------------------------------------------------------===//
1457
1458ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1459 Expr *opaqueRef = E->IgnoreParens();
1460 if (ObjCPropertyRefExpr *refExpr
1461 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1462 ObjCPropertyOpBuilder builder(*this, refExpr);
1463 return builder.buildRValueOperation(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001464 }
1465 else if (ObjCSubscriptRefExpr *refExpr
1466 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1467 ObjCSubscriptOpBuilder builder(*this, refExpr);
1468 return builder.buildRValueOperation(E);
John McCall5e77d762013-04-16 07:28:30 +00001469 } else if (MSPropertyRefExpr *refExpr
1470 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1471 MSPropertyOpBuilder builder(*this, refExpr);
1472 return builder.buildRValueOperation(E);
John McCallfe96e0b2011-11-06 09:01:30 +00001473 } else {
1474 llvm_unreachable("unknown pseudo-object kind!");
1475 }
1476}
1477
1478/// Check an increment or decrement of a pseudo-object expression.
1479ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1480 UnaryOperatorKind opcode, Expr *op) {
1481 // Do nothing if the operand is dependent.
1482 if (op->isTypeDependent())
1483 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1484 VK_RValue, OK_Ordinary, opcLoc);
1485
1486 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1487 Expr *opaqueRef = op->IgnoreParens();
1488 if (ObjCPropertyRefExpr *refExpr
1489 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1490 ObjCPropertyOpBuilder builder(*this, refExpr);
1491 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001492 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1493 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1494 return ExprError();
John McCall5e77d762013-04-16 07:28:30 +00001495 } else if (MSPropertyRefExpr *refExpr
1496 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1497 MSPropertyOpBuilder builder(*this, refExpr);
1498 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCallfe96e0b2011-11-06 09:01:30 +00001499 } else {
1500 llvm_unreachable("unknown pseudo-object kind!");
1501 }
1502}
1503
1504ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1505 BinaryOperatorKind opcode,
1506 Expr *LHS, Expr *RHS) {
1507 // Do nothing if either argument is dependent.
1508 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1509 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00001510 VK_RValue, OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +00001511
1512 // Filter out non-overload placeholder types in the RHS.
John McCalld5c98ae2011-11-15 01:35:18 +00001513 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1514 ExprResult result = CheckPlaceholderExpr(RHS);
1515 if (result.isInvalid()) return ExprError();
1516 RHS = result.take();
John McCallfe96e0b2011-11-06 09:01:30 +00001517 }
1518
1519 Expr *opaqueRef = LHS->IgnoreParens();
1520 if (ObjCPropertyRefExpr *refExpr
1521 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1522 ObjCPropertyOpBuilder builder(*this, refExpr);
1523 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001524 } else if (ObjCSubscriptRefExpr *refExpr
1525 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1526 ObjCSubscriptOpBuilder builder(*this, refExpr);
1527 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall5e77d762013-04-16 07:28:30 +00001528 } else if (MSPropertyRefExpr *refExpr
1529 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1530 MSPropertyOpBuilder builder(*this, refExpr);
1531 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCallfe96e0b2011-11-06 09:01:30 +00001532 } else {
1533 llvm_unreachable("unknown pseudo-object kind!");
1534 }
1535}
John McCalle9290822011-11-30 04:42:31 +00001536
1537/// Given a pseudo-object reference, rebuild it without the opaque
1538/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1539/// This should never operate in-place.
1540static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1541 Expr *opaqueRef = E->IgnoreParens();
1542 if (ObjCPropertyRefExpr *refExpr
1543 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregoraa0df2d2012-04-13 16:05:42 +00001544 // Class and super property references don't have opaque values in them.
1545 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1546 return E;
1547
1548 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1549 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1550 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001551 } else if (ObjCSubscriptRefExpr *refExpr
1552 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1553 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1554 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1555 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1556 keyOVE->getSourceExpr()).rebuild(E);
John McCall5e77d762013-04-16 07:28:30 +00001557 } else if (MSPropertyRefExpr *refExpr
1558 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1559 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1560 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCalle9290822011-11-30 04:42:31 +00001561 } else {
1562 llvm_unreachable("unknown pseudo-object kind!");
1563 }
1564}
1565
1566/// Given a pseudo-object expression, recreate what it looks like
1567/// syntactically without the attendant OpaqueValueExprs.
1568///
1569/// This is a hack which should be removed when TreeTransform is
1570/// capable of rebuilding a tree without stripping implicit
1571/// operations.
1572Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1573 Expr *syntax = E->getSyntacticForm();
1574 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1575 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1576 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1577 uop->getValueKind(), uop->getObjectKind(),
1578 uop->getOperatorLoc());
1579 } else if (CompoundAssignOperator *cop
1580 = dyn_cast<CompoundAssignOperator>(syntax)) {
1581 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1582 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1583 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1584 cop->getType(),
1585 cop->getValueKind(),
1586 cop->getObjectKind(),
1587 cop->getComputationLHSType(),
1588 cop->getComputationResultType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001589 cop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001590 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1591 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1592 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1593 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1594 bop->getType(), bop->getValueKind(),
1595 bop->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001596 bop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001597 } else {
1598 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1599 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1600 }
1601}