blob: b07a59b81c2ea8259e046760e8e6c26369c438bf [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"
Jordan Rose58b6bdc2012-09-28 22:21:30 +000034#include "clang/Sema/ScopeInfo.h"
John McCall3c3b7f92011-10-25 17:37:35 +000035#include "clang/Sema/Initialization.h"
36#include "clang/AST/ExprObjC.h"
37#include "clang/Lex/Preprocessor.h"
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +000038#include "llvm/ADT/SmallString.h"
John McCall3c3b7f92011-10-25 17:37:35 +000039
40using namespace clang;
41using namespace sema;
42
John McCall4b9c2d22011-11-06 09:01:30 +000043namespace {
44 // Basically just a very focused copy of TreeTransform.
45 template <class T> struct Rebuilder {
46 Sema &S;
47 Rebuilder(Sema &S) : S(S) {}
48
49 T &getDerived() { return static_cast<T&>(*this); }
50
51 Expr *rebuild(Expr *e) {
52 // Fast path: nothing to look through.
53 if (typename T::specific_type *specific
54 = dyn_cast<typename T::specific_type>(e))
55 return getDerived().rebuildSpecific(specific);
56
57 // Otherwise, we should look through and rebuild anything that
58 // IgnoreParens would.
59
60 if (ParenExpr *parens = dyn_cast<ParenExpr>(e)) {
61 e = rebuild(parens->getSubExpr());
62 return new (S.Context) ParenExpr(parens->getLParen(),
63 parens->getRParen(),
64 e);
65 }
66
67 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(e)) {
68 assert(uop->getOpcode() == UO_Extension);
69 e = rebuild(uop->getSubExpr());
70 return new (S.Context) UnaryOperator(e, uop->getOpcode(),
71 uop->getType(),
72 uop->getValueKind(),
73 uop->getObjectKind(),
74 uop->getOperatorLoc());
75 }
76
77 if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) {
78 assert(!gse->isResultDependent());
79 unsigned resultIndex = gse->getResultIndex();
80 unsigned numAssocs = gse->getNumAssocs();
81
82 SmallVector<Expr*, 8> assocs(numAssocs);
83 SmallVector<TypeSourceInfo*, 8> assocTypes(numAssocs);
84
85 for (unsigned i = 0; i != numAssocs; ++i) {
86 Expr *assoc = gse->getAssocExpr(i);
87 if (i == resultIndex) assoc = rebuild(assoc);
88 assocs[i] = assoc;
89 assocTypes[i] = gse->getAssocTypeSourceInfo(i);
90 }
91
92 return new (S.Context) GenericSelectionExpr(S.Context,
93 gse->getGenericLoc(),
94 gse->getControllingExpr(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +000095 assocTypes,
96 assocs,
John McCall4b9c2d22011-11-06 09:01:30 +000097 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
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000190 virtual ExprResult complete(Expr *syntacticForm);
John McCall4b9c2d22011-11-06 09:01:30 +0000191
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
Dmitri Gribenkoe23fb902012-09-12 17:01:48 +0000209 /// A PseudoOpBuilder for Objective-C \@properties.
John McCall4b9c2d22011-11-06 09:01:30 +0000210 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);
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000242 ExprResult complete(Expr *SyntacticForm);
243
244 bool isWeakProperty() const;
John McCall4b9c2d22011-11-06 09:01:30 +0000245 };
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000246
247 /// A PseudoOpBuilder for Objective-C array/dictionary indexing.
248 class ObjCSubscriptOpBuilder : public PseudoOpBuilder {
249 ObjCSubscriptRefExpr *RefExpr;
250 OpaqueValueExpr *InstanceBase;
251 OpaqueValueExpr *InstanceKey;
252 ObjCMethodDecl *AtIndexGetter;
253 Selector AtIndexGetterSelector;
254
255 ObjCMethodDecl *AtIndexSetter;
256 Selector AtIndexSetterSelector;
257
258 public:
259 ObjCSubscriptOpBuilder(Sema &S, ObjCSubscriptRefExpr *refExpr) :
260 PseudoOpBuilder(S, refExpr->getSourceRange().getBegin()),
261 RefExpr(refExpr),
262 InstanceBase(0), InstanceKey(0),
263 AtIndexGetter(0), AtIndexSetter(0) { }
264
265 ExprResult buildRValueOperation(Expr *op);
266 ExprResult buildAssignmentOperation(Scope *Sc,
267 SourceLocation opLoc,
268 BinaryOperatorKind opcode,
269 Expr *LHS, Expr *RHS);
270 Expr *rebuildAndCaptureObject(Expr *syntacticBase);
271
272 bool findAtIndexGetter();
273 bool findAtIndexSetter();
274
275 ExprResult buildGet();
276 ExprResult buildSet(Expr *op, SourceLocation, bool);
277 };
278
John McCall4b9c2d22011-11-06 09:01:30 +0000279}
280
281/// Capture the given expression in an OpaqueValueExpr.
282OpaqueValueExpr *PseudoOpBuilder::capture(Expr *e) {
283 // Make a new OVE whose source is the given expression.
284 OpaqueValueExpr *captured =
285 new (S.Context) OpaqueValueExpr(GenericLoc, e->getType(),
Douglas Gregor97df54e2012-02-23 22:17:26 +0000286 e->getValueKind(), e->getObjectKind(),
287 e);
John McCall4b9c2d22011-11-06 09:01:30 +0000288
289 // Make sure we bind that in the semantics.
290 addSemanticExpr(captured);
291 return captured;
292}
293
294/// Capture the given expression as the result of this pseudo-object
295/// operation. This routine is safe against expressions which may
296/// already be captured.
297///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000298/// \returns the captured expression, which will be the
John McCall4b9c2d22011-11-06 09:01:30 +0000299/// same as the input if the input was already captured
300OpaqueValueExpr *PseudoOpBuilder::captureValueAsResult(Expr *e) {
301 assert(ResultIndex == PseudoObjectExpr::NoResult);
302
303 // If the expression hasn't already been captured, just capture it
304 // and set the new semantic
305 if (!isa<OpaqueValueExpr>(e)) {
306 OpaqueValueExpr *cap = capture(e);
307 setResultToLastSemantic();
308 return cap;
309 }
310
311 // Otherwise, it must already be one of our semantic expressions;
312 // set ResultIndex to its index.
313 unsigned index = 0;
314 for (;; ++index) {
315 assert(index < Semantics.size() &&
316 "captured expression not found in semantics!");
317 if (e == Semantics[index]) break;
318 }
319 ResultIndex = index;
320 return cast<OpaqueValueExpr>(e);
321}
322
323/// The routine which creates the final PseudoObjectExpr.
324ExprResult PseudoOpBuilder::complete(Expr *syntactic) {
325 return PseudoObjectExpr::Create(S.Context, syntactic,
326 Semantics, ResultIndex);
327}
328
329/// The main skeleton for building an r-value operation.
330ExprResult PseudoOpBuilder::buildRValueOperation(Expr *op) {
331 Expr *syntacticBase = rebuildAndCaptureObject(op);
332
333 ExprResult getExpr = buildGet();
334 if (getExpr.isInvalid()) return ExprError();
335 addResultSemanticExpr(getExpr.take());
336
337 return complete(syntacticBase);
338}
339
340/// The basic skeleton for building a simple or compound
341/// assignment operation.
342ExprResult
343PseudoOpBuilder::buildAssignmentOperation(Scope *Sc, SourceLocation opcLoc,
344 BinaryOperatorKind opcode,
345 Expr *LHS, Expr *RHS) {
346 assert(BinaryOperator::isAssignmentOp(opcode));
347
348 Expr *syntacticLHS = rebuildAndCaptureObject(LHS);
349 OpaqueValueExpr *capturedRHS = capture(RHS);
350
351 Expr *syntactic;
352
353 ExprResult result;
354 if (opcode == BO_Assign) {
355 result = capturedRHS;
356 syntactic = new (S.Context) BinaryOperator(syntacticLHS, capturedRHS,
357 opcode, capturedRHS->getType(),
358 capturedRHS->getValueKind(),
359 OK_Ordinary, opcLoc);
360 } else {
361 ExprResult opLHS = buildGet();
362 if (opLHS.isInvalid()) return ExprError();
363
364 // Build an ordinary, non-compound operation.
365 BinaryOperatorKind nonCompound =
366 BinaryOperator::getOpForCompoundAssignment(opcode);
367 result = S.BuildBinOp(Sc, opcLoc, nonCompound,
368 opLHS.take(), capturedRHS);
369 if (result.isInvalid()) return ExprError();
370
371 syntactic =
372 new (S.Context) CompoundAssignOperator(syntacticLHS, capturedRHS, opcode,
373 result.get()->getType(),
374 result.get()->getValueKind(),
375 OK_Ordinary,
376 opLHS.get()->getType(),
377 result.get()->getType(),
378 opcLoc);
379 }
380
381 // The result of the assignment, if not void, is the value set into
382 // the l-value.
383 result = buildSet(result.take(), opcLoc, assignmentsHaveResult());
384 if (result.isInvalid()) return ExprError();
385 addSemanticExpr(result.take());
386
387 return complete(syntactic);
388}
389
390/// The basic skeleton for building an increment or decrement
391/// operation.
392ExprResult
393PseudoOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
394 UnaryOperatorKind opcode,
395 Expr *op) {
396 assert(UnaryOperator::isIncrementDecrementOp(opcode));
397
398 Expr *syntacticOp = rebuildAndCaptureObject(op);
399
400 // Load the value.
401 ExprResult result = buildGet();
402 if (result.isInvalid()) return ExprError();
403
404 QualType resultType = result.get()->getType();
405
406 // That's the postfix result.
407 if (UnaryOperator::isPostfix(opcode) && assignmentsHaveResult()) {
408 result = capture(result.take());
409 setResultToLastSemantic();
410 }
411
412 // Add or subtract a literal 1.
413 llvm::APInt oneV(S.Context.getTypeSize(S.Context.IntTy), 1);
414 Expr *one = IntegerLiteral::Create(S.Context, oneV, S.Context.IntTy,
415 GenericLoc);
416
417 if (UnaryOperator::isIncrementOp(opcode)) {
418 result = S.BuildBinOp(Sc, opcLoc, BO_Add, result.take(), one);
419 } else {
420 result = S.BuildBinOp(Sc, opcLoc, BO_Sub, result.take(), one);
421 }
422 if (result.isInvalid()) return ExprError();
423
424 // Store that back into the result. The value stored is the result
425 // of a prefix operation.
426 result = buildSet(result.take(), opcLoc,
427 UnaryOperator::isPrefix(opcode) && assignmentsHaveResult());
428 if (result.isInvalid()) return ExprError();
429 addSemanticExpr(result.take());
430
431 UnaryOperator *syntactic =
432 new (S.Context) UnaryOperator(syntacticOp, opcode, resultType,
433 VK_LValue, OK_Ordinary, opcLoc);
434 return complete(syntactic);
435}
436
437
438//===----------------------------------------------------------------------===//
439// Objective-C @property and implicit property references
440//===----------------------------------------------------------------------===//
441
442/// Look up a method in the receiver type of an Objective-C property
443/// reference.
John McCall3c3b7f92011-10-25 17:37:35 +0000444static ObjCMethodDecl *LookupMethodInReceiverType(Sema &S, Selector sel,
445 const ObjCPropertyRefExpr *PRE) {
John McCall3c3b7f92011-10-25 17:37:35 +0000446 if (PRE->isObjectReceiver()) {
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000447 const ObjCObjectPointerType *PT =
448 PRE->getBase()->getType()->castAs<ObjCObjectPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +0000449
450 // Special case for 'self' in class method implementations.
451 if (PT->isObjCClassType() &&
452 S.isSelfExpr(const_cast<Expr*>(PRE->getBase()))) {
453 // This cast is safe because isSelfExpr is only true within
454 // methods.
455 ObjCMethodDecl *method =
456 cast<ObjCMethodDecl>(S.CurContext->getNonClosureAncestor());
457 return S.LookupMethodInObjectType(sel,
458 S.Context.getObjCInterfaceType(method->getClassInterface()),
459 /*instance*/ false);
460 }
461
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000462 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
John McCall3c3b7f92011-10-25 17:37:35 +0000463 }
464
Benjamin Krameraa9807a2011-10-28 13:21:18 +0000465 if (PRE->isSuperReceiver()) {
466 if (const ObjCObjectPointerType *PT =
467 PRE->getSuperReceiverType()->getAs<ObjCObjectPointerType>())
468 return S.LookupMethodInObjectType(sel, PT->getPointeeType(), true);
469
470 return S.LookupMethodInObjectType(sel, PRE->getSuperReceiverType(), false);
471 }
472
473 assert(PRE->isClassReceiver() && "Invalid expression");
474 QualType IT = S.Context.getObjCInterfaceType(PRE->getClassReceiver());
475 return S.LookupMethodInObjectType(sel, IT, false);
John McCall3c3b7f92011-10-25 17:37:35 +0000476}
477
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000478bool ObjCPropertyOpBuilder::isWeakProperty() const {
479 QualType T;
480 if (RefExpr->isExplicitProperty()) {
481 const ObjCPropertyDecl *Prop = RefExpr->getExplicitProperty();
482 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)
483 return true;
484
485 T = Prop->getType();
486 } else if (Getter) {
487 T = Getter->getResultType();
488 } else {
489 return false;
490 }
491
492 return T.getObjCLifetime() == Qualifiers::OCL_Weak;
493}
494
John McCall4b9c2d22011-11-06 09:01:30 +0000495bool ObjCPropertyOpBuilder::findGetter() {
496 if (Getter) return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000497
John McCalldc4df512011-11-07 22:49:50 +0000498 // For implicit properties, just trust the lookup we already did.
499 if (RefExpr->isImplicitProperty()) {
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000500 if ((Getter = RefExpr->getImplicitPropertyGetter())) {
501 GetterSelector = Getter->getSelector();
502 return true;
503 }
504 else {
505 // Must build the getter selector the hard way.
506 ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter();
507 assert(setter && "both setter and getter are null - cannot happen");
508 IdentifierInfo *setterName =
509 setter->getSelector().getIdentifierInfoForSlot(0);
510 const char *compStr = setterName->getNameStart();
511 compStr += 3;
512 IdentifierInfo *getterName = &S.Context.Idents.get(compStr);
513 GetterSelector =
514 S.PP.getSelectorTable().getNullarySelector(getterName);
515 return false;
516
517 }
John McCalldc4df512011-11-07 22:49:50 +0000518 }
519
520 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
521 Getter = LookupMethodInReceiverType(S, prop->getGetterName(), RefExpr);
John McCall4b9c2d22011-11-06 09:01:30 +0000522 return (Getter != 0);
523}
524
525/// Try to find the most accurate setter declaration for the property
526/// reference.
527///
528/// \return true if a setter was found, in which case Setter
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000529bool ObjCPropertyOpBuilder::findSetter(bool warn) {
John McCall4b9c2d22011-11-06 09:01:30 +0000530 // For implicit properties, just trust the lookup we already did.
531 if (RefExpr->isImplicitProperty()) {
532 if (ObjCMethodDecl *setter = RefExpr->getImplicitPropertySetter()) {
533 Setter = setter;
534 SetterSelector = setter->getSelector();
535 return true;
John McCall3c3b7f92011-10-25 17:37:35 +0000536 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000537 IdentifierInfo *getterName =
538 RefExpr->getImplicitPropertyGetter()->getSelector()
539 .getIdentifierInfoForSlot(0);
540 SetterSelector =
541 SelectorTable::constructSetterName(S.PP.getIdentifierTable(),
542 S.PP.getSelectorTable(),
543 getterName);
544 return false;
John McCall3c3b7f92011-10-25 17:37:35 +0000545 }
John McCall4b9c2d22011-11-06 09:01:30 +0000546 }
547
548 // For explicit properties, this is more involved.
549 ObjCPropertyDecl *prop = RefExpr->getExplicitProperty();
550 SetterSelector = prop->getSetterName();
551
552 // Do a normal method lookup first.
553 if (ObjCMethodDecl *setter =
554 LookupMethodInReceiverType(S, SetterSelector, RefExpr)) {
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000555 if (setter->isSynthesized() && warn)
556 if (const ObjCInterfaceDecl *IFace =
557 dyn_cast<ObjCInterfaceDecl>(setter->getDeclContext())) {
558 const StringRef thisPropertyName(prop->getName());
559 char front = thisPropertyName.front();
560 front = islower(front) ? toupper(front) : tolower(front);
561 SmallString<100> PropertyName = thisPropertyName;
562 PropertyName[0] = front;
563 IdentifierInfo *AltMember = &S.PP.getIdentifierTable().get(PropertyName);
564 if (ObjCPropertyDecl *prop1 = IFace->FindPropertyDeclaration(AltMember))
565 if (prop != prop1 && (prop1->getSetterMethodDecl() == setter)) {
Fariborz Jahaniancba0ebc2012-05-26 16:10:06 +0000566 S.Diag(RefExpr->getExprLoc(), diag::error_property_setter_ambiguous_use)
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000567 << prop->getName() << prop1->getName() << setter->getSelector();
568 S.Diag(prop->getLocation(), diag::note_property_declare);
569 S.Diag(prop1->getLocation(), diag::note_property_declare);
570 }
571 }
John McCall4b9c2d22011-11-06 09:01:30 +0000572 Setter = setter;
573 return true;
574 }
575
576 // That can fail in the somewhat crazy situation that we're
577 // type-checking a message send within the @interface declaration
578 // that declared the @property. But it's not clear that that's
579 // valuable to support.
580
581 return false;
582}
583
584/// Capture the base object of an Objective-C property expression.
585Expr *ObjCPropertyOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
586 assert(InstanceReceiver == 0);
587
588 // If we have a base, capture it in an OVE and rebuild the syntactic
589 // form to use the OVE as its base.
590 if (RefExpr->isObjectReceiver()) {
591 InstanceReceiver = capture(RefExpr->getBase());
592
593 syntacticBase =
594 ObjCPropertyRefRebuilder(S, InstanceReceiver).rebuild(syntacticBase);
595 }
596
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000597 if (ObjCPropertyRefExpr *
598 refE = dyn_cast<ObjCPropertyRefExpr>(syntacticBase->IgnoreParens()))
599 SyntacticRefExpr = refE;
600
John McCall4b9c2d22011-11-06 09:01:30 +0000601 return syntacticBase;
602}
603
604/// Load from an Objective-C property reference.
605ExprResult ObjCPropertyOpBuilder::buildGet() {
606 findGetter();
607 assert(Getter);
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000608
609 if (SyntacticRefExpr)
610 SyntacticRefExpr->setIsMessagingGetter();
611
John McCall4b9c2d22011-11-06 09:01:30 +0000612 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000613 if (RefExpr->isClassReceiver()) {
614 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
615 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000616 receiverType = RefExpr->getSuperReceiverType();
John McCall3c3b7f92011-10-25 17:37:35 +0000617 } else {
John McCall4b9c2d22011-11-06 09:01:30 +0000618 assert(InstanceReceiver);
619 receiverType = InstanceReceiver->getType();
620 }
John McCall3c3b7f92011-10-25 17:37:35 +0000621
John McCall4b9c2d22011-11-06 09:01:30 +0000622 // Build a message-send.
623 ExprResult msg;
624 if (Getter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
625 assert(InstanceReceiver || RefExpr->isSuperReceiver());
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000626 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
627 GenericLoc, Getter->getSelector(),
628 Getter, MultiExprArg());
John McCall4b9c2d22011-11-06 09:01:30 +0000629 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000630 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
631 GenericLoc,
632 Getter->getSelector(), Getter,
633 MultiExprArg());
John McCall4b9c2d22011-11-06 09:01:30 +0000634 }
635 return msg;
636}
John McCall3c3b7f92011-10-25 17:37:35 +0000637
John McCall4b9c2d22011-11-06 09:01:30 +0000638/// Store to an Objective-C property reference.
639///
Dmitri Gribenko70517ca2012-08-23 17:58:28 +0000640/// \param captureSetValueAsResult If true, capture the actual
John McCall4b9c2d22011-11-06 09:01:30 +0000641/// value being set as the value of the property operation.
642ExprResult ObjCPropertyOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
643 bool captureSetValueAsResult) {
Fariborz Jahanianb5b155c2012-05-24 22:48:38 +0000644 bool hasSetter = findSetter(false);
John McCall4b9c2d22011-11-06 09:01:30 +0000645 assert(hasSetter); (void) hasSetter;
646
Argyrios Kyrtzidisb085d892012-03-30 00:19:18 +0000647 if (SyntacticRefExpr)
648 SyntacticRefExpr->setIsMessagingSetter();
649
John McCall4b9c2d22011-11-06 09:01:30 +0000650 QualType receiverType;
John McCall4b9c2d22011-11-06 09:01:30 +0000651 if (RefExpr->isClassReceiver()) {
652 receiverType = S.Context.getObjCInterfaceType(RefExpr->getClassReceiver());
653 } else if (RefExpr->isSuperReceiver()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000654 receiverType = RefExpr->getSuperReceiverType();
655 } else {
656 assert(InstanceReceiver);
657 receiverType = InstanceReceiver->getType();
658 }
659
660 // Use assignment constraints when possible; they give us better
661 // diagnostics. "When possible" basically means anything except a
662 // C++ class type.
David Blaikie4e4d0842012-03-11 07:00:24 +0000663 if (!S.getLangOpts().CPlusPlus || !op->getType()->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000664 QualType paramType = (*Setter->param_begin())->getType();
David Blaikie4e4d0842012-03-11 07:00:24 +0000665 if (!S.getLangOpts().CPlusPlus || !paramType->isRecordType()) {
John McCall4b9c2d22011-11-06 09:01:30 +0000666 ExprResult opResult = op;
667 Sema::AssignConvertType assignResult
668 = S.CheckSingleAssignmentConstraints(paramType, opResult);
669 if (S.DiagnoseAssignmentResult(assignResult, opcLoc, paramType,
670 op->getType(), opResult.get(),
671 Sema::AA_Assigning))
672 return ExprError();
673
674 op = opResult.take();
675 assert(op && "successful assignment left argument invalid?");
John McCall3c3b7f92011-10-25 17:37:35 +0000676 }
677 }
678
John McCall4b9c2d22011-11-06 09:01:30 +0000679 // Arguments.
680 Expr *args[] = { op };
John McCall3c3b7f92011-10-25 17:37:35 +0000681
John McCall4b9c2d22011-11-06 09:01:30 +0000682 // Build a message-send.
683 ExprResult msg;
684 if (Setter->isInstanceMethod() || RefExpr->isObjectReceiver()) {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000685 msg = S.BuildInstanceMessageImplicit(InstanceReceiver, receiverType,
686 GenericLoc, SetterSelector, Setter,
687 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000688 } else {
Argyrios Kyrtzidis746f5bc2012-01-12 02:34:39 +0000689 msg = S.BuildClassMessageImplicit(receiverType, RefExpr->isSuperReceiver(),
690 GenericLoc,
691 SetterSelector, Setter,
692 MultiExprArg(args, 1));
John McCall4b9c2d22011-11-06 09:01:30 +0000693 }
694
695 if (!msg.isInvalid() && captureSetValueAsResult) {
696 ObjCMessageExpr *msgExpr =
697 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
698 Expr *arg = msgExpr->getArg(0);
699 msgExpr->setArg(0, captureValueAsResult(arg));
700 }
701
702 return msg;
John McCall3c3b7f92011-10-25 17:37:35 +0000703}
704
John McCall4b9c2d22011-11-06 09:01:30 +0000705/// @property-specific behavior for doing lvalue-to-rvalue conversion.
706ExprResult ObjCPropertyOpBuilder::buildRValueOperation(Expr *op) {
707 // Explicit properties always have getters, but implicit ones don't.
708 // Check that before proceeding.
709 if (RefExpr->isImplicitProperty() &&
710 !RefExpr->getImplicitPropertyGetter()) {
711 S.Diag(RefExpr->getLocation(), diag::err_getter_not_found)
712 << RefExpr->getBase()->getType();
John McCall3c3b7f92011-10-25 17:37:35 +0000713 return ExprError();
714 }
715
John McCall4b9c2d22011-11-06 09:01:30 +0000716 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
John McCall3c3b7f92011-10-25 17:37:35 +0000717 if (result.isInvalid()) return ExprError();
718
John McCall4b9c2d22011-11-06 09:01:30 +0000719 if (RefExpr->isExplicitProperty() && !Getter->hasRelatedResultType())
720 S.DiagnosePropertyAccessorMismatch(RefExpr->getExplicitProperty(),
721 Getter, RefExpr->getLocation());
722
723 // As a special case, if the method returns 'id', try to get
724 // a better type from the property.
725 if (RefExpr->isExplicitProperty() && result.get()->isRValue() &&
726 result.get()->getType()->isObjCIdType()) {
727 QualType propType = RefExpr->getExplicitProperty()->getType();
728 if (const ObjCObjectPointerType *ptr
729 = propType->getAs<ObjCObjectPointerType>()) {
730 if (!ptr->isObjCIdType())
731 result = S.ImpCastExprToType(result.get(), propType, CK_BitCast);
732 }
733 }
734
John McCall3c3b7f92011-10-25 17:37:35 +0000735 return result;
736}
737
John McCall4b9c2d22011-11-06 09:01:30 +0000738/// Try to build this as a call to a getter that returns a reference.
739///
740/// \return true if it was possible, whether or not it actually
741/// succeeded
742bool ObjCPropertyOpBuilder::tryBuildGetOfReference(Expr *op,
743 ExprResult &result) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000744 if (!S.getLangOpts().CPlusPlus) return false;
John McCall4b9c2d22011-11-06 09:01:30 +0000745
746 findGetter();
747 assert(Getter && "property has no setter and no getter!");
748
749 // Only do this if the getter returns an l-value reference type.
750 QualType resultType = Getter->getResultType();
751 if (!resultType->isLValueReferenceType()) return false;
752
753 result = buildRValueOperation(op);
754 return true;
755}
756
757/// @property-specific behavior for doing assignments.
758ExprResult
759ObjCPropertyOpBuilder::buildAssignmentOperation(Scope *Sc,
760 SourceLocation opcLoc,
761 BinaryOperatorKind opcode,
762 Expr *LHS, Expr *RHS) {
John McCall3c3b7f92011-10-25 17:37:35 +0000763 assert(BinaryOperator::isAssignmentOp(opcode));
John McCall3c3b7f92011-10-25 17:37:35 +0000764
765 // If there's no setter, we have no choice but to try to assign to
766 // the result of the getter.
John McCall4b9c2d22011-11-06 09:01:30 +0000767 if (!findSetter()) {
768 ExprResult result;
769 if (tryBuildGetOfReference(LHS, result)) {
770 if (result.isInvalid()) return ExprError();
771 return S.BuildBinOp(Sc, opcLoc, opcode, result.take(), RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000772 }
773
774 // Otherwise, it's an error.
John McCall4b9c2d22011-11-06 09:01:30 +0000775 S.Diag(opcLoc, diag::err_nosetter_property_assignment)
776 << unsigned(RefExpr->isImplicitProperty())
777 << SetterSelector
John McCall3c3b7f92011-10-25 17:37:35 +0000778 << LHS->getSourceRange() << RHS->getSourceRange();
779 return ExprError();
780 }
781
782 // If there is a setter, we definitely want to use it.
783
John McCall4b9c2d22011-11-06 09:01:30 +0000784 // Verify that we can do a compound assignment.
785 if (opcode != BO_Assign && !findGetter()) {
786 S.Diag(opcLoc, diag::err_nogetter_property_compound_assignment)
John McCall3c3b7f92011-10-25 17:37:35 +0000787 << LHS->getSourceRange() << RHS->getSourceRange();
788 return ExprError();
789 }
790
John McCall4b9c2d22011-11-06 09:01:30 +0000791 ExprResult result =
792 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
John McCall3c3b7f92011-10-25 17:37:35 +0000793 if (result.isInvalid()) return ExprError();
794
John McCall4b9c2d22011-11-06 09:01:30 +0000795 // Various warnings about property assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000796 if (S.getLangOpts().ObjCAutoRefCount && InstanceReceiver) {
John McCall4b9c2d22011-11-06 09:01:30 +0000797 S.checkRetainCycles(InstanceReceiver->getSourceExpr(), RHS);
798 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
799 }
800
John McCall3c3b7f92011-10-25 17:37:35 +0000801 return result;
802}
John McCall4b9c2d22011-11-06 09:01:30 +0000803
804/// @property-specific behavior for doing increments and decrements.
805ExprResult
806ObjCPropertyOpBuilder::buildIncDecOperation(Scope *Sc, SourceLocation opcLoc,
807 UnaryOperatorKind opcode,
808 Expr *op) {
809 // If there's no setter, we have no choice but to try to assign to
810 // the result of the getter.
811 if (!findSetter()) {
812 ExprResult result;
813 if (tryBuildGetOfReference(op, result)) {
814 if (result.isInvalid()) return ExprError();
815 return S.BuildUnaryOp(Sc, opcLoc, opcode, result.take());
816 }
817
818 // Otherwise, it's an error.
819 S.Diag(opcLoc, diag::err_nosetter_property_incdec)
820 << unsigned(RefExpr->isImplicitProperty())
821 << unsigned(UnaryOperator::isDecrementOp(opcode))
822 << SetterSelector
823 << op->getSourceRange();
824 return ExprError();
825 }
826
827 // If there is a setter, we definitely want to use it.
828
829 // We also need a getter.
830 if (!findGetter()) {
831 assert(RefExpr->isImplicitProperty());
832 S.Diag(opcLoc, diag::err_nogetter_property_incdec)
833 << unsigned(UnaryOperator::isDecrementOp(opcode))
Fariborz Jahaniana2c91e72012-04-18 19:13:23 +0000834 << GetterSelector
John McCall4b9c2d22011-11-06 09:01:30 +0000835 << op->getSourceRange();
836 return ExprError();
837 }
838
839 return PseudoOpBuilder::buildIncDecOperation(Sc, opcLoc, opcode, op);
840}
841
Jordan Rose58b6bdc2012-09-28 22:21:30 +0000842ExprResult ObjCPropertyOpBuilder::complete(Expr *SyntacticForm) {
843 if (S.getLangOpts().ObjCAutoRefCount && isWeakProperty()) {
844 DiagnosticsEngine::Level Level =
845 S.Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
846 SyntacticForm->getLocStart());
847 if (Level != DiagnosticsEngine::Ignored)
848 S.getCurFunction()->recordUseOfWeak(SyntacticRefExpr);
849 }
850
851 return PseudoOpBuilder::complete(SyntacticForm);
852}
853
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000854// ObjCSubscript build stuff.
855//
856
857/// objective-c subscripting-specific behavior for doing lvalue-to-rvalue
858/// conversion.
859/// FIXME. Remove this routine if it is proven that no additional
860/// specifity is needed.
861ExprResult ObjCSubscriptOpBuilder::buildRValueOperation(Expr *op) {
862 ExprResult result = PseudoOpBuilder::buildRValueOperation(op);
863 if (result.isInvalid()) return ExprError();
864 return result;
865}
866
867/// objective-c subscripting-specific behavior for doing assignments.
868ExprResult
869ObjCSubscriptOpBuilder::buildAssignmentOperation(Scope *Sc,
870 SourceLocation opcLoc,
871 BinaryOperatorKind opcode,
872 Expr *LHS, Expr *RHS) {
873 assert(BinaryOperator::isAssignmentOp(opcode));
874 // There must be a method to do the Index'ed assignment.
875 if (!findAtIndexSetter())
876 return ExprError();
877
878 // Verify that we can do a compound assignment.
879 if (opcode != BO_Assign && !findAtIndexGetter())
880 return ExprError();
881
882 ExprResult result =
883 PseudoOpBuilder::buildAssignmentOperation(Sc, opcLoc, opcode, LHS, RHS);
884 if (result.isInvalid()) return ExprError();
885
886 // Various warnings about objc Index'ed assignments in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +0000887 if (S.getLangOpts().ObjCAutoRefCount && InstanceBase) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000888 S.checkRetainCycles(InstanceBase->getSourceExpr(), RHS);
889 S.checkUnsafeExprAssigns(opcLoc, LHS, RHS);
890 }
891
892 return result;
893}
894
895/// Capture the base object of an Objective-C Index'ed expression.
896Expr *ObjCSubscriptOpBuilder::rebuildAndCaptureObject(Expr *syntacticBase) {
897 assert(InstanceBase == 0);
898
899 // Capture base expression in an OVE and rebuild the syntactic
900 // form to use the OVE as its base expression.
901 InstanceBase = capture(RefExpr->getBaseExpr());
902 InstanceKey = capture(RefExpr->getKeyExpr());
903
904 syntacticBase =
905 ObjCSubscriptRefRebuilder(S, InstanceBase,
906 InstanceKey).rebuild(syntacticBase);
907
908 return syntacticBase;
909}
910
911/// CheckSubscriptingKind - This routine decide what type
912/// of indexing represented by "FromE" is being done.
913Sema::ObjCSubscriptKind
914 Sema::CheckSubscriptingKind(Expr *FromE) {
915 // If the expression already has integral or enumeration type, we're golden.
916 QualType T = FromE->getType();
917 if (T->isIntegralOrEnumerationType())
918 return OS_Array;
919
920 // If we don't have a class type in C++, there's no way we can get an
921 // expression of integral or enumeration type.
922 const RecordType *RecordTy = T->getAs<RecordType>();
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000923 if (!RecordTy && T->isObjCObjectPointerType())
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000924 // All other scalar cases are assumed to be dictionary indexing which
925 // caller handles, with diagnostics if needed.
926 return OS_Dictionary;
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000927 if (!getLangOpts().CPlusPlus ||
928 !RecordTy || RecordTy->isIncompleteType()) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000929 // No indexing can be done. Issue diagnostics and quit.
Fariborz Jahaniana78eca22012-03-28 17:56:49 +0000930 const Expr *IndexExpr = FromE->IgnoreParenImpCasts();
931 if (isa<StringLiteral>(IndexExpr))
932 Diag(FromE->getExprLoc(), diag::err_objc_subscript_pointer)
933 << T << FixItHint::CreateInsertion(FromE->getExprLoc(), "@");
934 else
935 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
936 << T;
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000937 return OS_Error;
938 }
939
940 // We must have a complete class type.
941 if (RequireCompleteType(FromE->getExprLoc(), T,
Douglas Gregord10099e2012-05-04 16:32:21 +0000942 diag::err_objc_index_incomplete_class_type, FromE))
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000943 return OS_Error;
944
945 // Look for a conversion to an integral, enumeration type, or
946 // objective-C pointer type.
947 UnresolvedSet<4> ViableConversions;
948 UnresolvedSet<4> ExplicitConversions;
949 const UnresolvedSetImpl *Conversions
950 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
951
952 int NoIntegrals=0, NoObjCIdPointers=0;
953 SmallVector<CXXConversionDecl *, 4> ConversionDecls;
954
955 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
956 E = Conversions->end();
957 I != E;
958 ++I) {
959 if (CXXConversionDecl *Conversion
960 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl())) {
961 QualType CT = Conversion->getConversionType().getNonReferenceType();
962 if (CT->isIntegralOrEnumerationType()) {
963 ++NoIntegrals;
964 ConversionDecls.push_back(Conversion);
965 }
966 else if (CT->isObjCIdType() ||CT->isBlockPointerType()) {
967 ++NoObjCIdPointers;
968 ConversionDecls.push_back(Conversion);
969 }
970 }
971 }
972 if (NoIntegrals ==1 && NoObjCIdPointers == 0)
973 return OS_Array;
974 if (NoIntegrals == 0 && NoObjCIdPointers == 1)
975 return OS_Dictionary;
976 if (NoIntegrals == 0 && NoObjCIdPointers == 0) {
977 // No conversion function was found. Issue diagnostic and return.
978 Diag(FromE->getExprLoc(), diag::err_objc_subscript_type_conversion)
979 << FromE->getType();
980 return OS_Error;
981 }
982 Diag(FromE->getExprLoc(), diag::err_objc_multiple_subscript_type_conversion)
983 << FromE->getType();
984 for (unsigned int i = 0; i < ConversionDecls.size(); i++)
985 Diag(ConversionDecls[i]->getLocation(), diag::not_conv_function_declared_at);
986
987 return OS_Error;
988}
989
Fariborz Jahaniandc483052012-08-02 18:03:58 +0000990/// CheckKeyForObjCARCConversion - This routine suggests bridge casting of CF
991/// objects used as dictionary subscript key objects.
992static void CheckKeyForObjCARCConversion(Sema &S, QualType ContainerT,
993 Expr *Key) {
994 if (ContainerT.isNull())
995 return;
996 // dictionary subscripting.
997 // - (id)objectForKeyedSubscript:(id)key;
998 IdentifierInfo *KeyIdents[] = {
999 &S.Context.Idents.get("objectForKeyedSubscript")
1000 };
1001 Selector GetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1002 ObjCMethodDecl *Getter = S.LookupMethodInObjectType(GetterSelector, ContainerT,
1003 true /*instance*/);
1004 if (!Getter)
1005 return;
1006 QualType T = Getter->param_begin()[0]->getType();
1007 S.CheckObjCARCConversion(Key->getSourceRange(),
1008 T, Key, Sema::CCK_ImplicitConversion);
1009}
1010
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001011bool ObjCSubscriptOpBuilder::findAtIndexGetter() {
1012 if (AtIndexGetter)
1013 return true;
1014
1015 Expr *BaseExpr = RefExpr->getBaseExpr();
1016 QualType BaseT = BaseExpr->getType();
1017
1018 QualType ResultType;
1019 if (const ObjCObjectPointerType *PTy =
1020 BaseT->getAs<ObjCObjectPointerType>()) {
1021 ResultType = PTy->getPointeeType();
1022 if (const ObjCObjectType *iQFaceTy =
1023 ResultType->getAsObjCQualifiedInterfaceType())
1024 ResultType = iQFaceTy->getBaseType();
1025 }
1026 Sema::ObjCSubscriptKind Res =
1027 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001028 if (Res == Sema::OS_Error) {
1029 if (S.getLangOpts().ObjCAutoRefCount)
1030 CheckKeyForObjCARCConversion(S, ResultType,
1031 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001032 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001033 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001034 bool arrayRef = (Res == Sema::OS_Array);
1035
1036 if (ResultType.isNull()) {
1037 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1038 << BaseExpr->getType() << arrayRef;
1039 return false;
1040 }
1041 if (!arrayRef) {
1042 // dictionary subscripting.
1043 // - (id)objectForKeyedSubscript:(id)key;
1044 IdentifierInfo *KeyIdents[] = {
1045 &S.Context.Idents.get("objectForKeyedSubscript")
1046 };
1047 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1048 }
1049 else {
1050 // - (id)objectAtIndexedSubscript:(size_t)index;
1051 IdentifierInfo *KeyIdents[] = {
1052 &S.Context.Idents.get("objectAtIndexedSubscript")
1053 };
1054
1055 AtIndexGetterSelector = S.Context.Selectors.getSelector(1, KeyIdents);
1056 }
1057
1058 AtIndexGetter = S.LookupMethodInObjectType(AtIndexGetterSelector, ResultType,
1059 true /*instance*/);
1060 bool receiverIdType = (BaseT->isObjCIdType() ||
1061 BaseT->isObjCQualifiedIdType());
1062
David Blaikie4e4d0842012-03-11 07:00:24 +00001063 if (!AtIndexGetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001064 AtIndexGetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1065 SourceLocation(), AtIndexGetterSelector,
1066 S.Context.getObjCIdType() /*ReturnType*/,
1067 0 /*TypeSourceInfo */,
1068 S.Context.getTranslationUnitDecl(),
1069 true /*Instance*/, false/*isVariadic*/,
1070 /*isSynthesized=*/false,
1071 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1072 ObjCMethodDecl::Required,
1073 false);
1074 ParmVarDecl *Argument = ParmVarDecl::Create(S.Context, AtIndexGetter,
1075 SourceLocation(), SourceLocation(),
1076 arrayRef ? &S.Context.Idents.get("index")
1077 : &S.Context.Idents.get("key"),
1078 arrayRef ? S.Context.UnsignedLongTy
1079 : S.Context.getObjCIdType(),
1080 /*TInfo=*/0,
1081 SC_None,
1082 SC_None,
1083 0);
1084 AtIndexGetter->setMethodParams(S.Context, Argument,
1085 ArrayRef<SourceLocation>());
1086 }
1087
1088 if (!AtIndexGetter) {
1089 if (!receiverIdType) {
1090 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_method_not_found)
1091 << BaseExpr->getType() << 0 << arrayRef;
1092 return false;
1093 }
1094 AtIndexGetter =
1095 S.LookupInstanceMethodInGlobalPool(AtIndexGetterSelector,
1096 RefExpr->getSourceRange(),
1097 true, false);
1098 }
1099
1100 if (AtIndexGetter) {
1101 QualType T = AtIndexGetter->param_begin()[0]->getType();
1102 if ((arrayRef && !T->isIntegralOrEnumerationType()) ||
1103 (!arrayRef && !T->isObjCObjectPointerType())) {
1104 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1105 arrayRef ? diag::err_objc_subscript_index_type
1106 : diag::err_objc_subscript_key_type) << T;
1107 S.Diag(AtIndexGetter->param_begin()[0]->getLocation(),
1108 diag::note_parameter_type) << T;
1109 return false;
1110 }
1111 QualType R = AtIndexGetter->getResultType();
1112 if (!R->isObjCObjectPointerType()) {
1113 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1114 diag::err_objc_indexing_method_result_type) << R << arrayRef;
1115 S.Diag(AtIndexGetter->getLocation(), diag::note_method_declared_at) <<
1116 AtIndexGetter->getDeclName();
1117 }
1118 }
1119 return true;
1120}
1121
1122bool ObjCSubscriptOpBuilder::findAtIndexSetter() {
1123 if (AtIndexSetter)
1124 return true;
1125
1126 Expr *BaseExpr = RefExpr->getBaseExpr();
1127 QualType BaseT = BaseExpr->getType();
1128
1129 QualType ResultType;
1130 if (const ObjCObjectPointerType *PTy =
1131 BaseT->getAs<ObjCObjectPointerType>()) {
1132 ResultType = PTy->getPointeeType();
1133 if (const ObjCObjectType *iQFaceTy =
1134 ResultType->getAsObjCQualifiedInterfaceType())
1135 ResultType = iQFaceTy->getBaseType();
1136 }
1137
1138 Sema::ObjCSubscriptKind Res =
1139 S.CheckSubscriptingKind(RefExpr->getKeyExpr());
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001140 if (Res == Sema::OS_Error) {
1141 if (S.getLangOpts().ObjCAutoRefCount)
1142 CheckKeyForObjCARCConversion(S, ResultType,
1143 RefExpr->getKeyExpr());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001144 return false;
Fariborz Jahaniandc483052012-08-02 18:03:58 +00001145 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001146 bool arrayRef = (Res == Sema::OS_Array);
1147
1148 if (ResultType.isNull()) {
1149 S.Diag(BaseExpr->getExprLoc(), diag::err_objc_subscript_base_type)
1150 << BaseExpr->getType() << arrayRef;
1151 return false;
1152 }
1153
1154 if (!arrayRef) {
1155 // dictionary subscripting.
1156 // - (void)setObject:(id)object forKeyedSubscript:(id)key;
1157 IdentifierInfo *KeyIdents[] = {
1158 &S.Context.Idents.get("setObject"),
1159 &S.Context.Idents.get("forKeyedSubscript")
1160 };
1161 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1162 }
1163 else {
1164 // - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
1165 IdentifierInfo *KeyIdents[] = {
1166 &S.Context.Idents.get("setObject"),
1167 &S.Context.Idents.get("atIndexedSubscript")
1168 };
1169 AtIndexSetterSelector = S.Context.Selectors.getSelector(2, KeyIdents);
1170 }
1171 AtIndexSetter = S.LookupMethodInObjectType(AtIndexSetterSelector, ResultType,
1172 true /*instance*/);
1173
1174 bool receiverIdType = (BaseT->isObjCIdType() ||
1175 BaseT->isObjCQualifiedIdType());
1176
David Blaikie4e4d0842012-03-11 07:00:24 +00001177 if (!AtIndexSetter && S.getLangOpts().DebuggerObjCLiteral) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001178 TypeSourceInfo *ResultTInfo = 0;
1179 QualType ReturnType = S.Context.VoidTy;
1180 AtIndexSetter = ObjCMethodDecl::Create(S.Context, SourceLocation(),
1181 SourceLocation(), AtIndexSetterSelector,
1182 ReturnType,
1183 ResultTInfo,
1184 S.Context.getTranslationUnitDecl(),
1185 true /*Instance*/, false/*isVariadic*/,
1186 /*isSynthesized=*/false,
1187 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1188 ObjCMethodDecl::Required,
1189 false);
1190 SmallVector<ParmVarDecl *, 2> Params;
1191 ParmVarDecl *object = ParmVarDecl::Create(S.Context, AtIndexSetter,
1192 SourceLocation(), SourceLocation(),
1193 &S.Context.Idents.get("object"),
1194 S.Context.getObjCIdType(),
1195 /*TInfo=*/0,
1196 SC_None,
1197 SC_None,
1198 0);
1199 Params.push_back(object);
1200 ParmVarDecl *key = ParmVarDecl::Create(S.Context, AtIndexSetter,
1201 SourceLocation(), SourceLocation(),
1202 arrayRef ? &S.Context.Idents.get("index")
1203 : &S.Context.Idents.get("key"),
1204 arrayRef ? S.Context.UnsignedLongTy
1205 : S.Context.getObjCIdType(),
1206 /*TInfo=*/0,
1207 SC_None,
1208 SC_None,
1209 0);
1210 Params.push_back(key);
1211 AtIndexSetter->setMethodParams(S.Context, Params, ArrayRef<SourceLocation>());
1212 }
1213
1214 if (!AtIndexSetter) {
1215 if (!receiverIdType) {
1216 S.Diag(BaseExpr->getExprLoc(),
1217 diag::err_objc_subscript_method_not_found)
1218 << BaseExpr->getType() << 1 << arrayRef;
1219 return false;
1220 }
1221 AtIndexSetter =
1222 S.LookupInstanceMethodInGlobalPool(AtIndexSetterSelector,
1223 RefExpr->getSourceRange(),
1224 true, false);
1225 }
1226
1227 bool err = false;
1228 if (AtIndexSetter && arrayRef) {
1229 QualType T = AtIndexSetter->param_begin()[1]->getType();
1230 if (!T->isIntegralOrEnumerationType()) {
1231 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1232 diag::err_objc_subscript_index_type) << T;
1233 S.Diag(AtIndexSetter->param_begin()[1]->getLocation(),
1234 diag::note_parameter_type) << T;
1235 err = true;
1236 }
1237 T = AtIndexSetter->param_begin()[0]->getType();
1238 if (!T->isObjCObjectPointerType()) {
1239 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1240 diag::err_objc_subscript_object_type) << T << arrayRef;
1241 S.Diag(AtIndexSetter->param_begin()[0]->getLocation(),
1242 diag::note_parameter_type) << T;
1243 err = true;
1244 }
1245 }
1246 else if (AtIndexSetter && !arrayRef)
1247 for (unsigned i=0; i <2; i++) {
1248 QualType T = AtIndexSetter->param_begin()[i]->getType();
1249 if (!T->isObjCObjectPointerType()) {
1250 if (i == 1)
1251 S.Diag(RefExpr->getKeyExpr()->getExprLoc(),
1252 diag::err_objc_subscript_key_type) << T;
1253 else
1254 S.Diag(RefExpr->getBaseExpr()->getExprLoc(),
1255 diag::err_objc_subscript_dic_object_type) << T;
1256 S.Diag(AtIndexSetter->param_begin()[i]->getLocation(),
1257 diag::note_parameter_type) << T;
1258 err = true;
1259 }
1260 }
1261
1262 return !err;
1263}
1264
1265// Get the object at "Index" position in the container.
1266// [BaseExpr objectAtIndexedSubscript : IndexExpr];
1267ExprResult ObjCSubscriptOpBuilder::buildGet() {
1268 if (!findAtIndexGetter())
1269 return ExprError();
1270
1271 QualType receiverType = InstanceBase->getType();
1272
1273 // Build a message-send.
1274 ExprResult msg;
1275 Expr *Index = InstanceKey;
1276
1277 // Arguments.
1278 Expr *args[] = { Index };
1279 assert(InstanceBase);
1280 msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1281 GenericLoc,
1282 AtIndexGetterSelector, AtIndexGetter,
1283 MultiExprArg(args, 1));
1284 return msg;
1285}
1286
1287/// Store into the container the "op" object at "Index"'ed location
1288/// by building this messaging expression:
1289/// - (void)setObject:(id)object atIndexedSubscript:(NSInteger)index;
Dmitri Gribenko70517ca2012-08-23 17:58:28 +00001290/// \param captureSetValueAsResult If true, capture the actual
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001291/// value being set as the value of the property operation.
1292ExprResult ObjCSubscriptOpBuilder::buildSet(Expr *op, SourceLocation opcLoc,
1293 bool captureSetValueAsResult) {
1294 if (!findAtIndexSetter())
1295 return ExprError();
1296
1297 QualType receiverType = InstanceBase->getType();
1298 Expr *Index = InstanceKey;
1299
1300 // Arguments.
1301 Expr *args[] = { op, Index };
1302
1303 // Build a message-send.
1304 ExprResult msg = S.BuildInstanceMessageImplicit(InstanceBase, receiverType,
1305 GenericLoc,
1306 AtIndexSetterSelector,
1307 AtIndexSetter,
1308 MultiExprArg(args, 2));
1309
1310 if (!msg.isInvalid() && captureSetValueAsResult) {
1311 ObjCMessageExpr *msgExpr =
1312 cast<ObjCMessageExpr>(msg.get()->IgnoreImplicit());
1313 Expr *arg = msgExpr->getArg(0);
1314 msgExpr->setArg(0, captureValueAsResult(arg));
1315 }
1316
1317 return msg;
1318}
1319
John McCall4b9c2d22011-11-06 09:01:30 +00001320//===----------------------------------------------------------------------===//
1321// General Sema routines.
1322//===----------------------------------------------------------------------===//
1323
1324ExprResult Sema::checkPseudoObjectRValue(Expr *E) {
1325 Expr *opaqueRef = E->IgnoreParens();
1326 if (ObjCPropertyRefExpr *refExpr
1327 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1328 ObjCPropertyOpBuilder builder(*this, refExpr);
1329 return builder.buildRValueOperation(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001330 }
1331 else if (ObjCSubscriptRefExpr *refExpr
1332 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1333 ObjCSubscriptOpBuilder builder(*this, refExpr);
1334 return builder.buildRValueOperation(E);
John McCall4b9c2d22011-11-06 09:01:30 +00001335 } else {
1336 llvm_unreachable("unknown pseudo-object kind!");
1337 }
1338}
1339
1340/// Check an increment or decrement of a pseudo-object expression.
1341ExprResult Sema::checkPseudoObjectIncDec(Scope *Sc, SourceLocation opcLoc,
1342 UnaryOperatorKind opcode, Expr *op) {
1343 // Do nothing if the operand is dependent.
1344 if (op->isTypeDependent())
1345 return new (Context) UnaryOperator(op, opcode, Context.DependentTy,
1346 VK_RValue, OK_Ordinary, opcLoc);
1347
1348 assert(UnaryOperator::isIncrementDecrementOp(opcode));
1349 Expr *opaqueRef = op->IgnoreParens();
1350 if (ObjCPropertyRefExpr *refExpr
1351 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1352 ObjCPropertyOpBuilder builder(*this, refExpr);
1353 return builder.buildIncDecOperation(Sc, opcLoc, opcode, op);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001354 } else if (isa<ObjCSubscriptRefExpr>(opaqueRef)) {
1355 Diag(opcLoc, diag::err_illegal_container_subscripting_op);
1356 return ExprError();
John McCall4b9c2d22011-11-06 09:01:30 +00001357 } else {
1358 llvm_unreachable("unknown pseudo-object kind!");
1359 }
1360}
1361
1362ExprResult Sema::checkPseudoObjectAssignment(Scope *S, SourceLocation opcLoc,
1363 BinaryOperatorKind opcode,
1364 Expr *LHS, Expr *RHS) {
1365 // Do nothing if either argument is dependent.
1366 if (LHS->isTypeDependent() || RHS->isTypeDependent())
1367 return new (Context) BinaryOperator(LHS, RHS, opcode, Context.DependentTy,
1368 VK_RValue, OK_Ordinary, opcLoc);
1369
1370 // Filter out non-overload placeholder types in the RHS.
John McCall32509f12011-11-15 01:35:18 +00001371 if (RHS->getType()->isNonOverloadPlaceholderType()) {
1372 ExprResult result = CheckPlaceholderExpr(RHS);
1373 if (result.isInvalid()) return ExprError();
1374 RHS = result.take();
John McCall4b9c2d22011-11-06 09:01:30 +00001375 }
1376
1377 Expr *opaqueRef = LHS->IgnoreParens();
1378 if (ObjCPropertyRefExpr *refExpr
1379 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
1380 ObjCPropertyOpBuilder builder(*this, refExpr);
1381 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001382 } else if (ObjCSubscriptRefExpr *refExpr
1383 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1384 ObjCSubscriptOpBuilder builder(*this, refExpr);
1385 return builder.buildAssignmentOperation(S, opcLoc, opcode, LHS, RHS);
John McCall4b9c2d22011-11-06 09:01:30 +00001386 } else {
1387 llvm_unreachable("unknown pseudo-object kind!");
1388 }
1389}
John McCall01e19be2011-11-30 04:42:31 +00001390
1391/// Given a pseudo-object reference, rebuild it without the opaque
1392/// values. Basically, undo the behavior of rebuildAndCaptureObject.
1393/// This should never operate in-place.
1394static Expr *stripOpaqueValuesFromPseudoObjectRef(Sema &S, Expr *E) {
1395 Expr *opaqueRef = E->IgnoreParens();
1396 if (ObjCPropertyRefExpr *refExpr
1397 = dyn_cast<ObjCPropertyRefExpr>(opaqueRef)) {
Douglas Gregor88507dd2012-04-13 16:05:42 +00001398 // Class and super property references don't have opaque values in them.
1399 if (refExpr->isClassReceiver() || refExpr->isSuperReceiver())
1400 return E;
1401
1402 assert(refExpr->isObjectReceiver() && "Unknown receiver kind?");
1403 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBase());
1404 return ObjCPropertyRefRebuilder(S, baseOVE->getSourceExpr()).rebuild(E);
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001405 } else if (ObjCSubscriptRefExpr *refExpr
1406 = dyn_cast<ObjCSubscriptRefExpr>(opaqueRef)) {
1407 OpaqueValueExpr *baseOVE = cast<OpaqueValueExpr>(refExpr->getBaseExpr());
1408 OpaqueValueExpr *keyOVE = cast<OpaqueValueExpr>(refExpr->getKeyExpr());
1409 return ObjCSubscriptRefRebuilder(S, baseOVE->getSourceExpr(),
1410 keyOVE->getSourceExpr()).rebuild(E);
John McCall01e19be2011-11-30 04:42:31 +00001411 } else {
1412 llvm_unreachable("unknown pseudo-object kind!");
1413 }
1414}
1415
1416/// Given a pseudo-object expression, recreate what it looks like
1417/// syntactically without the attendant OpaqueValueExprs.
1418///
1419/// This is a hack which should be removed when TreeTransform is
1420/// capable of rebuilding a tree without stripping implicit
1421/// operations.
1422Expr *Sema::recreateSyntacticForm(PseudoObjectExpr *E) {
1423 Expr *syntax = E->getSyntacticForm();
1424 if (UnaryOperator *uop = dyn_cast<UnaryOperator>(syntax)) {
1425 Expr *op = stripOpaqueValuesFromPseudoObjectRef(*this, uop->getSubExpr());
1426 return new (Context) UnaryOperator(op, uop->getOpcode(), uop->getType(),
1427 uop->getValueKind(), uop->getObjectKind(),
1428 uop->getOperatorLoc());
1429 } else if (CompoundAssignOperator *cop
1430 = dyn_cast<CompoundAssignOperator>(syntax)) {
1431 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, cop->getLHS());
1432 Expr *rhs = cast<OpaqueValueExpr>(cop->getRHS())->getSourceExpr();
1433 return new (Context) CompoundAssignOperator(lhs, rhs, cop->getOpcode(),
1434 cop->getType(),
1435 cop->getValueKind(),
1436 cop->getObjectKind(),
1437 cop->getComputationLHSType(),
1438 cop->getComputationResultType(),
1439 cop->getOperatorLoc());
1440 } else if (BinaryOperator *bop = dyn_cast<BinaryOperator>(syntax)) {
1441 Expr *lhs = stripOpaqueValuesFromPseudoObjectRef(*this, bop->getLHS());
1442 Expr *rhs = cast<OpaqueValueExpr>(bop->getRHS())->getSourceExpr();
1443 return new (Context) BinaryOperator(lhs, rhs, bop->getOpcode(),
1444 bop->getType(), bop->getValueKind(),
1445 bop->getObjectKind(),
1446 bop->getOperatorLoc());
1447 } else {
1448 assert(syntax->hasPlaceholderType(BuiltinType::PseudoObject));
1449 return stripOpaqueValuesFromPseudoObjectRef(*this, syntax);
1450 }
1451}