blob: b5e908b47c9c6e91d8b2d1216761ad843b10db00 [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///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000295/// \returns the captured expression, which will be the
John McCall4b9c2d22011-11-06 09:01:30 +0000296/// 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///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000620/// \param captureSetValueAsResult If true, capture the actual
John McCall4b9c2d22011-11-06 09:01:30 +0000621/// 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
Fariborz Jahaniandc483052012-08-02 18:03:58 +0000958/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
959/// objects used as dictionary subscript key objects.
960static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
961 Expr *Key) {
962 if (ContainerT.isNull())
963 return;
964 // dictionary subscripting.
965 // - (id)objectForKeyedSubscript:(id)key;
966 IdentifierInfo *KeyIdents[] = {
967 &S.Context.Idents.get("objectForKeyedSubscript")
968 };
969 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
970 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
971 true /*instance*/);
972 if (!Getter)
973 return;
974 QualType T = Getter->param_begin()[0]->getType();
975 S.CheckObjCARCConversion(Key->getSourceRange(),
976 T, Key, Sema::CCK_ImplicitConversion);
977}
978
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000979bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
980 if (AtIndexGetter)
981 return true;
982
983 Expr *BaseExpr = RefExpr->getBaseExpr();
984 QualType BaseT = BaseExpr->getType();
985
986 QualType ResultType;
987 if (const ObjCObjectPointerType *PTy =
988 BaseT->getAs<ObjCObjectPointerType>()) {
989 ResultType = PTy->getPointeeType();
990 if (const ObjCObjectType *iQFaceTy =
991 ResultType->getAsObjCQualifiedInterfaceType())
992 ResultType = iQFaceTy->getBaseType();
993 }
994 Sema::ObjCSubscriptKind Res =
995 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +0000996 if (Res == Sema::OS_Error) {
997 if (S.getLangOpts().ObjCAutoRefCount)
998 CheckKeyForObjCARCConversion(S, ResultType,
999 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001000 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001001 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001002 bool arrayRef = (Res == Sema::OS_Array);
1003
1004 if (ResultType.isNull()) {
1005 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1006 << BaseExpr->getType() << arrayRef;
1007 return false;
1008 }
1009 if (!arrayRef) {
1010 // dictionary subscripting.
1011 // - (id)objectForKeyedSubscript:(id)key;
1012 IdentifierInfo *KeyIdents[] = {
1013 &S.Context.Idents.get("objectForKeyedSubscript")
1014 };
1015 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1016 }
1017 else {
1018 // - (id)objectAtIndexedSubscript:(size_t)index;
1019 IdentifierInfo *KeyIdents[] = {
1020 &S.Context.Idents.get("objectAtIndexedSubscript")
1021 };
1022
1023 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1024 }
1025
1026 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1027 true /*instance*/);
1028 bool receiverIdType = (BaseT->isObjCIdType() ||
1029 BaseT->isObjCQualifiedIdType());
1030
David Blaikie4e4d0842012-03-11 07:00:24 +00001031 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001032 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1033 SourceLocation(), AtIndexGetterSelector,
1034 S.Context.getObjCIdType() /*ReturnType*/,
1035 0 /*TypeSourceInfo */,
1036 S.Context.getTranslationUnitDecl(),
1037 true /*Instance*/, false/*isVariadic*/,
1038 /*isSynthesized=*/false,
1039 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1040 ObjCMethodDecl::Required,
1041 false);
1042 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1043 SourceLocation(), SourceLocation(),
1044 arrayRef ? &S.Context.Idents.get("index")
1045 : &S.Context.Idents.get("key"),
1046 arrayRef ? S.Context.UnsignedLongTy
1047 : S.Context.getObjCIdType(),
1048 /*TInfo=*/0,
1049 SC_None,
1050 SC_None,
1051 0);
1052 AtIndexGetter->setMethodParams(S.Context, Argument,
1053 ArrayRef<SourceLocation>());
1054 }
1055
1056 if (!AtIndexGetter) {
1057 if (!receiverIdType) {
1058 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1059 << BaseExpr->getType() << 0 << arrayRef;
1060 return false;
1061 }
1062 AtIndexGetter =
1063 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1064 RefExpr->getSourceRange(),
1065 true, false);
1066 }
1067
1068 if (AtIndexGetter) {
1069 QualType T = AtIndexGetter->param_begin()[0]->getType();
1070 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1071 (!arrayRef && !T->isObjCObjectPointerType())) {
1072 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1073 arrayRef ? diag::err_objc_subscript_index_type
1074 : diag::err_objc_subscript_key_type) << T;
1075 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1076 diag::note_parameter_type) << T;
1077 return false;
1078 }
1079 QualType R = AtIndexGetter->getResultType();
1080 if (!R->isObjCObjectPointerType()) {
1081 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1082 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1083 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1084 AtIndexGetter->getDeclName();
1085 }
1086 }
1087 return true;
1088}
1089
1090bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1091 if (AtIndexSetter)
1092 return true;
1093
1094 Expr *BaseExpr = RefExpr->getBaseExpr();
1095 QualType BaseT = BaseExpr->getType();
1096
1097 QualType ResultType;
1098 if (const ObjCObjectPointerType *PTy =
1099 BaseT->getAs<ObjCObjectPointerType>()) {
1100 ResultType = PTy->getPointeeType();
1101 if (const ObjCObjectType *iQFaceTy =
1102 ResultType->getAsObjCQualifiedInterfaceType())
1103 ResultType = iQFaceTy->getBaseType();
1104 }
1105
1106 Sema::ObjCSubscriptKind Res =
1107 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001108 if (Res == Sema::OS_Error) {
1109 if (S.getLangOpts().ObjCAutoRefCount)
1110 CheckKeyForObjCARCConversion(S, ResultType,
1111 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001112 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001113 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001114 bool arrayRef = (Res == Sema::OS_Array);
1115
1116 if (ResultType.isNull()) {
1117 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1118 << BaseExpr->getType() << arrayRef;
1119 return false;
1120 }
1121
1122 if (!arrayRef) {
1123 // dictionary subscripting.
1124 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1125 IdentifierInfo *KeyIdents[] = {
1126 &S.Context.Idents.get("setObject"),
1127 &S.Context.Idents.get("forKeyedSubscript")
1128 };
1129 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1130 }
1131 else {
1132 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1133 IdentifierInfo *KeyIdents[] = {
1134 &S.Context.Idents.get("setObject"),
1135 &S.Context.Idents.get("atIndexedSubscript")
1136 };
1137 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1138 }
1139 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1140 true /*instance*/);
1141
1142 bool receiverIdType = (BaseT->isObjCIdType() ||
1143 BaseT->isObjCQualifiedIdType());
1144
David Blaikie4e4d0842012-03-11 07:00:24 +00001145 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001146 TypeSourceInfo *ResultTInfo = 0;
1147 QualType ReturnType = S.Context.VoidTy;
1148 AtIndexSetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1149 SourceLocation(), AtIndexSetterSelector,
1150 ReturnType,
1151 ResultTInfo,
1152 S.Context.getTranslationUnitDecl(),
1153 true /*Instance*/, false/*isVariadic*/,
1154 /*isSynthesized=*/false,
1155 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1156 ObjCMethodDecl::Required,
1157 false);
1158 SmallVector<ParmVarDecl *, 2> Params;
1159 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1160 SourceLocation(), SourceLocation(),
1161 &S.Context.Idents.get("object"),
1162 S.Context.getObjCIdType(),
1163 /*TInfo=*/0,
1164 SC_None,
1165 SC_None,
1166 0);
1167 Params.push_back(object);
1168 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1169 SourceLocation(), SourceLocation(),
1170 arrayRef ? &S.Context.Idents.get("index")
1171 : &S.Context.Idents.get("key"),
1172 arrayRef ? S.Context.UnsignedLongTy
1173 : S.Context.getObjCIdType(),
1174 /*TInfo=*/0,
1175 SC_None,
1176 SC_None,
1177 0);
1178 Params.push_back(key);
1179 AtIndexSetter->setMethodParams(S.Context, Params, ArrayRef<SourceLocation>());
1180 }
1181
1182 if (!AtIndexSetter) {
1183 if (!receiverIdType) {
1184 S.Diag(BaseExpr->getExprLoc(),
1185 diag::err_objc_subscript_method_not_found)
1186 << BaseExpr->getType() << 1 << arrayRef;
1187 return false;
1188 }
1189 AtIndexSetter =
1190 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1191 RefExpr->getSourceRange(),
1192 true, false);
1193 }
1194
1195 bool err = false;
1196 if (AtIndexSetter && arrayRef) {
1197 QualType T = AtIndexSetter->param_begin()[1]->getType();
1198 if (!T->isIntegralOrEnumerationType()) {
1199 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1200 diag::err_objc_subscript_index_type) << T;
1201 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1202 diag::note_parameter_type) << T;
1203 err = true;
1204 }
1205 T = AtIndexSetter->param_begin()[0]->getType();
1206 if (!T->isObjCObjectPointerType()) {
1207 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1208 diag::err_objc_subscript_object_type) << T << arrayRef;
1209 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1210 diag::note_parameter_type) << T;
1211 err = true;
1212 }
1213 }
1214 else if (AtIndexSetter && !arrayRef)
1215 for (unsigned i=0; i <2; i++) {
1216 QualType T = AtIndexSetter->param_begin()[i]->getType();
1217 if (!T->isObjCObjectPointerType()) {
1218 if (i == 1)
1219 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1220 diag::err_objc_subscript_key_type) << T;
1221 else
1222 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1223 diag::err_objc_subscript_dic_object_type) << T;
1224 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1225 diag::note_parameter_type) << T;
1226 err = true;
1227 }
1228 }
1229
1230 return !err;
1231}
1232
1233// Get the object at "Index" position in the container.
1234// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1235ExprResult ObjCSubscriptOpBuilder::buildGet() {
1236 if (!findAtIndexGetter())
1237 return ExprError();
1238
1239 QualType receiverType = InstanceBase->getType();
1240
1241 // Build a message-send.
1242 ExprResult msg;
1243 Expr *Index = InstanceKey;
1244
1245 // Arguments.
1246 Expr *args[] = { Index };
1247 assert(InstanceBase);
1248 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1249 GenericLoc,
1250 AtIndexGetterSelector, AtIndexGetter,
1251 MultiExprArg(args, 1));
1252 return msg;
1253}
1254
1255/// Store into the container the "op" object at "Index"'ed location
1256/// by building this messaging expression:
1257/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001258/// \param captureSetValueAsResult If true, capture the actual
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001259/// value being set as the value of the property operation.
1260ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1261 bool captureSetValueAsResult) {
1262 if (!findAtIndexSetter())
1263 return ExprError();
1264
1265 QualType receiverType = InstanceBase->getType();
1266 Expr *Index = InstanceKey;
1267
1268 // Arguments.
1269 Expr *args[] = { op, Index };
1270
1271 // Build a message-send.
1272 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1273 GenericLoc,
1274 AtIndexSetterSelector,
1275 AtIndexSetter,
1276 MultiExprArg(args, 2));
1277
1278 if (!msg.isInvalid() && captureSetValueAsResult) {
1279 ObjCMessageExpr *msgExpr =
1280 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1281 Expr *arg = msgExpr->getArg(0);
1282 msgExpr->setArg(0, captureValueAsResult(arg));
1283 }
1284
1285 return msg;
1286}
1287
John McCall4b9c2d22011-11-06 09:01:30 +00001288//===----------------------------------------------------------------------===//
1289// General Sema routines.
1290//===----------------------------------------------------------------------===//
1291
1292ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1293 Expr *opaqueRef = E->IgnoreParens();
1294 if (ObjCPropertyRefExpr *refExpr
1295 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1296 ObjCPropertyOpBuilder builder(*this, refExpr);
1297 return builder.buildRValueOperation(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001298 }
1299 else if (ObjCSubscriptRefExpr *refExpr
1300 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1301 ObjCSubscriptOpBuilder builder(*this, refExpr);
1302 return builder.buildRValueOperation(E);
John McCall4b9c2d22011-11-06 09:01:30 +00001303 } else {
1304 llvm_unreachable("unknown pseudo-object kind!");
1305 }
1306}
1307
1308/// Check an increment or decrement of a pseudo-object expression.
1309ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1310 UnaryOperatorKind opcode, Expr *op) {
1311 // Do nothing if the operand is dependent.
1312 if (op->isTypeDependent())
1313 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1314 VK_RValue, OK_Ordinary, opcLoc);
1315
1316 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1317 Expr *opaqueRef = op->IgnoreParens();
1318 if (ObjCPropertyRefExpr *refExpr
1319 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1320 ObjCPropertyOpBuilder builder(*this, refExpr);
1321 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001322 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1323 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1324 return ExprError();
John McCall4b9c2d22011-11-06 09:01:30 +00001325 } else {
1326 llvm_unreachable("unknown pseudo-object kind!");
1327 }
1328}
1329
1330ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1331 BinaryOperatorKind opcode,
1332 Expr *LHS, Expr *RHS) {
1333 // Do nothing if either argument is dependent.
1334 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1335 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
1336 VK_RValue, OK_Ordinary, opcLoc);
1337
1338 // Filter out non-overload placeholder types in the RHS.
John McCall32509f12011-11-15 01:35:18 +00001339 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1340 ExprResult result = CheckPlaceholderExpr(RHS);
1341 if (result.isInvalid()) return ExprError();
1342 RHS = result.take();
John McCall4b9c2d22011-11-06 09:01:30 +00001343 }
1344
1345 Expr *opaqueRef = LHS->IgnoreParens();
1346 if (ObjCPropertyRefExpr *refExpr
1347 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1348 ObjCPropertyOpBuilder builder(*this, refExpr);
1349 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001350 } else if (ObjCSubscriptRefExpr *refExpr
1351 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1352 ObjCSubscriptOpBuilder builder(*this, refExpr);
1353 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall4b9c2d22011-11-06 09:01:30 +00001354 } else {
1355 llvm_unreachable("unknown pseudo-object kind!");
1356 }
1357}
John McCall01e19be2011-11-30 04:42:31 +00001358
1359/// Given a pseudo-object reference, rebuild it without the opaque
1360/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1361/// This should never operate in-place.
1362static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1363 Expr *opaqueRef = E->IgnoreParens();
1364 if (ObjCPropertyRefExpr *refExpr
1365 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregor88507dd2012-04-13 16:05:42 +00001366 // Class and super property references don't have opaque values in them.
1367 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1368 return E;
1369
1370 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1371 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1372 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001373 } else if (ObjCSubscriptRefExpr *refExpr
1374 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1375 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1376 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1377 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1378 keyOVE->getSourceExpr()).rebuild(E);
John McCall01e19be2011-11-30 04:42:31 +00001379 } else {
1380 llvm_unreachable("unknown pseudo-object kind!");
1381 }
1382}
1383
1384/// Given a pseudo-object expression, recreate what it looks like
1385/// syntactically without the attendant OpaqueValueExprs.
1386///
1387/// This is a hack which should be removed when TreeTransform is
1388/// capable of rebuilding a tree without stripping implicit
1389/// operations.
1390Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1391 Expr *syntax = E->getSyntacticForm();
1392 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1393 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1394 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1395 uop->getValueKind(), uop->getObjectKind(),
1396 uop->getOperatorLoc());
1397 } else if (CompoundAssignOperator *cop
1398 = dyn_cast<CompoundAssignOperator>(syntax)) {
1399 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1400 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1401 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1402 cop->getType(),
1403 cop->getValueKind(),
1404 cop->getObjectKind(),
1405 cop->getComputationLHSType(),
1406 cop->getComputationResultType(),
1407 cop->getOperatorLoc());
1408 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1409 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1410 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1411 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1412 bop->getType(), bop->getValueKind(),
1413 bop->getObjectKind(),
1414 bop->getOperatorLoc());
1415 } else {
1416 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1417 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1418 }
1419}