blob: a8463cdbd4ef662d4928c7e6afec91baf78aaa17 [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
Craig Toppere14c0f82014-03-12 04:55:44 +0000286 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
287 ExprResult buildGet() override;
288 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
289 ExprResult complete(Expr *SyntacticForm) override;
Jordan Rosed3934582012-09-28 22:21:30 +0000290
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);
Craig Toppere14c0f82014-03-12 04:55:44 +0000317 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
318
Ted Kremeneke65b0862012-03-06 20:05:56 +0000319 bool findAtIndexGetter();
320 bool findAtIndexSetter();
Craig Toppere14c0f82014-03-12 04:55:44 +0000321
322 ExprResult buildGet() override;
323 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000324 };
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
Craig Toppere14c0f82014-03-12 04:55:44 +0000334 Expr *rebuildAndCaptureObject(Expr *) override;
335 ExprResult buildGet() override;
336 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
John McCall5e77d762013-04-16 07:28:30 +0000337 };
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;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000684 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
685 RefExpr->isObjectReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000686 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000687 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
688 GenericLoc, Getter->getSelector(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000689 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000690 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000691 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000692 GenericLoc, Getter->getSelector(),
693 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000694 }
695 return msg;
696}
John McCall526ab472011-10-25 17:37:35 +0000697
John McCallfe96e0b2011-11-06 09:01:30 +0000698/// Store to an Objective-C property reference.
699///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000700/// \param captureSetValueAsResult If true, capture the actual
John McCallfe96e0b2011-11-06 09:01:30 +0000701/// value being set as the value of the property operation.
702ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
703 bool captureSetValueAsResult) {
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000704 bool hasSetter = findSetter(false);
John McCallfe96e0b2011-11-06 09:01:30 +0000705 assert(hasSetter); (void) hasSetter;
706
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000707 if (SyntacticRefExpr)
708 SyntacticRefExpr->setIsMessagingSetter();
709
John McCallfe96e0b2011-11-06 09:01:30 +0000710 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000711 if (RefExpr->isClassReceiver()) {
712 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
713 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000714 receiverType = RefExpr->getSuperReceiverType();
715 } else {
716 assert(InstanceReceiver);
717 receiverType = InstanceReceiver->getType();
718 }
719
720 // Use assignment constraints when possible; they give us better
721 // diagnostics. "When possible" basically means anything except a
722 // C++ class type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000723 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000724 QualType paramType = (*Setter->param_begin())->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000725 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000726 ExprResult opResult = op;
727 Sema::AssignConvertType assignResult
728 = S.CheckSingleAssignmentConstraints(paramType, opResult);
729 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
730 op->getType(), opResult.get(),
731 Sema::AA_Assigning))
732 return ExprError();
733
734 op = opResult.take();
735 assert(op && "successful assignment left argument invalid?");
John McCall526ab472011-10-25 17:37:35 +0000736 }
Fariborz Jahanian2eaec612013-10-16 17:51:43 +0000737 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
738 Expr *Initializer = OVE->getSourceExpr();
739 // passing C++11 style initialized temporaries to objc++ properties
740 // requires special treatment by removing OpaqueValueExpr so type
741 // conversion takes place and adding the OpaqueValueExpr later on.
742 if (isa<InitListExpr>(Initializer) &&
743 Initializer->getType()->isVoidType()) {
744 op = Initializer;
745 }
746 }
John McCall526ab472011-10-25 17:37:35 +0000747 }
748
John McCallfe96e0b2011-11-06 09:01:30 +0000749 // Arguments.
750 Expr *args[] = { op };
John McCall526ab472011-10-25 17:37:35 +0000751
John McCallfe96e0b2011-11-06 09:01:30 +0000752 // Build a message-send.
753 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000754 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
755 RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000756 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
757 GenericLoc, SetterSelector, Setter,
758 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000759 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000760 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
761 GenericLoc,
762 SetterSelector, Setter,
763 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000764 }
765
766 if (!msg.isInvalid() && captureSetValueAsResult) {
767 ObjCMessageExpr *msgExpr =
768 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
769 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000770 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +0000771 msgExpr->setArg(0, captureValueAsResult(arg));
John McCallfe96e0b2011-11-06 09:01:30 +0000772 }
773
774 return msg;
John McCall526ab472011-10-25 17:37:35 +0000775}
776
John McCallfe96e0b2011-11-06 09:01:30 +0000777/// @property-specific behavior for doing lvalue-to-rvalue conversion.
778ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
779 // Explicit properties always have getters, but implicit ones don't.
780 // Check that before proceeding.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000781 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000782 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000783 << RefExpr->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +0000784 return ExprError();
785 }
786
John McCallfe96e0b2011-11-06 09:01:30 +0000787 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall526ab472011-10-25 17:37:35 +0000788 if (result.isInvalid()) return ExprError();
789
John McCallfe96e0b2011-11-06 09:01:30 +0000790 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
791 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
792 Getter, RefExpr->getLocation());
793
794 // As a special case, if the method returns 'id', try to get
795 // a better type from the property.
796 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
797 result.get()->getType()->isObjCIdType()) {
798 QualType propType = RefExpr->getExplicitProperty()->getType();
799 if (const ObjCObjectPointerType *ptr
800 = propType->getAs<ObjCObjectPointerType>()) {
801 if (!ptr->isObjCIdType())
802 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
803 }
804 }
805
John McCall526ab472011-10-25 17:37:35 +0000806 return result;
807}
808
John McCallfe96e0b2011-11-06 09:01:30 +0000809/// Try to build this as a call to a getter that returns a reference.
810///
811/// \return true if it was possible, whether or not it actually
812/// succeeded
813bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
814 ExprResult &result) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000815 if (!S.getLangOpts().CPlusPlus) return false;
John McCallfe96e0b2011-11-06 09:01:30 +0000816
817 findGetter();
818 assert(Getter && "property has no setter and no getter!");
819
820 // Only do this if the getter returns an l-value reference type.
Alp Toker314cc812014-01-25 16:55:45 +0000821 QualType resultType = Getter->getReturnType();
John McCallfe96e0b2011-11-06 09:01:30 +0000822 if (!resultType->isLValueReferenceType()) return false;
823
824 result = buildRValueOperation(op);
825 return true;
826}
827
828/// @property-specific behavior for doing assignments.
829ExprResult
830ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
831 SourceLocation opcLoc,
832 BinaryOperatorKind opcode,
833 Expr *LHS, Expr *RHS) {
John McCall526ab472011-10-25 17:37:35 +0000834 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall526ab472011-10-25 17:37:35 +0000835
836 // If there's no setter, we have no choice but to try to assign to
837 // the result of the getter.
John McCallfe96e0b2011-11-06 09:01:30 +0000838 if (!findSetter()) {
839 ExprResult result;
840 if (tryBuildGetOfReference(LHS, result)) {
841 if (result.isInvalid()) return ExprError();
842 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall526ab472011-10-25 17:37:35 +0000843 }
844
845 // Otherwise, it's an error.
John McCallfe96e0b2011-11-06 09:01:30 +0000846 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
847 << unsigned(RefExpr->isImplicitProperty())
848 << SetterSelector
John McCall526ab472011-10-25 17:37:35 +0000849 << LHS->getSourceRange() << RHS->getSourceRange();
850 return ExprError();
851 }
852
853 // If there is a setter, we definitely want to use it.
854
John McCallfe96e0b2011-11-06 09:01:30 +0000855 // Verify that we can do a compound assignment.
856 if (opcode != BO_Assign && !findGetter()) {
857 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall526ab472011-10-25 17:37:35 +0000858 << LHS->getSourceRange() << RHS->getSourceRange();
859 return ExprError();
860 }
861
John McCallfe96e0b2011-11-06 09:01:30 +0000862 ExprResult result =
863 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall526ab472011-10-25 17:37:35 +0000864 if (result.isInvalid()) return ExprError();
865
John McCallfe96e0b2011-11-06 09:01:30 +0000866 // Various warnings about property assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000867 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCallfe96e0b2011-11-06 09:01:30 +0000868 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
869 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
870 }
871
John McCall526ab472011-10-25 17:37:35 +0000872 return result;
873}
John McCallfe96e0b2011-11-06 09:01:30 +0000874
875/// @property-specific behavior for doing increments and decrements.
876ExprResult
877ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
878 UnaryOperatorKind opcode,
879 Expr *op) {
880 // If there's no setter, we have no choice but to try to assign to
881 // the result of the getter.
882 if (!findSetter()) {
883 ExprResult result;
884 if (tryBuildGetOfReference(op, result)) {
885 if (result.isInvalid()) return ExprError();
886 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
887 }
888
889 // Otherwise, it's an error.
890 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
891 << unsigned(RefExpr->isImplicitProperty())
892 << unsigned(UnaryOperator::isDecrementOp(opcode))
893 << SetterSelector
894 << op->getSourceRange();
895 return ExprError();
896 }
897
898 // If there is a setter, we definitely want to use it.
899
900 // We also need a getter.
901 if (!findGetter()) {
902 assert(RefExpr->isImplicitProperty());
903 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
904 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000905 << GetterSelector
John McCallfe96e0b2011-11-06 09:01:30 +0000906 << op->getSourceRange();
907 return ExprError();
908 }
909
910 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
911}
912
Jordan Rosed3934582012-09-28 22:21:30 +0000913ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
914 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
915 DiagnosticsEngine::Level Level =
916 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
917 SyntacticForm->getLocStart());
918 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +0000919 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
920 SyntacticRefExpr->isMessagingGetter());
Jordan Rosed3934582012-09-28 22:21:30 +0000921 }
922
923 return PseudoOpBuilder::complete(SyntacticForm);
924}
925
Ted Kremeneke65b0862012-03-06 20:05:56 +0000926// ObjCSubscript build stuff.
927//
928
929/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
930/// conversion.
931/// FIXME. Remove this routine if it is proven that no additional
932/// specifity is needed.
933ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
934 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
935 if (result.isInvalid()) return ExprError();
936 return result;
937}
938
939/// objective-c subscripting-specific behavior for doing assignments.
940ExprResult
941ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
942 SourceLocation opcLoc,
943 BinaryOperatorKind opcode,
944 Expr *LHS, Expr *RHS) {
945 assert(BinaryOperator::isAssignmentOp(opcode));
946 // There must be a method to do the Index'ed assignment.
947 if (!findAtIndexSetter())
948 return ExprError();
949
950 // Verify that we can do a compound assignment.
951 if (opcode != BO_Assign && !findAtIndexGetter())
952 return ExprError();
953
954 ExprResult result =
955 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
956 if (result.isInvalid()) return ExprError();
957
958 // Various warnings about objc Index'ed assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000959 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000960 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
961 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
962 }
963
964 return result;
965}
966
967/// Capture the base object of an Objective-C Index'ed expression.
968Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
969 assert(InstanceBase == 0);
970
971 // Capture base expression in an OVE and rebuild the syntactic
972 // form to use the OVE as its base expression.
973 InstanceBase = capture(RefExpr->getBaseExpr());
974 InstanceKey = capture(RefExpr->getKeyExpr());
975
976 syntacticBase =
977 ObjCSubscriptRefRebuilder(S, InstanceBase,
978 InstanceKey).rebuild(syntacticBase);
979
980 return syntacticBase;
981}
982
983/// CheckSubscriptingKind - This routine decide what type
984/// of indexing represented by "FromE" is being done.
985Sema::ObjCSubscriptKind
986 Sema::CheckSubscriptingKind(Expr *FromE) {
987 // If the expression already has integral or enumeration type, we're golden.
988 QualType T = FromE->getType();
989 if (T->isIntegralOrEnumerationType())
990 return OS_Array;
991
992 // If we don't have a class type in C++, there's no way we can get an
993 // expression of integral or enumeration type.
994 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000995 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremeneke65b0862012-03-06 20:05:56 +0000996 // All other scalar cases are assumed to be dictionary indexing which
997 // caller handles, with diagnostics if needed.
998 return OS_Dictionary;
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000999 if (!getLangOpts().CPlusPlus ||
1000 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001001 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001002 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1003 if (isa<StringLiteral>(IndexExpr))
1004 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1005 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1006 else
1007 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1008 << T;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001009 return OS_Error;
1010 }
1011
1012 // We must have a complete class type.
1013 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001014 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001015 return OS_Error;
1016
1017 // Look for a conversion to an integral, enumeration type, or
1018 // objective-C pointer type.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001019 std::pair<CXXRecordDecl::conversion_iterator,
1020 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremeneke65b0862012-03-06 20:05:56 +00001021 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1022
1023 int NoIntegrals=0, NoObjCIdPointers=0;
1024 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1025
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001026 for (CXXRecordDecl::conversion_iterator
1027 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001028 if (CXXConversionDecl *Conversion
1029 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1030 QualType CT = Conversion->getConversionType().getNonReferenceType();
1031 if (CT->isIntegralOrEnumerationType()) {
1032 ++NoIntegrals;
1033 ConversionDecls.push_back(Conversion);
1034 }
1035 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1036 ++NoObjCIdPointers;
1037 ConversionDecls.push_back(Conversion);
1038 }
1039 }
1040 }
1041 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1042 return OS_Array;
1043 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1044 return OS_Dictionary;
1045 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1046 // No conversion function was found. Issue diagnostic and return.
1047 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1048 << FromE->getType();
1049 return OS_Error;
1050 }
1051 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1052 << FromE->getType();
1053 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1054 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1055
1056 return OS_Error;
1057}
1058
Fariborz Jahanian90804912012-08-02 18:03:58 +00001059/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1060/// objects used as dictionary subscript key objects.
1061static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1062 Expr *Key) {
1063 if (ContainerT.isNull())
1064 return;
1065 // dictionary subscripting.
1066 // - (id)objectForKeyedSubscript:(id)key;
1067 IdentifierInfo *KeyIdents[] = {
1068 &S.Context.Idents.get("objectForKeyedSubscript")
1069 };
1070 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1071 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1072 true /*instance*/);
1073 if (!Getter)
1074 return;
1075 QualType T = Getter->param_begin()[0]->getType();
1076 S.CheckObjCARCConversion(Key->getSourceRange(),
1077 T, Key, Sema::CCK_ImplicitConversion);
1078}
1079
Ted Kremeneke65b0862012-03-06 20:05:56 +00001080bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1081 if (AtIndexGetter)
1082 return true;
1083
1084 Expr *BaseExpr = RefExpr->getBaseExpr();
1085 QualType BaseT = BaseExpr->getType();
1086
1087 QualType ResultType;
1088 if (const ObjCObjectPointerType *PTy =
1089 BaseT->getAs<ObjCObjectPointerType>()) {
1090 ResultType = PTy->getPointeeType();
1091 if (const ObjCObjectType *iQFaceTy =
1092 ResultType->getAsObjCQualifiedInterfaceType())
1093 ResultType = iQFaceTy->getBaseType();
1094 }
1095 Sema::ObjCSubscriptKind Res =
1096 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001097 if (Res == Sema::OS_Error) {
1098 if (S.getLangOpts().ObjCAutoRefCount)
1099 CheckKeyForObjCARCConversion(S, ResultType,
1100 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001101 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001102 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001103 bool arrayRef = (Res == Sema::OS_Array);
1104
1105 if (ResultType.isNull()) {
1106 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1107 << BaseExpr->getType() << arrayRef;
1108 return false;
1109 }
1110 if (!arrayRef) {
1111 // dictionary subscripting.
1112 // - (id)objectForKeyedSubscript:(id)key;
1113 IdentifierInfo *KeyIdents[] = {
1114 &S.Context.Idents.get("objectForKeyedSubscript")
1115 };
1116 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1117 }
1118 else {
1119 // - (id)objectAtIndexedSubscript:(size_t)index;
1120 IdentifierInfo *KeyIdents[] = {
1121 &S.Context.Idents.get("objectAtIndexedSubscript")
1122 };
1123
1124 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1125 }
1126
1127 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1128 true /*instance*/);
1129 bool receiverIdType = (BaseT->isObjCIdType() ||
1130 BaseT->isObjCQualifiedIdType());
1131
David Blaikiebbafb8a2012-03-11 07:00:24 +00001132 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001133 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1134 SourceLocation(), AtIndexGetterSelector,
1135 S.Context.getObjCIdType() /*ReturnType*/,
1136 0 /*TypeSourceInfo */,
1137 S.Context.getTranslationUnitDecl(),
1138 true /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +00001139 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001140 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1141 ObjCMethodDecl::Required,
1142 false);
1143 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1144 SourceLocation(), SourceLocation(),
1145 arrayRef ? &S.Context.Idents.get("index")
1146 : &S.Context.Idents.get("key"),
1147 arrayRef ? S.Context.UnsignedLongTy
1148 : S.Context.getObjCIdType(),
1149 /*TInfo=*/0,
1150 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001151 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001152 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001153 }
1154
1155 if (!AtIndexGetter) {
1156 if (!receiverIdType) {
1157 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1158 << BaseExpr->getType() << 0 << arrayRef;
1159 return false;
1160 }
1161 AtIndexGetter =
1162 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1163 RefExpr->getSourceRange(),
1164 true, false);
1165 }
1166
1167 if (AtIndexGetter) {
1168 QualType T = AtIndexGetter->param_begin()[0]->getType();
1169 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1170 (!arrayRef && !T->isObjCObjectPointerType())) {
1171 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1172 arrayRef ? diag::err_objc_subscript_index_type
1173 : diag::err_objc_subscript_key_type) << T;
1174 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1175 diag::note_parameter_type) << T;
1176 return false;
1177 }
Alp Toker314cc812014-01-25 16:55:45 +00001178 QualType R = AtIndexGetter->getReturnType();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001179 if (!R->isObjCObjectPointerType()) {
1180 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1181 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1182 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1183 AtIndexGetter->getDeclName();
1184 }
1185 }
1186 return true;
1187}
1188
1189bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1190 if (AtIndexSetter)
1191 return true;
1192
1193 Expr *BaseExpr = RefExpr->getBaseExpr();
1194 QualType BaseT = BaseExpr->getType();
1195
1196 QualType ResultType;
1197 if (const ObjCObjectPointerType *PTy =
1198 BaseT->getAs<ObjCObjectPointerType>()) {
1199 ResultType = PTy->getPointeeType();
1200 if (const ObjCObjectType *iQFaceTy =
1201 ResultType->getAsObjCQualifiedInterfaceType())
1202 ResultType = iQFaceTy->getBaseType();
1203 }
1204
1205 Sema::ObjCSubscriptKind Res =
1206 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001207 if (Res == Sema::OS_Error) {
1208 if (S.getLangOpts().ObjCAutoRefCount)
1209 CheckKeyForObjCARCConversion(S, ResultType,
1210 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001211 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001212 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001213 bool arrayRef = (Res == Sema::OS_Array);
1214
1215 if (ResultType.isNull()) {
1216 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1217 << BaseExpr->getType() << arrayRef;
1218 return false;
1219 }
1220
1221 if (!arrayRef) {
1222 // dictionary subscripting.
1223 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1224 IdentifierInfo *KeyIdents[] = {
1225 &S.Context.Idents.get("setObject"),
1226 &S.Context.Idents.get("forKeyedSubscript")
1227 };
1228 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1229 }
1230 else {
1231 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1232 IdentifierInfo *KeyIdents[] = {
1233 &S.Context.Idents.get("setObject"),
1234 &S.Context.Idents.get("atIndexedSubscript")
1235 };
1236 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1237 }
1238 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1239 true /*instance*/);
1240
1241 bool receiverIdType = (BaseT->isObjCIdType() ||
1242 BaseT->isObjCQualifiedIdType());
1243
David Blaikiebbafb8a2012-03-11 07:00:24 +00001244 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Alp Toker314cc812014-01-25 16:55:45 +00001245 TypeSourceInfo *ReturnTInfo = 0;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001246 QualType ReturnType = S.Context.VoidTy;
Alp Toker314cc812014-01-25 16:55:45 +00001247 AtIndexSetter = ObjCMethodDecl::Create(
1248 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1249 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1250 true /*Instance*/, false /*isVariadic*/,
1251 /*isPropertyAccessor=*/false,
1252 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1253 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001254 SmallVector<ParmVarDecl *, 2> Params;
1255 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1256 SourceLocation(), SourceLocation(),
1257 &S.Context.Idents.get("object"),
1258 S.Context.getObjCIdType(),
1259 /*TInfo=*/0,
1260 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001261 0);
1262 Params.push_back(object);
1263 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1264 SourceLocation(), SourceLocation(),
1265 arrayRef ? &S.Context.Idents.get("index")
1266 : &S.Context.Idents.get("key"),
1267 arrayRef ? S.Context.UnsignedLongTy
1268 : S.Context.getObjCIdType(),
1269 /*TInfo=*/0,
1270 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001271 0);
1272 Params.push_back(key);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001273 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001274 }
1275
1276 if (!AtIndexSetter) {
1277 if (!receiverIdType) {
1278 S.Diag(BaseExpr->getExprLoc(),
1279 diag::err_objc_subscript_method_not_found)
1280 << BaseExpr->getType() << 1 << arrayRef;
1281 return false;
1282 }
1283 AtIndexSetter =
1284 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1285 RefExpr->getSourceRange(),
1286 true, false);
1287 }
1288
1289 bool err = false;
1290 if (AtIndexSetter && arrayRef) {
1291 QualType T = AtIndexSetter->param_begin()[1]->getType();
1292 if (!T->isIntegralOrEnumerationType()) {
1293 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1294 diag::err_objc_subscript_index_type) << T;
1295 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1296 diag::note_parameter_type) << T;
1297 err = true;
1298 }
1299 T = AtIndexSetter->param_begin()[0]->getType();
1300 if (!T->isObjCObjectPointerType()) {
1301 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1302 diag::err_objc_subscript_object_type) << T << arrayRef;
1303 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1304 diag::note_parameter_type) << T;
1305 err = true;
1306 }
1307 }
1308 else if (AtIndexSetter && !arrayRef)
1309 for (unsigned i=0; i <2; i++) {
1310 QualType T = AtIndexSetter->param_begin()[i]->getType();
1311 if (!T->isObjCObjectPointerType()) {
1312 if (i == 1)
1313 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1314 diag::err_objc_subscript_key_type) << T;
1315 else
1316 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1317 diag::err_objc_subscript_dic_object_type) << T;
1318 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1319 diag::note_parameter_type) << T;
1320 err = true;
1321 }
1322 }
1323
1324 return !err;
1325}
1326
1327// Get the object at "Index" position in the container.
1328// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1329ExprResult ObjCSubscriptOpBuilder::buildGet() {
1330 if (!findAtIndexGetter())
1331 return ExprError();
1332
1333 QualType receiverType = InstanceBase->getType();
1334
1335 // Build a message-send.
1336 ExprResult msg;
1337 Expr *Index = InstanceKey;
1338
1339 // Arguments.
1340 Expr *args[] = { Index };
1341 assert(InstanceBase);
1342 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1343 GenericLoc,
1344 AtIndexGetterSelector, AtIndexGetter,
1345 MultiExprArg(args, 1));
1346 return msg;
1347}
1348
1349/// Store into the container the "op" object at "Index"'ed location
1350/// by building this messaging expression:
1351/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001352/// \param captureSetValueAsResult If true, capture the actual
Ted Kremeneke65b0862012-03-06 20:05:56 +00001353/// value being set as the value of the property operation.
1354ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1355 bool captureSetValueAsResult) {
1356 if (!findAtIndexSetter())
1357 return ExprError();
1358
1359 QualType receiverType = InstanceBase->getType();
1360 Expr *Index = InstanceKey;
1361
1362 // Arguments.
1363 Expr *args[] = { op, Index };
1364
1365 // Build a message-send.
1366 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1367 GenericLoc,
1368 AtIndexSetterSelector,
1369 AtIndexSetter,
1370 MultiExprArg(args, 2));
1371
1372 if (!msg.isInvalid() && captureSetValueAsResult) {
1373 ObjCMessageExpr *msgExpr =
1374 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1375 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +00001376 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +00001377 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremeneke65b0862012-03-06 20:05:56 +00001378 }
1379
1380 return msg;
1381}
1382
John McCallfe96e0b2011-11-06 09:01:30 +00001383//===----------------------------------------------------------------------===//
John McCall5e77d762013-04-16 07:28:30 +00001384// MSVC __declspec(property) references
1385//===----------------------------------------------------------------------===//
1386
1387Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1388 Expr *NewBase = capture(RefExpr->getBaseExpr());
1389
1390 syntacticBase =
1391 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1392
1393 return syntacticBase;
1394}
1395
1396ExprResult MSPropertyOpBuilder::buildGet() {
1397 if (!RefExpr->getPropertyDecl()->hasGetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001398 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001399 << 0 /* getter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001400 return ExprError();
1401 }
1402
1403 UnqualifiedId GetterName;
1404 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1405 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1406 CXXScopeSpec SS;
1407 SS.Adopt(RefExpr->getQualifierLoc());
1408 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1409 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1410 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1411 GetterName, 0, true);
1412 if (GetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001413 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001414 diag::error_cannot_find_suitable_accessor) << 0 /* getter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001415 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001416 return ExprError();
1417 }
1418
1419 MultiExprArg ArgExprs;
1420 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1421 RefExpr->getSourceRange().getBegin(), ArgExprs,
1422 RefExpr->getSourceRange().getEnd());
1423}
1424
1425ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1426 bool captureSetValueAsResult) {
1427 if (!RefExpr->getPropertyDecl()->hasSetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001428 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001429 << 1 /* setter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001430 return ExprError();
1431 }
1432
1433 UnqualifiedId SetterName;
1434 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1435 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1436 CXXScopeSpec SS;
1437 SS.Adopt(RefExpr->getQualifierLoc());
1438 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1439 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1440 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1441 SetterName, 0, true);
1442 if (SetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001443 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001444 diag::error_cannot_find_suitable_accessor) << 1 /* setter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001445 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001446 return ExprError();
1447 }
1448
1449 SmallVector<Expr*, 1> ArgExprs;
1450 ArgExprs.push_back(op);
1451 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(),
1452 RefExpr->getSourceRange().getBegin(), ArgExprs,
1453 op->getSourceRange().getEnd());
1454}
1455
1456//===----------------------------------------------------------------------===//
John McCallfe96e0b2011-11-06 09:01:30 +00001457// General Sema routines.
1458//===----------------------------------------------------------------------===//
1459
1460ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1461 Expr *opaqueRef = E->IgnoreParens();
1462 if (ObjCPropertyRefExpr *refExpr
1463 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1464 ObjCPropertyOpBuilder builder(*this, refExpr);
1465 return builder.buildRValueOperation(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001466 }
1467 else if (ObjCSubscriptRefExpr *refExpr
1468 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1469 ObjCSubscriptOpBuilder builder(*this, refExpr);
1470 return builder.buildRValueOperation(E);
John McCall5e77d762013-04-16 07:28:30 +00001471 } else if (MSPropertyRefExpr *refExpr
1472 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1473 MSPropertyOpBuilder builder(*this, refExpr);
1474 return builder.buildRValueOperation(E);
John McCallfe96e0b2011-11-06 09:01:30 +00001475 } else {
1476 llvm_unreachable("unknown pseudo-object kind!");
1477 }
1478}
1479
1480/// Check an increment or decrement of a pseudo-object expression.
1481ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1482 UnaryOperatorKind opcode, Expr *op) {
1483 // Do nothing if the operand is dependent.
1484 if (op->isTypeDependent())
1485 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1486 VK_RValue, OK_Ordinary, opcLoc);
1487
1488 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1489 Expr *opaqueRef = op->IgnoreParens();
1490 if (ObjCPropertyRefExpr *refExpr
1491 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1492 ObjCPropertyOpBuilder builder(*this, refExpr);
1493 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001494 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1495 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1496 return ExprError();
John McCall5e77d762013-04-16 07:28:30 +00001497 } else if (MSPropertyRefExpr *refExpr
1498 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1499 MSPropertyOpBuilder builder(*this, refExpr);
1500 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCallfe96e0b2011-11-06 09:01:30 +00001501 } else {
1502 llvm_unreachable("unknown pseudo-object kind!");
1503 }
1504}
1505
1506ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1507 BinaryOperatorKind opcode,
1508 Expr *LHS, Expr *RHS) {
1509 // Do nothing if either argument is dependent.
1510 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1511 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00001512 VK_RValue, OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +00001513
1514 // Filter out non-overload placeholder types in the RHS.
John McCalld5c98ae2011-11-15 01:35:18 +00001515 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1516 ExprResult result = CheckPlaceholderExpr(RHS);
1517 if (result.isInvalid()) return ExprError();
1518 RHS = result.take();
John McCallfe96e0b2011-11-06 09:01:30 +00001519 }
1520
1521 Expr *opaqueRef = LHS->IgnoreParens();
1522 if (ObjCPropertyRefExpr *refExpr
1523 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1524 ObjCPropertyOpBuilder builder(*this, refExpr);
1525 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001526 } else if (ObjCSubscriptRefExpr *refExpr
1527 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1528 ObjCSubscriptOpBuilder builder(*this, refExpr);
1529 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall5e77d762013-04-16 07:28:30 +00001530 } else if (MSPropertyRefExpr *refExpr
1531 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1532 MSPropertyOpBuilder builder(*this, refExpr);
1533 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCallfe96e0b2011-11-06 09:01:30 +00001534 } else {
1535 llvm_unreachable("unknown pseudo-object kind!");
1536 }
1537}
John McCalle9290822011-11-30 04:42:31 +00001538
1539/// Given a pseudo-object reference, rebuild it without the opaque
1540/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1541/// This should never operate in-place.
1542static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1543 Expr *opaqueRef = E->IgnoreParens();
1544 if (ObjCPropertyRefExpr *refExpr
1545 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregoraa0df2d2012-04-13 16:05:42 +00001546 // Class and super property references don't have opaque values in them.
1547 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1548 return E;
1549
1550 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1551 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1552 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001553 } else if (ObjCSubscriptRefExpr *refExpr
1554 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1555 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1556 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1557 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1558 keyOVE->getSourceExpr()).rebuild(E);
John McCall5e77d762013-04-16 07:28:30 +00001559 } else if (MSPropertyRefExpr *refExpr
1560 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1561 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1562 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCalle9290822011-11-30 04:42:31 +00001563 } else {
1564 llvm_unreachable("unknown pseudo-object kind!");
1565 }
1566}
1567
1568/// Given a pseudo-object expression, recreate what it looks like
1569/// syntactically without the attendant OpaqueValueExprs.
1570///
1571/// This is a hack which should be removed when TreeTransform is
1572/// capable of rebuilding a tree without stripping implicit
1573/// operations.
1574Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1575 Expr *syntax = E->getSyntacticForm();
1576 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1577 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1578 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1579 uop->getValueKind(), uop->getObjectKind(),
1580 uop->getOperatorLoc());
1581 } else if (CompoundAssignOperator *cop
1582 = dyn_cast<CompoundAssignOperator>(syntax)) {
1583 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1584 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1585 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1586 cop->getType(),
1587 cop->getValueKind(),
1588 cop->getObjectKind(),
1589 cop->getComputationLHSType(),
1590 cop->getComputationResultType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001591 cop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001592 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1593 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1594 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1595 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1596 bop->getType(), bop->getValueKind(),
1597 bop->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001598 bop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001599 } else {
1600 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1601 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1602 }
1603}