blob: a28ad5eb0701d9fa6c3cbbc607a83da1aefb753e [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"
Benjamin Kramerf3ca26982014-05-10 16:31:55 +000034#include "clang/AST/ExprCXX.h"
John McCall526ab472011-10-25 17:37:35 +000035#include "clang/AST/ExprObjC.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000036#include "clang/Basic/CharInfo.h"
John McCall526ab472011-10-25 17:37:35 +000037#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000038#include "clang/Sema/Initialization.h"
39#include "clang/Sema/ScopeInfo.h"
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +000040#include "llvm/ADT/SmallString.h"
John McCall526ab472011-10-25 17:37:35 +000041
42using namespace clang;
43using namespace sema;
44
John McCallfe96e0b2011-11-06 09:01:30 +000045namespace {
46 // Basically just a very focused copy of TreeTransform.
47 template <class T> struct Rebuilder {
48 Sema &S;
49 Rebuilder(Sema &S) : S(S) {}
50
51 T &getDerived() { return static_cast<T&>(*this); }
52
53 Expr *rebuild(Expr *e) {
54 // Fast path: nothing to look through.
55 if (typename T::specific_type *specific
56 = dyn_cast<typename T::specific_type>(e))
57 return getDerived().rebuildSpecific(specific);
58
59 // Otherwise, we should look through and rebuild anything that
60 // IgnoreParens would.
61
62 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
63 e = rebuild(parens->getSubExpr());
64 return new (S.Context) ParenExpr(parens->getLParen(),
65 parens->getRParen(),
66 e);
67 }
68
69 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
70 assert(uop->getOpcode() == UO_Extension);
71 e = rebuild(uop->getSubExpr());
72 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
73 uop->getType(),
74 uop->getValueKind(),
75 uop->getObjectKind(),
76 uop->getOperatorLoc());
77 }
78
79 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
80 assert(!gse->isResultDependent());
81 unsigned resultIndex = gse->getResultIndex();
82 unsigned numAssocs = gse->getNumAssocs();
83
84 SmallVector<Expr*, 8> assocs(numAssocs);
85 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
86
87 for (unsigned i = 0; i != numAssocs; ++i) {
88 Expr *assoc = gse->getAssocExpr(i);
89 if (i == resultIndex) assoc = rebuild(assoc);
90 assocs[i] = assoc;
91 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
92 }
93
94 return new (S.Context) GenericSelectionExpr(S.Context,
95 gse->getGenericLoc(),
96 gse->getControllingExpr(),
Benjamin Kramerc215e762012-08-24 11:54:20 +000097 assocTypes,
98 assocs,
John McCallfe96e0b2011-11-06 09:01:30 +000099 gse->getDefaultLoc(),
100 gse->getRParenLoc(),
101 gse->containsUnexpandedParameterPack(),
102 resultIndex);
103 }
104
Eli Friedman75807f22013-07-20 00:40:58 +0000105 if (ChooseExpr *ce = dyn_cast<ChooseExpr>(e)) {
106 assert(!ce->isConditionDependent());
107
108 Expr *LHS = ce->getLHS(), *RHS = ce->getRHS();
109 Expr *&rebuiltExpr = ce->isConditionTrue() ? LHS : RHS;
110 rebuiltExpr = rebuild(rebuiltExpr);
111
112 return new (S.Context) ChooseExpr(ce->getBuiltinLoc(),
113 ce->getCond(),
114 LHS, RHS,
115 rebuiltExpr->getType(),
116 rebuiltExpr->getValueKind(),
117 rebuiltExpr->getObjectKind(),
118 ce->getRParenLoc(),
119 ce->isConditionTrue(),
120 rebuiltExpr->isTypeDependent(),
121 rebuiltExpr->isValueDependent());
122 }
123
John McCallfe96e0b2011-11-06 09:01:30 +0000124 llvm_unreachable("bad expression to rebuild!");
125 }
126 };
127
128 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
129 Expr *NewBase;
130 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Kramer5c29d692011-11-06 09:50:13 +0000131 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCallfe96e0b2011-11-06 09:01:30 +0000132
133 typedef ObjCPropertyRefExpr specific_type;
134 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
135 // Fortunately, the constraint that we're rebuilding something
136 // with a base limits the number of cases here.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000137 assert(refExpr->isObjectReceiver());
John McCallfe96e0b2011-11-06 09:01:30 +0000138
139 if (refExpr->isExplicitProperty()) {
140 return new (S.Context)
141 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
142 refExpr->getType(), refExpr->getValueKind(),
143 refExpr->getObjectKind(), refExpr->getLocation(),
144 NewBase);
145 }
146 return new (S.Context)
147 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
148 refExpr->getImplicitPropertySetter(),
149 refExpr->getType(), refExpr->getValueKind(),
150 refExpr->getObjectKind(),refExpr->getLocation(),
151 NewBase);
152 }
153 };
154
Ted Kremeneke65b0862012-03-06 20:05:56 +0000155 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
156 Expr *NewBase;
157 Expr *NewKeyExpr;
158 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
159 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
160 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
161
162 typedef ObjCSubscriptRefExpr specific_type;
163 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
164 assert(refExpr->getBaseExpr());
165 assert(refExpr->getKeyExpr());
166
167 return new (S.Context)
168 ObjCSubscriptRefExpr(NewBase,
169 NewKeyExpr,
170 refExpr->getType(), refExpr->getValueKind(),
171 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
172 refExpr->setAtIndexMethodDecl(),
173 refExpr->getRBracket());
174 }
175 };
John McCall5e77d762013-04-16 07:28:30 +0000176
177 struct MSPropertyRefRebuilder : Rebuilder<MSPropertyRefRebuilder> {
178 Expr *NewBase;
179 MSPropertyRefRebuilder(Sema &S, Expr *newBase)
180 : Rebuilder<MSPropertyRefRebuilder>(S), NewBase(newBase) {}
181
182 typedef MSPropertyRefExpr specific_type;
183 Expr *rebuildSpecific(MSPropertyRefExpr *refExpr) {
184 assert(refExpr->getBaseExpr());
185
186 return new (S.Context)
187 MSPropertyRefExpr(NewBase, refExpr->getPropertyDecl(),
188 refExpr->isArrow(), refExpr->getType(),
189 refExpr->getValueKind(), refExpr->getQualifierLoc(),
190 refExpr->getMemberLoc());
191 }
192 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000193
John McCallfe96e0b2011-11-06 09:01:30 +0000194 class PseudoOpBuilder {
195 public:
196 Sema &S;
197 unsigned ResultIndex;
198 SourceLocation GenericLoc;
199 SmallVector<Expr *, 4> Semantics;
200
201 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
202 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
203 GenericLoc(genericLoc) {}
204
Matt Beaumont-Gayfb3cb9a2011-11-08 01:53:17 +0000205 virtual ~PseudoOpBuilder() {}
206
John McCallfe96e0b2011-11-06 09:01:30 +0000207 /// Add a normal semantic expression.
208 void addSemanticExpr(Expr *semantic) {
209 Semantics.push_back(semantic);
210 }
211
212 /// Add the 'result' semantic expression.
213 void addResultSemanticExpr(Expr *resultExpr) {
214 assert(ResultIndex == PseudoObjectExpr::NoResult);
215 ResultIndex = Semantics.size();
216 Semantics.push_back(resultExpr);
217 }
218
219 ExprResult buildRValueOperation(Expr *op);
220 ExprResult buildAssignmentOperation(Scope *Sc,
221 SourceLocation opLoc,
222 BinaryOperatorKind opcode,
223 Expr *LHS, Expr *RHS);
224 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
225 UnaryOperatorKind opcode,
226 Expr *op);
227
Jordan Rosed3934582012-09-28 22:21:30 +0000228 virtual ExprResult complete(Expr *syntacticForm);
John McCallfe96e0b2011-11-06 09:01:30 +0000229
230 OpaqueValueExpr *capture(Expr *op);
231 OpaqueValueExpr *captureValueAsResult(Expr *op);
232
233 void setResultToLastSemantic() {
234 assert(ResultIndex == PseudoObjectExpr::NoResult);
235 ResultIndex = Semantics.size() - 1;
236 }
237
238 /// Return true if assignments have a non-void result.
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000239 bool CanCaptureValue(Expr *exp) {
240 if (exp->isGLValue())
241 return true;
242 QualType ty = exp->getType();
Eli Friedman00fa4292012-11-13 23:16:33 +0000243 assert(!ty->isIncompleteType());
244 assert(!ty->isDependentType());
245
246 if (const CXXRecordDecl *ClassDecl = ty->getAsCXXRecordDecl())
247 return ClassDecl->isTriviallyCopyable();
248 return true;
249 }
John McCallfe96e0b2011-11-06 09:01:30 +0000250
251 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
252 virtual ExprResult buildGet() = 0;
253 virtual ExprResult buildSet(Expr *, SourceLocation,
254 bool captureSetValueAsResult) = 0;
255 };
256
Dmitri Gribenko00bcdd32012-09-12 17:01:48 +0000257 /// A PseudoOpBuilder for Objective-C \@properties.
John McCallfe96e0b2011-11-06 09:01:30 +0000258 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
259 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000260 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCallfe96e0b2011-11-06 09:01:30 +0000261 OpaqueValueExpr *InstanceReceiver;
262 ObjCMethodDecl *Getter;
263
264 ObjCMethodDecl *Setter;
265 Selector SetterSelector;
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000266 Selector GetterSelector;
John McCallfe96e0b2011-11-06 09:01:30 +0000267
268 public:
269 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
270 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000271 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) {
John McCallfe96e0b2011-11-06 09:01:30 +0000272 }
273
274 ExprResult buildRValueOperation(Expr *op);
275 ExprResult buildAssignmentOperation(Scope *Sc,
276 SourceLocation opLoc,
277 BinaryOperatorKind opcode,
278 Expr *LHS, Expr *RHS);
279 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
280 UnaryOperatorKind opcode,
281 Expr *op);
282
283 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000284 bool findSetter(bool warn=true);
John McCallfe96e0b2011-11-06 09:01:30 +0000285 bool findGetter();
286
Craig Toppere14c0f82014-03-12 04:55:44 +0000287 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
288 ExprResult buildGet() override;
289 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
290 ExprResult complete(Expr *SyntacticForm) override;
Jordan Rosed3934582012-09-28 22:21:30 +0000291
292 bool isWeakProperty() const;
John McCallfe96e0b2011-11-06 09:01:30 +0000293 };
Ted Kremeneke65b0862012-03-06 20:05:56 +0000294
295 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
296 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
297 ObjCSubscriptRefExpr *RefExpr;
298 OpaqueValueExpr *InstanceBase;
299 OpaqueValueExpr *InstanceKey;
300 ObjCMethodDecl *AtIndexGetter;
301 Selector AtIndexGetterSelector;
302
303 ObjCMethodDecl *AtIndexSetter;
304 Selector AtIndexSetterSelector;
305
306 public:
307 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
308 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
309 RefExpr(refExpr),
310 InstanceBase(0), InstanceKey(0),
311 AtIndexGetter(0), AtIndexSetter(0) { }
312
313 ExprResult buildRValueOperation(Expr *op);
314 ExprResult buildAssignmentOperation(Scope *Sc,
315 SourceLocation opLoc,
316 BinaryOperatorKind opcode,
317 Expr *LHS, Expr *RHS);
Craig Toppere14c0f82014-03-12 04:55:44 +0000318 Expr *rebuildAndCaptureObject(Expr *syntacticBase) override;
319
Ted Kremeneke65b0862012-03-06 20:05:56 +0000320 bool findAtIndexGetter();
321 bool findAtIndexSetter();
Craig Toppere14c0f82014-03-12 04:55:44 +0000322
323 ExprResult buildGet() override;
324 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000325 };
326
John McCall5e77d762013-04-16 07:28:30 +0000327 class MSPropertyOpBuilder : public PseudoOpBuilder {
328 MSPropertyRefExpr *RefExpr;
329
330 public:
331 MSPropertyOpBuilder(Sema &S, MSPropertyRefExpr *refExpr) :
332 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
333 RefExpr(refExpr) {}
334
Craig Toppere14c0f82014-03-12 04:55:44 +0000335 Expr *rebuildAndCaptureObject(Expr *) override;
336 ExprResult buildGet() override;
337 ExprResult buildSet(Expr *op, SourceLocation, bool) override;
John McCall5e77d762013-04-16 07:28:30 +0000338 };
John McCallfe96e0b2011-11-06 09:01:30 +0000339}
340
341/// Capture the given expression in an OpaqueValueExpr.
342OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
343 // Make a new OVE whose source is the given expression.
344 OpaqueValueExpr *captured =
345 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor2d5aea02012-02-23 22:17:26 +0000346 e->getValueKind(), e->getObjectKind(),
347 e);
John McCallfe96e0b2011-11-06 09:01:30 +0000348
349 // Make sure we bind that in the semantics.
350 addSemanticExpr(captured);
351 return captured;
352}
353
354/// Capture the given expression as the result of this pseudo-object
355/// operation. This routine is safe against expressions which may
356/// already be captured.
357///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000358/// \returns the captured expression, which will be the
John McCallfe96e0b2011-11-06 09:01:30 +0000359/// same as the input if the input was already captured
360OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
361 assert(ResultIndex == PseudoObjectExpr::NoResult);
362
363 // If the expression hasn't already been captured, just capture it
364 // and set the new semantic
365 if (!isa<OpaqueValueExpr>(e)) {
366 OpaqueValueExpr *cap = capture(e);
367 setResultToLastSemantic();
368 return cap;
369 }
370
371 // Otherwise, it must already be one of our semantic expressions;
372 // set ResultIndex to its index.
373 unsigned index = 0;
374 for (;; ++index) {
375 assert(index < Semantics.size() &&
376 "captured expression not found in semantics!");
377 if (e == Semantics[index]) break;
378 }
379 ResultIndex = index;
380 return cast<OpaqueValueExpr>(e);
381}
382
383/// The routine which creates the final PseudoObjectExpr.
384ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
385 return PseudoObjectExpr::Create(S.Context, syntactic,
386 Semantics, ResultIndex);
387}
388
389/// The main skeleton for building an r-value operation.
390ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
391 Expr *syntacticBase = rebuildAndCaptureObject(op);
392
393 ExprResult getExpr = buildGet();
394 if (getExpr.isInvalid()) return ExprError();
395 addResultSemanticExpr(getExpr.take());
396
397 return complete(syntacticBase);
398}
399
400/// The basic skeleton for building a simple or compound
401/// assignment operation.
402ExprResult
403PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
404 BinaryOperatorKind opcode,
405 Expr *LHS, Expr *RHS) {
406 assert(BinaryOperator::isAssignmentOp(opcode));
407
408 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
409 OpaqueValueExpr *capturedRHS = capture(RHS);
410
411 Expr *syntactic;
412
413 ExprResult result;
414 if (opcode == BO_Assign) {
415 result = capturedRHS;
416 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
417 opcode, capturedRHS->getType(),
418 capturedRHS->getValueKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000419 OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000420 } else {
421 ExprResult opLHS = buildGet();
422 if (opLHS.isInvalid()) return ExprError();
423
424 // Build an ordinary, non-compound operation.
425 BinaryOperatorKind nonCompound =
426 BinaryOperator::getOpForCompoundAssignment(opcode);
427 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
428 opLHS.take(), capturedRHS);
429 if (result.isInvalid()) return ExprError();
430
431 syntactic =
432 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
433 result.get()->getType(),
434 result.get()->getValueKind(),
435 OK_Ordinary,
436 opLHS.get()->getType(),
437 result.get()->getType(),
Lang Hames5de91cc2012-10-02 04:45:10 +0000438 opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +0000439 }
440
441 // The result of the assignment, if not void, is the value set into
442 // the l-value.
Eli Friedman00fa4292012-11-13 23:16:33 +0000443 result = buildSet(result.take(), opcLoc, /*captureSetValueAsResult*/ true);
John McCallfe96e0b2011-11-06 09:01:30 +0000444 if (result.isInvalid()) return ExprError();
445 addSemanticExpr(result.take());
446
447 return complete(syntactic);
448}
449
450/// The basic skeleton for building an increment or decrement
451/// operation.
452ExprResult
453PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
454 UnaryOperatorKind opcode,
455 Expr *op) {
456 assert(UnaryOperator::isIncrementDecrementOp(opcode));
457
458 Expr *syntacticOp = rebuildAndCaptureObject(op);
459
460 // Load the value.
461 ExprResult result = buildGet();
462 if (result.isInvalid()) return ExprError();
463
464 QualType resultType = result.get()->getType();
465
466 // That's the postfix result.
John McCall0d9dd732013-04-16 22:32:04 +0000467 if (UnaryOperator::isPostfix(opcode) &&
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000468 (result.get()->isTypeDependent() || CanCaptureValue(result.get()))) {
John McCallfe96e0b2011-11-06 09:01:30 +0000469 result = capture(result.take());
470 setResultToLastSemantic();
471 }
472
473 // Add or subtract a literal 1.
474 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
475 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
476 GenericLoc);
477
478 if (UnaryOperator::isIncrementOp(opcode)) {
479 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
480 } else {
481 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
482 }
483 if (result.isInvalid()) return ExprError();
484
485 // Store that back into the result. The value stored is the result
486 // of a prefix operation.
Eli Friedman00fa4292012-11-13 23:16:33 +0000487 result = buildSet(result.take(), opcLoc, UnaryOperator::isPrefix(opcode));
John McCallfe96e0b2011-11-06 09:01:30 +0000488 if (result.isInvalid()) return ExprError();
489 addSemanticExpr(result.take());
490
491 UnaryOperator *syntactic =
492 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
493 VK_LValue, OK_Ordinary, opcLoc);
494 return complete(syntactic);
495}
496
497
498//===----------------------------------------------------------------------===//
499// Objective-C @property and implicit property references
500//===----------------------------------------------------------------------===//
501
502/// Look up a method in the receiver type of an Objective-C property
503/// reference.
John McCall526ab472011-10-25 17:37:35 +0000504static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
505 const ObjCPropertyRefExpr *PRE) {
John McCall526ab472011-10-25 17:37:35 +0000506 if (PRE->isObjectReceiver()) {
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000507 const ObjCObjectPointerType *PT =
508 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCallfe96e0b2011-11-06 09:01:30 +0000509
510 // Special case for 'self' in class method implementations.
511 if (PT->isObjCClassType() &&
512 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
513 // This cast is safe because isSelfExpr is only true within
514 // methods.
515 ObjCMethodDecl *method =
516 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
517 return S.LookupMethodInObjectType(sel,
518 S.Context.getObjCInterfaceType(method->getClassInterface()),
519 /*instance*/ false);
520 }
521
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000522 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall526ab472011-10-25 17:37:35 +0000523 }
524
Benjamin Kramer8dc57602011-10-28 13:21:18 +0000525 if (PRE->isSuperReceiver()) {
526 if (const ObjCObjectPointerType *PT =
527 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
528 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
529
530 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
531 }
532
533 assert(PRE->isClassReceiver() && "Invalid expression");
534 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
535 return S.LookupMethodInObjectType(sel, IT, false);
John McCall526ab472011-10-25 17:37:35 +0000536}
537
Jordan Rosed3934582012-09-28 22:21:30 +0000538bool ObjCPropertyOpBuilder::isWeakProperty() const {
539 QualType T;
540 if (RefExpr->isExplicitProperty()) {
541 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
542 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
543 return true;
544
545 T = Prop->getType();
546 } else if (Getter) {
Alp Toker314cc812014-01-25 16:55:45 +0000547 T = Getter->getReturnType();
Jordan Rosed3934582012-09-28 22:21:30 +0000548 } else {
549 return false;
550 }
551
552 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
553}
554
John McCallfe96e0b2011-11-06 09:01:30 +0000555bool ObjCPropertyOpBuilder::findGetter() {
556 if (Getter) return true;
John McCall526ab472011-10-25 17:37:35 +0000557
John McCallcfef5462011-11-07 22:49:50 +0000558 // For implicit properties, just trust the lookup we already did.
559 if (RefExpr->isImplicitProperty()) {
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000560 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
561 GetterSelector = Getter->getSelector();
562 return true;
563 }
564 else {
565 // Must build the getter selector the hard way.
566 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
567 assert(setter && "both setter and getter are null - cannot happen");
568 IdentifierInfo *setterName =
569 setter->getSelector().getIdentifierInfoForSlot(0);
570 const char *compStr = setterName->getNameStart();
571 compStr += 3;
572 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
573 GetterSelector =
574 S.PP.getSelectorTable().getNullarySelector(getterName);
575 return false;
576
577 }
John McCallcfef5462011-11-07 22:49:50 +0000578 }
579
580 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
581 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
John McCallfe96e0b2011-11-06 09:01:30 +0000582 return (Getter != 0);
583}
584
585/// Try to find the most accurate setter declaration for the property
586/// reference.
587///
588/// \return true if a setter was found, in which case Setter
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000589bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCallfe96e0b2011-11-06 09:01:30 +0000590 // For implicit properties, just trust the lookup we already did.
591 if (RefExpr->isImplicitProperty()) {
592 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
593 Setter = setter;
594 SetterSelector = setter->getSelector();
595 return true;
John McCall526ab472011-10-25 17:37:35 +0000596 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000597 IdentifierInfo *getterName =
598 RefExpr->getImplicitPropertyGetter()->getSelector()
599 .getIdentifierInfoForSlot(0);
600 SetterSelector =
Adrian Prantla4ce9062013-06-07 22:29:12 +0000601 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
602 S.PP.getSelectorTable(),
603 getterName);
John McCallfe96e0b2011-11-06 09:01:30 +0000604 return false;
John McCall526ab472011-10-25 17:37:35 +0000605 }
John McCallfe96e0b2011-11-06 09:01:30 +0000606 }
607
608 // For explicit properties, this is more involved.
609 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
610 SetterSelector = prop->getSetterName();
611
612 // Do a normal method lookup first.
613 if (ObjCMethodDecl *setter =
614 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Jordan Rosed01e83a2012-10-10 16:42:25 +0000615 if (setter->isPropertyAccessor() && warn)
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000616 if (const ObjCInterfaceDecl *IFace =
617 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
618 const StringRef thisPropertyName(prop->getName());
Jordan Rosea7d03842013-02-08 22:30:41 +0000619 // Try flipping the case of the first character.
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000620 char front = thisPropertyName.front();
Jordan Rosea7d03842013-02-08 22:30:41 +0000621 front = isLowercase(front) ? toUppercase(front) : toLowercase(front);
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000622 SmallString<100> PropertyName = thisPropertyName;
623 PropertyName[0] = front;
624 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
625 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
626 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
Fariborz Jahanianf3b76812012-05-26 16:10:06 +0000627 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Aaron Ballman1fb39552014-01-03 14:23:03 +0000628 << prop << prop1 << setter->getSelector();
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000629 S.Diag(prop->getLocation(), diag::note_property_declare);
630 S.Diag(prop1->getLocation(), diag::note_property_declare);
631 }
632 }
John McCallfe96e0b2011-11-06 09:01:30 +0000633 Setter = setter;
634 return true;
635 }
636
637 // That can fail in the somewhat crazy situation that we're
638 // type-checking a message send within the @interface declaration
639 // that declared the @property. But it's not clear that that's
640 // valuable to support.
641
642 return false;
643}
644
645/// Capture the base object of an Objective-C property expression.
646Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
647 assert(InstanceReceiver == 0);
648
649 // If we have a base, capture it in an OVE and rebuild the syntactic
650 // form to use the OVE as its base.
651 if (RefExpr->isObjectReceiver()) {
652 InstanceReceiver = capture(RefExpr->getBase());
653
654 syntacticBase =
655 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
656 }
657
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000658 if (ObjCPropertyRefExpr *
659 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
660 SyntacticRefExpr = refE;
661
John McCallfe96e0b2011-11-06 09:01:30 +0000662 return syntacticBase;
663}
664
665/// Load from an Objective-C property reference.
666ExprResult ObjCPropertyOpBuilder::buildGet() {
667 findGetter();
668 assert(Getter);
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000669
670 if (SyntacticRefExpr)
671 SyntacticRefExpr->setIsMessagingGetter();
672
John McCallfe96e0b2011-11-06 09:01:30 +0000673 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000674 if (RefExpr->isClassReceiver()) {
675 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
676 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000677 receiverType = RefExpr->getSuperReceiverType();
John McCall526ab472011-10-25 17:37:35 +0000678 } else {
John McCallfe96e0b2011-11-06 09:01:30 +0000679 assert(InstanceReceiver);
680 receiverType = InstanceReceiver->getType();
681 }
John McCall526ab472011-10-25 17:37:35 +0000682
John McCallfe96e0b2011-11-06 09:01:30 +0000683 // Build a message-send.
684 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000685 if ((Getter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
686 RefExpr->isObjectReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000687 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000688 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
689 GenericLoc, Getter->getSelector(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000690 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000691 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000692 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
Dmitri Gribenko78852e92013-05-05 20:40:26 +0000693 GenericLoc, Getter->getSelector(),
694 Getter, None);
John McCallfe96e0b2011-11-06 09:01:30 +0000695 }
696 return msg;
697}
John McCall526ab472011-10-25 17:37:35 +0000698
John McCallfe96e0b2011-11-06 09:01:30 +0000699/// Store to an Objective-C property reference.
700///
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +0000701/// \param captureSetValueAsResult If true, capture the actual
John McCallfe96e0b2011-11-06 09:01:30 +0000702/// value being set as the value of the property operation.
703ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
704 bool captureSetValueAsResult) {
Fariborz Jahanian3f88afa2012-05-24 22:48:38 +0000705 bool hasSetter = findSetter(false);
John McCallfe96e0b2011-11-06 09:01:30 +0000706 assert(hasSetter); (void) hasSetter;
707
Argyrios Kyrtzidisab468b02012-03-30 00:19:18 +0000708 if (SyntacticRefExpr)
709 SyntacticRefExpr->setIsMessagingSetter();
710
John McCallfe96e0b2011-11-06 09:01:30 +0000711 QualType receiverType;
John McCallfe96e0b2011-11-06 09:01:30 +0000712 if (RefExpr->isClassReceiver()) {
713 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
714 } else if (RefExpr->isSuperReceiver()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000715 receiverType = RefExpr->getSuperReceiverType();
716 } else {
717 assert(InstanceReceiver);
718 receiverType = InstanceReceiver->getType();
719 }
720
721 // Use assignment constraints when possible; they give us better
722 // diagnostics. "When possible" basically means anything except a
723 // C++ class type.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000725 QualType paramType = (*Setter->param_begin())->getType();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000726 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000727 ExprResult opResult = op;
728 Sema::AssignConvertType assignResult
729 = S.CheckSingleAssignmentConstraints(paramType, opResult);
730 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
731 op->getType(), opResult.get(),
732 Sema::AA_Assigning))
733 return ExprError();
734
735 op = opResult.take();
736 assert(op && "successful assignment left argument invalid?");
John McCall526ab472011-10-25 17:37:35 +0000737 }
Fariborz Jahanian2eaec612013-10-16 17:51:43 +0000738 else if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(op)) {
739 Expr *Initializer = OVE->getSourceExpr();
740 // passing C++11 style initialized temporaries to objc++ properties
741 // requires special treatment by removing OpaqueValueExpr so type
742 // conversion takes place and adding the OpaqueValueExpr later on.
743 if (isa<InitListExpr>(Initializer) &&
744 Initializer->getType()->isVoidType()) {
745 op = Initializer;
746 }
747 }
John McCall526ab472011-10-25 17:37:35 +0000748 }
749
John McCallfe96e0b2011-11-06 09:01:30 +0000750 // Arguments.
751 Expr *args[] = { op };
John McCall526ab472011-10-25 17:37:35 +0000752
John McCallfe96e0b2011-11-06 09:01:30 +0000753 // Build a message-send.
754 ExprResult msg;
Fariborz Jahanian29cdbc62014-04-21 20:22:17 +0000755 if ((Setter->isInstanceMethod() && !RefExpr->isClassReceiver()) ||
756 RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000757 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
758 GenericLoc, SetterSelector, Setter,
759 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000760 } else {
Argyrios Kyrtzidisa80f1bf2012-01-12 02:34:39 +0000761 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
762 GenericLoc,
763 SetterSelector, Setter,
764 MultiExprArg(args, 1));
John McCallfe96e0b2011-11-06 09:01:30 +0000765 }
766
767 if (!msg.isInvalid() && captureSetValueAsResult) {
768 ObjCMessageExpr *msgExpr =
769 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
770 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +0000771 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +0000772 msgExpr->setArg(0, captureValueAsResult(arg));
John McCallfe96e0b2011-11-06 09:01:30 +0000773 }
774
775 return msg;
John McCall526ab472011-10-25 17:37:35 +0000776}
777
John McCallfe96e0b2011-11-06 09:01:30 +0000778/// @property-specific behavior for doing lvalue-to-rvalue conversion.
779ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
780 // Explicit properties always have getters, but implicit ones don't.
781 // Check that before proceeding.
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000782 if (RefExpr->isImplicitProperty() && !RefExpr->getImplicitPropertyGetter()) {
John McCallfe96e0b2011-11-06 09:01:30 +0000783 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
Eli Friedmanfd41aee2012-11-29 03:13:49 +0000784 << RefExpr->getSourceRange();
John McCall526ab472011-10-25 17:37:35 +0000785 return ExprError();
786 }
787
John McCallfe96e0b2011-11-06 09:01:30 +0000788 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall526ab472011-10-25 17:37:35 +0000789 if (result.isInvalid()) return ExprError();
790
John McCallfe96e0b2011-11-06 09:01:30 +0000791 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
792 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
793 Getter, RefExpr->getLocation());
794
795 // As a special case, if the method returns 'id', try to get
796 // a better type from the property.
797 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
798 result.get()->getType()->isObjCIdType()) {
799 QualType propType = RefExpr->getExplicitProperty()->getType();
800 if (const ObjCObjectPointerType *ptr
801 = propType->getAs<ObjCObjectPointerType>()) {
802 if (!ptr->isObjCIdType())
803 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
804 }
805 }
806
John McCall526ab472011-10-25 17:37:35 +0000807 return result;
808}
809
John McCallfe96e0b2011-11-06 09:01:30 +0000810/// Try to build this as a call to a getter that returns a reference.
811///
812/// \return true if it was possible, whether or not it actually
813/// succeeded
814bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
815 ExprResult &result) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000816 if (!S.getLangOpts().CPlusPlus) return false;
John McCallfe96e0b2011-11-06 09:01:30 +0000817
818 findGetter();
819 assert(Getter && "property has no setter and no getter!");
820
821 // Only do this if the getter returns an l-value reference type.
Alp Toker314cc812014-01-25 16:55:45 +0000822 QualType resultType = Getter->getReturnType();
John McCallfe96e0b2011-11-06 09:01:30 +0000823 if (!resultType->isLValueReferenceType()) return false;
824
825 result = buildRValueOperation(op);
826 return true;
827}
828
829/// @property-specific behavior for doing assignments.
830ExprResult
831ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
832 SourceLocation opcLoc,
833 BinaryOperatorKind opcode,
834 Expr *LHS, Expr *RHS) {
John McCall526ab472011-10-25 17:37:35 +0000835 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall526ab472011-10-25 17:37:35 +0000836
837 // If there's no setter, we have no choice but to try to assign to
838 // the result of the getter.
John McCallfe96e0b2011-11-06 09:01:30 +0000839 if (!findSetter()) {
840 ExprResult result;
841 if (tryBuildGetOfReference(LHS, result)) {
842 if (result.isInvalid()) return ExprError();
843 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall526ab472011-10-25 17:37:35 +0000844 }
845
846 // Otherwise, it's an error.
John McCallfe96e0b2011-11-06 09:01:30 +0000847 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
848 << unsigned(RefExpr->isImplicitProperty())
849 << SetterSelector
John McCall526ab472011-10-25 17:37:35 +0000850 << LHS->getSourceRange() << RHS->getSourceRange();
851 return ExprError();
852 }
853
854 // If there is a setter, we definitely want to use it.
855
John McCallfe96e0b2011-11-06 09:01:30 +0000856 // Verify that we can do a compound assignment.
857 if (opcode != BO_Assign && !findGetter()) {
858 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall526ab472011-10-25 17:37:35 +0000859 << LHS->getSourceRange() << RHS->getSourceRange();
860 return ExprError();
861 }
862
John McCallfe96e0b2011-11-06 09:01:30 +0000863 ExprResult result =
864 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall526ab472011-10-25 17:37:35 +0000865 if (result.isInvalid()) return ExprError();
866
John McCallfe96e0b2011-11-06 09:01:30 +0000867 // Various warnings about property assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000868 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCallfe96e0b2011-11-06 09:01:30 +0000869 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
870 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
871 }
872
John McCall526ab472011-10-25 17:37:35 +0000873 return result;
874}
John McCallfe96e0b2011-11-06 09:01:30 +0000875
876/// @property-specific behavior for doing increments and decrements.
877ExprResult
878ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
879 UnaryOperatorKind opcode,
880 Expr *op) {
881 // If there's no setter, we have no choice but to try to assign to
882 // the result of the getter.
883 if (!findSetter()) {
884 ExprResult result;
885 if (tryBuildGetOfReference(op, result)) {
886 if (result.isInvalid()) return ExprError();
887 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
888 }
889
890 // Otherwise, it's an error.
891 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
892 << unsigned(RefExpr->isImplicitProperty())
893 << unsigned(UnaryOperator::isDecrementOp(opcode))
894 << SetterSelector
895 << op->getSourceRange();
896 return ExprError();
897 }
898
899 // If there is a setter, we definitely want to use it.
900
901 // We also need a getter.
902 if (!findGetter()) {
903 assert(RefExpr->isImplicitProperty());
904 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
905 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahanianb525b522012-04-18 19:13:23 +0000906 << GetterSelector
John McCallfe96e0b2011-11-06 09:01:30 +0000907 << op->getSourceRange();
908 return ExprError();
909 }
910
911 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
912}
913
Jordan Rosed3934582012-09-28 22:21:30 +0000914ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
915 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
916 DiagnosticsEngine::Level Level =
917 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
918 SyntacticForm->getLocStart());
919 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +0000920 S.recordUseOfEvaluatedWeak(SyntacticRefExpr,
921 SyntacticRefExpr->isMessagingGetter());
Jordan Rosed3934582012-09-28 22:21:30 +0000922 }
923
924 return PseudoOpBuilder::complete(SyntacticForm);
925}
926
Ted Kremeneke65b0862012-03-06 20:05:56 +0000927// ObjCSubscript build stuff.
928//
929
930/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
931/// conversion.
932/// FIXME. Remove this routine if it is proven that no additional
933/// specifity is needed.
934ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
935 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
936 if (result.isInvalid()) return ExprError();
937 return result;
938}
939
940/// objective-c subscripting-specific behavior for doing assignments.
941ExprResult
942ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
943 SourceLocation opcLoc,
944 BinaryOperatorKind opcode,
945 Expr *LHS, Expr *RHS) {
946 assert(BinaryOperator::isAssignmentOp(opcode));
947 // There must be a method to do the Index'ed assignment.
948 if (!findAtIndexSetter())
949 return ExprError();
950
951 // Verify that we can do a compound assignment.
952 if (opcode != BO_Assign && !findAtIndexGetter())
953 return ExprError();
954
955 ExprResult result =
956 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
957 if (result.isInvalid()) return ExprError();
958
959 // Various warnings about objc Index'ed assignments in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000960 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremeneke65b0862012-03-06 20:05:56 +0000961 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
962 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
963 }
964
965 return result;
966}
967
968/// Capture the base object of an Objective-C Index'ed expression.
969Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
970 assert(InstanceBase == 0);
971
972 // Capture base expression in an OVE and rebuild the syntactic
973 // form to use the OVE as its base expression.
974 InstanceBase = capture(RefExpr->getBaseExpr());
975 InstanceKey = capture(RefExpr->getKeyExpr());
976
977 syntacticBase =
978 ObjCSubscriptRefRebuilder(S, InstanceBase,
979 InstanceKey).rebuild(syntacticBase);
980
981 return syntacticBase;
982}
983
984/// CheckSubscriptingKind - This routine decide what type
985/// of indexing represented by "FromE" is being done.
986Sema::ObjCSubscriptKind
987 Sema::CheckSubscriptingKind(Expr *FromE) {
988 // If the expression already has integral or enumeration type, we're golden.
989 QualType T = FromE->getType();
990 if (T->isIntegralOrEnumerationType())
991 return OS_Array;
992
993 // If we don't have a class type in C++, there's no way we can get an
994 // expression of integral or enumeration type.
995 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahanianba0afde2012-03-28 17:56:49 +0000996 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremeneke65b0862012-03-06 20:05:56 +0000997 // All other scalar cases are assumed to be dictionary indexing which
998 // caller handles, with diagnostics if needed.
999 return OS_Dictionary;
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001000 if (!getLangOpts().CPlusPlus ||
1001 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001002 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahanianba0afde2012-03-28 17:56:49 +00001003 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
1004 if (isa<StringLiteral>(IndexExpr))
1005 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
1006 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
1007 else
1008 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1009 << T;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001010 return OS_Error;
1011 }
1012
1013 // We must have a complete class type.
1014 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001015 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremeneke65b0862012-03-06 20:05:56 +00001016 return OS_Error;
1017
1018 // Look for a conversion to an integral, enumeration type, or
1019 // objective-C pointer type.
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001020 std::pair<CXXRecordDecl::conversion_iterator,
1021 CXXRecordDecl::conversion_iterator> Conversions
Ted Kremeneke65b0862012-03-06 20:05:56 +00001022 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
1023
1024 int NoIntegrals=0, NoObjCIdPointers=0;
1025 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
1026
Argyrios Kyrtzidisa6567c42012-11-28 03:56:09 +00001027 for (CXXRecordDecl::conversion_iterator
1028 I = Conversions.first, E = Conversions.second; I != E; ++I) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001029 if (CXXConversionDecl *Conversion
1030 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
1031 QualType CT = Conversion->getConversionType().getNonReferenceType();
1032 if (CT->isIntegralOrEnumerationType()) {
1033 ++NoIntegrals;
1034 ConversionDecls.push_back(Conversion);
1035 }
1036 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
1037 ++NoObjCIdPointers;
1038 ConversionDecls.push_back(Conversion);
1039 }
1040 }
1041 }
1042 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
1043 return OS_Array;
1044 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
1045 return OS_Dictionary;
1046 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
1047 // No conversion function was found. Issue diagnostic and return.
1048 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
1049 << FromE->getType();
1050 return OS_Error;
1051 }
1052 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
1053 << FromE->getType();
1054 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
1055 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
1056
1057 return OS_Error;
1058}
1059
Fariborz Jahanian90804912012-08-02 18:03:58 +00001060/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
1061/// objects used as dictionary subscript key objects.
1062static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
1063 Expr *Key) {
1064 if (ContainerT.isNull())
1065 return;
1066 // dictionary subscripting.
1067 // - (id)objectForKeyedSubscript:(id)key;
1068 IdentifierInfo *KeyIdents[] = {
1069 &S.Context.Idents.get("objectForKeyedSubscript")
1070 };
1071 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1072 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1073 true /*instance*/);
1074 if (!Getter)
1075 return;
1076 QualType T = Getter->param_begin()[0]->getType();
1077 S.CheckObjCARCConversion(Key->getSourceRange(),
1078 T, Key, Sema::CCK_ImplicitConversion);
1079}
1080
Ted Kremeneke65b0862012-03-06 20:05:56 +00001081bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1082 if (AtIndexGetter)
1083 return true;
1084
1085 Expr *BaseExpr = RefExpr->getBaseExpr();
1086 QualType BaseT = BaseExpr->getType();
1087
1088 QualType ResultType;
1089 if (const ObjCObjectPointerType *PTy =
1090 BaseT->getAs<ObjCObjectPointerType>()) {
1091 ResultType = PTy->getPointeeType();
1092 if (const ObjCObjectType *iQFaceTy =
1093 ResultType->getAsObjCQualifiedInterfaceType())
1094 ResultType = iQFaceTy->getBaseType();
1095 }
1096 Sema::ObjCSubscriptKind Res =
1097 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001098 if (Res == Sema::OS_Error) {
1099 if (S.getLangOpts().ObjCAutoRefCount)
1100 CheckKeyForObjCARCConversion(S, ResultType,
1101 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001102 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001103 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001104 bool arrayRef = (Res == Sema::OS_Array);
1105
1106 if (ResultType.isNull()) {
1107 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1108 << BaseExpr->getType() << arrayRef;
1109 return false;
1110 }
1111 if (!arrayRef) {
1112 // dictionary subscripting.
1113 // - (id)objectForKeyedSubscript:(id)key;
1114 IdentifierInfo *KeyIdents[] = {
1115 &S.Context.Idents.get("objectForKeyedSubscript")
1116 };
1117 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1118 }
1119 else {
1120 // - (id)objectAtIndexedSubscript:(size_t)index;
1121 IdentifierInfo *KeyIdents[] = {
1122 &S.Context.Idents.get("objectAtIndexedSubscript")
1123 };
1124
1125 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1126 }
1127
1128 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1129 true /*instance*/);
1130 bool receiverIdType = (BaseT->isObjCIdType() ||
1131 BaseT->isObjCQualifiedIdType());
1132
David Blaikiebbafb8a2012-03-11 07:00:24 +00001133 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001134 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1135 SourceLocation(), AtIndexGetterSelector,
1136 S.Context.getObjCIdType() /*ReturnType*/,
1137 0 /*TypeSourceInfo */,
1138 S.Context.getTranslationUnitDecl(),
1139 true /*Instance*/, false/*isVariadic*/,
Jordan Rosed01e83a2012-10-10 16:42:25 +00001140 /*isPropertyAccessor=*/false,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001141 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1142 ObjCMethodDecl::Required,
1143 false);
1144 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1145 SourceLocation(), SourceLocation(),
1146 arrayRef ? &S.Context.Idents.get("index")
1147 : &S.Context.Idents.get("key"),
1148 arrayRef ? S.Context.UnsignedLongTy
1149 : S.Context.getObjCIdType(),
1150 /*TInfo=*/0,
1151 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001152 0);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001153 AtIndexGetter->setMethodParams(S.Context, Argument, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001154 }
1155
1156 if (!AtIndexGetter) {
1157 if (!receiverIdType) {
1158 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1159 << BaseExpr->getType() << 0 << arrayRef;
1160 return false;
1161 }
1162 AtIndexGetter =
1163 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1164 RefExpr->getSourceRange(),
1165 true, false);
1166 }
1167
1168 if (AtIndexGetter) {
1169 QualType T = AtIndexGetter->param_begin()[0]->getType();
1170 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1171 (!arrayRef && !T->isObjCObjectPointerType())) {
1172 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1173 arrayRef ? diag::err_objc_subscript_index_type
1174 : diag::err_objc_subscript_key_type) << T;
1175 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1176 diag::note_parameter_type) << T;
1177 return false;
1178 }
Alp Toker314cc812014-01-25 16:55:45 +00001179 QualType R = AtIndexGetter->getReturnType();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001180 if (!R->isObjCObjectPointerType()) {
1181 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1182 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1183 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1184 AtIndexGetter->getDeclName();
1185 }
1186 }
1187 return true;
1188}
1189
1190bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1191 if (AtIndexSetter)
1192 return true;
1193
1194 Expr *BaseExpr = RefExpr->getBaseExpr();
1195 QualType BaseT = BaseExpr->getType();
1196
1197 QualType ResultType;
1198 if (const ObjCObjectPointerType *PTy =
1199 BaseT->getAs<ObjCObjectPointerType>()) {
1200 ResultType = PTy->getPointeeType();
1201 if (const ObjCObjectType *iQFaceTy =
1202 ResultType->getAsObjCQualifiedInterfaceType())
1203 ResultType = iQFaceTy->getBaseType();
1204 }
1205
1206 Sema::ObjCSubscriptKind Res =
1207 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahanian90804912012-08-02 18:03:58 +00001208 if (Res == Sema::OS_Error) {
1209 if (S.getLangOpts().ObjCAutoRefCount)
1210 CheckKeyForObjCARCConversion(S, ResultType,
1211 RefExpr->getKeyExpr());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001212 return false;
Fariborz Jahanian90804912012-08-02 18:03:58 +00001213 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001214 bool arrayRef = (Res == Sema::OS_Array);
1215
1216 if (ResultType.isNull()) {
1217 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1218 << BaseExpr->getType() << arrayRef;
1219 return false;
1220 }
1221
1222 if (!arrayRef) {
1223 // dictionary subscripting.
1224 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1225 IdentifierInfo *KeyIdents[] = {
1226 &S.Context.Idents.get("setObject"),
1227 &S.Context.Idents.get("forKeyedSubscript")
1228 };
1229 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1230 }
1231 else {
1232 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1233 IdentifierInfo *KeyIdents[] = {
1234 &S.Context.Idents.get("setObject"),
1235 &S.Context.Idents.get("atIndexedSubscript")
1236 };
1237 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1238 }
1239 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1240 true /*instance*/);
1241
1242 bool receiverIdType = (BaseT->isObjCIdType() ||
1243 BaseT->isObjCQualifiedIdType());
1244
David Blaikiebbafb8a2012-03-11 07:00:24 +00001245 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Alp Toker314cc812014-01-25 16:55:45 +00001246 TypeSourceInfo *ReturnTInfo = 0;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001247 QualType ReturnType = S.Context.VoidTy;
Alp Toker314cc812014-01-25 16:55:45 +00001248 AtIndexSetter = ObjCMethodDecl::Create(
1249 S.Context, SourceLocation(), SourceLocation(), AtIndexSetterSelector,
1250 ReturnType, ReturnTInfo, S.Context.getTranslationUnitDecl(),
1251 true /*Instance*/, false /*isVariadic*/,
1252 /*isPropertyAccessor=*/false,
1253 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1254 ObjCMethodDecl::Required, false);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001255 SmallVector<ParmVarDecl *, 2> Params;
1256 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1257 SourceLocation(), SourceLocation(),
1258 &S.Context.Idents.get("object"),
1259 S.Context.getObjCIdType(),
1260 /*TInfo=*/0,
1261 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001262 0);
1263 Params.push_back(object);
1264 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1265 SourceLocation(), SourceLocation(),
1266 arrayRef ? &S.Context.Idents.get("index")
1267 : &S.Context.Idents.get("key"),
1268 arrayRef ? S.Context.UnsignedLongTy
1269 : S.Context.getObjCIdType(),
1270 /*TInfo=*/0,
1271 SC_None,
Ted Kremeneke65b0862012-03-06 20:05:56 +00001272 0);
1273 Params.push_back(key);
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001274 AtIndexSetter->setMethodParams(S.Context, Params, None);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001275 }
1276
1277 if (!AtIndexSetter) {
1278 if (!receiverIdType) {
1279 S.Diag(BaseExpr->getExprLoc(),
1280 diag::err_objc_subscript_method_not_found)
1281 << BaseExpr->getType() << 1 << arrayRef;
1282 return false;
1283 }
1284 AtIndexSetter =
1285 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1286 RefExpr->getSourceRange(),
1287 true, false);
1288 }
1289
1290 bool err = false;
1291 if (AtIndexSetter && arrayRef) {
1292 QualType T = AtIndexSetter->param_begin()[1]->getType();
1293 if (!T->isIntegralOrEnumerationType()) {
1294 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1295 diag::err_objc_subscript_index_type) << T;
1296 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1297 diag::note_parameter_type) << T;
1298 err = true;
1299 }
1300 T = AtIndexSetter->param_begin()[0]->getType();
1301 if (!T->isObjCObjectPointerType()) {
1302 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1303 diag::err_objc_subscript_object_type) << T << arrayRef;
1304 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1305 diag::note_parameter_type) << T;
1306 err = true;
1307 }
1308 }
1309 else if (AtIndexSetter && !arrayRef)
1310 for (unsigned i=0; i <2; i++) {
1311 QualType T = AtIndexSetter->param_begin()[i]->getType();
1312 if (!T->isObjCObjectPointerType()) {
1313 if (i == 1)
1314 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1315 diag::err_objc_subscript_key_type) << T;
1316 else
1317 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1318 diag::err_objc_subscript_dic_object_type) << T;
1319 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1320 diag::note_parameter_type) << T;
1321 err = true;
1322 }
1323 }
1324
1325 return !err;
1326}
1327
1328// Get the object at "Index" position in the container.
1329// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1330ExprResult ObjCSubscriptOpBuilder::buildGet() {
1331 if (!findAtIndexGetter())
1332 return ExprError();
1333
1334 QualType receiverType = InstanceBase->getType();
1335
1336 // Build a message-send.
1337 ExprResult msg;
1338 Expr *Index = InstanceKey;
1339
1340 // Arguments.
1341 Expr *args[] = { Index };
1342 assert(InstanceBase);
1343 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1344 GenericLoc,
1345 AtIndexGetterSelector, AtIndexGetter,
1346 MultiExprArg(args, 1));
1347 return msg;
1348}
1349
1350/// Store into the container the "op" object at "Index"'ed location
1351/// by building this messaging expression:
1352/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenkoadba9be2012-08-23 17:58:28 +00001353/// \param captureSetValueAsResult If true, capture the actual
Ted Kremeneke65b0862012-03-06 20:05:56 +00001354/// value being set as the value of the property operation.
1355ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1356 bool captureSetValueAsResult) {
1357 if (!findAtIndexSetter())
1358 return ExprError();
1359
1360 QualType receiverType = InstanceBase->getType();
1361 Expr *Index = InstanceKey;
1362
1363 // Arguments.
1364 Expr *args[] = { op, Index };
1365
1366 // Build a message-send.
1367 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1368 GenericLoc,
1369 AtIndexSetterSelector,
1370 AtIndexSetter,
1371 MultiExprArg(args, 2));
1372
1373 if (!msg.isInvalid() && captureSetValueAsResult) {
1374 ObjCMessageExpr *msgExpr =
1375 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1376 Expr *arg = msgExpr->getArg(0);
Fariborz Jahanian15dde892014-03-06 00:34:05 +00001377 if (CanCaptureValue(arg))
Eli Friedman00fa4292012-11-13 23:16:33 +00001378 msgExpr->setArg(0, captureValueAsResult(arg));
Ted Kremeneke65b0862012-03-06 20:05:56 +00001379 }
1380
1381 return msg;
1382}
1383
John McCallfe96e0b2011-11-06 09:01:30 +00001384//===----------------------------------------------------------------------===//
John McCall5e77d762013-04-16 07:28:30 +00001385// MSVC __declspec(property) references
1386//===----------------------------------------------------------------------===//
1387
1388Expr *MSPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
1389 Expr *NewBase = capture(RefExpr->getBaseExpr());
1390
1391 syntacticBase =
1392 MSPropertyRefRebuilder(S, NewBase).rebuild(syntacticBase);
1393
1394 return syntacticBase;
1395}
1396
1397ExprResult MSPropertyOpBuilder::buildGet() {
1398 if (!RefExpr->getPropertyDecl()->hasGetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001399 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001400 << 0 /* getter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001401 return ExprError();
1402 }
1403
1404 UnqualifiedId GetterName;
1405 IdentifierInfo *II = RefExpr->getPropertyDecl()->getGetterId();
1406 GetterName.setIdentifier(II, RefExpr->getMemberLoc());
1407 CXXScopeSpec SS;
1408 SS.Adopt(RefExpr->getQualifierLoc());
1409 ExprResult GetterExpr = S.ActOnMemberAccessExpr(
1410 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1411 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1412 GetterName, 0, true);
1413 if (GetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001414 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001415 diag::error_cannot_find_suitable_accessor) << 0 /* getter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001416 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001417 return ExprError();
1418 }
1419
1420 MultiExprArg ArgExprs;
1421 return S.ActOnCallExpr(S.getCurScope(), GetterExpr.take(),
1422 RefExpr->getSourceRange().getBegin(), ArgExprs,
1423 RefExpr->getSourceRange().getEnd());
1424}
1425
1426ExprResult MSPropertyOpBuilder::buildSet(Expr *op, SourceLocation sl,
1427 bool captureSetValueAsResult) {
1428 if (!RefExpr->getPropertyDecl()->hasSetter()) {
Aaron Ballman213cf412013-12-26 16:35:04 +00001429 S.Diag(RefExpr->getMemberLoc(), diag::err_no_accessor_for_property)
Aaron Ballman1bda4592014-01-03 01:09:27 +00001430 << 1 /* setter */ << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001431 return ExprError();
1432 }
1433
1434 UnqualifiedId SetterName;
1435 IdentifierInfo *II = RefExpr->getPropertyDecl()->getSetterId();
1436 SetterName.setIdentifier(II, RefExpr->getMemberLoc());
1437 CXXScopeSpec SS;
1438 SS.Adopt(RefExpr->getQualifierLoc());
1439 ExprResult SetterExpr = S.ActOnMemberAccessExpr(
1440 S.getCurScope(), RefExpr->getBaseExpr(), SourceLocation(),
1441 RefExpr->isArrow() ? tok::arrow : tok::period, SS, SourceLocation(),
1442 SetterName, 0, true);
1443 if (SetterExpr.isInvalid()) {
Aaron Ballman9e35bfe2013-12-26 15:46:38 +00001444 S.Diag(RefExpr->getMemberLoc(),
Aaron Ballman213cf412013-12-26 16:35:04 +00001445 diag::error_cannot_find_suitable_accessor) << 1 /* setter */
Aaron Ballman1bda4592014-01-03 01:09:27 +00001446 << RefExpr->getPropertyDecl();
John McCall5e77d762013-04-16 07:28:30 +00001447 return ExprError();
1448 }
1449
1450 SmallVector<Expr*, 1> ArgExprs;
1451 ArgExprs.push_back(op);
1452 return S.ActOnCallExpr(S.getCurScope(), SetterExpr.take(),
1453 RefExpr->getSourceRange().getBegin(), ArgExprs,
1454 op->getSourceRange().getEnd());
1455}
1456
1457//===----------------------------------------------------------------------===//
John McCallfe96e0b2011-11-06 09:01:30 +00001458// General Sema routines.
1459//===----------------------------------------------------------------------===//
1460
1461ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1462 Expr *opaqueRef = E->IgnoreParens();
1463 if (ObjCPropertyRefExpr *refExpr
1464 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1465 ObjCPropertyOpBuilder builder(*this, refExpr);
1466 return builder.buildRValueOperation(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001467 }
1468 else if (ObjCSubscriptRefExpr *refExpr
1469 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1470 ObjCSubscriptOpBuilder builder(*this, refExpr);
1471 return builder.buildRValueOperation(E);
John McCall5e77d762013-04-16 07:28:30 +00001472 } else if (MSPropertyRefExpr *refExpr
1473 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1474 MSPropertyOpBuilder builder(*this, refExpr);
1475 return builder.buildRValueOperation(E);
John McCallfe96e0b2011-11-06 09:01:30 +00001476 } else {
1477 llvm_unreachable("unknown pseudo-object kind!");
1478 }
1479}
1480
1481/// Check an increment or decrement of a pseudo-object expression.
1482ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1483 UnaryOperatorKind opcode, Expr *op) {
1484 // Do nothing if the operand is dependent.
1485 if (op->isTypeDependent())
1486 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1487 VK_RValue, OK_Ordinary, opcLoc);
1488
1489 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1490 Expr *opaqueRef = op->IgnoreParens();
1491 if (ObjCPropertyRefExpr *refExpr
1492 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1493 ObjCPropertyOpBuilder builder(*this, refExpr);
1494 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001495 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1496 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1497 return ExprError();
John McCall5e77d762013-04-16 07:28:30 +00001498 } else if (MSPropertyRefExpr *refExpr
1499 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1500 MSPropertyOpBuilder builder(*this, refExpr);
1501 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
John McCallfe96e0b2011-11-06 09:01:30 +00001502 } else {
1503 llvm_unreachable("unknown pseudo-object kind!");
1504 }
1505}
1506
1507ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1508 BinaryOperatorKind opcode,
1509 Expr *LHS, Expr *RHS) {
1510 // Do nothing if either argument is dependent.
1511 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1512 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
Lang Hames5de91cc2012-10-02 04:45:10 +00001513 VK_RValue, OK_Ordinary, opcLoc, false);
John McCallfe96e0b2011-11-06 09:01:30 +00001514
1515 // Filter out non-overload placeholder types in the RHS.
John McCalld5c98ae2011-11-15 01:35:18 +00001516 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1517 ExprResult result = CheckPlaceholderExpr(RHS);
1518 if (result.isInvalid()) return ExprError();
1519 RHS = result.take();
John McCallfe96e0b2011-11-06 09:01:30 +00001520 }
1521
1522 Expr *opaqueRef = LHS->IgnoreParens();
1523 if (ObjCPropertyRefExpr *refExpr
1524 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1525 ObjCPropertyOpBuilder builder(*this, refExpr);
1526 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001527 } else if (ObjCSubscriptRefExpr *refExpr
1528 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1529 ObjCSubscriptOpBuilder builder(*this, refExpr);
1530 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall5e77d762013-04-16 07:28:30 +00001531 } else if (MSPropertyRefExpr *refExpr
1532 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1533 MSPropertyOpBuilder builder(*this, refExpr);
1534 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCallfe96e0b2011-11-06 09:01:30 +00001535 } else {
1536 llvm_unreachable("unknown pseudo-object kind!");
1537 }
1538}
John McCalle9290822011-11-30 04:42:31 +00001539
1540/// Given a pseudo-object reference, rebuild it without the opaque
1541/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1542/// This should never operate in-place.
1543static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1544 Expr *opaqueRef = E->IgnoreParens();
1545 if (ObjCPropertyRefExpr *refExpr
1546 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregoraa0df2d2012-04-13 16:05:42 +00001547 // Class and super property references don't have opaque values in them.
1548 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1549 return E;
1550
1551 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1552 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1553 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001554 } else if (ObjCSubscriptRefExpr *refExpr
1555 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1556 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1557 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1558 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1559 keyOVE->getSourceExpr()).rebuild(E);
John McCall5e77d762013-04-16 07:28:30 +00001560 } else if (MSPropertyRefExpr *refExpr
1561 = dyn_cast<MSPropertyRefExpr>(opaqueRef)) {
1562 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1563 return MSPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
John McCalle9290822011-11-30 04:42:31 +00001564 } else {
1565 llvm_unreachable("unknown pseudo-object kind!");
1566 }
1567}
1568
1569/// Given a pseudo-object expression, recreate what it looks like
1570/// syntactically without the attendant OpaqueValueExprs.
1571///
1572/// This is a hack which should be removed when TreeTransform is
1573/// capable of rebuilding a tree without stripping implicit
1574/// operations.
1575Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1576 Expr *syntax = E->getSyntacticForm();
1577 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1578 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1579 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1580 uop->getValueKind(), uop->getObjectKind(),
1581 uop->getOperatorLoc());
1582 } else if (CompoundAssignOperator *cop
1583 = dyn_cast<CompoundAssignOperator>(syntax)) {
1584 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1585 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1586 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1587 cop->getType(),
1588 cop->getValueKind(),
1589 cop->getObjectKind(),
1590 cop->getComputationLHSType(),
1591 cop->getComputationResultType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001592 cop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001593 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1594 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1595 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1596 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1597 bop->getType(), bop->getValueKind(),
1598 bop->getObjectKind(),
Lang Hames5de91cc2012-10-02 04:45:10 +00001599 bop->getOperatorLoc(), false);
John McCalle9290822011-11-30 04:42:31 +00001600 } else {
1601 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1602 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1603 }
1604}