blob: 5e44c9bb8b0d2657aae03fb5cf31074f2843f491 [file] [log] [blame]
John McCall3c3b7f92011-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"
34#include "clang/Sema/Initialization.h"
35#include "clang/AST/ExprObjC.h"
36#include "clang/Lex/Preprocessor.h"
37
38using namespace clang;
39using namespace sema;
40
John McCall4b9c2d22011-11-06 09:01:30 +000041namespace {
42 // Basically just a very focused copy of TreeTransform.
43 template <class T> struct Rebuilder {
44 Sema &S;
45 Rebuilder(Sema &S) : S(S) {}
46
47 T &getDerived() { return static_cast<T&>(*this); }
48
49 Expr *rebuild(Expr *e) {
50 // Fast path: nothing to look through.
51 if (typename T::specific_type *specific
52 = dyn_cast<typename T::specific_type>(e))
53 return getDerived().rebuildSpecific(specific);
54
55 // Otherwise, we should look through and rebuild anything that
56 // IgnoreParens would.
57
58 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
59 e = rebuild(parens->getSubExpr());
60 return new (S.Context) ParenExpr(parens->getLParen(),
61 parens->getRParen(),
62 e);
63 }
64
65 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
66 assert(uop->getOpcode() == UO_Extension);
67 e = rebuild(uop->getSubExpr());
68 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
69 uop->getType(),
70 uop->getValueKind(),
71 uop->getObjectKind(),
72 uop->getOperatorLoc());
73 }
74
75 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
76 assert(!gse->isResultDependent());
77 unsigned resultIndex = gse->getResultIndex();
78 unsigned numAssocs = gse->getNumAssocs();
79
80 SmallVector<Expr*, 8> assocs(numAssocs);
81 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
82
83 for (unsigned i = 0; i != numAssocs; ++i) {
84 Expr *assoc = gse->getAssocExpr(i);
85 if (i == resultIndex) assoc = rebuild(assoc);
86 assocs[i] = assoc;
87 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
88 }
89
90 return new (S.Context) GenericSelectionExpr(S.Context,
91 gse->getGenericLoc(),
92 gse->getControllingExpr(),
93 assocTypes.data(),
94 assocs.data(),
95 numAssocs,
96 gse->getDefaultLoc(),
97 gse->getRParenLoc(),
98 gse->containsUnexpandedParameterPack(),
99 resultIndex);
100 }
101
102 llvm_unreachable("bad expression to rebuild!");
103 }
104 };
105
106 struct ObjCPropertyRefRebuilder : Rebuilder<ObjCPropertyRefRebuilder> {
107 Expr *NewBase;
108 ObjCPropertyRefRebuilder(Sema &S, Expr *newBase)
Benjamin Krameracf9e822011-11-06 09:50:13 +0000109 : Rebuilder<ObjCPropertyRefRebuilder>(S), NewBase(newBase) {}
John McCall4b9c2d22011-11-06 09:01:30 +0000110
111 typedef ObjCPropertyRefExpr specific_type;
112 Expr *rebuildSpecific(ObjCPropertyRefExpr *refExpr) {
113 // Fortunately, the constraint that we're rebuilding something
114 // with a base limits the number of cases here.
115 assert(refExpr->getBase());
116
117 if (refExpr->isExplicitProperty()) {
118 return new (S.Context)
119 ObjCPropertyRefExpr(refExpr->getExplicitProperty(),
120 refExpr->getType(), refExpr->getValueKind(),
121 refExpr->getObjectKind(), refExpr->getLocation(),
122 NewBase);
123 }
124 return new (S.Context)
125 ObjCPropertyRefExpr(refExpr->getImplicitPropertyGetter(),
126 refExpr->getImplicitPropertySetter(),
127 refExpr->getType(), refExpr->getValueKind(),
128 refExpr->getObjectKind(),refExpr->getLocation(),
129 NewBase);
130 }
131 };
132
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000133 struct ObjCSubscriptRefRebuilder : Rebuilder<ObjCSubscriptRefRebuilder> {
134 Expr *NewBase;
135 Expr *NewKeyExpr;
136 ObjCSubscriptRefRebuilder(Sema &S, Expr *newBase, Expr *newKeyExpr)
137 : Rebuilder<ObjCSubscriptRefRebuilder>(S),
138 NewBase(newBase), NewKeyExpr(newKeyExpr) {}
139
140 typedef ObjCSubscriptRefExpr specific_type;
141 Expr *rebuildSpecific(ObjCSubscriptRefExpr *refExpr) {
142 assert(refExpr->getBaseExpr());
143 assert(refExpr->getKeyExpr());
144
145 return new (S.Context)
146 ObjCSubscriptRefExpr(NewBase,
147 NewKeyExpr,
148 refExpr->getType(), refExpr->getValueKind(),
149 refExpr->getObjectKind(),refExpr->getAtIndexMethodDecl(),
150 refExpr->setAtIndexMethodDecl(),
151 refExpr->getRBracket());
152 }
153 };
154
John McCall4b9c2d22011-11-06 09:01:30 +0000155 class PseudoOpBuilder {
156 public:
157 Sema &S;
158 unsigned ResultIndex;
159 SourceLocation GenericLoc;
160 SmallVector<Expr *, 4> Semantics;
161
162 PseudoOpBuilder(Sema &S, SourceLocation genericLoc)
163 : S(S), ResultIndex(PseudoObjectExpr::NoResult),
164 GenericLoc(genericLoc) {}
165
Matt Beaumont-Gay1aa17212011-11-08 01:53:17 +0000166 virtual ~PseudoOpBuilder() {}
167
John McCall4b9c2d22011-11-06 09:01:30 +0000168 /// Add a normal semantic expression.
169 void addSemanticExpr(Expr *semantic) {
170 Semantics.push_back(semantic);
171 }
172
173 /// Add the 'result' semantic expression.
174 void addResultSemanticExpr(Expr *resultExpr) {
175 assert(ResultIndex == PseudoObjectExpr::NoResult);
176 ResultIndex = Semantics.size();
177 Semantics.push_back(resultExpr);
178 }
179
180 ExprResult buildRValueOperation(Expr *op);
181 ExprResult buildAssignmentOperation(Scope *Sc,
182 SourceLocation opLoc,
183 BinaryOperatorKind opcode,
184 Expr *LHS, Expr *RHS);
185 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
186 UnaryOperatorKind opcode,
187 Expr *op);
188
189 ExprResult complete(Expr *syntacticForm);
190
191 OpaqueValueExpr *capture(Expr *op);
192 OpaqueValueExpr *captureValueAsResult(Expr *op);
193
194 void setResultToLastSemantic() {
195 assert(ResultIndex == PseudoObjectExpr::NoResult);
196 ResultIndex = Semantics.size() - 1;
197 }
198
199 /// Return true if assignments have a non-void result.
200 virtual bool assignmentsHaveResult() { return true; }
201
202 virtual Expr *rebuildAndCaptureObject(Expr *) = 0;
203 virtual ExprResult buildGet() = 0;
204 virtual ExprResult buildSet(Expr *, SourceLocation,
205 bool captureSetValueAsResult) = 0;
206 };
207
208 /// A PseudoOpBuilder for Objective-C @properties.
209 class ObjCPropertyOpBuilder : public PseudoOpBuilder {
210 ObjCPropertyRefExpr *RefExpr;
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000211 ObjCPropertyRefExpr *SyntacticRefExpr;
John McCall4b9c2d22011-11-06 09:01:30 +0000212 OpaqueValueExpr *InstanceReceiver;
213 ObjCMethodDecl *Getter;
214
215 ObjCMethodDecl *Setter;
216 Selector SetterSelector;
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000217 Selector GetterSelector;
John McCall4b9c2d22011-11-06 09:01:30 +0000218
219 public:
220 ObjCPropertyOpBuilder(Sema &S, ObjCPropertyRefExpr *refExpr) :
221 PseudoOpBuilder(S, refExpr->getLocation()), RefExpr(refExpr),
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000222 SyntacticRefExpr(0), InstanceReceiver(0), Getter(0), Setter(0) {
John McCall4b9c2d22011-11-06 09:01:30 +0000223 }
224
225 ExprResult buildRValueOperation(Expr *op);
226 ExprResult buildAssignmentOperation(Scope *Sc,
227 SourceLocation opLoc,
228 BinaryOperatorKind opcode,
229 Expr *LHS, Expr *RHS);
230 ExprResult buildIncDecOperation(Scope *Sc, SourceLocation opLoc,
231 UnaryOperatorKind opcode,
232 Expr *op);
233
234 bool tryBuildGetOfReference(Expr *op, ExprResult &result);
235 bool findSetter();
236 bool findGetter();
237
238 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
239 ExprResult buildGet();
240 ExprResult buildSet(Expr *op, SourceLocation, bool);
241 };
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000242
243 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
244 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
245 ObjCSubscriptRefExpr *RefExpr;
246 OpaqueValueExpr *InstanceBase;
247 OpaqueValueExpr *InstanceKey;
248 ObjCMethodDecl *AtIndexGetter;
249 Selector AtIndexGetterSelector;
250
251 ObjCMethodDecl *AtIndexSetter;
252 Selector AtIndexSetterSelector;
253
254 public:
255 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
256 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
257 RefExpr(refExpr),
258 InstanceBase(0), InstanceKey(0),
259 AtIndexGetter(0), AtIndexSetter(0) { }
260
261 ExprResult buildRValueOperation(Expr *op);
262 ExprResult buildAssignmentOperation(Scope *Sc,
263 SourceLocation opLoc,
264 BinaryOperatorKind opcode,
265 Expr *LHS, Expr *RHS);
266 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
267
268 bool findAtIndexGetter();
269 bool findAtIndexSetter();
270
271 ExprResult buildGet();
272 ExprResult buildSet(Expr *op, SourceLocation, bool);
273 };
274
John McCall4b9c2d22011-11-06 09:01:30 +0000275}
276
277/// Capture the given expression in an OpaqueValueExpr.
278OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
279 // Make a new OVE whose source is the given expression.
280 OpaqueValueExpr *captured =
281 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor97df54e2012-02-23 22:17:26 +0000282 e->getValueKind(), e->getObjectKind(),
283 e);
John McCall4b9c2d22011-11-06 09:01:30 +0000284
285 // Make sure we bind that in the semantics.
286 addSemanticExpr(captured);
287 return captured;
288}
289
290/// Capture the given expression as the result of this pseudo-object
291/// operation. This routine is safe against expressions which may
292/// already be captured.
293///
294/// \param Returns the captured expression, which will be the
295/// same as the input if the input was already captured
296OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
297 assert(ResultIndex == PseudoObjectExpr::NoResult);
298
299 // If the expression hasn't already been captured, just capture it
300 // and set the new semantic
301 if (!isa<OpaqueValueExpr>(e)) {
302 OpaqueValueExpr *cap = capture(e);
303 setResultToLastSemantic();
304 return cap;
305 }
306
307 // Otherwise, it must already be one of our semantic expressions;
308 // set ResultIndex to its index.
309 unsigned index = 0;
310 for (;; ++index) {
311 assert(index < Semantics.size() &&
312 "captured expression not found in semantics!");
313 if (e == Semantics[index]) break;
314 }
315 ResultIndex = index;
316 return cast<OpaqueValueExpr>(e);
317}
318
319/// The routine which creates the final PseudoObjectExpr.
320ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
321 return PseudoObjectExpr::Create(S.Context, syntactic,
322 Semantics, ResultIndex);
323}
324
325/// The main skeleton for building an r-value operation.
326ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
327 Expr *syntacticBase = rebuildAndCaptureObject(op);
328
329 ExprResult getExpr = buildGet();
330 if (getExpr.isInvalid()) return ExprError();
331 addResultSemanticExpr(getExpr.take());
332
333 return complete(syntacticBase);
334}
335
336/// The basic skeleton for building a simple or compound
337/// assignment operation.
338ExprResult
339PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
340 BinaryOperatorKind opcode,
341 Expr *LHS, Expr *RHS) {
342 assert(BinaryOperator::isAssignmentOp(opcode));
343
344 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
345 OpaqueValueExpr *capturedRHS = capture(RHS);
346
347 Expr *syntactic;
348
349 ExprResult result;
350 if (opcode == BO_Assign) {
351 result = capturedRHS;
352 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
353 opcode, capturedRHS->getType(),
354 capturedRHS->getValueKind(),
355 OK_Ordinary, opcLoc);
356 } else {
357 ExprResult opLHS = buildGet();
358 if (opLHS.isInvalid()) return ExprError();
359
360 // Build an ordinary, non-compound operation.
361 BinaryOperatorKind nonCompound =
362 BinaryOperator::getOpForCompoundAssignment(opcode);
363 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
364 opLHS.take(), capturedRHS);
365 if (result.isInvalid()) return ExprError();
366
367 syntactic =
368 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
369 result.get()->getType(),
370 result.get()->getValueKind(),
371 OK_Ordinary,
372 opLHS.get()->getType(),
373 result.get()->getType(),
374 opcLoc);
375 }
376
377 // The result of the assignment, if not void, is the value set into
378 // the l-value.
379 result = buildSet(result.take(), opcLoc, assignmentsHaveResult());
380 if (result.isInvalid()) return ExprError();
381 addSemanticExpr(result.take());
382
383 return complete(syntactic);
384}
385
386/// The basic skeleton for building an increment or decrement
387/// operation.
388ExprResult
389PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
390 UnaryOperatorKind opcode,
391 Expr *op) {
392 assert(UnaryOperator::isIncrementDecrementOp(opcode));
393
394 Expr *syntacticOp = rebuildAndCaptureObject(op);
395
396 // Load the value.
397 ExprResult result = buildGet();
398 if (result.isInvalid()) return ExprError();
399
400 QualType resultType = result.get()->getType();
401
402 // That's the postfix result.
403 if (UnaryOperator::isPostfix(opcode) && assignmentsHaveResult()) {
404 result = capture(result.take());
405 setResultToLastSemantic();
406 }
407
408 // Add or subtract a literal 1.
409 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
410 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
411 GenericLoc);
412
413 if (UnaryOperator::isIncrementOp(opcode)) {
414 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
415 } else {
416 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
417 }
418 if (result.isInvalid()) return ExprError();
419
420 // Store that back into the result. The value stored is the result
421 // of a prefix operation.
422 result = buildSet(result.take(), opcLoc,
423 UnaryOperator::isPrefix(opcode) && assignmentsHaveResult());
424 if (result.isInvalid()) return ExprError();
425 addSemanticExpr(result.take());
426
427 UnaryOperator *syntactic =
428 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
429 VK_LValue, OK_Ordinary, opcLoc);
430 return complete(syntactic);
431}
432
433
434//===----------------------------------------------------------------------===//
435// Objective-C @property and implicit property references
436//===----------------------------------------------------------------------===//
437
438/// Look up a method in the receiver type of an Objective-C property
439/// reference.
John McCall3c3b7f92011-10-25 17:37:35 +0000440static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
441 const ObjCPropertyRefExpr *PRE) {
John McCall3c3b7f92011-10-25 17:37:35 +0000442 if (PRE->isObjectReceiver()) {
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000443 const ObjCObjectPointerType *PT =
444 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +0000445
446 // Special case for 'self' in class method implementations.
447 if (PT->isObjCClassType() &&
448 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
449 // This cast is safe because isSelfExpr is only true within
450 // methods.
451 ObjCMethodDecl *method =
452 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
453 return S.LookupMethodInObjectType(sel,
454 S.Context.getObjCInterfaceType(method->getClassInterface()),
455 /*instance*/ false);
456 }
457
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000458 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall3c3b7f92011-10-25 17:37:35 +0000459 }
460
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000461 if (PRE->isSuperReceiver()) {
462 if (const ObjCObjectPointerType *PT =
463 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
464 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
465
466 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
467 }
468
469 assert(PRE->isClassReceiver() && "Invalid expression");
470 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
471 return S.LookupMethodInObjectType(sel, IT, false);
John McCall3c3b7f92011-10-25 17:37:35 +0000472}
473
John McCall4b9c2d22011-11-06 09:01:30 +0000474bool ObjCPropertyOpBuilder::findGetter() {
475 if (Getter) return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000476
John McCalldc4df512011-11-07 22:49:50 +0000477 // For implicit properties, just trust the lookup we already did.
478 if (RefExpr->isImplicitProperty()) {
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000479 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
480 GetterSelector = Getter->getSelector();
481 return true;
482 }
483 else {
484 // Must build the getter selector the hard way.
485 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
486 assert(setter && "both setter and getter are null - cannot happen");
487 IdentifierInfo *setterName =
488 setter->getSelector().getIdentifierInfoForSlot(0);
489 const char *compStr = setterName->getNameStart();
490 compStr += 3;
491 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
492 GetterSelector =
493 S.PP.getSelectorTable().getNullarySelector(getterName);
494 return false;
495
496 }
John McCalldc4df512011-11-07 22:49:50 +0000497 }
498
499 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
500 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
John McCall4b9c2d22011-11-06 09:01:30 +0000501 return (Getter != 0);
502}
503
504/// Try to find the most accurate setter declaration for the property
505/// reference.
506///
507/// \return true if a setter was found, in which case Setter
508bool ObjCPropertyOpBuilder::findSetter() {
509 // For implicit properties, just trust the lookup we already did.
510 if (RefExpr->isImplicitProperty()) {
511 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
512 Setter = setter;
513 SetterSelector = setter->getSelector();
514 return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000515 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000516 IdentifierInfo *getterName =
517 RefExpr->getImplicitPropertyGetter()->getSelector()
518 .getIdentifierInfoForSlot(0);
519 SetterSelector =
520 SelectorTable::constructSetterName(S.PP.getIdentifierTable(),
521 S.PP.getSelectorTable(),
522 getterName);
523 return false;
John McCall3c3b7f92011-10-25 17:37:35 +0000524 }
John McCall4b9c2d22011-11-06 09:01:30 +0000525 }
526
527 // For explicit properties, this is more involved.
528 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
529 SetterSelector = prop->getSetterName();
530
531 // Do a normal method lookup first.
532 if (ObjCMethodDecl *setter =
533 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
534 Setter = setter;
535 return true;
536 }
537
538 // That can fail in the somewhat crazy situation that we're
539 // type-checking a message send within the @interface declaration
540 // that declared the @property. But it's not clear that that's
541 // valuable to support.
542
543 return false;
544}
545
546/// Capture the base object of an Objective-C property expression.
547Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
548 assert(InstanceReceiver == 0);
549
550 // If we have a base, capture it in an OVE and rebuild the syntactic
551 // form to use the OVE as its base.
552 if (RefExpr->isObjectReceiver()) {
553 InstanceReceiver = capture(RefExpr->getBase());
554
555 syntacticBase =
556 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
557 }
558
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000559 if (ObjCPropertyRefExpr *
560 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
561 SyntacticRefExpr = refE;
562
John McCall4b9c2d22011-11-06 09:01:30 +0000563 return syntacticBase;
564}
565
566/// Load from an Objective-C property reference.
567ExprResult ObjCPropertyOpBuilder::buildGet() {
568 findGetter();
569 assert(Getter);
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000570
571 if (SyntacticRefExpr)
572 SyntacticRefExpr->setIsMessagingGetter();
573
John McCall4b9c2d22011-11-06 09:01:30 +0000574 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000575 if (RefExpr->isClassReceiver()) {
576 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
577 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000578 receiverType = RefExpr->getSuperReceiverType();
John McCall3c3b7f92011-10-25 17:37:35 +0000579 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000580 assert(InstanceReceiver);
581 receiverType = InstanceReceiver->getType();
582 }
John McCall3c3b7f92011-10-25 17:37:35 +0000583
John McCall4b9c2d22011-11-06 09:01:30 +0000584 // Build a message-send.
585 ExprResult msg;
586 if (Getter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
587 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000588 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
589 GenericLoc, Getter->getSelector(),
590 Getter, MultiExprArg());
John McCall4b9c2d22011-11-06 09:01:30 +0000591 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000592 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
593 GenericLoc,
594 Getter->getSelector(), Getter,
595 MultiExprArg());
John McCall4b9c2d22011-11-06 09:01:30 +0000596 }
597 return msg;
598}
John McCall3c3b7f92011-10-25 17:37:35 +0000599
John McCall4b9c2d22011-11-06 09:01:30 +0000600/// Store to an Objective-C property reference.
601///
602/// \param bindSetValueAsResult - If true, capture the actual
603/// value being set as the value of the property operation.
604ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
605 bool captureSetValueAsResult) {
606 bool hasSetter = findSetter();
607 assert(hasSetter); (void) hasSetter;
608
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000609 if (SyntacticRefExpr)
610 SyntacticRefExpr->setIsMessagingSetter();
611
John McCall4b9c2d22011-11-06 09:01:30 +0000612 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000613 if (RefExpr->isClassReceiver()) {
614 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
615 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000616 receiverType = RefExpr->getSuperReceiverType();
617 } else {
618 assert(InstanceReceiver);
619 receiverType = InstanceReceiver->getType();
620 }
621
622 // Use assignment constraints when possible; they give us better
623 // diagnostics. "When possible" basically means anything except a
624 // C++ class type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000625 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000626 QualType paramType = (*Setter->param_begin())->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +0000627 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000628 ExprResult opResult = op;
629 Sema::AssignConvertType assignResult
630 = S.CheckSingleAssignmentConstraints(paramType, opResult);
631 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
632 op->getType(), opResult.get(),
633 Sema::AA_Assigning))
634 return ExprError();
635
636 op = opResult.take();
637 assert(op && "successful assignment left argument invalid?");
John McCall3c3b7f92011-10-25 17:37:35 +0000638 }
639 }
640
John McCall4b9c2d22011-11-06 09:01:30 +0000641 // Arguments.
642 Expr *args[] = { op };
John McCall3c3b7f92011-10-25 17:37:35 +0000643
John McCall4b9c2d22011-11-06 09:01:30 +0000644 // Build a message-send.
645 ExprResult msg;
646 if (Setter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000647 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
648 GenericLoc, SetterSelector, Setter,
649 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000650 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000651 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
652 GenericLoc,
653 SetterSelector, Setter,
654 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000655 }
656
657 if (!msg.isInvalid() && captureSetValueAsResult) {
658 ObjCMessageExpr *msgExpr =
659 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
660 Expr *arg = msgExpr->getArg(0);
661 msgExpr->setArg(0, captureValueAsResult(arg));
662 }
663
664 return msg;
John McCall3c3b7f92011-10-25 17:37:35 +0000665}
666
John McCall4b9c2d22011-11-06 09:01:30 +0000667/// @property-specific behavior for doing lvalue-to-rvalue conversion.
668ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
669 // Explicit properties always have getters, but implicit ones don't.
670 // Check that before proceeding.
671 if (RefExpr->isImplicitProperty() &&
672 !RefExpr->getImplicitPropertyGetter()) {
673 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
674 << RefExpr->getBase()->getType();
John McCall3c3b7f92011-10-25 17:37:35 +0000675 return ExprError();
676 }
677
John McCall4b9c2d22011-11-06 09:01:30 +0000678 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall3c3b7f92011-10-25 17:37:35 +0000679 if (result.isInvalid()) return ExprError();
680
John McCall4b9c2d22011-11-06 09:01:30 +0000681 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
682 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
683 Getter, RefExpr->getLocation());
684
685 // As a special case, if the method returns 'id', try to get
686 // a better type from the property.
687 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
688 result.get()->getType()->isObjCIdType()) {
689 QualType propType = RefExpr->getExplicitProperty()->getType();
690 if (const ObjCObjectPointerType *ptr
691 = propType->getAs<ObjCObjectPointerType>()) {
692 if (!ptr->isObjCIdType())
693 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
694 }
695 }
696
John McCall3c3b7f92011-10-25 17:37:35 +0000697 return result;
698}
699
John McCall4b9c2d22011-11-06 09:01:30 +0000700/// Try to build this as a call to a getter that returns a reference.
701///
702/// \return true if it was possible, whether or not it actually
703/// succeeded
704bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
705 ExprResult &result) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000706 if (!S.getLangOpts().CPlusPlus) return false;
John McCall4b9c2d22011-11-06 09:01:30 +0000707
708 findGetter();
709 assert(Getter && "property has no setter and no getter!");
710
711 // Only do this if the getter returns an l-value reference type.
712 QualType resultType = Getter->getResultType();
713 if (!resultType->isLValueReferenceType()) return false;
714
715 result = buildRValueOperation(op);
716 return true;
717}
718
719/// @property-specific behavior for doing assignments.
720ExprResult
721ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
722 SourceLocation opcLoc,
723 BinaryOperatorKind opcode,
724 Expr *LHS, Expr *RHS) {
John McCall3c3b7f92011-10-25 17:37:35 +0000725 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall3c3b7f92011-10-25 17:37:35 +0000726
727 // If there's no setter, we have no choice but to try to assign to
728 // the result of the getter.
John McCall4b9c2d22011-11-06 09:01:30 +0000729 if (!findSetter()) {
730 ExprResult result;
731 if (tryBuildGetOfReference(LHS, result)) {
732 if (result.isInvalid()) return ExprError();
733 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000734 }
735
736 // Otherwise, it's an error.
John McCall4b9c2d22011-11-06 09:01:30 +0000737 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
738 << unsigned(RefExpr->isImplicitProperty())
739 << SetterSelector
John McCall3c3b7f92011-10-25 17:37:35 +0000740 << LHS->getSourceRange() << RHS->getSourceRange();
741 return ExprError();
742 }
743
744 // If there is a setter, we definitely want to use it.
745
John McCall4b9c2d22011-11-06 09:01:30 +0000746 // Verify that we can do a compound assignment.
747 if (opcode != BO_Assign && !findGetter()) {
748 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall3c3b7f92011-10-25 17:37:35 +0000749 << LHS->getSourceRange() << RHS->getSourceRange();
750 return ExprError();
751 }
752
John McCall4b9c2d22011-11-06 09:01:30 +0000753 ExprResult result =
754 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000755 if (result.isInvalid()) return ExprError();
756
John McCall4b9c2d22011-11-06 09:01:30 +0000757 // Various warnings about property assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000758 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCall4b9c2d22011-11-06 09:01:30 +0000759 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
760 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
761 }
762
John McCall3c3b7f92011-10-25 17:37:35 +0000763 return result;
764}
John McCall4b9c2d22011-11-06 09:01:30 +0000765
766/// @property-specific behavior for doing increments and decrements.
767ExprResult
768ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
769 UnaryOperatorKind opcode,
770 Expr *op) {
771 // If there's no setter, we have no choice but to try to assign to
772 // the result of the getter.
773 if (!findSetter()) {
774 ExprResult result;
775 if (tryBuildGetOfReference(op, result)) {
776 if (result.isInvalid()) return ExprError();
777 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
778 }
779
780 // Otherwise, it's an error.
781 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
782 << unsigned(RefExpr->isImplicitProperty())
783 << unsigned(UnaryOperator::isDecrementOp(opcode))
784 << SetterSelector
785 << op->getSourceRange();
786 return ExprError();
787 }
788
789 // If there is a setter, we definitely want to use it.
790
791 // We also need a getter.
792 if (!findGetter()) {
793 assert(RefExpr->isImplicitProperty());
794 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
795 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000796 << GetterSelector
John McCall4b9c2d22011-11-06 09:01:30 +0000797 << op->getSourceRange();
798 return ExprError();
799 }
800
801 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
802}
803
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000804// ObjCSubscript build stuff.
805//
806
807/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
808/// conversion.
809/// FIXME. Remove this routine if it is proven that no additional
810/// specifity is needed.
811ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
812 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
813 if (result.isInvalid()) return ExprError();
814 return result;
815}
816
817/// objective-c subscripting-specific behavior for doing assignments.
818ExprResult
819ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
820 SourceLocation opcLoc,
821 BinaryOperatorKind opcode,
822 Expr *LHS, Expr *RHS) {
823 assert(BinaryOperator::isAssignmentOp(opcode));
824 // There must be a method to do the Index'ed assignment.
825 if (!findAtIndexSetter())
826 return ExprError();
827
828 // Verify that we can do a compound assignment.
829 if (opcode != BO_Assign && !findAtIndexGetter())
830 return ExprError();
831
832 ExprResult result =
833 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
834 if (result.isInvalid()) return ExprError();
835
836 // Various warnings about objc Index'ed assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000837 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000838 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
839 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
840 }
841
842 return result;
843}
844
845/// Capture the base object of an Objective-C Index'ed expression.
846Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
847 assert(InstanceBase == 0);
848
849 // Capture base expression in an OVE and rebuild the syntactic
850 // form to use the OVE as its base expression.
851 InstanceBase = capture(RefExpr->getBaseExpr());
852 InstanceKey = capture(RefExpr->getKeyExpr());
853
854 syntacticBase =
855 ObjCSubscriptRefRebuilder(S, InstanceBase,
856 InstanceKey).rebuild(syntacticBase);
857
858 return syntacticBase;
859}
860
861/// CheckSubscriptingKind - This routine decide what type
862/// of indexing represented by "FromE" is being done.
863Sema::ObjCSubscriptKind
864 Sema::CheckSubscriptingKind(Expr *FromE) {
865 // If the expression already has integral or enumeration type, we're golden.
866 QualType T = FromE->getType();
867 if (T->isIntegralOrEnumerationType())
868 return OS_Array;
869
870 // If we don't have a class type in C++, there's no way we can get an
871 // expression of integral or enumeration type.
872 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000873 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000874 // All other scalar cases are assumed to be dictionary indexing which
875 // caller handles, with diagnostics if needed.
876 return OS_Dictionary;
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000877 if (!getLangOpts().CPlusPlus ||
878 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000879 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000880 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
881 if (isa<StringLiteral>(IndexExpr))
882 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
883 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
884 else
885 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
886 << T;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000887 return OS_Error;
888 }
889
890 // We must have a complete class type.
891 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregord10099e2012-05-04 16:32:21 +0000892 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000893 return OS_Error;
894
895 // Look for a conversion to an integral, enumeration type, or
896 // objective-C pointer type.
897 UnresolvedSet<4> ViableConversions;
898 UnresolvedSet<4> ExplicitConversions;
899 const UnresolvedSetImpl *Conversions
900 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
901
902 int NoIntegrals=0, NoObjCIdPointers=0;
903 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
904
905 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
906 E = Conversions->end();
907 I != E;
908 ++I) {
909 if (CXXConversionDecl *Conversion
910 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
911 QualType CT = Conversion->getConversionType().getNonReferenceType();
912 if (CT->isIntegralOrEnumerationType()) {
913 ++NoIntegrals;
914 ConversionDecls.push_back(Conversion);
915 }
916 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
917 ++NoObjCIdPointers;
918 ConversionDecls.push_back(Conversion);
919 }
920 }
921 }
922 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
923 return OS_Array;
924 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
925 return OS_Dictionary;
926 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
927 // No conversion function was found. Issue diagnostic and return.
928 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
929 << FromE->getType();
930 return OS_Error;
931 }
932 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
933 << FromE->getType();
934 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
935 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
936
937 return OS_Error;
938}
939
940bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
941 if (AtIndexGetter)
942 return true;
943
944 Expr *BaseExpr = RefExpr->getBaseExpr();
945 QualType BaseT = BaseExpr->getType();
946
947 QualType ResultType;
948 if (const ObjCObjectPointerType *PTy =
949 BaseT->getAs<ObjCObjectPointerType>()) {
950 ResultType = PTy->getPointeeType();
951 if (const ObjCObjectType *iQFaceTy =
952 ResultType->getAsObjCQualifiedInterfaceType())
953 ResultType = iQFaceTy->getBaseType();
954 }
955 Sema::ObjCSubscriptKind Res =
956 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
957 if (Res == Sema::OS_Error)
958 return false;
959 bool arrayRef = (Res == Sema::OS_Array);
960
961 if (ResultType.isNull()) {
962 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
963 << BaseExpr->getType() << arrayRef;
964 return false;
965 }
966 if (!arrayRef) {
967 // dictionary subscripting.
968 // - (id)objectForKeyedSubscript:(id)key;
969 IdentifierInfo *KeyIdents[] = {
970 &S.Context.Idents.get("objectForKeyedSubscript")
971 };
972 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
973 }
974 else {
975 // - (id)objectAtIndexedSubscript:(size_t)index;
976 IdentifierInfo *KeyIdents[] = {
977 &S.Context.Idents.get("objectAtIndexedSubscript")
978 };
979
980 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
981 }
982
983 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
984 true /*instance*/);
985 bool receiverIdType = (BaseT->isObjCIdType() ||
986 BaseT->isObjCQualifiedIdType());
987
David Blaikie4e4d0842012-03-11 07:00:24 +0000988 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000989 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
990 SourceLocation(), AtIndexGetterSelector,
991 S.Context.getObjCIdType() /*ReturnType*/,
992 0 /*TypeSourceInfo */,
993 S.Context.getTranslationUnitDecl(),
994 true /*Instance*/, false/*isVariadic*/,
995 /*isSynthesized=*/false,
996 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
997 ObjCMethodDecl::Required,
998 false);
999 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1000 SourceLocation(), SourceLocation(),
1001 arrayRef ? &S.Context.Idents.get("index")
1002 : &S.Context.Idents.get("key"),
1003 arrayRef ? S.Context.UnsignedLongTy
1004 : S.Context.getObjCIdType(),
1005 /*TInfo=*/0,
1006 SC_None,
1007 SC_None,
1008 0);
1009 AtIndexGetter->setMethodParams(S.Context, Argument,
1010 ArrayRef<SourceLocation>());
1011 }
1012
1013 if (!AtIndexGetter) {
1014 if (!receiverIdType) {
1015 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1016 << BaseExpr->getType() << 0 << arrayRef;
1017 return false;
1018 }
1019 AtIndexGetter =
1020 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1021 RefExpr->getSourceRange(),
1022 true, false);
1023 }
1024
1025 if (AtIndexGetter) {
1026 QualType T = AtIndexGetter->param_begin()[0]->getType();
1027 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1028 (!arrayRef && !T->isObjCObjectPointerType())) {
1029 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1030 arrayRef ? diag::err_objc_subscript_index_type
1031 : diag::err_objc_subscript_key_type) << T;
1032 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1033 diag::note_parameter_type) << T;
1034 return false;
1035 }
1036 QualType R = AtIndexGetter->getResultType();
1037 if (!R->isObjCObjectPointerType()) {
1038 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1039 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1040 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1041 AtIndexGetter->getDeclName();
1042 }
1043 }
1044 return true;
1045}
1046
1047bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1048 if (AtIndexSetter)
1049 return true;
1050
1051 Expr *BaseExpr = RefExpr->getBaseExpr();
1052 QualType BaseT = BaseExpr->getType();
1053
1054 QualType ResultType;
1055 if (const ObjCObjectPointerType *PTy =
1056 BaseT->getAs<ObjCObjectPointerType>()) {
1057 ResultType = PTy->getPointeeType();
1058 if (const ObjCObjectType *iQFaceTy =
1059 ResultType->getAsObjCQualifiedInterfaceType())
1060 ResultType = iQFaceTy->getBaseType();
1061 }
1062
1063 Sema::ObjCSubscriptKind Res =
1064 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
1065 if (Res == Sema::OS_Error)
1066 return false;
1067 bool arrayRef = (Res == Sema::OS_Array);
1068
1069 if (ResultType.isNull()) {
1070 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1071 << BaseExpr->getType() << arrayRef;
1072 return false;
1073 }
1074
1075 if (!arrayRef) {
1076 // dictionary subscripting.
1077 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1078 IdentifierInfo *KeyIdents[] = {
1079 &S.Context.Idents.get("setObject"),
1080 &S.Context.Idents.get("forKeyedSubscript")
1081 };
1082 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1083 }
1084 else {
1085 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1086 IdentifierInfo *KeyIdents[] = {
1087 &S.Context.Idents.get("setObject"),
1088 &S.Context.Idents.get("atIndexedSubscript")
1089 };
1090 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1091 }
1092 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1093 true /*instance*/);
1094
1095 bool receiverIdType = (BaseT->isObjCIdType() ||
1096 BaseT->isObjCQualifiedIdType());
1097
David Blaikie4e4d0842012-03-11 07:00:24 +00001098 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001099 TypeSourceInfo *ResultTInfo = 0;
1100 QualType ReturnType = S.Context.VoidTy;
1101 AtIndexSetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1102 SourceLocation(), AtIndexSetterSelector,
1103 ReturnType,
1104 ResultTInfo,
1105 S.Context.getTranslationUnitDecl(),
1106 true /*Instance*/, false/*isVariadic*/,
1107 /*isSynthesized=*/false,
1108 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1109 ObjCMethodDecl::Required,
1110 false);
1111 SmallVector<ParmVarDecl *, 2> Params;
1112 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1113 SourceLocation(), SourceLocation(),
1114 &S.Context.Idents.get("object"),
1115 S.Context.getObjCIdType(),
1116 /*TInfo=*/0,
1117 SC_None,
1118 SC_None,
1119 0);
1120 Params.push_back(object);
1121 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1122 SourceLocation(), SourceLocation(),
1123 arrayRef ? &S.Context.Idents.get("index")
1124 : &S.Context.Idents.get("key"),
1125 arrayRef ? S.Context.UnsignedLongTy
1126 : S.Context.getObjCIdType(),
1127 /*TInfo=*/0,
1128 SC_None,
1129 SC_None,
1130 0);
1131 Params.push_back(key);
1132 AtIndexSetter->setMethodParams(S.Context, Params, ArrayRef<SourceLocation>());
1133 }
1134
1135 if (!AtIndexSetter) {
1136 if (!receiverIdType) {
1137 S.Diag(BaseExpr->getExprLoc(),
1138 diag::err_objc_subscript_method_not_found)
1139 << BaseExpr->getType() << 1 << arrayRef;
1140 return false;
1141 }
1142 AtIndexSetter =
1143 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1144 RefExpr->getSourceRange(),
1145 true, false);
1146 }
1147
1148 bool err = false;
1149 if (AtIndexSetter && arrayRef) {
1150 QualType T = AtIndexSetter->param_begin()[1]->getType();
1151 if (!T->isIntegralOrEnumerationType()) {
1152 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1153 diag::err_objc_subscript_index_type) << T;
1154 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1155 diag::note_parameter_type) << T;
1156 err = true;
1157 }
1158 T = AtIndexSetter->param_begin()[0]->getType();
1159 if (!T->isObjCObjectPointerType()) {
1160 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1161 diag::err_objc_subscript_object_type) << T << arrayRef;
1162 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1163 diag::note_parameter_type) << T;
1164 err = true;
1165 }
1166 }
1167 else if (AtIndexSetter && !arrayRef)
1168 for (unsigned i=0; i <2; i++) {
1169 QualType T = AtIndexSetter->param_begin()[i]->getType();
1170 if (!T->isObjCObjectPointerType()) {
1171 if (i == 1)
1172 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1173 diag::err_objc_subscript_key_type) << T;
1174 else
1175 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1176 diag::err_objc_subscript_dic_object_type) << T;
1177 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1178 diag::note_parameter_type) << T;
1179 err = true;
1180 }
1181 }
1182
1183 return !err;
1184}
1185
1186// Get the object at "Index" position in the container.
1187// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1188ExprResult ObjCSubscriptOpBuilder::buildGet() {
1189 if (!findAtIndexGetter())
1190 return ExprError();
1191
1192 QualType receiverType = InstanceBase->getType();
1193
1194 // Build a message-send.
1195 ExprResult msg;
1196 Expr *Index = InstanceKey;
1197
1198 // Arguments.
1199 Expr *args[] = { Index };
1200 assert(InstanceBase);
1201 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1202 GenericLoc,
1203 AtIndexGetterSelector, AtIndexGetter,
1204 MultiExprArg(args, 1));
1205 return msg;
1206}
1207
1208/// Store into the container the "op" object at "Index"'ed location
1209/// by building this messaging expression:
1210/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1211/// \param bindSetValueAsResult - If true, capture the actual
1212/// value being set as the value of the property operation.
1213ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1214 bool captureSetValueAsResult) {
1215 if (!findAtIndexSetter())
1216 return ExprError();
1217
1218 QualType receiverType = InstanceBase->getType();
1219 Expr *Index = InstanceKey;
1220
1221 // Arguments.
1222 Expr *args[] = { op, Index };
1223
1224 // Build a message-send.
1225 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1226 GenericLoc,
1227 AtIndexSetterSelector,
1228 AtIndexSetter,
1229 MultiExprArg(args, 2));
1230
1231 if (!msg.isInvalid() && captureSetValueAsResult) {
1232 ObjCMessageExpr *msgExpr =
1233 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1234 Expr *arg = msgExpr->getArg(0);
1235 msgExpr->setArg(0, captureValueAsResult(arg));
1236 }
1237
1238 return msg;
1239}
1240
John McCall4b9c2d22011-11-06 09:01:30 +00001241//===----------------------------------------------------------------------===//
1242// General Sema routines.
1243//===----------------------------------------------------------------------===//
1244
1245ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1246 Expr *opaqueRef = E->IgnoreParens();
1247 if (ObjCPropertyRefExpr *refExpr
1248 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1249 ObjCPropertyOpBuilder builder(*this, refExpr);
1250 return builder.buildRValueOperation(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001251 }
1252 else if (ObjCSubscriptRefExpr *refExpr
1253 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1254 ObjCSubscriptOpBuilder builder(*this, refExpr);
1255 return builder.buildRValueOperation(E);
John McCall4b9c2d22011-11-06 09:01:30 +00001256 } else {
1257 llvm_unreachable("unknown pseudo-object kind!");
1258 }
1259}
1260
1261/// Check an increment or decrement of a pseudo-object expression.
1262ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1263 UnaryOperatorKind opcode, Expr *op) {
1264 // Do nothing if the operand is dependent.
1265 if (op->isTypeDependent())
1266 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1267 VK_RValue, OK_Ordinary, opcLoc);
1268
1269 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1270 Expr *opaqueRef = op->IgnoreParens();
1271 if (ObjCPropertyRefExpr *refExpr
1272 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1273 ObjCPropertyOpBuilder builder(*this, refExpr);
1274 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001275 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1276 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1277 return ExprError();
John McCall4b9c2d22011-11-06 09:01:30 +00001278 } else {
1279 llvm_unreachable("unknown pseudo-object kind!");
1280 }
1281}
1282
1283ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1284 BinaryOperatorKind opcode,
1285 Expr *LHS, Expr *RHS) {
1286 // Do nothing if either argument is dependent.
1287 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1288 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
1289 VK_RValue, OK_Ordinary, opcLoc);
1290
1291 // Filter out non-overload placeholder types in the RHS.
John McCall32509f12011-11-15 01:35:18 +00001292 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1293 ExprResult result = CheckPlaceholderExpr(RHS);
1294 if (result.isInvalid()) return ExprError();
1295 RHS = result.take();
John McCall4b9c2d22011-11-06 09:01:30 +00001296 }
1297
1298 Expr *opaqueRef = LHS->IgnoreParens();
1299 if (ObjCPropertyRefExpr *refExpr
1300 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1301 ObjCPropertyOpBuilder builder(*this, refExpr);
1302 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001303 } else if (ObjCSubscriptRefExpr *refExpr
1304 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1305 ObjCSubscriptOpBuilder builder(*this, refExpr);
1306 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall4b9c2d22011-11-06 09:01:30 +00001307 } else {
1308 llvm_unreachable("unknown pseudo-object kind!");
1309 }
1310}
John McCall01e19be2011-11-30 04:42:31 +00001311
1312/// Given a pseudo-object reference, rebuild it without the opaque
1313/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1314/// This should never operate in-place.
1315static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1316 Expr *opaqueRef = E->IgnoreParens();
1317 if (ObjCPropertyRefExpr *refExpr
1318 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregor88507dd2012-04-13 16:05:42 +00001319 // Class and super property references don't have opaque values in them.
1320 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1321 return E;
1322
1323 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1324 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1325 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001326 } else if (ObjCSubscriptRefExpr *refExpr
1327 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1328 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1329 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1330 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1331 keyOVE->getSourceExpr()).rebuild(E);
John McCall01e19be2011-11-30 04:42:31 +00001332 } else {
1333 llvm_unreachable("unknown pseudo-object kind!");
1334 }
1335}
1336
1337/// Given a pseudo-object expression, recreate what it looks like
1338/// syntactically without the attendant OpaqueValueExprs.
1339///
1340/// This is a hack which should be removed when TreeTransform is
1341/// capable of rebuilding a tree without stripping implicit
1342/// operations.
1343Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1344 Expr *syntax = E->getSyntacticForm();
1345 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1346 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1347 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1348 uop->getValueKind(), uop->getObjectKind(),
1349 uop->getOperatorLoc());
1350 } else if (CompoundAssignOperator *cop
1351 = dyn_cast<CompoundAssignOperator>(syntax)) {
1352 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1353 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1354 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1355 cop->getType(),
1356 cop->getValueKind(),
1357 cop->getObjectKind(),
1358 cop->getComputationLHSType(),
1359 cop->getComputationResultType(),
1360 cop->getOperatorLoc());
1361 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1362 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1363 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1364 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1365 bop->getType(), bop->getValueKind(),
1366 bop->getObjectKind(),
1367 bop->getOperatorLoc());
1368 } else {
1369 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1370 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1371 }
1372}