blob: f1047bd3b9a11b20873a68c02389ead3d9900769 [file] [log] [blame]
Anders Carlsson76f4a902007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Anders Carlsson76f4a902007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Pateld2d66652011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek43e06332008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCall31168b02011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar9e22c0d2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattnerf0b64d72009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbarc5d33042008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
Daniel Dunbara08dff12008-09-24 04:04:31 +000024#include "llvm/Target/TargetData.h"
John McCall31168b02011-06-15 23:02:42 +000025#include "llvm/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCall31168b02011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000032static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +000033 QualType ET,
Ted Kremeneke65b0862012-03-06 20:05:56 +000034 const ObjCMethodDecl *Method,
35 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2192fe52011-07-18 04:24:23 +000040 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattnerb1d329d2008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000047{
David Chisnall481e3a82010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000052}
53
Patrick Beard0caa3942012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
56/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000057///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000058llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Patrick Beard0caa3942012-04-19 00:25:12 +000061 const Expr *SubExpr = E->getSubExpr();
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000067
68 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000069 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
73 llvm::Value *Receiver = Runtime.GetClass(Builder, ClassDecl);
74
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beard0caa3942012-04-19 00:25:12 +000077 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremeneke65b0862012-03-06 20:05:56 +000078 CallArgList Args;
79 Args.add(RV, ArgQT);
Patrick Beard0caa3942012-04-19 00:25:12 +000080
Ted Kremeneke65b0862012-03-06 20:05:56 +000081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beard0caa3942012-04-19 00:25:12 +000082 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +000084 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
166 llvm::Value *Receiver = Runtime.GetClass(Builder, Class);
167
168 // Generate the message send.
Eric Christopher5d2b8d92012-03-29 17:31:31 +0000169 RValue result
170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
171 MethodWithObjects->getResultType(),
172 Sel,
173 Receiver, Args, Class,
174 MethodWithObjects);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000175 return Builder.CreateBitCast(result.getScalarVal(),
176 ConvertType(E->getType()));
177}
178
179llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
181}
182
183llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
184 const ObjCDictionaryLiteral *E) {
185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
186}
187
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000188/// Emit a selector.
189llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
190 // Untyped selector.
191 // Note that this implementation allows for non-constant strings to be passed
192 // as arguments to @selector(). Currently, the only thing preventing this
193 // behaviour is the type checking in the front end.
Daniel Dunbar45858d22010-02-03 20:11:42 +0000194 return CGM.getObjCRuntime().GetSelector(Builder, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000195}
196
Daniel Dunbar66912a12008-08-20 00:28:19 +0000197llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
198 // FIXME: This should pass the Decl not the name.
199 return CGM.getObjCRuntime().GenerateProtocolRef(Builder, E->getProtocol());
200}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000201
Douglas Gregor33823722011-06-11 01:09:30 +0000202/// \brief Adjust the type of the result of an Objective-C message send
203/// expression when the method has a related result type.
204static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000205 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
John McCall31168b02011-06-15 23:02:42 +0000210
Douglas Gregor33823722011-06-11 01:09:30 +0000211 if (!Method->hasRelatedResultType() ||
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000212 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor33823722011-06-11 01:09:30 +0000213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000218 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000219}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000220
John McCallcf166702011-07-22 08:53:00 +0000221/// Decide whether to extend the lifetime of the receiver of a
222/// returns-inner-pointer message.
223static bool
224shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266}
267
John McCall78a15112010-05-22 01:48:05 +0000268RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000273
John McCall31168b02011-06-15 23:02:42 +0000274 bool isDelegateInit = E->isDelegateInitCall();
275
John McCallcf166702011-07-22 08:53:00 +0000276 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000277
John McCall31168b02011-06-15 23:02:42 +0000278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000284 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000287
Daniel Dunbar8d480592008-08-11 18:12:00 +0000288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000289 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000290 bool isClassMessage = false;
David Chisnall01aa4672010-04-28 19:33:36 +0000291 ObjCInterfaceDecl *OID = 0;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000292 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000293 QualType ReceiverType;
Daniel Dunbarb2197802010-04-22 03:17:06 +0000294 llvm::Value *Receiver = 0;
Douglas Gregor9a129192010-04-21 00:45:42 +0000295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000297 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000302 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000305 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000306
Douglas Gregor9a129192010-04-21 00:45:42 +0000307 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
David Chisnall01aa4672010-04-28 19:33:36 +0000313 Receiver = Runtime.GetClass(Builder, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000314 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000315 break;
316 }
317
318 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000319 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000320 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000321 isSuperMessage = true;
322 break;
323
324 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000325 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000326 Receiver = LoadObjCSelf();
327 isSuperMessage = true;
328 isClassMessage = true;
329 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000330 }
331
John McCallcf166702011-07-22 08:53:00 +0000332 if (retainSelf)
333 Receiver = EmitARCRetainNonBlock(Receiver);
334
335 // In ARC, we sometimes want to "extend the lifetime"
336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
337 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000339 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
340 shouldExtendReceiverForInnerPointerMessage(E))
341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
342
John McCall31168b02011-06-15 23:02:42 +0000343 QualType ResultType =
John McCallcf166702011-07-22 08:53:00 +0000344 method ? method->getResultType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000345
Daniel Dunbarc722b852008-08-30 03:02:31 +0000346 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000348
John McCall31168b02011-06-15 23:02:42 +0000349 // For delegate init calls in ARC, do an unsafe store of null into
350 // self. This represents the call taking direct ownership of that
351 // value. We have to do this after emitting the other call
352 // arguments because they might also reference self, but we don't
353 // have to worry about any of them modifying self because that would
354 // be an undefined read and write of an object in unordered
355 // expressions.
356 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000357 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000358 "delegate init calls should only be marked in ARC");
359
360 // Do an unsafe store of null into self.
361 llvm::Value *selfAddr =
362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
363 assert(selfAddr && "no self entry for a delegate init call?");
364
365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
366 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000367
Douglas Gregor33823722011-06-11 01:09:30 +0000368 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000369 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000370 // super is only valid in an Objective-C method
371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
374 E->getSelector(),
375 OMD->getClassInterface(),
376 isCategoryImpl,
377 Receiver,
378 isClassMessage,
379 Args,
John McCallcf166702011-07-22 08:53:00 +0000380 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000381 } else {
382 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
383 E->getSelector(),
384 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000385 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000386 }
John McCall31168b02011-06-15 23:02:42 +0000387
388 // For delegate init calls in ARC, implicitly store the result of
389 // the call back into self. This takes ownership of the value.
390 if (isDelegateInit) {
391 llvm::Value *selfAddr =
392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
393 llvm::Value *newSelf = result.getScalarVal();
394
395 // The delegate return type isn't necessarily a matching type; in
396 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000397 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000398 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
399 newSelf = Builder.CreateBitCast(newSelf, selfTy);
400
401 Builder.CreateStore(newSelf, selfAddr);
402 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000403
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000404 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000405}
406
John McCall31168b02011-06-15 23:02:42 +0000407namespace {
408struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCall30317fd2011-07-12 20:27:29 +0000409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +0000410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
John McCalldffafde2011-07-13 18:26:47 +0000416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
John McCall31168b02011-06-15 23:02:42 +0000418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
John McCalldffafde2011-07-13 18:26:47 +0000426 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432};
433}
434
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000435/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436/// the LLVM function and sets the other context used by
437/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000438void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patele7ce5402011-05-19 23:37:41 +0000439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
John McCalla738c252011-03-09 04:27:21 +0000441 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000442 // Check if we should generate debug info for this method.
Devang Pateld6ffebb2011-03-07 18:45:56 +0000443 if (CGM.getModuleDebugInfo() && !OMD->hasAttr<NoDebugAttr>())
444 DebugInfo = CGM.getModuleDebugInfo();
Devang Patela2c048e2010-04-05 21:09:15 +0000445
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000447
John McCalla729c622012-02-17 03:33:10 +0000448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000450
John McCalla738c252011-03-09 04:27:21 +0000451 args.push_back(OMD->getSelfDecl());
452 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000453
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +0000455 E = OMD->param_end(); PI != E; ++PI)
John McCalla738c252011-03-09 04:27:21 +0000456 args.push_back(*PI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000457
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000458 CurGD = OMD;
459
Devang Patele7ce5402011-05-19 23:37:41 +0000460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000461
462 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000463 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000464 OMD->isInstanceMethod() &&
465 OMD->getSelector().isUnarySelector()) {
466 const IdentifierInfo *ident =
467 OMD->getSelector().getIdentifierInfoForSlot(0);
468 if (ident->isStr("dealloc"))
469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
470 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000471}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000472
John McCall31168b02011-06-15 23:02:42 +0000473static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
474 LValue lvalue, QualType type);
475
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000476/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000477/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000478void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patele7ce5402011-05-19 23:37:41 +0000479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000480 EmitStmt(OMD->getBody());
481 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000482}
483
John McCallb923ece2011-09-12 23:06:44 +0000484/// emitStructGetterCall - Call the runtime function to load a property
485/// into the return value slot.
486static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
487 bool isAtomic, bool hasStrong) {
488 ASTContext &Context = CGF.getContext();
489
490 llvm::Value *src =
491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
492 ivar, 0).getAddress();
493
494 // objc_copyStruct (ReturnValue, &structIvar,
495 // sizeof (Type of Ivar), isAtomic, false);
496 CallArgList args;
497
498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
499 args.add(RValue::get(dest), Context.VoidPtrTy);
500
501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
502 args.add(RValue::get(src), Context.VoidPtrTy);
503
504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
508
509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCalla729c622012-02-17 03:33:10 +0000510 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(Context.VoidTy, args,
511 FunctionType::ExtInfo(),
512 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000513 fn, ReturnValueSlot(), args);
514}
515
John McCallf4528ae2011-09-13 03:34:09 +0000516/// Determine whether the given architecture supports unaligned atomic
517/// accesses. They don't have to be fast, just faster than a function
518/// call and a mutex.
519static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000520 // FIXME: Allow unaligned atomic load/store on x86. (It is not
521 // currently supported by the backend.)
522 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000523}
524
525/// Return the maximum size that permits atomic accesses for the given
526/// architecture.
527static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
528 llvm::Triple::ArchType arch) {
529 // ARM has 8-byte atomic accesses, but it's not clear whether we
530 // want to rely on them here.
531
532 // In the default case, just assume that any size up to a pointer is
533 // fine given adequate alignment.
534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
535}
536
537namespace {
538 class PropertyImplStrategy {
539 public:
540 enum StrategyKind {
541 /// The 'native' strategy is to use the architecture's provided
542 /// reads and writes.
543 Native,
544
545 /// Use objc_setProperty and objc_getProperty.
546 GetSetProperty,
547
548 /// Use objc_setProperty for the setter, but use expression
549 /// evaluation for the getter.
550 SetPropertyAndExpressionGet,
551
552 /// Use objc_copyStruct.
553 CopyStruct,
554
555 /// The 'expression' strategy is to emit normal assignment or
556 /// lvalue-to-rvalue expressions.
557 Expression
558 };
559
560 StrategyKind getKind() const { return StrategyKind(Kind); }
561
562 bool hasStrongMember() const { return HasStrong; }
563 bool isAtomic() const { return IsAtomic; }
564 bool isCopy() const { return IsCopy; }
565
566 CharUnits getIvarSize() const { return IvarSize; }
567 CharUnits getIvarAlignment() const { return IvarAlignment; }
568
569 PropertyImplStrategy(CodeGenModule &CGM,
570 const ObjCPropertyImplDecl *propImpl);
571
572 private:
573 unsigned Kind : 8;
574 unsigned IsAtomic : 1;
575 unsigned IsCopy : 1;
576 unsigned HasStrong : 1;
577
578 CharUnits IvarSize;
579 CharUnits IvarAlignment;
580 };
581}
582
583/// Pick an implementation strategy for the the given property synthesis.
584PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
585 const ObjCPropertyImplDecl *propImpl) {
586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000588
John McCall43192862011-09-13 18:31:23 +0000589 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
590 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000591 HasStrong = false; // doesn't matter here.
592
593 // Evaluate the ivar's size and alignment.
594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
595 QualType ivarType = ivar->getType();
596 llvm::tie(IvarSize, IvarAlignment)
597 = CGM.getContext().getTypeInfoInChars(ivarType);
598
599 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000600 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000601 if (IsCopy) {
602 Kind = GetSetProperty;
603 return;
604 }
605
John McCall43192862011-09-13 18:31:23 +0000606 // Handle retain.
607 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000608 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000610 // fallthrough
611
612 // In ARC, if the property is non-atomic, use expression emission,
613 // which translates to objc_storeStrong. This isn't required, but
614 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCallf4528ae2011-09-13 03:34:09 +0000616 Kind = Expression;
617 return;
618
619 // Otherwise, we need to at least use setProperty. However, if
620 // the property isn't atomic, we can use normal expression
621 // emission for the getter.
622 } else if (!IsAtomic) {
623 Kind = SetPropertyAndExpressionGet;
624 return;
625
626 // Otherwise, we have to use both setProperty and getProperty.
627 } else {
628 Kind = GetSetProperty;
629 return;
630 }
631 }
632
633 // If we're not atomic, just use expression accesses.
634 if (!IsAtomic) {
635 Kind = Expression;
636 return;
637 }
638
John McCall0e5c0862011-09-13 05:36:29 +0000639 // Properties on bitfield ivars need to be emitted using expression
640 // accesses even if they're nominally atomic.
641 if (ivar->isBitField()) {
642 Kind = Expression;
643 return;
644 }
645
John McCallf4528ae2011-09-13 03:34:09 +0000646 // GC-qualified or ARC-qualified ivars need to be emitted as
647 // expressions. This actually works out to being atomic anyway,
648 // except for ARC __strong, but that should trigger the above code.
649 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000650 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000651 CGM.getContext().getObjCGCAttrKind(ivarType))) {
652 Kind = Expression;
653 return;
654 }
655
656 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000657 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000658 if (const RecordType *recordType = ivarType->getAs<RecordType>())
659 HasStrong = recordType->getDecl()->hasObjectMember();
660
661 // We can never access structs with object members with a native
662 // access, because we need to use write barriers. This is what
663 // objc_copyStruct is for.
664 if (HasStrong) {
665 Kind = CopyStruct;
666 return;
667 }
668
669 // Otherwise, this is target-dependent and based on the size and
670 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000671
672 // If the size of the ivar is not a power of two, give up. We don't
673 // want to get into the business of doing compare-and-swaps.
674 if (!IvarSize.isPowerOfTwo()) {
675 Kind = CopyStruct;
676 return;
677 }
678
John McCallf4528ae2011-09-13 03:34:09 +0000679 llvm::Triple::ArchType arch =
680 CGM.getContext().getTargetInfo().getTriple().getArch();
681
682 // Most architectures require memory to fit within a single cache
683 // line, so the alignment has to be at least the size of the access.
684 // Otherwise we have to grab a lock.
685 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
686 Kind = CopyStruct;
687 return;
688 }
689
690 // If the ivar's size exceeds the architecture's maximum atomic
691 // access size, we have to use CopyStruct.
692 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
693 Kind = CopyStruct;
694 return;
695 }
696
697 // Otherwise, we can use native loads and stores.
698 Kind = Native;
699}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000700
James Dennettbe302452012-06-15 22:10:14 +0000701/// \brief Generate an Objective-C property getter function.
702///
703/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000704/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000705void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
706 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000707 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000708 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000709 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
710 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
711 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +0000712 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +0000713
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000714 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000715
716 FinishFunction();
717}
718
John McCallbdd81852011-09-13 06:00:03 +0000719static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
720 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000721 if (!getter) return true;
722
723 // Sema only makes only of these when the ivar has a C++ class type,
724 // so the form is pretty constrained.
725
John McCallbdd81852011-09-13 06:00:03 +0000726 // If the property has a reference type, we might just be binding a
727 // reference, in which case the result will be a gl-value. We should
728 // treat this as a non-trivial operation.
729 if (getter->isGLValue())
730 return false;
731
John McCallf4528ae2011-09-13 03:34:09 +0000732 // If we selected a trivial copy-constructor, we're okay.
733 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
734 return (construct->getConstructor()->isTrivial());
735
736 // The constructor might require cleanups (in which case it's never
737 // trivial).
738 assert(isa<ExprWithCleanups>(getter));
739 return false;
740}
741
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000742/// emitCPPObjectAtomicGetterCall - Call the runtime function to
743/// copy the ivar into the resturn slot.
744static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
745 llvm::Value *returnAddr,
746 ObjCIvarDecl *ivar,
747 llvm::Constant *AtomicHelperFn) {
748 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
749 // AtomicHelperFn);
750 CallArgList args;
751
752 // The 1st argument is the return Slot.
753 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
754
755 // The 2nd argument is the address of the ivar.
756 llvm::Value *ivarAddr =
757 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
758 CGF.LoadObjCSelf(), ivar, 0).getAddress();
759 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
760 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
761
762 // Third argument is the helper function.
763 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
764
765 llvm::Value *copyCppAtomicObjectFn =
766 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCalla729c622012-02-17 03:33:10 +0000767 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
768 FunctionType::ExtInfo(),
769 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000770 copyCppAtomicObjectFn, ReturnValueSlot(), args);
771}
772
John McCallf4528ae2011-09-13 03:34:09 +0000773void
774CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000775 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000776 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000777 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000778 // If there's a non-trivial 'get' expression, we just have to emit that.
779 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000780 if (!AtomicHelperFn) {
781 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
782 /*nrvo*/ 0);
783 EmitReturnStmt(ret);
784 }
785 else {
786 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
787 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
788 ivar, AtomicHelperFn);
789 }
John McCallf4528ae2011-09-13 03:34:09 +0000790 return;
791 }
792
793 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
794 QualType propType = prop->getType();
795 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
796
797 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
798
799 // Pick an implementation strategy.
800 PropertyImplStrategy strategy(CGM, propImpl);
801 switch (strategy.getKind()) {
802 case PropertyImplStrategy::Native: {
803 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
804
805 // Currently, all atomic accesses have to be through integer
806 // types, so there's no point in trying to pick a prettier type.
807 llvm::Type *bitcastType =
808 llvm::Type::getIntNTy(getLLVMContext(),
809 getContext().toBits(strategy.getIvarSize()));
810 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
811
812 // Perform an atomic load. This does not impose ordering constraints.
813 llvm::Value *ivarAddr = LV.getAddress();
814 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
815 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
816 load->setAlignment(strategy.getIvarAlignment().getQuantity());
817 load->setAtomic(llvm::Unordered);
818
819 // Store that value into the return address. Doing this with a
820 // bitcast is likely to produce some pretty ugly IR, but it's not
821 // the *most* terrible thing in the world.
822 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
823
824 // Make sure we don't do an autorelease.
825 AutoreleaseResult = false;
826 return;
827 }
828
829 case PropertyImplStrategy::GetSetProperty: {
830 llvm::Value *getPropertyFn =
831 CGM.getObjCRuntime().GetPropertyGetFunction();
832 if (!getPropertyFn) {
833 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000834 return;
835 }
836
837 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
838 // FIXME: Can't this be simpler? This might even be worse than the
839 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000840 llvm::Value *cmd =
841 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
842 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
843 llvm::Value *ivarOffset =
844 EmitIvarOffset(classImpl->getClassInterface(), ivar);
845
846 CallArgList args;
847 args.add(RValue::get(self), getContext().getObjCIdType());
848 args.add(RValue::get(cmd), getContext().getObjCSelType());
849 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000850 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
851 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000852
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000853 // FIXME: We shouldn't need to get the function info here, the
854 // runtime already should have computed it to build the function.
John McCalla729c622012-02-17 03:33:10 +0000855 RValue RV = EmitCall(getTypes().arrangeFunctionCall(propType, args,
856 FunctionType::ExtInfo(),
857 RequiredArgs::All),
John McCallf4528ae2011-09-13 03:34:09 +0000858 getPropertyFn, ReturnValueSlot(), args);
859
Daniel Dunbara08dff12008-09-24 04:04:31 +0000860 // We need to fix the type here. Ivars with copy & retain are
861 // always objects so we don't need to worry about complex or
862 // aggregates.
Mike Stump11289f42009-09-09 15:08:12 +0000863 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian0ec8fbe2012-04-26 21:33:14 +0000864 getTypes().ConvertType(getterMethod->getResultType())));
John McCallf4528ae2011-09-13 03:34:09 +0000865
866 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000867
868 // objc_getProperty does an autorelease, so we should suppress ours.
869 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000870
John McCallf4528ae2011-09-13 03:34:09 +0000871 return;
872 }
873
874 case PropertyImplStrategy::CopyStruct:
875 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
876 strategy.hasStrongMember());
877 return;
878
879 case PropertyImplStrategy::Expression:
880 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
881 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
882
883 QualType ivarType = ivar->getType();
884 if (ivarType->isAnyComplexType()) {
885 ComplexPairTy pair = LoadComplexFromAddr(LV.getAddress(),
886 LV.isVolatileQualified());
887 StoreComplexToAddr(pair, ReturnValue, LV.isVolatileQualified());
888 } else if (hasAggregateLLVMType(ivarType)) {
889 // The return value slot is guaranteed to not be aliased, but
890 // that's not necessarily the same as "on the stack", so
891 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000892 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000893 } else {
John McCall24fada12011-07-22 05:23:13 +0000894 llvm::Value *value;
895 if (propType->isReferenceType()) {
896 value = LV.getAddress();
897 } else {
898 // We want to load and autoreleaseReturnValue ARC __weak ivars.
899 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000900 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000901
902 // Otherwise we want to do a simple load, suppressing the
903 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000904 } else {
John McCall24fada12011-07-22 05:23:13 +0000905 value = EmitLoadOfLValue(LV).getScalarVal();
906 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000907 }
John McCall31168b02011-06-15 23:02:42 +0000908
John McCall24fada12011-07-22 05:23:13 +0000909 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000910 value = Builder.CreateBitCast(value,
911 ConvertType(GetterMethodDecl->getResultType()));
John McCall24fada12011-07-22 05:23:13 +0000912 }
913
914 EmitReturnOfRValue(RValue::get(value), propType);
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000915 }
John McCallf4528ae2011-09-13 03:34:09 +0000916 return;
Daniel Dunbara08dff12008-09-24 04:04:31 +0000917 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000918
John McCallf4528ae2011-09-13 03:34:09 +0000919 }
920 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000921}
922
John McCallb923ece2011-09-12 23:06:44 +0000923/// emitStructSetterCall - Call the runtime function to store the value
924/// from the first formal parameter into the given ivar.
925static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
926 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000927 // objc_copyStruct (&structIvar, &Arg,
928 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000929 CallArgList args;
930
931 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000932 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
933 CGF.LoadObjCSelf(), ivar, 0)
934 .getAddress();
935 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
936 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000937
938 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000939 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000940 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000941 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000942 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
943 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
944 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000945
946 // The third argument is the sizeof the type.
947 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000948 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
949 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +0000950
John McCallb923ece2011-09-12 23:06:44 +0000951 // The fourth argument is the 'isAtomic' flag.
952 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +0000953
John McCallb923ece2011-09-12 23:06:44 +0000954 // The fifth argument is the 'hasStrong' flag.
955 // FIXME: should this really always be false?
956 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
957
958 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCalla729c622012-02-17 03:33:10 +0000959 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
960 FunctionType::ExtInfo(),
961 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000962 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000963}
964
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000965/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
966/// the value from the first formal parameter into the given ivar, using
967/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
968static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
969 ObjCMethodDecl *OMD,
970 ObjCIvarDecl *ivar,
971 llvm::Constant *AtomicHelperFn) {
972 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
973 // AtomicHelperFn);
974 CallArgList args;
975
976 // The first argument is the address of the ivar.
977 llvm::Value *ivarAddr =
978 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
979 CGF.LoadObjCSelf(), ivar, 0).getAddress();
980 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
981 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
982
983 // The second argument is the address of the parameter variable.
984 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000985 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000986 VK_LValue, SourceLocation());
987 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
988 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
989 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
990
991 // Third argument is the helper function.
992 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
993
994 llvm::Value *copyCppAtomicObjectFn =
995 CGF.CGM.getObjCRuntime().GetCppAtomicObjectFunction();
John McCalla729c622012-02-17 03:33:10 +0000996 CGF.EmitCall(CGF.getTypes().arrangeFunctionCall(CGF.getContext().VoidTy, args,
997 FunctionType::ExtInfo(),
998 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +0000999 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1000
1001
1002}
1003
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001004
John McCallf4528ae2011-09-13 03:34:09 +00001005static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1006 Expr *setter = PID->getSetterCXXAssignment();
1007 if (!setter) return true;
1008
1009 // Sema only makes only of these when the ivar has a C++ class type,
1010 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001011
1012 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001013 // This also implies that there's nothing non-trivial going on with
1014 // the arguments, because operator= can only be trivial if it's a
1015 // synthesized assignment operator and therefore both parameters are
1016 // references.
1017 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001018 if (const FunctionDecl *callee
1019 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1020 if (callee->isTrivial())
1021 return true;
1022 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001023 }
John McCall7f16c422011-09-10 09:17:20 +00001024
John McCallf4528ae2011-09-13 03:34:09 +00001025 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001026 return false;
1027}
1028
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001029static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001030 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001031 return false;
1032 const TargetInfo &Target = CGM.getContext().getTargetInfo();
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001033
1034 if (Target.getPlatformName() != "macosx")
Ted Kremeneke65b0862012-03-06 20:05:56 +00001035 return false;
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001036
1037 return Target.getPlatformMinVersion() >= VersionTuple(10, 8);
Ted Kremeneke65b0862012-03-06 20:05:56 +00001038}
1039
John McCall7f16c422011-09-10 09:17:20 +00001040void
1041CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001042 const ObjCPropertyImplDecl *propImpl,
1043 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001044 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001045 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001046 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001047
1048 // Just use the setter expression if Sema gave us one and it's
1049 // non-trivial.
1050 if (!hasTrivialSetExpr(propImpl)) {
1051 if (!AtomicHelperFn)
1052 // If non-atomic, assignment is called directly.
1053 EmitStmt(propImpl->getSetterCXXAssignment());
1054 else
1055 // If atomic, assignment is called via a locking api.
1056 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1057 AtomicHelperFn);
1058 return;
1059 }
John McCall7f16c422011-09-10 09:17:20 +00001060
John McCallf4528ae2011-09-13 03:34:09 +00001061 PropertyImplStrategy strategy(CGM, propImpl);
1062 switch (strategy.getKind()) {
1063 case PropertyImplStrategy::Native: {
1064 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001065
John McCallf4528ae2011-09-13 03:34:09 +00001066 LValue ivarLValue =
1067 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1068 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001069
John McCallf4528ae2011-09-13 03:34:09 +00001070 // Currently, all atomic accesses have to be through integer
1071 // types, so there's no point in trying to pick a prettier type.
1072 llvm::Type *bitcastType =
1073 llvm::Type::getIntNTy(getLLVMContext(),
1074 getContext().toBits(strategy.getIvarSize()));
1075 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1076
1077 // Cast both arguments to the chosen operation type.
1078 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1079 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1080
1081 // This bitcast load is likely to cause some nasty IR.
1082 llvm::Value *load = Builder.CreateLoad(argAddr);
1083
1084 // Perform an atomic store. There are no memory ordering requirements.
1085 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1086 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1087 store->setAtomic(llvm::Unordered);
1088 return;
1089 }
1090
1091 case PropertyImplStrategy::GetSetProperty:
1092 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremeneke65b0862012-03-06 20:05:56 +00001093
1094 llvm::Value *setOptimizedPropertyFn = 0;
1095 llvm::Value *setPropertyFn = 0;
1096 if (UseOptimizedSetter(CGM)) {
1097 // 10.8 code and GC is off
1098 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001099 CGM.getObjCRuntime()
1100 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1101 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001102 if (!setOptimizedPropertyFn) {
1103 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1104 return;
1105 }
John McCall7f16c422011-09-10 09:17:20 +00001106 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001107 else {
1108 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1109 if (!setPropertyFn) {
1110 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1111 return;
1112 }
1113 }
1114
John McCall7f16c422011-09-10 09:17:20 +00001115 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1116 // <is-atomic>, <is-copy>).
1117 llvm::Value *cmd =
1118 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1119 llvm::Value *self =
1120 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1121 llvm::Value *ivarOffset =
1122 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1123 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1124 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1125
1126 CallArgList args;
1127 args.add(RValue::get(self), getContext().getObjCIdType());
1128 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001129 if (setOptimizedPropertyFn) {
1130 args.add(RValue::get(arg), getContext().getObjCIdType());
1131 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1132 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1133 FunctionType::ExtInfo(),
1134 RequiredArgs::All),
1135 setOptimizedPropertyFn, ReturnValueSlot(), args);
1136 } else {
1137 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1138 args.add(RValue::get(arg), getContext().getObjCIdType());
1139 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1140 getContext().BoolTy);
1141 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1142 getContext().BoolTy);
1143 // FIXME: We shouldn't need to get the function info here, the runtime
1144 // already should have computed it to build the function.
1145 EmitCall(getTypes().arrangeFunctionCall(getContext().VoidTy, args,
1146 FunctionType::ExtInfo(),
1147 RequiredArgs::All),
1148 setPropertyFn, ReturnValueSlot(), args);
1149 }
1150
John McCall7f16c422011-09-10 09:17:20 +00001151 return;
1152 }
1153
John McCallf4528ae2011-09-13 03:34:09 +00001154 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001155 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001156 return;
John McCallf4528ae2011-09-13 03:34:09 +00001157
1158 case PropertyImplStrategy::Expression:
1159 break;
John McCall7f16c422011-09-10 09:17:20 +00001160 }
1161
1162 // Otherwise, fake up some ASTs and emit a normal assignment.
1163 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001164 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1165 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001166 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1167 selfDecl->getType(), CK_LValueToRValue, &self,
1168 VK_RValue);
1169 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1170 SourceLocation(), &selfLoad, true, true);
1171
1172 ParmVarDecl *argDecl = *setterMethod->param_begin();
1173 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001174 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001175 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1176 argType.getUnqualifiedType(), CK_LValueToRValue,
1177 &arg, VK_RValue);
1178
1179 // The property type can differ from the ivar type in some situations with
1180 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1181 // The following absurdity is just to ensure well-formed IR.
1182 CastKind argCK = CK_NoOp;
1183 if (ivarRef.getType()->isObjCObjectPointerType()) {
1184 if (argLoad.getType()->isObjCObjectPointerType())
1185 argCK = CK_BitCast;
1186 else if (argLoad.getType()->isBlockPointerType())
1187 argCK = CK_BlockPointerToObjCPointerCast;
1188 else
1189 argCK = CK_CPointerToObjCPointerCast;
1190 } else if (ivarRef.getType()->isBlockPointerType()) {
1191 if (argLoad.getType()->isBlockPointerType())
1192 argCK = CK_BitCast;
1193 else
1194 argCK = CK_AnyPointerToBlockPointerCast;
1195 } else if (ivarRef.getType()->isPointerType()) {
1196 argCK = CK_BitCast;
1197 }
1198 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1199 ivarRef.getType(), argCK, &argLoad,
1200 VK_RValue);
1201 Expr *finalArg = &argLoad;
1202 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1203 argLoad.getType()))
1204 finalArg = &argCast;
1205
1206
1207 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1208 ivarRef.getType(), VK_RValue, OK_Ordinary,
1209 SourceLocation());
1210 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001211}
1212
James Dennettbe302452012-06-15 22:10:14 +00001213/// \brief Generate an Objective-C property setter function.
1214///
1215/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001216/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001217void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1218 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian4b501a22012-01-07 18:56:22 +00001219 llvm::Constant *AtomicHelperFn =
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001220 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001221 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1222 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1223 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherb7e821a2012-04-03 00:44:15 +00001224 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001225
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001226 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001227
1228 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001229}
1230
John McCall6a4fa522011-03-22 07:05:39 +00001231namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001232 struct DestroyIvar : EHScopeStack::Cleanup {
1233 private:
1234 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001235 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001236 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001237 bool useEHCleanupForArray;
1238 public:
1239 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1240 CodeGenFunction::Destroyer *destroyer,
1241 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001242 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001243 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001244
John McCall30317fd2011-07-12 20:27:29 +00001245 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall4bd0fb12011-07-12 16:41:08 +00001246 LValue lvalue
1247 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1248 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001249 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001250 }
1251 };
1252}
1253
John McCall4bd0fb12011-07-12 16:41:08 +00001254/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1255static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1256 llvm::Value *addr,
1257 QualType type) {
1258 llvm::Value *null = getNullForVariable(addr);
1259 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1260}
John McCall31168b02011-06-15 23:02:42 +00001261
John McCall6a4fa522011-03-22 07:05:39 +00001262static void emitCXXDestructMethod(CodeGenFunction &CGF,
1263 ObjCImplementationDecl *impl) {
1264 CodeGenFunction::RunCleanupsScope scope(CGF);
1265
1266 llvm::Value *self = CGF.LoadObjCSelf();
1267
Jordy Rosea91768e2011-07-22 02:08:32 +00001268 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1269 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001270 ivar; ivar = ivar->getNextIvar()) {
1271 QualType type = ivar->getType();
1272
John McCall6a4fa522011-03-22 07:05:39 +00001273 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001274 QualType::DestructionKind dtorKind = type.isDestructedType();
1275 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001276
John McCall4bd0fb12011-07-12 16:41:08 +00001277 CodeGenFunction::Destroyer *destroyer = 0;
John McCall6a4fa522011-03-22 07:05:39 +00001278
John McCall4bd0fb12011-07-12 16:41:08 +00001279 // Use a call to objc_storeStrong to destroy strong ivars, for the
1280 // general benefit of the tools.
1281 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001282 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001283
John McCall4bd0fb12011-07-12 16:41:08 +00001284 // Otherwise use the default for the destruction kind.
1285 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001286 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001287 }
John McCall4bd0fb12011-07-12 16:41:08 +00001288
1289 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1290
1291 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1292 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001293 }
1294
1295 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1296}
1297
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001298void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1299 ObjCMethodDecl *MD,
1300 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001301 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patele7ce5402011-05-19 23:37:41 +00001302 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCall6a4fa522011-03-22 07:05:39 +00001303
1304 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001305 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001306 // Suppress the final autorelease in ARC.
1307 AutoreleaseResult = false;
1308
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001309 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCall6a4fa522011-03-22 07:05:39 +00001310 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1311 E = IMP->init_end(); B != E; ++B) {
1312 CXXCtorInitializer *IvarInit = (*B);
Francois Pichetd583da02010-12-04 09:14:42 +00001313 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001314 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001315 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1316 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001317 EmitAggExpr(IvarInit->getInit(),
1318 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001319 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001320 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001321 }
1322 // constructor returns 'self'.
1323 CodeGenTypes &Types = CGM.getTypes();
1324 QualType IdTy(CGM.getContext().getObjCIdType());
1325 llvm::Value *SelfAsId =
1326 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1327 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001328
1329 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001330 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001331 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001332 }
1333 FinishFunction();
1334}
1335
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001336bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1337 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1338 it++; it++;
1339 const ABIArgInfo &AI = it->info;
1340 // FIXME. Is this sufficient check?
1341 return (AI.getKind() == ABIArgInfo::Indirect);
1342}
1343
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001344bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001345 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001346 return false;
1347 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1348 return FDTTy->getDecl()->hasObjectMember();
1349 return false;
1350}
1351
Daniel Dunbara08dff12008-09-24 04:04:31 +00001352llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbara94ecd22008-08-16 03:19:19 +00001353 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1354 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner5696e7b2008-06-17 18:05:57 +00001355}
1356
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001357QualType CodeGenFunction::TypeOfSelfObject() {
1358 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1359 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001360 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1361 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001362 return PTy->getPointeeType();
1363}
1364
Chris Lattnerd4808922009-03-22 21:03:39 +00001365void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001366 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001367 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001368
Daniel Dunbara08dff12008-09-24 04:04:31 +00001369 if (!EnumerationMutationFn) {
1370 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1371 return;
1372 }
1373
Devang Pateld2d66652011-01-19 01:36:36 +00001374 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001375 if (DI)
1376 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001377
Devang Patel297207f2011-06-13 23:15:32 +00001378 // The local variable comes into scope immediately.
1379 AutoVarEmission variable = AutoVarEmission::invalid();
1380 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1381 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1382
John McCall1c926b72011-01-07 01:49:06 +00001383 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001384
Anders Carlsson75658592008-08-31 02:33:12 +00001385 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001386 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbara7566f12010-02-09 02:48:28 +00001387 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001388 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001389
Anders Carlsson75658592008-08-31 02:33:12 +00001390 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001391 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001392
John McCall1c926b72011-01-07 01:49:06 +00001393 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001394 IdentifierInfo *II[] = {
1395 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1396 &CGM.getContext().Idents.get("objects"),
1397 &CGM.getContext().Idents.get("count")
1398 };
1399 Selector FastEnumSel =
1400 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001401
1402 QualType ItemsTy =
1403 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001404 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001405 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001406 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001407
John McCall53848232011-07-27 01:07:15 +00001408 // Emit the collection pointer. In ARC, we do a retain.
1409 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001410 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001411 Collection = EmitARCRetainScalarExpr(S.getCollection());
1412
1413 // Enter a cleanup to do the release.
1414 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1415 } else {
1416 Collection = EmitScalarExpr(S.getCollection());
1417 }
Mike Stump11289f42009-09-09 15:08:12 +00001418
John McCall91e82dd2011-08-05 00:14:38 +00001419 // The 'continue' label needs to appear within the cleanup for the
1420 // collection object.
1421 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1422
John McCall1c926b72011-01-07 01:49:06 +00001423 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001424 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001425
1426 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001427 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001428
John McCall1c926b72011-01-07 01:49:06 +00001429 // The second argument is a temporary array with space for NumItems
1430 // pointers. We'll actually be loading elements from the array
1431 // pointer written into the control state; this buffer is so that
1432 // collections that *aren't* backed by arrays can still queue up
1433 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001434 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001435
John McCall1c926b72011-01-07 01:49:06 +00001436 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001437 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001438 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001439 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001440
John McCall1c926b72011-01-07 01:49:06 +00001441 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001442 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001443 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001444 getContext().UnsignedLongTy,
1445 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001446 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001447
John McCall1c926b72011-01-07 01:49:06 +00001448 // The initial number of objects that were returned in the buffer.
1449 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001450
John McCall1c926b72011-01-07 01:49:06 +00001451 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1452 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001453
John McCall1c926b72011-01-07 01:49:06 +00001454 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001455
John McCall1c926b72011-01-07 01:49:06 +00001456 // If the limit pointer was zero to begin with, the collection is
1457 // empty; skip all this.
1458 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1459 EmptyBB, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001460
John McCall1c926b72011-01-07 01:49:06 +00001461 // Otherwise, initialize the loop.
1462 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001463
John McCall1c926b72011-01-07 01:49:06 +00001464 // Save the initial mutations value. This is the value at an
1465 // address that was written into the state object by
1466 // countByEnumeratingWithState:objects:count:.
Mike Stump11289f42009-09-09 15:08:12 +00001467 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson3f35a262008-08-31 04:05:03 +00001468 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001469 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001470 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001471
John McCall1c926b72011-01-07 01:49:06 +00001472 llvm::Value *initialMutations =
1473 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001474
John McCall1c926b72011-01-07 01:49:06 +00001475 // Start looping. This is the point we return to whenever we have a
1476 // fresh, non-empty batch of objects.
1477 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1478 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001479
John McCall1c926b72011-01-07 01:49:06 +00001480 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001481 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001482 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001483
John McCall1c926b72011-01-07 01:49:06 +00001484 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001485 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001486 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001487
John McCall1c926b72011-01-07 01:49:06 +00001488 // Check whether the mutations value has changed from where it was
1489 // at start. StateMutationsPtr should actually be invariant between
1490 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001491 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001492 llvm::Value *currentMutations
1493 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001494
John McCall1c926b72011-01-07 01:49:06 +00001495 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001496 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001497
John McCall1c926b72011-01-07 01:49:06 +00001498 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1499 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001500
John McCall1c926b72011-01-07 01:49:06 +00001501 // If so, call the enumeration-mutation function.
1502 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001503 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001504 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001505 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001506 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001507 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001508 // FIXME: We shouldn't need to get the function info here, the runtime already
1509 // should have computed it to build the function.
John McCalla729c622012-02-17 03:33:10 +00001510 EmitCall(CGM.getTypes().arrangeFunctionCall(getContext().VoidTy, Args2,
1511 FunctionType::ExtInfo(),
1512 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001513 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001514
John McCall1c926b72011-01-07 01:49:06 +00001515 // Otherwise, or if the mutation function returns, just continue.
1516 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001517
John McCall1c926b72011-01-07 01:49:06 +00001518 // Initialize the element variable.
1519 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001520 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001521 LValue elementLValue;
1522 QualType elementType;
1523 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001524 // Initialize the variable, in case it's a __block variable or something.
1525 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001526
John McCall9e2e22f2011-02-22 07:16:58 +00001527 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001528 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001529 VK_LValue, SourceLocation());
1530 elementLValue = EmitLValue(&tempDRE);
1531 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001532 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001533
1534 if (D->isARCPseudoStrong())
1535 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001536 } else {
1537 elementLValue = LValue(); // suppress warning
1538 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001539 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001540 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001541 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001542
1543 // Fetch the buffer out of the enumeration state.
1544 // TODO: this pointer should actually be invariant between
1545 // refreshes, which would help us do certain loop optimizations.
Mike Stump11289f42009-09-09 15:08:12 +00001546 llvm::Value *StateItemsPtr =
Anders Carlsson75658592008-08-31 02:33:12 +00001547 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001548 llvm::Value *EnumStateItems =
1549 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001550
John McCall1c926b72011-01-07 01:49:06 +00001551 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001552 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001553 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1554 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001555
John McCall1c926b72011-01-07 01:49:06 +00001556 // Cast that value to the right type.
1557 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1558 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001559
John McCall1c926b72011-01-07 01:49:06 +00001560 // Make sure we have an l-value. Yes, this gets evaluated every
1561 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001562 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001563 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001564 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001565 } else {
1566 EmitScalarInit(CurrentItem, elementLValue);
1567 }
Mike Stump11289f42009-09-09 15:08:12 +00001568
John McCall9e2e22f2011-02-22 07:16:58 +00001569 // If we do have an element variable, this assignment is the end of
1570 // its initialization.
1571 if (elementIsVariable)
1572 EmitAutoVarCleanups(variable);
1573
John McCall1c926b72011-01-07 01:49:06 +00001574 // Perform the loop body, setting up break and continue labels.
Anders Carlsson33747b62009-02-10 05:52:02 +00001575 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001576 {
1577 RunCleanupsScope Scope(*this);
1578 EmitStmt(S.getBody());
1579 }
Anders Carlsson75658592008-08-31 02:33:12 +00001580 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001581
John McCall1c926b72011-01-07 01:49:06 +00001582 // Destroy the element variable now.
1583 elementVariableScope.ForceCleanup();
1584
1585 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001586 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001587
John McCall1c926b72011-01-07 01:49:06 +00001588 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001589
John McCall1c926b72011-01-07 01:49:06 +00001590 // First we check in the local buffer.
1591 llvm::Value *indexPlusOne
1592 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001593
John McCall1c926b72011-01-07 01:49:06 +00001594 // If we haven't overrun the buffer yet, we can continue.
1595 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1596 LoopBodyBB, FetchMoreBB);
1597
1598 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1599 count->addIncoming(count, AfterBody.getBlock());
1600
1601 // Otherwise, we have to fetch more elements.
1602 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001603
1604 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001605 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001606 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001607 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001608 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001609
John McCall1c926b72011-01-07 01:49:06 +00001610 // If we got a zero count, we're done.
1611 llvm::Value *refetchCount = CountRV.getScalarVal();
1612
1613 // (note that the message send might split FetchMoreBB)
1614 index->addIncoming(zero, Builder.GetInsertBlock());
1615 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1616
1617 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1618 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001619
Anders Carlsson75658592008-08-31 02:33:12 +00001620 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001621 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001622
John McCall9e2e22f2011-02-22 07:16:58 +00001623 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001624 // If the element was not a declaration, set it to be null.
1625
John McCall1c926b72011-01-07 01:49:06 +00001626 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1627 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001628 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001629 }
1630
Eric Christopher7cdf9482011-10-13 21:45:18 +00001631 if (DI)
1632 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001633
John McCall53848232011-07-27 01:07:15 +00001634 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001635 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001636 PopCleanupBlock();
1637
John McCallad5d61e2010-07-23 21:56:41 +00001638 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001639}
1640
Mike Stump11289f42009-09-09 15:08:12 +00001641void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001642 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001643}
1644
Mike Stump11289f42009-09-09 15:08:12 +00001645void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001646 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1647}
1648
Chris Lattnere132e242008-11-15 21:26:17 +00001649void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001650 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001651 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001652}
1653
John McCall2d637d22011-09-10 06:18:15 +00001654/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001655/// primitive retain.
1656llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1657 llvm::Value *value) {
1658 return EmitARCRetain(type, value);
1659}
1660
1661namespace {
1662 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001663 CallObjCRelease(llvm::Value *object) : object(object) {}
1664 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001665
John McCall30317fd2011-07-12 20:27:29 +00001666 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00001667 CGF.EmitARCRelease(object, /*precise*/ true);
John McCall31168b02011-06-15 23:02:42 +00001668 }
1669 };
1670}
1671
John McCall2d637d22011-09-10 06:18:15 +00001672/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001673/// release at the end of the full-expression.
1674llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1675 llvm::Value *object) {
1676 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001677 // conditional.
1678 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001679 return object;
1680}
1681
1682llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1683 llvm::Value *value) {
1684 return EmitARCRetainAutorelease(type, value);
1685}
1686
1687
1688static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001689 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001690 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001691 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1692
1693 // In -fobjc-no-arc-runtime, emit weak references to the runtime
1694 // support library.
John McCall24fc0de2011-07-06 00:26:06 +00001695 if (!CGM.getCodeGenOpts().ObjCRuntimeHasARC)
John McCall31168b02011-06-15 23:02:42 +00001696 if (llvm::Function *f = dyn_cast<llvm::Function>(fn))
1697 f->setLinkage(llvm::Function::ExternalWeakLinkage);
1698
1699 return fn;
1700}
1701
1702/// Perform an operation having the signature
1703/// i8* (i8*)
1704/// where a null input causes a no-op and returns null.
1705static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1706 llvm::Value *value,
1707 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001708 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001709 if (isa<llvm::ConstantPointerNull>(value)) return value;
1710
1711 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001712 std::vector<llvm::Type*> args(1, CGF.Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001713 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001714 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1715 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1716 }
1717
1718 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001719 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001720 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1721
1722 // Call the function.
1723 llvm::CallInst *call = CGF.Builder.CreateCall(fn, value);
1724 call->setDoesNotThrow();
1725
1726 // Cast the result back to the original type.
1727 return CGF.Builder.CreateBitCast(call, origType);
1728}
1729
1730/// Perform an operation having the following signature:
1731/// i8* (i8**)
1732static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1733 llvm::Value *addr,
1734 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001735 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001736 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001737 std::vector<llvm::Type*> args(1, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001738 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001739 llvm::FunctionType::get(CGF.Int8PtrTy, args, false);
1740 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1741 }
1742
1743 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001744 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001745 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1746
1747 // Call the function.
1748 llvm::CallInst *call = CGF.Builder.CreateCall(fn, addr);
1749 call->setDoesNotThrow();
1750
1751 // Cast the result back to a dereference of the original type.
1752 llvm::Value *result = call;
1753 if (origType != CGF.Int8PtrPtrTy)
1754 result = CGF.Builder.CreateBitCast(result,
1755 cast<llvm::PointerType>(origType)->getElementType());
1756
1757 return result;
1758}
1759
1760/// Perform an operation having the following signature:
1761/// i8* (i8**, i8*)
1762static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1763 llvm::Value *addr,
1764 llvm::Value *value,
1765 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001766 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001767 bool ignored) {
1768 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1769 == value->getType());
1770
1771 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001772 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001773
Chris Lattner2192fe52011-07-18 04:24:23 +00001774 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001775 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1776 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1777 }
1778
Chris Lattner2192fe52011-07-18 04:24:23 +00001779 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001780
1781 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1782 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1783
1784 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, addr, value);
1785 result->setDoesNotThrow();
1786
1787 if (ignored) return 0;
1788
1789 return CGF.Builder.CreateBitCast(result, origType);
1790}
1791
1792/// Perform an operation having the following signature:
1793/// void (i8**, i8**)
1794static void emitARCCopyOperation(CodeGenFunction &CGF,
1795 llvm::Value *dst,
1796 llvm::Value *src,
1797 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001798 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001799 assert(dst->getType() == src->getType());
1800
1801 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001802 std::vector<llvm::Type*> argTypes(2, CGF.Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001803 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001804 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1805 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1806 }
1807
1808 dst = CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy);
1809 src = CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy);
1810
1811 llvm::CallInst *result = CGF.Builder.CreateCall2(fn, dst, src);
1812 result->setDoesNotThrow();
1813}
1814
1815/// Produce the code to do a retain. Based on the type, calls one of:
1816/// call i8* @objc_retain(i8* %value)
1817/// call i8* @objc_retainBlock(i8* %value)
1818llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1819 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001820 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001821 else
1822 return EmitARCRetainNonBlock(value);
1823}
1824
1825/// Retain the given object, with normal retain semantics.
1826/// call i8* @objc_retain(i8* %value)
1827llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1828 return emitARCValueOperation(*this, value,
1829 CGM.getARCEntrypoints().objc_retain,
1830 "objc_retain");
1831}
1832
1833/// Retain the given block, with _Block_copy semantics.
1834/// call i8* @objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001835///
1836/// \param mandatory - If false, emit the call with metadata
1837/// indicating that it's okay for the optimizer to eliminate this call
1838/// if it can prove that the block never escapes except down the stack.
1839llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1840 bool mandatory) {
1841 llvm::Value *result
1842 = emitARCValueOperation(*this, value,
1843 CGM.getARCEntrypoints().objc_retainBlock,
1844 "objc_retainBlock");
1845
1846 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1847 // tell the optimizer that it doesn't need to do this copy if the
1848 // block doesn't escape, where being passed as an argument doesn't
1849 // count as escaping.
1850 if (!mandatory && isa<llvm::Instruction>(result)) {
1851 llvm::CallInst *call
1852 = cast<llvm::CallInst>(result->stripPointerCasts());
1853 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1854
1855 SmallVector<llvm::Value*,1> args;
1856 call->setMetadata("clang.arc.copy_on_escape",
1857 llvm::MDNode::get(Builder.getContext(), args));
1858 }
1859
1860 return result;
John McCall31168b02011-06-15 23:02:42 +00001861}
1862
1863/// Retain the given object which is the result of a function call.
1864/// call i8* @objc_retainAutoreleasedReturnValue(i8* %value)
1865///
1866/// Yes, this function name is one character away from a different
1867/// call with completely different semantics.
1868llvm::Value *
1869CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1870 // Fetch the void(void) inline asm which marks that we're going to
1871 // retain the autoreleased return value.
1872 llvm::InlineAsm *&marker
1873 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1874 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001875 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001876 = CGM.getTargetCodeGenInfo()
1877 .getARCRetainAutoreleasedReturnValueMarker();
1878
1879 // If we have an empty assembly string, there's nothing to do.
1880 if (assembly.empty()) {
1881
1882 // Otherwise, at -O0, build an inline asm that we're going to call
1883 // in a moment.
1884 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1885 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001886 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001887
1888 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1889
1890 // If we're at -O1 and above, we don't want to litter the code
1891 // with this marker yet, so leave a breadcrumb for the ARC
1892 // optimizer to pick up.
1893 } else {
1894 llvm::NamedMDNode *metadata =
1895 CGM.getModule().getOrInsertNamedMetadata(
1896 "clang.arc.retainAutoreleasedReturnValueMarker");
1897 assert(metadata->getNumOperands() <= 1);
1898 if (metadata->getNumOperands() == 0) {
1899 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foad5709f7c2011-07-29 13:56:53 +00001900 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCall31168b02011-06-15 23:02:42 +00001901 }
1902 }
1903 }
1904
1905 // Call the marker asm if we made one, which we do only at -O0.
1906 if (marker) Builder.CreateCall(marker);
1907
1908 return emitARCValueOperation(*this, value,
1909 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1910 "objc_retainAutoreleasedReturnValue");
1911}
1912
1913/// Release the given object.
1914/// call void @objc_release(i8* %value)
1915void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1916 if (isa<llvm::ConstantPointerNull>(value)) return;
1917
1918 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1919 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001920 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00001921 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00001922 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
1923 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1924 }
1925
1926 // Cast the argument to 'id'.
1927 value = Builder.CreateBitCast(value, Int8PtrTy);
1928
1929 // Call objc_release.
1930 llvm::CallInst *call = Builder.CreateCall(fn, value);
1931 call->setDoesNotThrow();
1932
1933 if (!precise) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001934 SmallVector<llvm::Value*,1> args;
John McCall31168b02011-06-15 23:02:42 +00001935 call->setMetadata("clang.imprecise_release",
1936 llvm::MDNode::get(Builder.getContext(), args));
1937 }
1938}
1939
1940/// Store into a strong object. Always calls this:
1941/// call void @objc_storeStrong(i8** %addr, i8* %value)
1942llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1943 llvm::Value *value,
1944 bool ignored) {
1945 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1946 == value->getType());
1947
1948 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1949 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00001950 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00001951 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001952 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
1953 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
1954 }
1955
1956 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
1957 llvm::Value *castValue = Builder.CreateBitCast(value, Int8PtrTy);
1958
1959 Builder.CreateCall2(fn, addr, castValue)->setDoesNotThrow();
1960
1961 if (ignored) return 0;
1962 return value;
1963}
1964
1965/// Store into a strong object. Sometimes calls this:
1966/// call void @objc_storeStrong(i8** %addr, i8* %value)
1967/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00001968llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00001969 llvm::Value *newValue,
1970 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00001971 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00001972 bool isBlock = type->isBlockPointerType();
1973
1974 // Use a store barrier at -O0 unless this is a block type or the
1975 // lvalue is inadequately aligned.
1976 if (shouldUseFusedARCCalls() &&
1977 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00001978 (dst.getAlignment().isZero() ||
1979 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00001980 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
1981 }
1982
1983 // Otherwise, split it out.
1984
1985 // Retain the new value.
1986 newValue = EmitARCRetain(type, newValue);
1987
1988 // Read the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001989 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCall31168b02011-06-15 23:02:42 +00001990
1991 // Store. We do this before the release so that any deallocs won't
1992 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00001993 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00001994
1995 // Finally, release the old value.
1996 EmitARCRelease(oldValue, /*precise*/ false);
1997
1998 return newValue;
1999}
2000
2001/// Autorelease the given object.
2002/// call i8* @objc_autorelease(i8* %value)
2003llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2004 return emitARCValueOperation(*this, value,
2005 CGM.getARCEntrypoints().objc_autorelease,
2006 "objc_autorelease");
2007}
2008
2009/// Autorelease the given object.
2010/// call i8* @objc_autoreleaseReturnValue(i8* %value)
2011llvm::Value *
2012CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2013 return emitARCValueOperation(*this, value,
2014 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
2015 "objc_autoreleaseReturnValue");
2016}
2017
2018/// Do a fused retain/autorelease of the given object.
2019/// call i8* @objc_retainAutoreleaseReturnValue(i8* %value)
2020llvm::Value *
2021CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2022 return emitARCValueOperation(*this, value,
2023 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
2024 "objc_retainAutoreleaseReturnValue");
2025}
2026
2027/// Do a fused retain/autorelease of the given object.
2028/// call i8* @objc_retainAutorelease(i8* %value)
2029/// or
2030/// %retain = call i8* @objc_retainBlock(i8* %value)
2031/// call i8* @objc_autorelease(i8* %retain)
2032llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2033 llvm::Value *value) {
2034 if (!type->isBlockPointerType())
2035 return EmitARCRetainAutoreleaseNonBlock(value);
2036
2037 if (isa<llvm::ConstantPointerNull>(value)) return value;
2038
Chris Lattner2192fe52011-07-18 04:24:23 +00002039 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002040 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002041 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002042 value = EmitARCAutorelease(value);
2043 return Builder.CreateBitCast(value, origType);
2044}
2045
2046/// Do a fused retain/autorelease of the given object.
2047/// call i8* @objc_retainAutorelease(i8* %value)
2048llvm::Value *
2049CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2050 return emitARCValueOperation(*this, value,
2051 CGM.getARCEntrypoints().objc_retainAutorelease,
2052 "objc_retainAutorelease");
2053}
2054
2055/// i8* @objc_loadWeak(i8** %addr)
2056/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2057llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2058 return emitARCLoadOperation(*this, addr,
2059 CGM.getARCEntrypoints().objc_loadWeak,
2060 "objc_loadWeak");
2061}
2062
2063/// i8* @objc_loadWeakRetained(i8** %addr)
2064llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2065 return emitARCLoadOperation(*this, addr,
2066 CGM.getARCEntrypoints().objc_loadWeakRetained,
2067 "objc_loadWeakRetained");
2068}
2069
2070/// i8* @objc_storeWeak(i8** %addr, i8* %value)
2071/// Returns %value.
2072llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2073 llvm::Value *value,
2074 bool ignored) {
2075 return emitARCStoreOperation(*this, addr, value,
2076 CGM.getARCEntrypoints().objc_storeWeak,
2077 "objc_storeWeak", ignored);
2078}
2079
2080/// i8* @objc_initWeak(i8** %addr, i8* %value)
2081/// Returns %value. %addr is known to not have a current weak entry.
2082/// Essentially equivalent to:
2083/// *addr = nil; objc_storeWeak(addr, value);
2084void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2085 // If we're initializing to null, just write null to memory; no need
2086 // to get the runtime involved. But don't do this if optimization
2087 // is enabled, because accounting for this would make the optimizer
2088 // much more complicated.
2089 if (isa<llvm::ConstantPointerNull>(value) &&
2090 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2091 Builder.CreateStore(value, addr);
2092 return;
2093 }
2094
2095 emitARCStoreOperation(*this, addr, value,
2096 CGM.getARCEntrypoints().objc_initWeak,
2097 "objc_initWeak", /*ignored*/ true);
2098}
2099
2100/// void @objc_destroyWeak(i8** %addr)
2101/// Essentially objc_storeWeak(addr, nil).
2102void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2103 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2104 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002105 std::vector<llvm::Type*> args(1, Int8PtrPtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00002106 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002107 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2108 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2109 }
2110
2111 // Cast the argument to 'id*'.
2112 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2113
2114 llvm::CallInst *call = Builder.CreateCall(fn, addr);
2115 call->setDoesNotThrow();
2116}
2117
2118/// void @objc_moveWeak(i8** %dest, i8** %src)
2119/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2120/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2121void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2122 emitARCCopyOperation(*this, dst, src,
2123 CGM.getARCEntrypoints().objc_moveWeak,
2124 "objc_moveWeak");
2125}
2126
2127/// void @objc_copyWeak(i8** %dest, i8** %src)
2128/// Disregards the current value in %dest. Essentially
2129/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2130void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2131 emitARCCopyOperation(*this, dst, src,
2132 CGM.getARCEntrypoints().objc_copyWeak,
2133 "objc_copyWeak");
2134}
2135
2136/// Produce the code to do a objc_autoreleasepool_push.
2137/// call i8* @objc_autoreleasePoolPush(void)
2138llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2139 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2140 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002141 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002142 llvm::FunctionType::get(Int8PtrTy, false);
2143 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2144 }
2145
2146 llvm::CallInst *call = Builder.CreateCall(fn);
2147 call->setDoesNotThrow();
2148
2149 return call;
2150}
2151
2152/// Produce the code to do a primitive release.
2153/// call void @objc_autoreleasePoolPop(i8* %ptr)
2154void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2155 assert(value->getType() == Int8PtrTy);
2156
2157 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2158 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002159 std::vector<llvm::Type*> args(1, Int8PtrTy);
Chris Lattner2192fe52011-07-18 04:24:23 +00002160 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002161 llvm::FunctionType::get(Builder.getVoidTy(), args, false);
2162
2163 // We don't want to use a weak import here; instead we should not
2164 // fall into this path.
2165 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2166 }
2167
2168 llvm::CallInst *call = Builder.CreateCall(fn, value);
2169 call->setDoesNotThrow();
2170}
2171
2172/// Produce the code to do an MRR version objc_autoreleasepool_push.
2173/// Which is: [[NSAutoreleasePool alloc] init];
2174/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2175/// init is declared as: - (id) init; in its NSObject super class.
2176///
2177llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2178 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2179 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(Builder);
2180 // [NSAutoreleasePool alloc]
2181 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2182 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2183 CallArgList Args;
2184 RValue AllocRV =
2185 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2186 getContext().getObjCIdType(),
2187 AllocSel, Receiver, Args);
2188
2189 // [Receiver init]
2190 Receiver = AllocRV.getScalarVal();
2191 II = &CGM.getContext().Idents.get("init");
2192 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2193 RValue InitRV =
2194 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2195 getContext().getObjCIdType(),
2196 InitSel, Receiver, Args);
2197 return InitRV.getScalarVal();
2198}
2199
2200/// Produce the code to do a primitive release.
2201/// [tmp drain];
2202void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2203 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2204 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2205 CallArgList Args;
2206 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2207 getContext().VoidTy, DrainSel, Arg, Args);
2208}
2209
John McCall82fe67b2011-07-09 01:37:26 +00002210void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2211 llvm::Value *addr,
2212 QualType type) {
2213 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2214 CGF.EmitARCRelease(ptr, /*precise*/ true);
2215}
2216
2217void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2218 llvm::Value *addr,
2219 QualType type) {
2220 llvm::Value *ptr = CGF.Builder.CreateLoad(addr, "strongdestroy");
2221 CGF.EmitARCRelease(ptr, /*precise*/ false);
2222}
2223
2224void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2225 llvm::Value *addr,
2226 QualType type) {
2227 CGF.EmitARCDestroyWeak(addr);
2228}
2229
John McCall31168b02011-06-15 23:02:42 +00002230namespace {
John McCall31168b02011-06-15 23:02:42 +00002231 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2232 llvm::Value *Token;
2233
2234 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2235
John McCall30317fd2011-07-12 20:27:29 +00002236 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002237 CGF.EmitObjCAutoreleasePoolPop(Token);
2238 }
2239 };
2240 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2241 llvm::Value *Token;
2242
2243 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2244
John McCall30317fd2011-07-12 20:27:29 +00002245 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall31168b02011-06-15 23:02:42 +00002246 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2247 }
2248 };
2249}
2250
2251void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002252 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002253 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2254 else
2255 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2256}
2257
John McCall31168b02011-06-15 23:02:42 +00002258static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2259 LValue lvalue,
2260 QualType type) {
2261 switch (type.getObjCLifetime()) {
2262 case Qualifiers::OCL_None:
2263 case Qualifiers::OCL_ExplicitNone:
2264 case Qualifiers::OCL_Strong:
2265 case Qualifiers::OCL_Autoreleasing:
John McCall55e1fbc2011-06-25 02:11:03 +00002266 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002267 false);
2268
2269 case Qualifiers::OCL_Weak:
2270 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2271 true);
2272 }
2273
2274 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002275}
2276
2277static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2278 const Expr *e) {
2279 e = e->IgnoreParens();
2280 QualType type = e->getType();
2281
John McCall154a2fd2011-08-30 00:57:29 +00002282 // If we're loading retained from a __strong xvalue, we can avoid
2283 // an extra retain/release pair by zeroing out the source of this
2284 // "move" operation.
2285 if (e->isXValue() &&
2286 !type.isConstQualified() &&
2287 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2288 // Emit the lvalue.
2289 LValue lv = CGF.EmitLValue(e);
2290
2291 // Load the object pointer.
2292 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2293
2294 // Set the source pointer to NULL.
2295 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2296
2297 return TryEmitResult(result, true);
2298 }
2299
John McCall31168b02011-06-15 23:02:42 +00002300 // As a very special optimization, in ARC++, if the l-value is the
2301 // result of a non-volatile assignment, do a simple retain of the
2302 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002303 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002304 !type.isVolatileQualified() &&
2305 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2306 isa<BinaryOperator>(e) &&
2307 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2308 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2309
2310 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2311}
2312
2313static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2314 llvm::Value *value);
2315
2316/// Given that the given expression is some sort of call (which does
2317/// not return retained), emit a retain following it.
2318static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2319 llvm::Value *value = CGF.EmitScalarExpr(e);
2320 return emitARCRetainAfterCall(CGF, value);
2321}
2322
2323static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2324 llvm::Value *value) {
2325 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2326 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2327
2328 // Place the retain immediately following the call.
2329 CGF.Builder.SetInsertPoint(call->getParent(),
2330 ++llvm::BasicBlock::iterator(call));
2331 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2332
2333 CGF.Builder.restoreIP(ip);
2334 return value;
2335 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2336 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2337
2338 // Place the retain at the beginning of the normal destination block.
2339 llvm::BasicBlock *BB = invoke->getNormalDest();
2340 CGF.Builder.SetInsertPoint(BB, BB->begin());
2341 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2342
2343 CGF.Builder.restoreIP(ip);
2344 return value;
2345
2346 // Bitcasts can arise because of related-result returns. Rewrite
2347 // the operand.
2348 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2349 llvm::Value *operand = bitcast->getOperand(0);
2350 operand = emitARCRetainAfterCall(CGF, operand);
2351 bitcast->setOperand(0, operand);
2352 return bitcast;
2353
2354 // Generic fall-back case.
2355 } else {
2356 // Retain using the non-block variant: we never need to do a copy
2357 // of a block that's been returned to us.
2358 return CGF.EmitARCRetainNonBlock(value);
2359 }
2360}
2361
John McCallcd78e802011-09-10 01:16:55 +00002362/// Determine whether it might be important to emit a separate
2363/// objc_retain_block on the result of the given expression, or
2364/// whether it's okay to just emit it in a +1 context.
2365static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2366 assert(e->getType()->isBlockPointerType());
2367 e = e->IgnoreParens();
2368
2369 // For future goodness, emit block expressions directly in +1
2370 // contexts if we can.
2371 if (isa<BlockExpr>(e))
2372 return false;
2373
2374 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2375 switch (cast->getCastKind()) {
2376 // Emitting these operations in +1 contexts is goodness.
2377 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002378 case CK_ARCReclaimReturnedObject:
2379 case CK_ARCConsumeObject:
2380 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002381 return false;
2382
2383 // These operations preserve a block type.
2384 case CK_NoOp:
2385 case CK_BitCast:
2386 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2387
2388 // These operations are known to be bad (or haven't been considered).
2389 case CK_AnyPointerToBlockPointerCast:
2390 default:
2391 return true;
2392 }
2393 }
2394
2395 return true;
2396}
2397
John McCallfe96e0b2011-11-06 09:01:30 +00002398/// Try to emit a PseudoObjectExpr at +1.
2399///
2400/// This massively duplicates emitPseudoObjectRValue.
2401static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2402 const PseudoObjectExpr *E) {
2403 llvm::SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
2404
2405 // Find the result expression.
2406 const Expr *resultExpr = E->getResultExpr();
2407 assert(resultExpr);
2408 TryEmitResult result;
2409
2410 for (PseudoObjectExpr::const_semantics_iterator
2411 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2412 const Expr *semantic = *i;
2413
2414 // If this semantic expression is an opaque value, bind it
2415 // to the result of its source expression.
2416 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2417 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2418 OVMA opaqueData;
2419
2420 // If this semantic is the result of the pseudo-object
2421 // expression, try to evaluate the source as +1.
2422 if (ov == resultExpr) {
2423 assert(!OVMA::shouldBindAsLValue(ov));
2424 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2425 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2426
2427 // Otherwise, just bind it.
2428 } else {
2429 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2430 }
2431 opaques.push_back(opaqueData);
2432
2433 // Otherwise, if the expression is the result, evaluate it
2434 // and remember the result.
2435 } else if (semantic == resultExpr) {
2436 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2437
2438 // Otherwise, evaluate the expression in an ignored context.
2439 } else {
2440 CGF.EmitIgnoredExpr(semantic);
2441 }
2442 }
2443
2444 // Unbind all the opaques now.
2445 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2446 opaques[i].unbind(CGF);
2447
2448 return result;
2449}
2450
John McCall31168b02011-06-15 23:02:42 +00002451static TryEmitResult
2452tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall53848232011-07-27 01:07:15 +00002453 // Look through cleanups.
2454 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
John McCall08ef4662011-11-10 08:15:53 +00002455 CGF.enterFullExpression(cleanups);
John McCall53848232011-07-27 01:07:15 +00002456 CodeGenFunction::RunCleanupsScope scope(CGF);
2457 return tryEmitARCRetainScalarExpr(CGF, cleanups->getSubExpr());
2458 }
2459
John McCall31168b02011-06-15 23:02:42 +00002460 // The desired result type, if it differs from the type of the
2461 // ultimate opaque expression.
Chris Lattner2192fe52011-07-18 04:24:23 +00002462 llvm::Type *resultType = 0;
John McCall31168b02011-06-15 23:02:42 +00002463
2464 while (true) {
2465 e = e->IgnoreParens();
2466
2467 // There's a break at the end of this if-chain; anything
2468 // that wants to keep looping has to explicitly continue.
2469 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2470 switch (ce->getCastKind()) {
2471 // No-op casts don't change the type, so we just ignore them.
2472 case CK_NoOp:
2473 e = ce->getSubExpr();
2474 continue;
2475
2476 case CK_LValueToRValue: {
2477 TryEmitResult loadResult
2478 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2479 if (resultType) {
2480 llvm::Value *value = loadResult.getPointer();
2481 value = CGF.Builder.CreateBitCast(value, resultType);
2482 loadResult.setPointer(value);
2483 }
2484 return loadResult;
2485 }
2486
2487 // These casts can change the type, so remember that and
2488 // soldier on. We only need to remember the outermost such
2489 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002490 case CK_CPointerToObjCPointerCast:
2491 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002492 case CK_AnyPointerToBlockPointerCast:
2493 case CK_BitCast:
2494 if (!resultType)
2495 resultType = CGF.ConvertType(ce->getType());
2496 e = ce->getSubExpr();
2497 assert(e->getType()->hasPointerRepresentation());
2498 continue;
2499
2500 // For consumptions, just emit the subexpression and thus elide
2501 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002502 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002503 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2504 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2505 return TryEmitResult(result, true);
2506 }
2507
John McCallcd78e802011-09-10 01:16:55 +00002508 // Block extends are net +0. Naively, we could just recurse on
2509 // the subexpression, but actually we need to ensure that the
2510 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002511 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002512 llvm::Value *result; // will be a +0 value
2513
2514 // If we can't safely assume the sub-expression will produce a
2515 // block-copied value, emit the sub-expression at +0.
2516 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2517 result = CGF.EmitScalarExpr(ce->getSubExpr());
2518
2519 // Otherwise, try to emit the sub-expression at +1 recursively.
2520 } else {
2521 TryEmitResult subresult
2522 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2523 result = subresult.getPointer();
2524
2525 // If that produced a retained value, just use that,
2526 // possibly casting down.
2527 if (subresult.getInt()) {
2528 if (resultType)
2529 result = CGF.Builder.CreateBitCast(result, resultType);
2530 return TryEmitResult(result, true);
2531 }
2532
2533 // Otherwise it's +0.
2534 }
2535
2536 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002537 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002538 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2539 return TryEmitResult(result, true);
2540 }
2541
John McCall4db5c3c2011-07-07 06:58:02 +00002542 // For reclaims, emit the subexpression as a retained call and
2543 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002544 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002545 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2546 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2547 return TryEmitResult(result, true);
2548 }
2549
John McCall31168b02011-06-15 23:02:42 +00002550 default:
2551 break;
2552 }
2553
2554 // Skip __extension__.
2555 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2556 if (op->getOpcode() == UO_Extension) {
2557 e = op->getSubExpr();
2558 continue;
2559 }
2560
2561 // For calls and message sends, use the retained-call logic.
2562 // Delegate inits are a special case in that they're the only
2563 // returns-retained expression that *isn't* surrounded by
2564 // a consume.
2565 } else if (isa<CallExpr>(e) ||
2566 (isa<ObjCMessageExpr>(e) &&
2567 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2568 llvm::Value *result = emitARCRetainCall(CGF, e);
2569 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2570 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002571
2572 // Look through pseudo-object expressions.
2573 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2574 TryEmitResult result
2575 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2576 if (resultType) {
2577 llvm::Value *value = result.getPointer();
2578 value = CGF.Builder.CreateBitCast(value, resultType);
2579 result.setPointer(value);
2580 }
2581 return result;
John McCall31168b02011-06-15 23:02:42 +00002582 }
2583
2584 // Conservatively halt the search at any other expression kind.
2585 break;
2586 }
2587
2588 // We didn't find an obvious production, so emit what we've got and
2589 // tell the caller that we didn't manage to retain.
2590 llvm::Value *result = CGF.EmitScalarExpr(e);
2591 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2592 return TryEmitResult(result, false);
2593}
2594
2595static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2596 LValue lvalue,
2597 QualType type) {
2598 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2599 llvm::Value *value = result.getPointer();
2600 if (!result.getInt())
2601 value = CGF.EmitARCRetain(type, value);
2602 return value;
2603}
2604
2605/// EmitARCRetainScalarExpr - Semantically equivalent to
2606/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2607/// best-effort attempt to peephole expressions that naturally produce
2608/// retained objects.
2609llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
2610 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2611 llvm::Value *value = result.getPointer();
2612 if (!result.getInt())
2613 value = EmitARCRetain(e->getType(), value);
2614 return value;
2615}
2616
2617llvm::Value *
2618CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
2619 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2620 llvm::Value *value = result.getPointer();
2621 if (result.getInt())
2622 value = EmitARCAutorelease(value);
2623 else
2624 value = EmitARCRetainAutorelease(e->getType(), value);
2625 return value;
2626}
2627
John McCallff613032011-10-04 06:23:45 +00002628llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2629 llvm::Value *result;
2630 bool doRetain;
2631
2632 if (shouldEmitSeparateBlockRetain(e)) {
2633 result = EmitScalarExpr(e);
2634 doRetain = true;
2635 } else {
2636 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2637 result = subresult.getPointer();
2638 doRetain = !subresult.getInt();
2639 }
2640
2641 if (doRetain)
2642 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2643 return EmitObjCConsumeObject(e->getType(), result);
2644}
2645
John McCall248512a2011-10-01 10:32:24 +00002646llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2647 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002648 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002649 // Do so before running any cleanups for the full-expression.
2650 // tryEmitARCRetainScalarExpr does make an effort to do things
2651 // inside cleanups, but there are crazy cases like
2652 // @throw A().foo;
2653 // where a full retain+autorelease is required and would
2654 // otherwise happen after the destructor for the temporary.
John McCall08ef4662011-11-10 08:15:53 +00002655 if (const ExprWithCleanups *ewc = dyn_cast<ExprWithCleanups>(expr)) {
2656 enterFullExpression(ewc);
John McCall248512a2011-10-01 10:32:24 +00002657 expr = ewc->getSubExpr();
John McCall08ef4662011-11-10 08:15:53 +00002658 }
John McCall248512a2011-10-01 10:32:24 +00002659
John McCall08ef4662011-11-10 08:15:53 +00002660 CodeGenFunction::RunCleanupsScope cleanups(*this);
John McCall248512a2011-10-01 10:32:24 +00002661 return EmitARCRetainAutoreleaseScalarExpr(expr);
2662 }
2663
2664 // Otherwise, use the normal scalar-expression emission. The
2665 // exception machinery doesn't do anything special with the
2666 // exception like retaining it, so there's no safety associated with
2667 // only running cleanups after the throw has started, and when it
2668 // matters it tends to be substantially inferior code.
2669 return EmitScalarExpr(expr);
2670}
2671
John McCall31168b02011-06-15 23:02:42 +00002672std::pair<LValue,llvm::Value*>
2673CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2674 bool ignored) {
2675 // Evaluate the RHS first.
2676 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2677 llvm::Value *value = result.getPointer();
2678
John McCallb726a552011-07-28 07:23:35 +00002679 bool hasImmediateRetain = result.getInt();
2680
2681 // If we didn't emit a retained object, and the l-value is of block
2682 // type, then we need to emit the block-retain immediately in case
2683 // it invalidates the l-value.
2684 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002685 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002686 hasImmediateRetain = true;
2687 }
2688
John McCall31168b02011-06-15 23:02:42 +00002689 LValue lvalue = EmitLValue(e->getLHS());
2690
2691 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002692 if (hasImmediateRetain) {
John McCall31168b02011-06-15 23:02:42 +00002693 llvm::Value *oldValue =
Eli Friedmana0544d62011-12-03 04:14:32 +00002694 EmitLoadOfScalar(lvalue);
2695 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002696 EmitARCRelease(oldValue, /*precise*/ false);
2697 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002698 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002699 }
2700
2701 return std::pair<LValue,llvm::Value*>(lvalue, value);
2702}
2703
2704std::pair<LValue,llvm::Value*>
2705CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2706 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2707 LValue lvalue = EmitLValue(e->getLHS());
2708
Eli Friedmana0544d62011-12-03 04:14:32 +00002709 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002710
2711 return std::pair<LValue,llvm::Value*>(lvalue, value);
2712}
2713
2714void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002715 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002716 const Stmt *subStmt = ARPS.getSubStmt();
2717 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2718
2719 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002720 if (DI)
2721 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002722
2723 // Keep track of the current cleanup stack depth.
2724 RunCleanupsScope Scope(*this);
John McCall24fc0de2011-07-06 00:26:06 +00002725 if (CGM.getCodeGenOpts().ObjCRuntimeHasARC) {
John McCall31168b02011-06-15 23:02:42 +00002726 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2727 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2728 } else {
2729 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2730 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2731 }
2732
2733 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2734 E = S.body_end(); I != E; ++I)
2735 EmitStmt(*I);
2736
Eric Christopher7cdf9482011-10-13 21:45:18 +00002737 if (DI)
2738 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002739}
John McCall1bd25562011-06-24 23:21:27 +00002740
2741/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2742/// make sure it survives garbage collection until this point.
2743void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2744 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002745 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002746 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002747 llvm::Value *extender
2748 = llvm::InlineAsm::get(extenderType,
2749 /* assembly */ "",
2750 /* constraints */ "r",
2751 /* side effects */ true);
2752
2753 object = Builder.CreateBitCast(object, VoidPtrTy);
2754 Builder.CreateCall(extender, object)->setDoesNotThrow();
2755}
2756
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002757/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002758/// non-trivial copy assignment function, produce following helper function.
2759/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2760///
2761llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002762CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2763 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002764 // FIXME. This api is for NeXt runtime only for now.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002765 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002766 return 0;
2767 QualType Ty = PID->getPropertyIvarDecl()->getType();
2768 if (!Ty->isRecordType())
2769 return 0;
2770 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002771 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002772 return 0;
Fariborz Jahanian1bed4132012-01-08 19:13:23 +00002773 llvm::Constant * HelperFn = 0;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002774 if (hasTrivialSetExpr(PID))
2775 return 0;
2776 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2777 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2778 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002779
2780 ASTContext &C = getContext();
2781 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002782 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002783 FunctionDecl *FD = FunctionDecl::Create(C,
2784 C.getTranslationUnitDecl(),
2785 SourceLocation(),
2786 SourceLocation(), II, C.VoidTy, 0,
2787 SC_Static,
2788 SC_None,
2789 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002790 false);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002791
2792 QualType DestTy = C.getPointerType(Ty);
2793 QualType SrcTy = Ty;
2794 SrcTy.addConst();
2795 SrcTy = C.getPointerType(SrcTy);
2796
2797 FunctionArgList args;
2798 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2799 args.push_back(&dstDecl);
2800 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2801 args.push_back(&srcDecl);
2802
2803 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002804 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2805 FunctionType::ExtInfo(),
2806 RequiredArgs::All);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002807
John McCalla729c622012-02-17 03:33:10 +00002808 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002809
2810 llvm::Function *Fn =
2811 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002812 "__assign_helper_atomic_property_",
2813 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002814
2815 if (CGM.getModuleDebugInfo())
2816 DebugInfo = CGM.getModuleDebugInfo();
2817
2818
2819 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2820
John McCall113bee02012-03-10 09:33:50 +00002821 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2822 VK_RValue, SourceLocation());
2823 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2824 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002825
John McCall113bee02012-03-10 09:33:50 +00002826 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2827 VK_RValue, SourceLocation());
2828 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2829 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002830
John McCall113bee02012-03-10 09:33:50 +00002831 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002832 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002833 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
2834 Args, 2, DestTy->getPointeeType(),
2835 VK_LValue, SourceLocation());
2836
2837 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002838
2839 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002840 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002841 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002842 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002843}
2844
2845llvm::Constant *
2846CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2847 const ObjCPropertyImplDecl *PID) {
2848 // FIXME. This api is for NeXt runtime only for now.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002849 if (!getLangOpts().CPlusPlus || !getLangOpts().NeXTRuntime)
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002850 return 0;
2851 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2852 QualType Ty = PD->getType();
2853 if (!Ty->isRecordType())
2854 return 0;
2855 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2856 return 0;
2857 llvm::Constant * HelperFn = 0;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002858
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002859 if (hasTrivialGetExpr(PID))
2860 return 0;
2861 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2862 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2863 return HelperFn;
2864
2865
2866 ASTContext &C = getContext();
2867 IdentifierInfo *II
2868 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2869 FunctionDecl *FD = FunctionDecl::Create(C,
2870 C.getTranslationUnitDecl(),
2871 SourceLocation(),
2872 SourceLocation(), II, C.VoidTy, 0,
2873 SC_Static,
2874 SC_None,
2875 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002876 false);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002877
2878 QualType DestTy = C.getPointerType(Ty);
2879 QualType SrcTy = Ty;
2880 SrcTy.addConst();
2881 SrcTy = C.getPointerType(SrcTy);
2882
2883 FunctionArgList args;
2884 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2885 args.push_back(&dstDecl);
2886 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2887 args.push_back(&srcDecl);
2888
2889 const CGFunctionInfo &FI =
John McCalla729c622012-02-17 03:33:10 +00002890 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2891 FunctionType::ExtInfo(),
2892 RequiredArgs::All);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002893
John McCalla729c622012-02-17 03:33:10 +00002894 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002895
2896 llvm::Function *Fn =
2897 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2898 "__copy_helper_atomic_property_", &CGM.getModule());
2899
2900 if (CGM.getModuleDebugInfo())
2901 DebugInfo = CGM.getModuleDebugInfo();
2902
2903
2904 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2905
John McCall113bee02012-03-10 09:33:50 +00002906 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002907 VK_RValue, SourceLocation());
2908
John McCall113bee02012-03-10 09:33:50 +00002909 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2910 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002911
2912 CXXConstructExpr *CXXConstExpr =
2913 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2914
2915 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00002916 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002917 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2918 ++A;
2919
2920 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2921 A != AEnd; ++A)
2922 ConstructorArgs.push_back(*A);
2923
2924 CXXConstructExpr *TheCXXConstructExpr =
2925 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2926 CXXConstExpr->getConstructor(),
2927 CXXConstExpr->isElidable(),
2928 &ConstructorArgs[0], ConstructorArgs.size(),
Sebastian Redla9351792012-02-11 23:51:47 +00002929 CXXConstExpr->hadMultipleCandidates(),
2930 CXXConstExpr->isListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002931 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002932 CXXConstExpr->getConstructionKind(),
2933 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002934
John McCall113bee02012-03-10 09:33:50 +00002935 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2936 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002937
John McCall113bee02012-03-10 09:33:50 +00002938 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002939 CharUnits Alignment
2940 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002941 EmitAggExpr(TheCXXConstructExpr,
2942 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2943 AggValueSlot::IsDestructed,
2944 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00002945 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002946
2947 FinishFunction();
2948 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2949 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2950 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002951}
2952
Eli Friedmanec75fec2012-02-28 01:08:45 +00002953llvm::Value *
2954CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2955 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00002956 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2957 Selector CopySelector =
2958 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00002959 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
2960 Selector AutoreleaseSelector =
2961 getContext().Selectors.getNullarySelector(AutoreleaseID);
2962
2963 // Emit calls to retain/autorelease.
2964 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
2965 llvm::Value *Val = Block;
2966 RValue Result;
2967 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00002968 Ty, CopySelector,
Eli Friedmanec75fec2012-02-28 01:08:45 +00002969 Val, CallArgList(), 0, 0);
2970 Val = Result.getScalarVal();
2971 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2972 Ty, AutoreleaseSelector,
2973 Val, CallArgList(), 0, 0);
2974 Val = Result.getScalarVal();
2975 return Val;
2976}
2977
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002978
Ted Kremenek43e06332008-04-09 15:51:31 +00002979CGObjCRuntime::~CGObjCRuntime() {}