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