blob: dfad13accf3e65d6374570e495c64391c0bf9cd6 [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"
Mark Laceya8e7df32013-10-30 21:53:58 +000023#include "clang/CodeGen/CGFunctionInfo.h"
Anders Carlsson2e744e82008-08-30 19:51:14 +000024#include "llvm/ADT/STLExtras.h"
Chandler Carruthc80ceea2014-03-04 11:02:08 +000025#include "llvm/IR/CallSite.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000026#include "llvm/IR/DataLayout.h"
27#include "llvm/IR/InlineAsm.h"
Anders Carlsson76f4a902007-08-21 17:43:55 +000028using namespace clang;
29using namespace CodeGen;
30
John McCall31168b02011-06-15 23:02:42 +000031typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
32static TryEmitResult
33tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremeneke65b0862012-03-06 20:05:56 +000034static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +000035 QualType ET,
Ted Kremeneke65b0862012-03-06 20:05:56 +000036 const ObjCMethodDecl *Method,
37 RValue Result);
John McCall31168b02011-06-15 23:02:42 +000038
39/// Given the address of a variable of pointer type, find the correct
40/// null to store into it.
41static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2192fe52011-07-18 04:24:23 +000042 llvm::Type *type =
John McCall31168b02011-06-15 23:02:42 +000043 cast<llvm::PointerType>(addr->getType())->getElementType();
44 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
45}
46
Chris Lattnerb1d329d2008-06-24 17:04:18 +000047/// Emits an instance of NSConstantString representing the object.
Mike Stump11289f42009-09-09 15:08:12 +000048llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar44b58a22008-11-25 21:53:21 +000049{
David Chisnall481e3a82010-01-23 02:40:42 +000050 llvm::Constant *C =
51 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbar66912a12008-08-20 00:28:19 +000052 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Andersonade90fd2009-07-29 18:54:39 +000053 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattnerb1d329d2008-06-24 17:04:18 +000054}
55
Patrick Beard0caa3942012-04-19 00:25:12 +000056/// EmitObjCBoxedExpr - This routine generates code to call
57/// the appropriate expression boxing method. This will either be
58/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremeneke65b0862012-03-06 20:05:56 +000059///
Eric Christopher5d2b8d92012-03-29 17:31:31 +000060llvm::Value *
Patrick Beard0caa3942012-04-19 00:25:12 +000061CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000062 // Generate the correct selector for this literal's concrete type.
Ted Kremeneke65b0862012-03-06 20:05:56 +000063 // Get the method.
Patrick Beard0caa3942012-04-19 00:25:12 +000064 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
65 assert(BoxingMethod && "BoxingMethod is null");
66 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
67 Selector Sel = BoxingMethod->getSelector();
Ted Kremeneke65b0862012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beard0caa3942012-04-19 00:25:12 +000070 // Assumes that the method was introduced in the class that should be
71 // messaged (avoids pulling it out of the result type).
Ted Kremeneke65b0862012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beard0caa3942012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCall882987f2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000075
Ted Kremeneke65b0862012-03-06 20:05:56 +000076 CallArgList Args;
Fariborz Jahanian661a97b2014-12-18 17:13:56 +000077 EmitCallArgs(Args, BoxingMethod, E->arg_begin(), E->arg_end());
Alp Toker314cc812014-01-25 16:55:45 +000078
79 RValue result = Runtime.GenerateMessageSend(
80 *this, ReturnValueSlot(), BoxingMethod->getReturnType(), Sel, Receiver,
81 Args, ClassDecl, BoxingMethod);
Ted Kremeneke65b0862012-03-06 20:05:56 +000082 return Builder.CreateBitCast(result.getScalarVal(),
83 ConvertType(E->getType()));
84}
85
86llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +000087 const ObjCMethodDecl *MethodWithObjects) {
Ted Kremeneke65b0862012-03-06 20:05:56 +000088 ASTContext &Context = CGM.getContext();
Craig Topper8a13c412014-05-21 05:09:00 +000089 const ObjCDictionaryLiteral *DLE = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +000090 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
91 if (!ALE)
92 DLE = cast<ObjCDictionaryLiteral>(E);
93
94 // Compute the type of the array we're initializing.
95 uint64_t NumElements =
96 ALE ? ALE->getNumElements() : DLE->getNumElements();
97 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
98 NumElements);
99 QualType ElementType = Context.getObjCIdType().withConst();
100 QualType ElementArrayType
101 = Context.getConstantArrayType(ElementType, APNumElements,
102 ArrayType::Normal, /*IndexTypeQuals=*/0);
103
104 // Allocate the temporary array(s).
David Blaikie1ed728c2015-04-05 22:45:47 +0000105 llvm::AllocaInst *Objects = CreateMemTemp(ElementArrayType, "objects");
106 llvm::AllocaInst *Keys = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +0000107 if (DLE)
108 Keys = CreateMemTemp(ElementArrayType, "keys");
109
John McCall770a4c12013-04-04 00:20:38 +0000110 // In ARC, we may need to do extra work to keep all the keys and
111 // values alive until after the call.
112 SmallVector<llvm::Value *, 16> NeededObjects;
113 bool TrackNeededObjects =
114 (getLangOpts().ObjCAutoRefCount &&
115 CGM.getCodeGenOpts().OptimizationLevel != 0);
116
Ted Kremeneke65b0862012-03-06 20:05:56 +0000117 // Perform the actual initialialization of the array(s).
118 for (uint64_t i = 0; i < NumElements; i++) {
119 if (ALE) {
John McCall770a4c12013-04-04 00:20:38 +0000120 // Emit the element and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000121 const Expr *Rhs = ALE->getElement(i);
David Blaikie1ed728c2015-04-05 22:45:47 +0000122 LValue LV = LValue::MakeAddr(
123 Builder.CreateStructGEP(Objects->getAllocatedType(), Objects, i),
124 ElementType, Context.getTypeAlignInChars(Rhs->getType()), Context);
John McCall770a4c12013-04-04 00:20:38 +0000125
126 llvm::Value *value = EmitScalarExpr(Rhs);
127 EmitStoreThroughLValue(RValue::get(value), LV, true);
128 if (TrackNeededObjects) {
129 NeededObjects.push_back(value);
130 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000131 } else {
John McCall770a4c12013-04-04 00:20:38 +0000132 // Emit the key and store it to the appropriate array slot.
Ted Kremeneke65b0862012-03-06 20:05:56 +0000133 const Expr *Key = DLE->getKeyValueElement(i).Key;
David Blaikie1ed728c2015-04-05 22:45:47 +0000134 LValue KeyLV = LValue::MakeAddr(
135 Builder.CreateStructGEP(Keys->getAllocatedType(), Keys, i),
136 ElementType, Context.getTypeAlignInChars(Key->getType()), Context);
John McCall770a4c12013-04-04 00:20:38 +0000137 llvm::Value *keyValue = EmitScalarExpr(Key);
138 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000139
John McCall770a4c12013-04-04 00:20:38 +0000140 // Emit the value and store it to the appropriate array slot.
David Blaikie1ed728c2015-04-05 22:45:47 +0000141 const Expr *Value = DLE->getKeyValueElement(i).Value;
142 LValue ValueLV = LValue::MakeAddr(
143 Builder.CreateStructGEP(Objects->getAllocatedType(), Objects, i),
144 ElementType, Context.getTypeAlignInChars(Value->getType()), Context);
John McCall770a4c12013-04-04 00:20:38 +0000145 llvm::Value *valueValue = EmitScalarExpr(Value);
146 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
147 if (TrackNeededObjects) {
148 NeededObjects.push_back(keyValue);
149 NeededObjects.push_back(valueValue);
150 }
Ted Kremeneke65b0862012-03-06 20:05:56 +0000151 }
152 }
153
154 // Generate the argument list.
155 CallArgList Args;
156 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
157 const ParmVarDecl *argDecl = *PI++;
158 QualType ArgQT = argDecl->getType().getUnqualifiedType();
159 Args.add(RValue::get(Objects), ArgQT);
160 if (DLE) {
161 argDecl = *PI++;
162 ArgQT = argDecl->getType().getUnqualifiedType();
163 Args.add(RValue::get(Keys), ArgQT);
164 }
165 argDecl = *PI;
166 ArgQT = argDecl->getType().getUnqualifiedType();
167 llvm::Value *Count =
168 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
169 Args.add(RValue::get(Count), ArgQT);
170
171 // Generate a reference to the class pointer, which will be the receiver.
172 Selector Sel = MethodWithObjects->getSelector();
173 QualType ResultType = E->getType();
174 const ObjCObjectPointerType *InterfacePointerType
175 = ResultType->getAsObjCInterfacePointerType();
176 ObjCInterfaceDecl *Class
177 = InterfacePointerType->getObjectType()->getInterface();
178 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +0000179 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremeneke65b0862012-03-06 20:05:56 +0000180
181 // Generate the message send.
Alp Toker314cc812014-01-25 16:55:45 +0000182 RValue result = Runtime.GenerateMessageSend(
183 *this, ReturnValueSlot(), MethodWithObjects->getReturnType(), Sel,
184 Receiver, Args, Class, MethodWithObjects);
John McCall770a4c12013-04-04 00:20:38 +0000185
186 // The above message send needs these objects, but in ARC they are
187 // passed in a buffer that is essentially __unsafe_unretained.
188 // Therefore we must prevent the optimizer from releasing them until
189 // after the call.
190 if (TrackNeededObjects) {
191 EmitARCIntrinsicUse(NeededObjects);
192 }
193
Ted Kremeneke65b0862012-03-06 20:05:56 +0000194 return Builder.CreateBitCast(result.getScalarVal(),
195 ConvertType(E->getType()));
196}
197
198llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000199 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000200}
201
202llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
203 const ObjCDictionaryLiteral *E) {
Fariborz Jahanian9ad94aa2014-10-28 18:28:16 +0000204 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
Ted Kremeneke65b0862012-03-06 20:05:56 +0000205}
206
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000207/// Emit a selector.
208llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
209 // Untyped selector.
210 // Note that this implementation allows for non-constant strings to be passed
211 // as arguments to @selector(). Currently, the only thing preventing this
212 // behaviour is the type checking in the front end.
John McCall882987f2013-02-28 19:01:20 +0000213 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000214}
215
Daniel Dunbar66912a12008-08-20 00:28:19 +0000216llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
217 // FIXME: This should pass the Decl not the name.
John McCall882987f2013-02-28 19:01:20 +0000218 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbar66912a12008-08-20 00:28:19 +0000219}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000220
Douglas Gregor33823722011-06-11 01:09:30 +0000221/// \brief Adjust the type of the result of an Objective-C message send
222/// expression when the method has a related result type.
223static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000224 QualType ExpT,
Douglas Gregor33823722011-06-11 01:09:30 +0000225 const ObjCMethodDecl *Method,
226 RValue Result) {
227 if (!Method)
228 return Result;
John McCall31168b02011-06-15 23:02:42 +0000229
Douglas Gregor33823722011-06-11 01:09:30 +0000230 if (!Method->hasRelatedResultType() ||
Alp Toker314cc812014-01-25 16:55:45 +0000231 CGF.getContext().hasSameType(ExpT, Method->getReturnType()) ||
Douglas Gregor33823722011-06-11 01:09:30 +0000232 !Result.isScalar())
233 return Result;
234
235 // We have applied a related result type. Cast the rvalue appropriately.
236 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000237 CGF.ConvertType(ExpT)));
Douglas Gregor33823722011-06-11 01:09:30 +0000238}
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000239
John McCallcf166702011-07-22 08:53:00 +0000240/// Decide whether to extend the lifetime of the receiver of a
241/// returns-inner-pointer message.
242static bool
243shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
244 switch (message->getReceiverKind()) {
245
246 // For a normal instance message, we should extend unless the
247 // receiver is loaded from a variable with precise lifetime.
248 case ObjCMessageExpr::Instance: {
249 const Expr *receiver = message->getInstanceReceiver();
250 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
251 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
252 receiver = ice->getSubExpr()->IgnoreParens();
253
254 // Only __strong variables.
255 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
256 return true;
257
258 // All ivars and fields have precise lifetime.
259 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
260 return false;
261
262 // Otherwise, check for variables.
263 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
264 if (!declRef) return true;
265 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
266 if (!var) return true;
267
268 // All variables have precise lifetime except local variables with
269 // automatic storage duration that aren't specially marked.
270 return (var->hasLocalStorage() &&
271 !var->hasAttr<ObjCPreciseLifetimeAttr>());
272 }
273
274 case ObjCMessageExpr::Class:
275 case ObjCMessageExpr::SuperClass:
276 // It's never necessary for class objects.
277 return false;
278
279 case ObjCMessageExpr::SuperInstance:
280 // We generally assume that 'self' lives throughout a method call.
281 return false;
282 }
283
284 llvm_unreachable("invalid receiver kind");
285}
286
John McCall78a15112010-05-22 01:48:05 +0000287RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
288 ReturnValueSlot Return) {
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000289 // Only the lookup mechanism and first two arguments of the method
290 // implementation vary between runtimes. We can get the receiver and
291 // arguments in generic code.
Mike Stump11289f42009-09-09 15:08:12 +0000292
John McCall31168b02011-06-15 23:02:42 +0000293 bool isDelegateInit = E->isDelegateInitCall();
294
John McCallcf166702011-07-22 08:53:00 +0000295 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000296
John McCall31168b02011-06-15 23:02:42 +0000297 // We don't retain the receiver in delegate init calls, and this is
298 // safe because the receiver value is always loaded from 'self',
299 // which we zero out. We don't want to Block_copy block receivers,
300 // though.
301 bool retainSelf =
302 (!isDelegateInit &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000303 CGM.getLangOpts().ObjCAutoRefCount &&
John McCallcf166702011-07-22 08:53:00 +0000304 method &&
305 method->hasAttr<NSConsumesSelfAttr>());
John McCall31168b02011-06-15 23:02:42 +0000306
Daniel Dunbar8d480592008-08-11 18:12:00 +0000307 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000308 bool isSuperMessage = false;
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000309 bool isClassMessage = false;
Craig Topper8a13c412014-05-21 05:09:00 +0000310 ObjCInterfaceDecl *OID = nullptr;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000311 // Find the receiver
Douglas Gregor33823722011-06-11 01:09:30 +0000312 QualType ReceiverType;
Craig Topper8a13c412014-05-21 05:09:00 +0000313 llvm::Value *Receiver = nullptr;
Douglas Gregor9a129192010-04-21 00:45:42 +0000314 switch (E->getReceiverKind()) {
315 case ObjCMessageExpr::Instance:
Douglas Gregor33823722011-06-11 01:09:30 +0000316 ReceiverType = E->getInstanceReceiver()->getType();
John McCall31168b02011-06-15 23:02:42 +0000317 if (retainSelf) {
318 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
319 E->getInstanceReceiver());
320 Receiver = ter.getPointer();
John McCallcf166702011-07-22 08:53:00 +0000321 if (ter.getInt()) retainSelf = false;
John McCall31168b02011-06-15 23:02:42 +0000322 } else
323 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor9a129192010-04-21 00:45:42 +0000324 break;
Daniel Dunbar7c6d3a72008-08-16 00:25:02 +0000325
Douglas Gregor9a129192010-04-21 00:45:42 +0000326 case ObjCMessageExpr::Class: {
Douglas Gregor33823722011-06-11 01:09:30 +0000327 ReceiverType = E->getClassReceiver();
328 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3e294922010-05-17 20:12:43 +0000329 assert(ObjTy && "Invalid Objective-C class message send");
330 OID = ObjTy->getInterface();
331 assert(OID && "Invalid Objective-C class message send");
John McCall882987f2013-02-28 19:01:20 +0000332 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarca8531a2008-08-25 08:19:24 +0000333 isClassMessage = true;
Douglas Gregor9a129192010-04-21 00:45:42 +0000334 break;
335 }
336
337 case ObjCMessageExpr::SuperInstance:
Douglas Gregor33823722011-06-11 01:09:30 +0000338 ReceiverType = E->getSuperType();
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000339 Receiver = LoadObjCSelf();
Douglas Gregor9a129192010-04-21 00:45:42 +0000340 isSuperMessage = true;
341 break;
342
343 case ObjCMessageExpr::SuperClass:
Douglas Gregor33823722011-06-11 01:09:30 +0000344 ReceiverType = E->getSuperType();
Douglas Gregor9a129192010-04-21 00:45:42 +0000345 Receiver = LoadObjCSelf();
346 isSuperMessage = true;
347 isClassMessage = true;
348 break;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000349 }
350
John McCallcf166702011-07-22 08:53:00 +0000351 if (retainSelf)
352 Receiver = EmitARCRetainNonBlock(Receiver);
353
354 // In ARC, we sometimes want to "extend the lifetime"
355 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
356 // messages.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000357 if (getLangOpts().ObjCAutoRefCount && method &&
John McCallcf166702011-07-22 08:53:00 +0000358 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
359 shouldExtendReceiverForInnerPointerMessage(E))
360 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
361
Alp Toker314cc812014-01-25 16:55:45 +0000362 QualType ResultType = method ? method->getReturnType() : E->getType();
John McCall31168b02011-06-15 23:02:42 +0000363
Daniel Dunbarc722b852008-08-30 03:02:31 +0000364 CallArgList Args;
John McCallcf166702011-07-22 08:53:00 +0000365 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump11289f42009-09-09 15:08:12 +0000366
John McCall31168b02011-06-15 23:02:42 +0000367 // For delegate init calls in ARC, do an unsafe store of null into
368 // self. This represents the call taking direct ownership of that
369 // value. We have to do this after emitting the other call
370 // arguments because they might also reference self, but we don't
371 // have to worry about any of them modifying self because that would
372 // be an undefined read and write of an object in unordered
373 // expressions.
374 if (isDelegateInit) {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000375 assert(getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000376 "delegate init calls should only be marked in ARC");
377
378 // Do an unsafe store of null into self.
379 llvm::Value *selfAddr =
380 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
381 assert(selfAddr && "no self entry for a delegate init call?");
382
383 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
384 }
Anders Carlsson280e61f12010-06-21 20:59:55 +0000385
Douglas Gregor33823722011-06-11 01:09:30 +0000386 RValue result;
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000387 if (isSuperMessage) {
Chris Lattner6cfec782008-06-26 04:42:20 +0000388 // super is only valid in an Objective-C method
389 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanianbac73ac2009-02-28 20:07:56 +0000390 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor33823722011-06-11 01:09:30 +0000391 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
392 E->getSelector(),
393 OMD->getClassInterface(),
394 isCategoryImpl,
395 Receiver,
396 isClassMessage,
397 Args,
John McCallcf166702011-07-22 08:53:00 +0000398 method);
Douglas Gregor33823722011-06-11 01:09:30 +0000399 } else {
400 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
401 E->getSelector(),
402 Receiver, Args, OID,
John McCallcf166702011-07-22 08:53:00 +0000403 method);
Chris Lattnerb1d329d2008-06-24 17:04:18 +0000404 }
John McCall31168b02011-06-15 23:02:42 +0000405
406 // For delegate init calls in ARC, implicitly store the result of
407 // the call back into self. This takes ownership of the value.
408 if (isDelegateInit) {
409 llvm::Value *selfAddr =
410 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
411 llvm::Value *newSelf = result.getScalarVal();
412
413 // The delegate return type isn't necessarily a matching type; in
414 // fact, it's quite likely to be 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +0000415 llvm::Type *selfTy =
John McCall31168b02011-06-15 23:02:42 +0000416 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
417 newSelf = Builder.CreateBitCast(newSelf, selfTy);
418
419 Builder.CreateStore(newSelf, selfAddr);
420 }
Fariborz Jahanian715fdd52012-01-29 20:27:13 +0000421
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000422 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson76f4a902007-08-21 17:43:55 +0000423}
424
John McCall31168b02011-06-15 23:02:42 +0000425namespace {
426struct FinishARCDealloc : EHScopeStack::Cleanup {
Craig Topper4f12f102014-03-12 06:41:41 +0000427 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +0000428 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCalldffafde2011-07-13 18:26:47 +0000429
430 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCall31168b02011-06-15 23:02:42 +0000431 const ObjCInterfaceDecl *iface = impl->getClassInterface();
432 if (!iface->getSuperClass()) return;
433
John McCalldffafde2011-07-13 18:26:47 +0000434 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
435
John McCall31168b02011-06-15 23:02:42 +0000436 // Call [super dealloc] if we have a superclass.
437 llvm::Value *self = CGF.LoadObjCSelf();
438
439 CallArgList args;
440 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
441 CGF.getContext().VoidTy,
442 method->getSelector(),
443 iface,
John McCalldffafde2011-07-13 18:26:47 +0000444 isCategory,
John McCall31168b02011-06-15 23:02:42 +0000445 self,
446 /*is class msg*/ false,
447 args,
448 method);
449 }
450};
451}
452
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000453/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
454/// the LLVM function and sets the other context used by
455/// CodeGenFunction.
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000456void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
David Blaikief1425802015-01-14 00:04:42 +0000457 const ObjCContainerDecl *CD) {
458 SourceLocation StartLoc = OMD->getLocStart();
John McCalla738c252011-03-09 04:27:21 +0000459 FunctionArgList args;
Devang Patela2c048e2010-04-05 21:09:15 +0000460 // Check if we should generate debug info for this method.
David Blaikie92848de2013-08-26 20:33:21 +0000461 if (OMD->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000462 DebugInfo = nullptr; // disable debug info indefinitely for this function
Devang Patela2c048e2010-04-05 21:09:15 +0000463
Fariborz Jahanian0196a1c2009-01-10 21:06:09 +0000464 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbar449a3392008-09-04 23:41:35 +0000465
John McCalla729c622012-02-17 03:33:10 +0000466 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbarc3e7cff2009-04-17 00:48:04 +0000467 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner5696e7b2008-06-17 18:05:57 +0000468
John McCalla738c252011-03-09 04:27:21 +0000469 args.push_back(OMD->getSelfDecl());
470 args.push_back(OMD->getCmdDecl());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000471
Benjamin Kramerf9890422015-02-17 16:48:30 +0000472 args.append(OMD->param_begin(), OMD->param_end());
Chris Lattner5696e7b2008-06-17 18:05:57 +0000473
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000474 CurGD = OMD;
David Blaikie47d28e02015-01-14 07:10:46 +0000475 CurEHLocation = OMD->getLocEnd();
Peter Collingbourne0ff0b372011-01-13 18:57:25 +0000476
Adrian Prantl42d71b92014-04-10 23:21:53 +0000477 StartFunction(OMD, OMD->getReturnType(), Fn, FI, args,
478 OMD->getLocation(), StartLoc);
John McCall31168b02011-06-15 23:02:42 +0000479
480 // In ARC, certain methods get an extra cleanup.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000481 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +0000482 OMD->isInstanceMethod() &&
483 OMD->getSelector().isUnarySelector()) {
484 const IdentifierInfo *ident =
485 OMD->getSelector().getIdentifierInfoForSlot(0);
486 if (ident->isStr("dealloc"))
487 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
488 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000489}
Daniel Dunbara94ecd22008-08-16 03:19:19 +0000490
John McCall31168b02011-06-15 23:02:42 +0000491static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
492 LValue lvalue, QualType type);
493
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000494/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump11289f42009-09-09 15:08:12 +0000495/// its pointer, name, and types registered in the class struture.
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000496void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
David Blaikief1425802015-01-14 00:04:42 +0000497 StartObjCMethod(OMD, OMD->getClassInterface());
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000498 PGO.assignRegionCounters(OMD, CurFn);
Adrian Prantl56741e22014-01-07 22:05:55 +0000499 assert(isa<CompoundStmt>(OMD->getBody()));
Bob Wilson5ec8fe12014-03-06 06:10:02 +0000500 RegionCounter Cnt = getPGORegionCounter(OMD->getBody());
501 Cnt.beginRegion(Builder);
Adrian Prantl56741e22014-01-07 22:05:55 +0000502 EmitCompoundStmtWithoutScope(*cast<CompoundStmt>(OMD->getBody()));
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +0000503 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000504}
505
John McCallb923ece2011-09-12 23:06:44 +0000506/// emitStructGetterCall - Call the runtime function to load a property
507/// into the return value slot.
508static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
509 bool isAtomic, bool hasStrong) {
510 ASTContext &Context = CGF.getContext();
511
512 llvm::Value *src =
513 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
514 ivar, 0).getAddress();
515
516 // objc_copyStruct (ReturnValue, &structIvar,
517 // sizeof (Type of Ivar), isAtomic, false);
518 CallArgList args;
519
520 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
521 args.add(RValue::get(dest), Context.VoidPtrTy);
522
523 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
524 args.add(RValue::get(src), Context.VoidPtrTy);
525
526 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
527 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
528 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
529 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
530
531 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000532 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
533 FunctionType::ExtInfo(),
534 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +0000535 fn, ReturnValueSlot(), args);
536}
537
John McCallf4528ae2011-09-13 03:34:09 +0000538/// Determine whether the given architecture supports unaligned atomic
539/// accesses. They don't have to be fast, just faster than a function
540/// call and a mutex.
541static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedman5be3e6a2011-09-13 20:48:30 +0000542 // FIXME: Allow unaligned atomic load/store on x86. (It is not
543 // currently supported by the backend.)
544 return 0;
John McCallf4528ae2011-09-13 03:34:09 +0000545}
546
547/// Return the maximum size that permits atomic accesses for the given
548/// architecture.
549static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
550 llvm::Triple::ArchType arch) {
551 // ARM has 8-byte atomic accesses, but it's not clear whether we
552 // want to rely on them here.
553
554 // In the default case, just assume that any size up to a pointer is
555 // fine given adequate alignment.
556 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
557}
558
559namespace {
560 class PropertyImplStrategy {
561 public:
562 enum StrategyKind {
563 /// The 'native' strategy is to use the architecture's provided
564 /// reads and writes.
565 Native,
566
567 /// Use objc_setProperty and objc_getProperty.
568 GetSetProperty,
569
570 /// Use objc_setProperty for the setter, but use expression
571 /// evaluation for the getter.
572 SetPropertyAndExpressionGet,
573
574 /// Use objc_copyStruct.
575 CopyStruct,
576
577 /// The 'expression' strategy is to emit normal assignment or
578 /// lvalue-to-rvalue expressions.
579 Expression
580 };
581
582 StrategyKind getKind() const { return StrategyKind(Kind); }
583
584 bool hasStrongMember() const { return HasStrong; }
585 bool isAtomic() const { return IsAtomic; }
586 bool isCopy() const { return IsCopy; }
587
588 CharUnits getIvarSize() const { return IvarSize; }
589 CharUnits getIvarAlignment() const { return IvarAlignment; }
590
591 PropertyImplStrategy(CodeGenModule &CGM,
592 const ObjCPropertyImplDecl *propImpl);
593
594 private:
595 unsigned Kind : 8;
596 unsigned IsAtomic : 1;
597 unsigned IsCopy : 1;
598 unsigned HasStrong : 1;
599
600 CharUnits IvarSize;
601 CharUnits IvarAlignment;
602 };
603}
604
Sylvestre Ledru830885c2012-07-23 08:59:39 +0000605/// Pick an implementation strategy for the given property synthesis.
John McCallf4528ae2011-09-13 03:34:09 +0000606PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
607 const ObjCPropertyImplDecl *propImpl) {
608 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall43192862011-09-13 18:31:23 +0000609 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCallf4528ae2011-09-13 03:34:09 +0000610
John McCall43192862011-09-13 18:31:23 +0000611 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
612 IsAtomic = prop->isAtomic();
John McCallf4528ae2011-09-13 03:34:09 +0000613 HasStrong = false; // doesn't matter here.
614
615 // Evaluate the ivar's size and alignment.
616 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
617 QualType ivarType = ivar->getType();
Benjamin Kramer867ea1d2014-03-02 13:01:17 +0000618 std::tie(IvarSize, IvarAlignment) =
619 CGM.getContext().getTypeInfoInChars(ivarType);
John McCallf4528ae2011-09-13 03:34:09 +0000620
621 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall43192862011-09-13 18:31:23 +0000622 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCallf4528ae2011-09-13 03:34:09 +0000623 if (IsCopy) {
624 Kind = GetSetProperty;
625 return;
626 }
627
John McCall43192862011-09-13 18:31:23 +0000628 // Handle retain.
629 if (setterKind == ObjCPropertyDecl::Retain) {
John McCallf4528ae2011-09-13 03:34:09 +0000630 // In GC-only, there's nothing special that needs to be done.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000631 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCallf4528ae2011-09-13 03:34:09 +0000632 // fallthrough
633
634 // In ARC, if the property is non-atomic, use expression emission,
635 // which translates to objc_storeStrong. This isn't required, but
636 // it's slightly nicer.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000637 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld8561f02012-08-20 23:36:59 +0000638 // Using standard expression emission for the setter is only
639 // acceptable if the ivar is __strong, which won't be true if
640 // the property is annotated with __attribute__((NSObject)).
641 // TODO: falling all the way back to objc_setProperty here is
642 // just laziness, though; we could still use objc_storeStrong
643 // if we hacked it right.
644 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
645 Kind = Expression;
646 else
647 Kind = SetPropertyAndExpressionGet;
John McCallf4528ae2011-09-13 03:34:09 +0000648 return;
649
650 // Otherwise, we need to at least use setProperty. However, if
651 // the property isn't atomic, we can use normal expression
652 // emission for the getter.
653 } else if (!IsAtomic) {
654 Kind = SetPropertyAndExpressionGet;
655 return;
656
657 // Otherwise, we have to use both setProperty and getProperty.
658 } else {
659 Kind = GetSetProperty;
660 return;
661 }
662 }
663
664 // If we're not atomic, just use expression accesses.
665 if (!IsAtomic) {
666 Kind = Expression;
667 return;
668 }
669
John McCall0e5c0862011-09-13 05:36:29 +0000670 // Properties on bitfield ivars need to be emitted using expression
671 // accesses even if they're nominally atomic.
672 if (ivar->isBitField()) {
673 Kind = Expression;
674 return;
675 }
676
John McCallf4528ae2011-09-13 03:34:09 +0000677 // GC-qualified or ARC-qualified ivars need to be emitted as
678 // expressions. This actually works out to being atomic anyway,
679 // except for ARC __strong, but that should trigger the above code.
680 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikiebbafb8a2012-03-11 07:00:24 +0000681 (CGM.getLangOpts().getGC() &&
John McCallf4528ae2011-09-13 03:34:09 +0000682 CGM.getContext().getObjCGCAttrKind(ivarType))) {
683 Kind = Expression;
684 return;
685 }
686
687 // Compute whether the ivar has strong members.
David Blaikiebbafb8a2012-03-11 07:00:24 +0000688 if (CGM.getLangOpts().getGC())
John McCallf4528ae2011-09-13 03:34:09 +0000689 if (const RecordType *recordType = ivarType->getAs<RecordType>())
690 HasStrong = recordType->getDecl()->hasObjectMember();
691
692 // We can never access structs with object members with a native
693 // access, because we need to use write barriers. This is what
694 // objc_copyStruct is for.
695 if (HasStrong) {
696 Kind = CopyStruct;
697 return;
698 }
699
700 // Otherwise, this is target-dependent and based on the size and
701 // alignment of the ivar.
John McCall0bef0ba2011-09-13 07:33:34 +0000702
703 // If the size of the ivar is not a power of two, give up. We don't
704 // want to get into the business of doing compare-and-swaps.
705 if (!IvarSize.isPowerOfTwo()) {
706 Kind = CopyStruct;
707 return;
708 }
709
John McCallf4528ae2011-09-13 03:34:09 +0000710 llvm::Triple::ArchType arch =
John McCallc8e01702013-04-16 22:48:15 +0000711 CGM.getTarget().getTriple().getArch();
John McCallf4528ae2011-09-13 03:34:09 +0000712
713 // Most architectures require memory to fit within a single cache
714 // line, so the alignment has to be at least the size of the access.
715 // Otherwise we have to grab a lock.
716 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
717 Kind = CopyStruct;
718 return;
719 }
720
721 // If the ivar's size exceeds the architecture's maximum atomic
722 // access size, we have to use CopyStruct.
723 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
724 Kind = CopyStruct;
725 return;
726 }
727
728 // Otherwise, we can use native loads and stores.
729 Kind = Native;
730}
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000731
James Dennettbe302452012-06-15 22:10:14 +0000732/// \brief Generate an Objective-C property getter function.
733///
734/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +0000735/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000736void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
737 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +0000738 llvm::Constant *AtomicHelperFn =
739 CodeGenFunction(CGM).GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000740 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
741 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
742 assert(OMD && "Invalid call to generate getter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +0000743 StartObjCMethod(OMD, IMP->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000744
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000745 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCallf4528ae2011-09-13 03:34:09 +0000746
747 FinishFunction();
748}
749
John McCallbdd81852011-09-13 06:00:03 +0000750static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
751 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCallf4528ae2011-09-13 03:34:09 +0000752 if (!getter) return true;
753
754 // Sema only makes only of these when the ivar has a C++ class type,
755 // so the form is pretty constrained.
756
John McCallbdd81852011-09-13 06:00:03 +0000757 // If the property has a reference type, we might just be binding a
758 // reference, in which case the result will be a gl-value. We should
759 // treat this as a non-trivial operation.
760 if (getter->isGLValue())
761 return false;
762
John McCallf4528ae2011-09-13 03:34:09 +0000763 // If we selected a trivial copy-constructor, we're okay.
764 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
765 return (construct->getConstructor()->isTrivial());
766
767 // The constructor might require cleanups (in which case it's never
768 // trivial).
769 assert(isa<ExprWithCleanups>(getter));
770 return false;
771}
772
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000773/// emitCPPObjectAtomicGetterCall - Call the runtime function to
774/// copy the ivar into the resturn slot.
775static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
776 llvm::Value *returnAddr,
777 ObjCIvarDecl *ivar,
778 llvm::Constant *AtomicHelperFn) {
779 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
780 // AtomicHelperFn);
781 CallArgList args;
782
783 // The 1st argument is the return Slot.
784 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
785
786 // The 2nd argument is the address of the ivar.
787 llvm::Value *ivarAddr =
788 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
789 CGF.LoadObjCSelf(), ivar, 0).getAddress();
790 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
791 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
792
793 // Third argument is the helper function.
794 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
795
796 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +0000797 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall8dda7b22012-07-07 06:41:13 +0000798 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
799 args,
800 FunctionType::ExtInfo(),
801 RequiredArgs::All),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000802 copyCppAtomicObjectFn, ReturnValueSlot(), args);
803}
804
John McCallf4528ae2011-09-13 03:34:09 +0000805void
806CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000807 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanianb5dd2cb2012-05-29 19:56:01 +0000808 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanian4b501a22012-01-07 18:56:22 +0000809 llvm::Constant *AtomicHelperFn) {
John McCallf4528ae2011-09-13 03:34:09 +0000810 // If there's a non-trivial 'get' expression, we just have to emit that.
811 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000812 if (!AtomicHelperFn) {
813 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
Craig Topper8a13c412014-05-21 05:09:00 +0000814 /*nrvo*/ nullptr);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +0000815 EmitReturnStmt(ret);
816 }
817 else {
818 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
819 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
820 ivar, AtomicHelperFn);
821 }
John McCallf4528ae2011-09-13 03:34:09 +0000822 return;
823 }
824
825 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
826 QualType propType = prop->getType();
827 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
828
829 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
830
831 // Pick an implementation strategy.
832 PropertyImplStrategy strategy(CGM, propImpl);
833 switch (strategy.getKind()) {
834 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +0000835 // We don't need to do anything for a zero-size struct.
836 if (strategy.getIvarSize().isZero())
837 return;
838
John McCallf4528ae2011-09-13 03:34:09 +0000839 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
840
841 // Currently, all atomic accesses have to be through integer
842 // types, so there's no point in trying to pick a prettier type.
843 llvm::Type *bitcastType =
844 llvm::Type::getIntNTy(getLLVMContext(),
845 getContext().toBits(strategy.getIvarSize()));
846 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
847
848 // Perform an atomic load. This does not impose ordering constraints.
849 llvm::Value *ivarAddr = LV.getAddress();
850 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
851 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
852 load->setAlignment(strategy.getIvarAlignment().getQuantity());
853 load->setAtomic(llvm::Unordered);
854
855 // Store that value into the return address. Doing this with a
856 // bitcast is likely to produce some pretty ugly IR, but it's not
857 // the *most* terrible thing in the world.
858 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
859
860 // Make sure we don't do an autorelease.
861 AutoreleaseResult = false;
862 return;
863 }
864
865 case PropertyImplStrategy::GetSetProperty: {
866 llvm::Value *getPropertyFn =
867 CGM.getObjCRuntime().GetPropertyGetFunction();
868 if (!getPropertyFn) {
869 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000870 return;
871 }
872
873 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
874 // FIXME: Can't this be simpler? This might even be worse than the
875 // corresponding gcc code.
John McCallf4528ae2011-09-13 03:34:09 +0000876 llvm::Value *cmd =
877 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
878 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
879 llvm::Value *ivarOffset =
880 EmitIvarOffset(classImpl->getClassInterface(), ivar);
881
882 CallArgList args;
883 args.add(RValue::get(self), getContext().getObjCIdType());
884 args.add(RValue::get(cmd), getContext().getObjCSelType());
885 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall43192862011-09-13 18:31:23 +0000886 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
887 getContext().BoolTy);
John McCallf4528ae2011-09-13 03:34:09 +0000888
Daniel Dunbar1ef73732009-02-03 23:43:59 +0000889 // FIXME: We shouldn't need to get the function info here, the
890 // runtime already should have computed it to build the function.
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000891 llvm::Instruction *CallInstruction;
John McCall8dda7b22012-07-07 06:41:13 +0000892 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
893 FunctionType::ExtInfo(),
894 RequiredArgs::All),
Craig Topper8a13c412014-05-21 05:09:00 +0000895 getPropertyFn, ReturnValueSlot(), args, nullptr,
Fariborz Jahanian13b43042014-01-30 00:16:39 +0000896 &CallInstruction);
897 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(CallInstruction))
898 call->setTailCall();
John McCallf4528ae2011-09-13 03:34:09 +0000899
Daniel Dunbara08dff12008-09-24 04:04:31 +0000900 // We need to fix the type here. Ivars with copy & retain are
901 // always objects so we don't need to worry about complex or
902 // aggregates.
Alp Toker314cc812014-01-25 16:55:45 +0000903 RV = RValue::get(Builder.CreateBitCast(
904 RV.getScalarVal(),
905 getTypes().ConvertType(getterMethod->getReturnType())));
John McCallf4528ae2011-09-13 03:34:09 +0000906
907 EmitReturnOfRValue(RV, propType);
John McCall31168b02011-06-15 23:02:42 +0000908
909 // objc_getProperty does an autorelease, so we should suppress ours.
910 AutoreleaseResult = false;
John McCall31168b02011-06-15 23:02:42 +0000911
John McCallf4528ae2011-09-13 03:34:09 +0000912 return;
913 }
914
915 case PropertyImplStrategy::CopyStruct:
916 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
917 strategy.hasStrongMember());
918 return;
919
920 case PropertyImplStrategy::Expression:
921 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
922 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
923
924 QualType ivarType = ivar->getType();
John McCall47fb9502013-03-07 21:37:08 +0000925 switch (getEvaluationKind(ivarType)) {
926 case TEK_Complex: {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000927 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall47fb9502013-03-07 21:37:08 +0000928 EmitStoreOfComplex(pair,
929 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
930 /*init*/ true);
931 return;
932 }
933 case TEK_Aggregate:
John McCallf4528ae2011-09-13 03:34:09 +0000934 // The return value slot is guaranteed to not be aliased, but
935 // that's not necessarily the same as "on the stack", so
936 // we still potentially need objc_memmove_collectable.
Chad Rosier615ed1a2012-03-29 17:37:10 +0000937 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall47fb9502013-03-07 21:37:08 +0000938 return;
939 case TEK_Scalar: {
John McCall24fada12011-07-22 05:23:13 +0000940 llvm::Value *value;
941 if (propType->isReferenceType()) {
942 value = LV.getAddress();
943 } else {
944 // We want to load and autoreleaseReturnValue ARC __weak ivars.
945 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCallf4528ae2011-09-13 03:34:09 +0000946 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCall24fada12011-07-22 05:23:13 +0000947
948 // Otherwise we want to do a simple load, suppressing the
949 // final autorelease.
John McCall31168b02011-06-15 23:02:42 +0000950 } else {
Nick Lewycky2d84e842013-10-02 02:29:49 +0000951 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCall24fada12011-07-22 05:23:13 +0000952 AutoreleaseResult = false;
Fariborz Jahanianb24b5682011-03-28 23:47:18 +0000953 }
John McCall31168b02011-06-15 23:02:42 +0000954
John McCall24fada12011-07-22 05:23:13 +0000955 value = Builder.CreateBitCast(value, ConvertType(propType));
Alp Toker314cc812014-01-25 16:55:45 +0000956 value = Builder.CreateBitCast(
957 value, ConvertType(GetterMethodDecl->getReturnType()));
John McCall24fada12011-07-22 05:23:13 +0000958 }
959
960 EmitReturnOfRValue(RValue::get(value), propType);
John McCall47fb9502013-03-07 21:37:08 +0000961 return;
Fariborz Jahanianeab5ecd2009-03-03 18:49:40 +0000962 }
John McCall47fb9502013-03-07 21:37:08 +0000963 }
964 llvm_unreachable("bad evaluation kind");
Daniel Dunbara08dff12008-09-24 04:04:31 +0000965 }
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000966
John McCallf4528ae2011-09-13 03:34:09 +0000967 }
968 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbar89654ee2008-08-26 08:29:31 +0000969}
970
John McCallb923ece2011-09-12 23:06:44 +0000971/// emitStructSetterCall - Call the runtime function to store the value
972/// from the first formal parameter into the given ivar.
973static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
974 ObjCIvarDecl *ivar) {
Fariborz Jahanian302a3d42011-02-18 19:15:13 +0000975 // objc_copyStruct (&structIvar, &Arg,
976 // sizeof (struct something), true, false);
John McCall6acaef92011-09-10 09:30:49 +0000977 CallArgList args;
978
979 // The first argument is the address of the ivar.
John McCallb923ece2011-09-12 23:06:44 +0000980 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
981 CGF.LoadObjCSelf(), ivar, 0)
982 .getAddress();
983 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
984 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000985
986 // The second argument is the address of the parameter variable.
John McCallb923ece2011-09-12 23:06:44 +0000987 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +0000988 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian088f1bc2012-01-05 00:10:16 +0000989 VK_LValue, SourceLocation());
John McCallb923ece2011-09-12 23:06:44 +0000990 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
991 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
992 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCall6acaef92011-09-10 09:30:49 +0000993
994 // The third argument is the sizeof the type.
995 llvm::Value *size =
John McCallb923ece2011-09-12 23:06:44 +0000996 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
997 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCall6acaef92011-09-10 09:30:49 +0000998
John McCallb923ece2011-09-12 23:06:44 +0000999 // The fourth argument is the 'isAtomic' flag.
1000 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCall6acaef92011-09-10 09:30:49 +00001001
John McCallb923ece2011-09-12 23:06:44 +00001002 // The fifth argument is the 'hasStrong' flag.
1003 // FIXME: should this really always be false?
1004 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1005
1006 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001007 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1008 args,
1009 FunctionType::ExtInfo(),
1010 RequiredArgs::All),
John McCallb923ece2011-09-12 23:06:44 +00001011 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian302a3d42011-02-18 19:15:13 +00001012}
1013
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001014/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1015/// the value from the first formal parameter into the given ivar, using
1016/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1017static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1018 ObjCMethodDecl *OMD,
1019 ObjCIvarDecl *ivar,
1020 llvm::Constant *AtomicHelperFn) {
1021 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1022 // AtomicHelperFn);
1023 CallArgList args;
1024
1025 // The first argument is the address of the ivar.
1026 llvm::Value *ivarAddr =
1027 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1028 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1029 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1030 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1031
1032 // The second argument is the address of the parameter variable.
1033 ParmVarDecl *argVar = *OMD->param_begin();
John McCall113bee02012-03-10 09:33:50 +00001034 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001035 VK_LValue, SourceLocation());
1036 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1037 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1038 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1039
1040 // Third argument is the helper function.
1041 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1042
1043 llvm::Value *copyCppAtomicObjectFn =
David Chisnall0d75e062012-12-17 18:54:24 +00001044 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall8dda7b22012-07-07 06:41:13 +00001045 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1046 args,
1047 FunctionType::ExtInfo(),
1048 RequiredArgs::All),
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001049 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001050}
1051
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00001052
John McCallf4528ae2011-09-13 03:34:09 +00001053static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1054 Expr *setter = PID->getSetterCXXAssignment();
1055 if (!setter) return true;
1056
1057 // Sema only makes only of these when the ivar has a C++ class type,
1058 // so the form is pretty constrained.
John McCall7f16c422011-09-10 09:17:20 +00001059
1060 // An operator call is trivial if the function it calls is trivial.
John McCallf4528ae2011-09-13 03:34:09 +00001061 // This also implies that there's nothing non-trivial going on with
1062 // the arguments, because operator= can only be trivial if it's a
1063 // synthesized assignment operator and therefore both parameters are
1064 // references.
1065 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall7f16c422011-09-10 09:17:20 +00001066 if (const FunctionDecl *callee
1067 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1068 if (callee->isTrivial())
1069 return true;
1070 return false;
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001071 }
John McCall7f16c422011-09-10 09:17:20 +00001072
John McCallf4528ae2011-09-13 03:34:09 +00001073 assert(isa<ExprWithCleanups>(setter));
John McCall7f16c422011-09-10 09:17:20 +00001074 return false;
1075}
1076
Benjamin Kramer53ba6362012-03-10 20:38:56 +00001077static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001078 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremeneke65b0862012-03-06 20:05:56 +00001079 return false;
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001080 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremeneke65b0862012-03-06 20:05:56 +00001081}
1082
John McCall7f16c422011-09-10 09:17:20 +00001083void
1084CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001085 const ObjCPropertyImplDecl *propImpl,
1086 llvm::Constant *AtomicHelperFn) {
John McCall7f16c422011-09-10 09:17:20 +00001087 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00001088 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall7f16c422011-09-10 09:17:20 +00001089 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001090
1091 // Just use the setter expression if Sema gave us one and it's
1092 // non-trivial.
1093 if (!hasTrivialSetExpr(propImpl)) {
1094 if (!AtomicHelperFn)
1095 // If non-atomic, assignment is called directly.
1096 EmitStmt(propImpl->getSetterCXXAssignment());
1097 else
1098 // If atomic, assignment is called via a locking api.
1099 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1100 AtomicHelperFn);
1101 return;
1102 }
John McCall7f16c422011-09-10 09:17:20 +00001103
John McCallf4528ae2011-09-13 03:34:09 +00001104 PropertyImplStrategy strategy(CGM, propImpl);
1105 switch (strategy.getKind()) {
1106 case PropertyImplStrategy::Native: {
Eli Friedman0e846022012-10-26 22:38:05 +00001107 // We don't need to do anything for a zero-size struct.
1108 if (strategy.getIvarSize().isZero())
1109 return;
1110
John McCallf4528ae2011-09-13 03:34:09 +00001111 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall7f16c422011-09-10 09:17:20 +00001112
John McCallf4528ae2011-09-13 03:34:09 +00001113 LValue ivarLValue =
1114 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1115 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall7f16c422011-09-10 09:17:20 +00001116
John McCallf4528ae2011-09-13 03:34:09 +00001117 // Currently, all atomic accesses have to be through integer
1118 // types, so there's no point in trying to pick a prettier type.
1119 llvm::Type *bitcastType =
1120 llvm::Type::getIntNTy(getLLVMContext(),
1121 getContext().toBits(strategy.getIvarSize()));
1122 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1123
1124 // Cast both arguments to the chosen operation type.
1125 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1126 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1127
1128 // This bitcast load is likely to cause some nasty IR.
1129 llvm::Value *load = Builder.CreateLoad(argAddr);
1130
1131 // Perform an atomic store. There are no memory ordering requirements.
1132 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1133 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1134 store->setAtomic(llvm::Unordered);
1135 return;
1136 }
1137
1138 case PropertyImplStrategy::GetSetProperty:
1139 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Craig Topper8a13c412014-05-21 05:09:00 +00001140
1141 llvm::Value *setOptimizedPropertyFn = nullptr;
1142 llvm::Value *setPropertyFn = nullptr;
Ted Kremeneke65b0862012-03-06 20:05:56 +00001143 if (UseOptimizedSetter(CGM)) {
Daniel Dunbarbd847cc2012-10-15 22:23:53 +00001144 // 10.8 and iOS 6.0 code and GC is off
Ted Kremeneke65b0862012-03-06 20:05:56 +00001145 setOptimizedPropertyFn =
Eric Christopher5d2b8d92012-03-29 17:31:31 +00001146 CGM.getObjCRuntime()
1147 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1148 strategy.isCopy());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001149 if (!setOptimizedPropertyFn) {
1150 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1151 return;
1152 }
John McCall7f16c422011-09-10 09:17:20 +00001153 }
Ted Kremeneke65b0862012-03-06 20:05:56 +00001154 else {
1155 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1156 if (!setPropertyFn) {
1157 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1158 return;
1159 }
1160 }
1161
John McCall7f16c422011-09-10 09:17:20 +00001162 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1163 // <is-atomic>, <is-copy>).
1164 llvm::Value *cmd =
1165 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1166 llvm::Value *self =
1167 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1168 llvm::Value *ivarOffset =
1169 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1170 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1171 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1172
1173 CallArgList args;
1174 args.add(RValue::get(self), getContext().getObjCIdType());
1175 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremeneke65b0862012-03-06 20:05:56 +00001176 if (setOptimizedPropertyFn) {
1177 args.add(RValue::get(arg), getContext().getObjCIdType());
1178 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall8dda7b22012-07-07 06:41:13 +00001179 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1180 FunctionType::ExtInfo(),
1181 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001182 setOptimizedPropertyFn, ReturnValueSlot(), args);
1183 } else {
1184 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1185 args.add(RValue::get(arg), getContext().getObjCIdType());
1186 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1187 getContext().BoolTy);
1188 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1189 getContext().BoolTy);
1190 // FIXME: We shouldn't need to get the function info here, the runtime
1191 // already should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001192 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1193 FunctionType::ExtInfo(),
1194 RequiredArgs::All),
Ted Kremeneke65b0862012-03-06 20:05:56 +00001195 setPropertyFn, ReturnValueSlot(), args);
1196 }
1197
John McCall7f16c422011-09-10 09:17:20 +00001198 return;
1199 }
1200
John McCallf4528ae2011-09-13 03:34:09 +00001201 case PropertyImplStrategy::CopyStruct:
John McCallb923ece2011-09-12 23:06:44 +00001202 emitStructSetterCall(*this, setterMethod, ivar);
John McCall7f16c422011-09-10 09:17:20 +00001203 return;
John McCallf4528ae2011-09-13 03:34:09 +00001204
1205 case PropertyImplStrategy::Expression:
1206 break;
John McCall7f16c422011-09-10 09:17:20 +00001207 }
1208
1209 // Otherwise, fake up some ASTs and emit a normal assignment.
1210 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCall113bee02012-03-10 09:33:50 +00001211 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1212 VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001213 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1214 selfDecl->getType(), CK_LValueToRValue, &self,
1215 VK_RValue);
1216 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001217 SourceLocation(), SourceLocation(),
1218 &selfLoad, true, true);
John McCall7f16c422011-09-10 09:17:20 +00001219
1220 ParmVarDecl *argDecl = *setterMethod->param_begin();
1221 QualType argType = argDecl->getType().getNonReferenceType();
John McCall113bee02012-03-10 09:33:50 +00001222 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall7f16c422011-09-10 09:17:20 +00001223 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1224 argType.getUnqualifiedType(), CK_LValueToRValue,
1225 &arg, VK_RValue);
1226
1227 // The property type can differ from the ivar type in some situations with
1228 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1229 // The following absurdity is just to ensure well-formed IR.
1230 CastKind argCK = CK_NoOp;
1231 if (ivarRef.getType()->isObjCObjectPointerType()) {
1232 if (argLoad.getType()->isObjCObjectPointerType())
1233 argCK = CK_BitCast;
1234 else if (argLoad.getType()->isBlockPointerType())
1235 argCK = CK_BlockPointerToObjCPointerCast;
1236 else
1237 argCK = CK_CPointerToObjCPointerCast;
1238 } else if (ivarRef.getType()->isBlockPointerType()) {
1239 if (argLoad.getType()->isBlockPointerType())
1240 argCK = CK_BitCast;
1241 else
1242 argCK = CK_AnyPointerToBlockPointerCast;
1243 } else if (ivarRef.getType()->isPointerType()) {
1244 argCK = CK_BitCast;
1245 }
1246 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1247 ivarRef.getType(), argCK, &argLoad,
1248 VK_RValue);
1249 Expr *finalArg = &argLoad;
1250 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1251 argLoad.getType()))
1252 finalArg = &argCast;
1253
1254
1255 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1256 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hames5de91cc2012-10-02 04:45:10 +00001257 SourceLocation(), false);
John McCall7f16c422011-09-10 09:17:20 +00001258 EmitStmt(&assign);
Fariborz Jahanian5de53132011-04-06 16:05:26 +00001259}
1260
James Dennettbe302452012-06-15 22:10:14 +00001261/// \brief Generate an Objective-C property setter function.
1262///
1263/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff5a7dd782009-01-10 22:55:25 +00001264/// is illegal within a category.
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +00001265void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1266 const ObjCPropertyImplDecl *PID) {
David Blaikie8e6c36e2014-10-14 16:43:46 +00001267 llvm::Constant *AtomicHelperFn =
1268 CodeGenFunction(CGM).GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001269 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1270 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1271 assert(OMD && "Invalid call to generate setter (empty method)");
David Blaikief1425802015-01-14 00:04:42 +00001272 StartObjCMethod(OMD, IMP->getClassInterface());
Daniel Dunbar5449ce52008-09-24 06:32:09 +00001273
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00001274 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbar89654ee2008-08-26 08:29:31 +00001275
1276 FinishFunction();
Chris Lattner5696e7b2008-06-17 18:05:57 +00001277}
1278
John McCall6a4fa522011-03-22 07:05:39 +00001279namespace {
John McCall4bd0fb12011-07-12 16:41:08 +00001280 struct DestroyIvar : EHScopeStack::Cleanup {
1281 private:
1282 llvm::Value *addr;
John McCall6a4fa522011-03-22 07:05:39 +00001283 const ObjCIvarDecl *ivar;
Peter Collingbourne1425b452012-01-26 03:33:36 +00001284 CodeGenFunction::Destroyer *destroyer;
John McCall4bd0fb12011-07-12 16:41:08 +00001285 bool useEHCleanupForArray;
1286 public:
1287 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1288 CodeGenFunction::Destroyer *destroyer,
1289 bool useEHCleanupForArray)
Peter Collingbourne1425b452012-01-26 03:33:36 +00001290 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall4bd0fb12011-07-12 16:41:08 +00001291 useEHCleanupForArray(useEHCleanupForArray) {}
John McCall6a4fa522011-03-22 07:05:39 +00001292
Craig Topper4f12f102014-03-12 06:41:41 +00001293 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall4bd0fb12011-07-12 16:41:08 +00001294 LValue lvalue
1295 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1296 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCall30317fd2011-07-12 20:27:29 +00001297 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCall6a4fa522011-03-22 07:05:39 +00001298 }
1299 };
1300}
1301
John McCall4bd0fb12011-07-12 16:41:08 +00001302/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1303static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1304 llvm::Value *addr,
1305 QualType type) {
1306 llvm::Value *null = getNullForVariable(addr);
1307 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1308}
John McCall31168b02011-06-15 23:02:42 +00001309
John McCall6a4fa522011-03-22 07:05:39 +00001310static void emitCXXDestructMethod(CodeGenFunction &CGF,
1311 ObjCImplementationDecl *impl) {
1312 CodeGenFunction::RunCleanupsScope scope(CGF);
1313
1314 llvm::Value *self = CGF.LoadObjCSelf();
1315
Jordy Rosea91768e2011-07-22 02:08:32 +00001316 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1317 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCall6a4fa522011-03-22 07:05:39 +00001318 ivar; ivar = ivar->getNextIvar()) {
1319 QualType type = ivar->getType();
1320
John McCall6a4fa522011-03-22 07:05:39 +00001321 // Check whether the ivar is a destructible type.
John McCall4bd0fb12011-07-12 16:41:08 +00001322 QualType::DestructionKind dtorKind = type.isDestructedType();
1323 if (!dtorKind) continue;
John McCall6a4fa522011-03-22 07:05:39 +00001324
Craig Topper8a13c412014-05-21 05:09:00 +00001325 CodeGenFunction::Destroyer *destroyer = nullptr;
John McCall6a4fa522011-03-22 07:05:39 +00001326
John McCall4bd0fb12011-07-12 16:41:08 +00001327 // Use a call to objc_storeStrong to destroy strong ivars, for the
1328 // general benefit of the tools.
1329 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001330 destroyer = destroyARCStrongWithStore;
John McCall31168b02011-06-15 23:02:42 +00001331
John McCall4bd0fb12011-07-12 16:41:08 +00001332 // Otherwise use the default for the destruction kind.
1333 } else {
Peter Collingbourne1425b452012-01-26 03:33:36 +00001334 destroyer = CGF.getDestroyer(dtorKind);
John McCall6a4fa522011-03-22 07:05:39 +00001335 }
John McCall4bd0fb12011-07-12 16:41:08 +00001336
1337 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1338
1339 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1340 cleanupKind & EHCleanup);
John McCall6a4fa522011-03-22 07:05:39 +00001341 }
1342
1343 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1344}
1345
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001346void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1347 ObjCMethodDecl *MD,
1348 bool ctor) {
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001349 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
David Blaikief1425802015-01-14 00:04:42 +00001350 StartObjCMethod(MD, IMP->getClassInterface());
John McCall6a4fa522011-03-22 07:05:39 +00001351
1352 // Emit .cxx_construct.
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001353 if (ctor) {
John McCall31168b02011-06-15 23:02:42 +00001354 // Suppress the final autorelease in ARC.
1355 AutoreleaseResult = false;
1356
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001357 for (const auto *IvarInit : IMP->inits()) {
Francois Pichetd583da02010-12-04 09:14:42 +00001358 FieldDecl *Field = IvarInit->getAnyMember();
Aaron Ballman9bc5f362014-03-13 17:35:02 +00001359 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian499b9022010-04-28 22:30:33 +00001360 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1361 LoadObjCSelf(), Ivar, 0);
John McCall8d6fc952011-08-25 20:40:09 +00001362 EmitAggExpr(IvarInit->getInit(),
1363 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCalla5efa732011-08-25 23:04:34 +00001364 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00001365 AggValueSlot::IsNotAliased));
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001366 }
1367 // constructor returns 'self'.
1368 CodeGenTypes &Types = CGM.getTypes();
1369 QualType IdTy(CGM.getContext().getObjCIdType());
1370 llvm::Value *SelfAsId =
1371 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1372 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCall6a4fa522011-03-22 07:05:39 +00001373
1374 // Emit .cxx_destruct.
Chandler Carruthf3983652010-05-06 00:20:39 +00001375 } else {
John McCall6a4fa522011-03-22 07:05:39 +00001376 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian0dec1e02010-04-28 21:28:56 +00001377 }
1378 FinishFunction();
1379}
1380
Fariborz Jahanian08b0f662010-04-13 00:38:05 +00001381bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1382 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1383 it++; it++;
1384 const ABIArgInfo &AI = it->info;
1385 // FIXME. Is this sufficient check?
1386 return (AI.getKind() == ABIArgInfo::Indirect);
1387}
1388
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001389bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001390 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian7e9d52a2010-04-13 18:32:24 +00001391 return false;
1392 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1393 return FDTTy->getDecl()->hasObjectMember();
1394 return false;
1395}
1396
Daniel Dunbara08dff12008-09-24 04:04:31 +00001397llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCalldec348f72013-05-03 07:33:41 +00001398 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1399 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1400 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky2d84e842013-10-02 02:29:49 +00001401 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner5696e7b2008-06-17 18:05:57 +00001402}
1403
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001404QualType CodeGenFunction::TypeOfSelfObject() {
1405 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1406 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff7cae42b2009-07-10 23:34:53 +00001407 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1408 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanianc88a70d2009-02-03 00:09:52 +00001409 return PTy->getPointeeType();
1410}
1411
Chris Lattnerd4808922009-03-22 21:03:39 +00001412void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump11289f42009-09-09 15:08:12 +00001413 llvm::Constant *EnumerationMutationFn =
Daniel Dunbara08dff12008-09-24 04:04:31 +00001414 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump11289f42009-09-09 15:08:12 +00001415
Daniel Dunbara08dff12008-09-24 04:04:31 +00001416 if (!EnumerationMutationFn) {
1417 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1418 return;
1419 }
1420
Devang Pateld2d66652011-01-19 01:36:36 +00001421 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00001422 if (DI)
1423 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Pateld2d66652011-01-19 01:36:36 +00001424
Devang Patel297207f2011-06-13 23:15:32 +00001425 // The local variable comes into scope immediately.
1426 AutoVarEmission variable = AutoVarEmission::invalid();
1427 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1428 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1429
John McCall1c926b72011-01-07 01:49:06 +00001430 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump11289f42009-09-09 15:08:12 +00001431
Anders Carlsson75658592008-08-31 02:33:12 +00001432 // Fast enumeration state.
Douglas Gregor636e2002011-08-09 17:23:49 +00001433 QualType StateTy = CGM.getObjCFastEnumerationStateType();
David Blaikie1ed728c2015-04-05 22:45:47 +00001434 llvm::AllocaInst *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlssonc0964b62010-05-22 17:35:42 +00001435 EmitNullInitialization(StatePtr, StateTy);
Mike Stump11289f42009-09-09 15:08:12 +00001436
Anders Carlsson75658592008-08-31 02:33:12 +00001437 // Number of elements in the items array.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001438 static const unsigned NumItems = 16;
Mike Stump11289f42009-09-09 15:08:12 +00001439
John McCall1c926b72011-01-07 01:49:06 +00001440 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramer9e649c32010-03-30 11:36:44 +00001441 IdentifierInfo *II[] = {
1442 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1443 &CGM.getContext().Idents.get("objects"),
1444 &CGM.getContext().Idents.get("count")
1445 };
1446 Selector FastEnumSel =
1447 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlsson75658592008-08-31 02:33:12 +00001448
1449 QualType ItemsTy =
1450 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00001451 llvm::APInt(32, NumItems),
Anders Carlsson75658592008-08-31 02:33:12 +00001452 ArrayType::Normal, 0);
Daniel Dunbara7566f12010-02-09 02:48:28 +00001453 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001454
John McCall53848232011-07-27 01:07:15 +00001455 // Emit the collection pointer. In ARC, we do a retain.
1456 llvm::Value *Collection;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001457 if (getLangOpts().ObjCAutoRefCount) {
John McCall53848232011-07-27 01:07:15 +00001458 Collection = EmitARCRetainScalarExpr(S.getCollection());
1459
1460 // Enter a cleanup to do the release.
1461 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1462 } else {
1463 Collection = EmitScalarExpr(S.getCollection());
1464 }
Mike Stump11289f42009-09-09 15:08:12 +00001465
John McCall91e82dd2011-08-05 00:14:38 +00001466 // The 'continue' label needs to appear within the cleanup for the
1467 // collection object.
1468 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1469
John McCall1c926b72011-01-07 01:49:06 +00001470 // Send it our message:
Anders Carlsson75658592008-08-31 02:33:12 +00001471 CallArgList Args;
John McCall1c926b72011-01-07 01:49:06 +00001472
1473 // The first argument is a temporary of the enumeration-state type.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001474 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump11289f42009-09-09 15:08:12 +00001475
John McCall1c926b72011-01-07 01:49:06 +00001476 // The second argument is a temporary array with space for NumItems
1477 // pointers. We'll actually be loading elements from the array
1478 // pointer written into the control state; this buffer is so that
1479 // collections that *aren't* backed by arrays can still queue up
1480 // batches of elements.
Eli Friedman43dca6a2011-05-02 17:57:46 +00001481 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump11289f42009-09-09 15:08:12 +00001482
John McCall1c926b72011-01-07 01:49:06 +00001483 // The third argument is the capacity of that temporary array.
Chris Lattner2192fe52011-07-18 04:24:23 +00001484 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Andersonb7a2fe62009-07-24 23:12:58 +00001485 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman43dca6a2011-05-02 17:57:46 +00001486 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump11289f42009-09-09 15:08:12 +00001487
John McCall1c926b72011-01-07 01:49:06 +00001488 // Start the enumeration.
Mike Stump11289f42009-09-09 15:08:12 +00001489 RValue CountRV =
John McCall78a15112010-05-22 01:48:05 +00001490 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001491 getContext().UnsignedLongTy,
1492 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001493 Collection, Args);
Anders Carlsson75658592008-08-31 02:33:12 +00001494
John McCall1c926b72011-01-07 01:49:06 +00001495 // The initial number of objects that were returned in the buffer.
1496 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump11289f42009-09-09 15:08:12 +00001497
John McCall1c926b72011-01-07 01:49:06 +00001498 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1499 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump11289f42009-09-09 15:08:12 +00001500
John McCall1c926b72011-01-07 01:49:06 +00001501 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlsson75658592008-08-31 02:33:12 +00001502
John McCall1c926b72011-01-07 01:49:06 +00001503 // If the limit pointer was zero to begin with, the collection is
Bob Wilson0ed74d92014-03-25 23:26:31 +00001504 // empty; skip all this. Set the branch weight assuming this has the same
1505 // probability of exiting the loop as any other loop exit.
1506 uint64_t EntryCount = PGO.getCurrentRegionCount();
1507 RegionCounter Cnt = getPGORegionCounter(&S);
John McCall1c926b72011-01-07 01:49:06 +00001508 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001509 EmptyBB, LoopInitBB,
1510 PGO.createBranchWeights(EntryCount, Cnt.getCount()));
Anders Carlsson75658592008-08-31 02:33:12 +00001511
John McCall1c926b72011-01-07 01:49:06 +00001512 // Otherwise, initialize the loop.
1513 EmitBlock(LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001514
John McCall1c926b72011-01-07 01:49:06 +00001515 // Save the initial mutations value. This is the value at an
1516 // address that was written into the state object by
1517 // countByEnumeratingWithState:objects:count:.
David Blaikie1ed728c2015-04-05 22:45:47 +00001518 llvm::Value *StateMutationsPtrPtr = Builder.CreateStructGEP(
1519 StatePtr->getAllocatedType(), StatePtr, 2, "mutationsptr.ptr");
Mike Stump11289f42009-09-09 15:08:12 +00001520 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson3f35a262008-08-31 04:05:03 +00001521 "mutationsptr");
Mike Stump11289f42009-09-09 15:08:12 +00001522
John McCall1c926b72011-01-07 01:49:06 +00001523 llvm::Value *initialMutations =
1524 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump11289f42009-09-09 15:08:12 +00001525
John McCall1c926b72011-01-07 01:49:06 +00001526 // Start looping. This is the point we return to whenever we have a
1527 // fresh, non-empty batch of objects.
1528 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1529 EmitBlock(LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001530
John McCall1c926b72011-01-07 01:49:06 +00001531 // The current index into the buffer.
Jay Foad20c0f022011-03-30 11:28:58 +00001532 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCall1c926b72011-01-07 01:49:06 +00001533 index->addIncoming(zero, LoopInitBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001534
John McCall1c926b72011-01-07 01:49:06 +00001535 // The current buffer size.
Jay Foad20c0f022011-03-30 11:28:58 +00001536 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCall1c926b72011-01-07 01:49:06 +00001537 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump11289f42009-09-09 15:08:12 +00001538
Bob Wilson8ab16912014-02-24 01:13:09 +00001539 Cnt.beginRegion(Builder);
1540
John McCall1c926b72011-01-07 01:49:06 +00001541 // Check whether the mutations value has changed from where it was
1542 // at start. StateMutationsPtr should actually be invariant between
1543 // refreshes.
Anders Carlsson3f35a262008-08-31 04:05:03 +00001544 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCall1c926b72011-01-07 01:49:06 +00001545 llvm::Value *currentMutations
1546 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson3f35a262008-08-31 04:05:03 +00001547
John McCall1c926b72011-01-07 01:49:06 +00001548 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman6ca99822011-03-02 22:39:34 +00001549 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump11289f42009-09-09 15:08:12 +00001550
John McCall1c926b72011-01-07 01:49:06 +00001551 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1552 WasNotMutatedBB, WasMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001553
John McCall1c926b72011-01-07 01:49:06 +00001554 // If so, call the enumeration-mutation function.
1555 EmitBlock(WasMutatedBB);
Anders Carlsson3f35a262008-08-31 04:05:03 +00001556 llvm::Value *V =
Mike Stump11289f42009-09-09 15:08:12 +00001557 Builder.CreateBitCast(Collection,
Benjamin Kramer76399eb2011-09-27 21:06:10 +00001558 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar84388bf2009-02-03 23:55:40 +00001559 CallArgList Args2;
Eli Friedman43dca6a2011-05-02 17:57:46 +00001560 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stump18bb9282009-05-16 07:57:57 +00001561 // FIXME: We shouldn't need to get the function info here, the runtime already
1562 // should have computed it to build the function.
John McCall8dda7b22012-07-07 06:41:13 +00001563 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1564 FunctionType::ExtInfo(),
1565 RequiredArgs::All),
Anders Carlsson61a401c2009-12-24 19:25:24 +00001566 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump11289f42009-09-09 15:08:12 +00001567
John McCall1c926b72011-01-07 01:49:06 +00001568 // Otherwise, or if the mutation function returns, just continue.
1569 EmitBlock(WasNotMutatedBB);
Mike Stump11289f42009-09-09 15:08:12 +00001570
John McCall1c926b72011-01-07 01:49:06 +00001571 // Initialize the element variable.
1572 RunCleanupsScope elementVariableScope(*this);
John McCall9e2e22f2011-02-22 07:16:58 +00001573 bool elementIsVariable;
John McCall1c926b72011-01-07 01:49:06 +00001574 LValue elementLValue;
1575 QualType elementType;
1576 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall9e2e22f2011-02-22 07:16:58 +00001577 // Initialize the variable, in case it's a __block variable or something.
1578 EmitAutoVarInit(variable);
John McCall1c926b72011-01-07 01:49:06 +00001579
John McCall9e2e22f2011-02-22 07:16:58 +00001580 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCall113bee02012-03-10 09:33:50 +00001581 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCall1c926b72011-01-07 01:49:06 +00001582 VK_LValue, SourceLocation());
1583 elementLValue = EmitLValue(&tempDRE);
1584 elementType = D->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001585 elementIsVariable = true;
John McCalld4631322011-06-17 06:42:21 +00001586
1587 if (D->isARCPseudoStrong())
1588 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCall1c926b72011-01-07 01:49:06 +00001589 } else {
1590 elementLValue = LValue(); // suppress warning
1591 elementType = cast<Expr>(S.getElement())->getType();
John McCall9e2e22f2011-02-22 07:16:58 +00001592 elementIsVariable = false;
John McCall1c926b72011-01-07 01:49:06 +00001593 }
Chris Lattner2192fe52011-07-18 04:24:23 +00001594 llvm::Type *convertedElementType = ConvertType(elementType);
John McCall1c926b72011-01-07 01:49:06 +00001595
1596 // Fetch the buffer out of the enumeration state.
1597 // TODO: this pointer should actually be invariant between
1598 // refreshes, which would help us do certain loop optimizations.
David Blaikie1ed728c2015-04-05 22:45:47 +00001599 llvm::Value *StateItemsPtr = Builder.CreateStructGEP(
1600 StatePtr->getAllocatedType(), StatePtr, 1, "stateitems.ptr");
John McCall1c926b72011-01-07 01:49:06 +00001601 llvm::Value *EnumStateItems =
1602 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlsson75658592008-08-31 02:33:12 +00001603
John McCall1c926b72011-01-07 01:49:06 +00001604 // Fetch the value at the current index from the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001605 llvm::Value *CurrentItemPtr =
John McCall1c926b72011-01-07 01:49:06 +00001606 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1607 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump11289f42009-09-09 15:08:12 +00001608
John McCall1c926b72011-01-07 01:49:06 +00001609 // Cast that value to the right type.
1610 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1611 "currentitem");
Mike Stump11289f42009-09-09 15:08:12 +00001612
John McCall1c926b72011-01-07 01:49:06 +00001613 // Make sure we have an l-value. Yes, this gets evaluated every
1614 // time through the loop.
John McCalld4631322011-06-17 06:42:21 +00001615 if (!elementIsVariable) {
John McCall1c926b72011-01-07 01:49:06 +00001616 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001617 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCalld4631322011-06-17 06:42:21 +00001618 } else {
1619 EmitScalarInit(CurrentItem, elementLValue);
1620 }
Mike Stump11289f42009-09-09 15:08:12 +00001621
John McCall9e2e22f2011-02-22 07:16:58 +00001622 // If we do have an element variable, this assignment is the end of
1623 // its initialization.
1624 if (elementIsVariable)
1625 EmitAutoVarCleanups(variable);
1626
John McCall1c926b72011-01-07 01:49:06 +00001627 // Perform the loop body, setting up break and continue labels.
Bob Wilsonbf854f02014-02-17 19:21:09 +00001628 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCall1c926b72011-01-07 01:49:06 +00001629 {
1630 RunCleanupsScope Scope(*this);
1631 EmitStmt(S.getBody());
1632 }
Anders Carlsson75658592008-08-31 02:33:12 +00001633 BreakContinueStack.pop_back();
Mike Stump11289f42009-09-09 15:08:12 +00001634
John McCall1c926b72011-01-07 01:49:06 +00001635 // Destroy the element variable now.
1636 elementVariableScope.ForceCleanup();
1637
1638 // Check whether there are more elements.
John McCallad5d61e2010-07-23 21:56:41 +00001639 EmitBlock(AfterBody.getBlock());
Mike Stump11289f42009-09-09 15:08:12 +00001640
John McCall1c926b72011-01-07 01:49:06 +00001641 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanian6e7ecc82009-01-06 18:56:31 +00001642
John McCall1c926b72011-01-07 01:49:06 +00001643 // First we check in the local buffer.
1644 llvm::Value *indexPlusOne
1645 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlsson75658592008-08-31 02:33:12 +00001646
John McCall1c926b72011-01-07 01:49:06 +00001647 // If we haven't overrun the buffer yet, we can continue.
Bob Wilson0ed74d92014-03-25 23:26:31 +00001648 // Set the branch weights based on the simplifying assumption that this is
1649 // like a while-loop, i.e., ignoring that the false branch fetches more
1650 // elements and then returns to the loop.
John McCall1c926b72011-01-07 01:49:06 +00001651 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
Bob Wilson0ed74d92014-03-25 23:26:31 +00001652 LoopBodyBB, FetchMoreBB,
1653 PGO.createBranchWeights(Cnt.getCount(), EntryCount));
John McCall1c926b72011-01-07 01:49:06 +00001654
1655 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1656 count->addIncoming(count, AfterBody.getBlock());
1657
1658 // Otherwise, we have to fetch more elements.
1659 EmitBlock(FetchMoreBB);
Mike Stump11289f42009-09-09 15:08:12 +00001660
1661 CountRV =
John McCall78a15112010-05-22 01:48:05 +00001662 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlsson75658592008-08-31 02:33:12 +00001663 getContext().UnsignedLongTy,
Mike Stump11289f42009-09-09 15:08:12 +00001664 FastEnumSel,
David Chisnall01aa4672010-04-28 19:33:36 +00001665 Collection, Args);
Mike Stump11289f42009-09-09 15:08:12 +00001666
John McCall1c926b72011-01-07 01:49:06 +00001667 // If we got a zero count, we're done.
1668 llvm::Value *refetchCount = CountRV.getScalarVal();
1669
1670 // (note that the message send might split FetchMoreBB)
1671 index->addIncoming(zero, Builder.GetInsertBlock());
1672 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1673
1674 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1675 EmptyBB, LoopBodyBB);
Mike Stump11289f42009-09-09 15:08:12 +00001676
Anders Carlsson75658592008-08-31 02:33:12 +00001677 // No more elements.
John McCall1c926b72011-01-07 01:49:06 +00001678 EmitBlock(EmptyBB);
Anders Carlsson75658592008-08-31 02:33:12 +00001679
John McCall9e2e22f2011-02-22 07:16:58 +00001680 if (!elementIsVariable) {
Anders Carlsson75658592008-08-31 02:33:12 +00001681 // If the element was not a declaration, set it to be null.
1682
John McCall1c926b72011-01-07 01:49:06 +00001683 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1684 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall55e1fbc2011-06-25 02:11:03 +00001685 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlsson75658592008-08-31 02:33:12 +00001686 }
1687
Eric Christopher7cdf9482011-10-13 21:45:18 +00001688 if (DI)
1689 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Pateld2d66652011-01-19 01:36:36 +00001690
John McCall53848232011-07-27 01:07:15 +00001691 // Leave the cleanup we entered in ARC.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001692 if (getLangOpts().ObjCAutoRefCount)
John McCall53848232011-07-27 01:07:15 +00001693 PopCleanupBlock();
1694
John McCallad5d61e2010-07-23 21:56:41 +00001695 EmitBlock(LoopEnd.getBlock());
Anders Carlsson2e744e82008-08-30 19:51:14 +00001696}
1697
Mike Stump11289f42009-09-09 15:08:12 +00001698void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001699 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001700}
1701
Mike Stump11289f42009-09-09 15:08:12 +00001702void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson1963b0c2008-09-09 10:04:29 +00001703 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1704}
1705
Chris Lattnere132e242008-11-15 21:26:17 +00001706void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump11289f42009-09-09 15:08:12 +00001707 const ObjCAtSynchronizedStmt &S) {
John McCallbd309292010-07-06 01:34:17 +00001708 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattnere132e242008-11-15 21:26:17 +00001709}
1710
John McCall2d637d22011-09-10 06:18:15 +00001711/// Produce the code for a CK_ARCProduceObject. Just does a
John McCall31168b02011-06-15 23:02:42 +00001712/// primitive retain.
1713llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1714 llvm::Value *value) {
1715 return EmitARCRetain(type, value);
1716}
1717
1718namespace {
1719 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCall9c8e1c92011-08-03 22:24:24 +00001720 CallObjCRelease(llvm::Value *object) : object(object) {}
1721 llvm::Value *object;
John McCall31168b02011-06-15 23:02:42 +00001722
Craig Topper4f12f102014-03-12 06:41:41 +00001723 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCallcdda29c2013-03-13 03:10:54 +00001724 // Releases at the end of the full-expression are imprecise.
1725 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCall31168b02011-06-15 23:02:42 +00001726 }
1727 };
1728}
1729
John McCall2d637d22011-09-10 06:18:15 +00001730/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCall31168b02011-06-15 23:02:42 +00001731/// release at the end of the full-expression.
1732llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1733 llvm::Value *object) {
1734 // If we're in a conditional branch, we need to make the cleanup
John McCall9c8e1c92011-08-03 22:24:24 +00001735 // conditional.
1736 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCall31168b02011-06-15 23:02:42 +00001737 return object;
1738}
1739
1740llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1741 llvm::Value *value) {
1742 return EmitARCRetainAutorelease(type, value);
1743}
1744
John McCalleff18842013-03-23 02:35:54 +00001745/// Given a number of pointers, inform the optimizer that they're
1746/// being intrinsically used up until this point in the program.
1747void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1748 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1749 if (!fn) {
1750 llvm::FunctionType *fnType =
Craig Topper5fc8fc22014-08-27 06:28:36 +00001751 llvm::FunctionType::get(CGM.VoidTy, None, true);
John McCalleff18842013-03-23 02:35:54 +00001752 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1753 }
1754
1755 // This isn't really a "runtime" function, but as an intrinsic it
1756 // doesn't really matter as long as we align things up.
1757 EmitNounwindRuntimeCall(fn, values);
1758}
1759
John McCall31168b02011-06-15 23:02:42 +00001760
1761static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2192fe52011-07-18 04:24:23 +00001762 llvm::FunctionType *type,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001763 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001764 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1765
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001766 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmanbe9614c2013-02-02 01:05:06 +00001767 // If the target runtime doesn't naturally support ARC, emit weak
1768 // references to the runtime support library. We don't really
1769 // permit this to fail, but we need a particular relocation style.
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001770 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00001771 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001772 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1773 // If we have Native ARC, set nonlazybind attribute for these APIs for
1774 // performance.
Bill Wendling207f0532012-12-20 19:27:06 +00001775 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmanb46072d2013-02-02 01:03:01 +00001776 }
Michael Gottesmancf50e6d2013-02-02 00:57:44 +00001777 }
John McCall31168b02011-06-15 23:02:42 +00001778
1779 return fn;
1780}
1781
1782/// Perform an operation having the signature
1783/// i8* (i8*)
1784/// where a null input causes a no-op and returns null.
1785static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1786 llvm::Value *value,
1787 llvm::Constant *&fn,
Chad Rosier13799b32012-12-12 17:52:21 +00001788 StringRef fnName,
1789 bool isTailCall = false) {
John McCall31168b02011-06-15 23:02:42 +00001790 if (isa<llvm::ConstantPointerNull>(value)) return value;
1791
1792 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001793 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001794 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001795 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1796 }
1797
1798 // Cast the argument to 'id'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001799 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001800 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1801
1802 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001803 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosier13799b32012-12-12 17:52:21 +00001804 if (isTailCall)
1805 call->setTailCall();
John McCall31168b02011-06-15 23:02:42 +00001806
1807 // Cast the result back to the original type.
1808 return CGF.Builder.CreateBitCast(call, origType);
1809}
1810
1811/// Perform an operation having the following signature:
1812/// i8* (i8**)
1813static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1814 llvm::Value *addr,
1815 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001816 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001817 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001818 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00001819 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00001820 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1821 }
1822
1823 // Cast the argument to 'id*'.
Chris Lattner2192fe52011-07-18 04:24:23 +00001824 llvm::Type *origType = addr->getType();
John McCall31168b02011-06-15 23:02:42 +00001825 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1826
1827 // Call the function.
John McCall882987f2013-02-28 19:01:20 +00001828 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00001829
1830 // Cast the result back to a dereference of the original type.
John McCall31168b02011-06-15 23:02:42 +00001831 if (origType != CGF.Int8PtrPtrTy)
1832 result = CGF.Builder.CreateBitCast(result,
1833 cast<llvm::PointerType>(origType)->getElementType());
1834
1835 return result;
1836}
1837
1838/// Perform an operation having the following signature:
1839/// i8* (i8**, i8*)
1840static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1841 llvm::Value *addr,
1842 llvm::Value *value,
1843 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001844 StringRef fnName,
John McCall31168b02011-06-15 23:02:42 +00001845 bool ignored) {
1846 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1847 == value->getType());
1848
1849 if (!fn) {
Benjamin Kramer22d24c22011-10-15 12:20:02 +00001850 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCall31168b02011-06-15 23:02:42 +00001851
Chris Lattner2192fe52011-07-18 04:24:23 +00001852 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001853 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1854 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1855 }
1856
Chris Lattner2192fe52011-07-18 04:24:23 +00001857 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00001858
John McCall882987f2013-02-28 19:01:20 +00001859 llvm::Value *args[] = {
1860 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1861 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1862 };
1863 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001864
Craig Topper8a13c412014-05-21 05:09:00 +00001865 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00001866
1867 return CGF.Builder.CreateBitCast(result, origType);
1868}
1869
1870/// Perform an operation having the following signature:
1871/// void (i8**, i8**)
1872static void emitARCCopyOperation(CodeGenFunction &CGF,
1873 llvm::Value *dst,
1874 llvm::Value *src,
1875 llvm::Constant *&fn,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001876 StringRef fnName) {
John McCall31168b02011-06-15 23:02:42 +00001877 assert(dst->getType() == src->getType());
1878
1879 if (!fn) {
Benjamin Kramer95e19362013-03-07 21:18:31 +00001880 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1881
Chris Lattner2192fe52011-07-18 04:24:23 +00001882 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00001883 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1884 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1885 }
1886
John McCall882987f2013-02-28 19:01:20 +00001887 llvm::Value *args[] = {
1888 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1889 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1890 };
1891 CGF.EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00001892}
1893
1894/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett14c41ea2012-06-22 05:41:30 +00001895/// call i8* \@objc_retain(i8* %value)
1896/// call i8* \@objc_retainBlock(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001897llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1898 if (type->isBlockPointerType())
John McCallff613032011-10-04 06:23:45 +00001899 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCall31168b02011-06-15 23:02:42 +00001900 else
1901 return EmitARCRetainNonBlock(value);
1902}
1903
1904/// Retain the given object, with normal retain semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001905/// call i8* \@objc_retain(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001906llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1907 return emitARCValueOperation(*this, value,
1908 CGM.getARCEntrypoints().objc_retain,
1909 "objc_retain");
1910}
1911
1912/// Retain the given block, with _Block_copy semantics.
James Dennett14c41ea2012-06-22 05:41:30 +00001913/// call i8* \@objc_retainBlock(i8* %value)
John McCallff613032011-10-04 06:23:45 +00001914///
1915/// \param mandatory - If false, emit the call with metadata
1916/// indicating that it's okay for the optimizer to eliminate this call
1917/// if it can prove that the block never escapes except down the stack.
1918llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1919 bool mandatory) {
1920 llvm::Value *result
1921 = emitARCValueOperation(*this, value,
1922 CGM.getARCEntrypoints().objc_retainBlock,
1923 "objc_retainBlock");
1924
1925 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1926 // tell the optimizer that it doesn't need to do this copy if the
1927 // block doesn't escape, where being passed as an argument doesn't
1928 // count as escaping.
1929 if (!mandatory && isa<llvm::Instruction>(result)) {
1930 llvm::CallInst *call
1931 = cast<llvm::CallInst>(result->stripPointerCasts());
1932 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1933
John McCallff613032011-10-04 06:23:45 +00001934 call->setMetadata("clang.arc.copy_on_escape",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001935 llvm::MDNode::get(Builder.getContext(), None));
John McCallff613032011-10-04 06:23:45 +00001936 }
1937
1938 return result;
John McCall31168b02011-06-15 23:02:42 +00001939}
1940
1941/// Retain the given object which is the result of a function call.
James Dennett14c41ea2012-06-22 05:41:30 +00001942/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00001943///
1944/// Yes, this function name is one character away from a different
1945/// call with completely different semantics.
1946llvm::Value *
1947CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1948 // Fetch the void(void) inline asm which marks that we're going to
1949 // retain the autoreleased return value.
1950 llvm::InlineAsm *&marker
1951 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1952 if (!marker) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001953 StringRef assembly
John McCall31168b02011-06-15 23:02:42 +00001954 = CGM.getTargetCodeGenInfo()
1955 .getARCRetainAutoreleasedReturnValueMarker();
1956
1957 // If we have an empty assembly string, there's nothing to do.
1958 if (assembly.empty()) {
1959
1960 // Otherwise, at -O0, build an inline asm that we're going to call
1961 // in a moment.
1962 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1963 llvm::FunctionType *type =
Chris Lattnerece04092012-02-07 00:39:47 +00001964 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCall31168b02011-06-15 23:02:42 +00001965
1966 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1967
1968 // If we're at -O1 and above, we don't want to litter the code
1969 // with this marker yet, so leave a breadcrumb for the ARC
1970 // optimizer to pick up.
1971 } else {
1972 llvm::NamedMDNode *metadata =
1973 CGM.getModule().getOrInsertNamedMetadata(
1974 "clang.arc.retainAutoreleasedReturnValueMarker");
1975 assert(metadata->getNumOperands() <= 1);
1976 if (metadata->getNumOperands() == 0) {
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00001977 metadata->addOperand(llvm::MDNode::get(
1978 getLLVMContext(), llvm::MDString::get(getLLVMContext(), assembly)));
John McCall31168b02011-06-15 23:02:42 +00001979 }
1980 }
1981 }
1982
1983 // Call the marker asm if we made one, which we do only at -O0.
1984 if (marker) Builder.CreateCall(marker);
1985
1986 return emitARCValueOperation(*this, value,
1987 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1988 "objc_retainAutoreleasedReturnValue");
1989}
1990
1991/// Release the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00001992/// call void \@objc_release(i8* %value)
John McCallcdda29c2013-03-13 03:10:54 +00001993void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1994 ARCPreciseLifetime_t precise) {
John McCall31168b02011-06-15 23:02:42 +00001995 if (isa<llvm::ConstantPointerNull>(value)) return;
1996
1997 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1998 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00001999 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002000 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002001 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
2002 }
2003
2004 // Cast the argument to 'id'.
2005 value = Builder.CreateBitCast(value, Int8PtrTy);
2006
2007 // Call objc_release.
John McCall882987f2013-02-28 19:01:20 +00002008 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002009
John McCallcdda29c2013-03-13 03:10:54 +00002010 if (precise == ARCImpreciseLifetime) {
John McCall31168b02011-06-15 23:02:42 +00002011 call->setMetadata("clang.imprecise_release",
Duncan P. N. Exon Smithfb494912014-12-09 18:39:32 +00002012 llvm::MDNode::get(Builder.getContext(), None));
John McCall31168b02011-06-15 23:02:42 +00002013 }
2014}
2015
John McCalle68b8f42012-10-17 02:28:37 +00002016/// Destroy a __strong variable.
2017///
2018/// At -O0, emit a call to store 'null' into the address;
2019/// instrumenting tools prefer this because the address is exposed,
2020/// but it's relatively cumbersome to optimize.
2021///
2022/// At -O1 and above, just load and call objc_release.
2023///
2024/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCallcdda29c2013-03-13 03:10:54 +00002025void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2026 ARCPreciseLifetime_t precise) {
John McCalle68b8f42012-10-17 02:28:37 +00002027 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2028 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2029 llvm::Value *null = llvm::ConstantPointerNull::get(
2030 cast<llvm::PointerType>(addrTy->getElementType()));
2031 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2032 return;
2033 }
2034
2035 llvm::Value *value = Builder.CreateLoad(addr);
2036 EmitARCRelease(value, precise);
2037}
2038
John McCall31168b02011-06-15 23:02:42 +00002039/// Store into a strong object. Always calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002040/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002041llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2042 llvm::Value *value,
2043 bool ignored) {
2044 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2045 == value->getType());
2046
2047 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2048 if (!fn) {
Chris Lattnera5f58b02011-07-09 17:41:47 +00002049 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2192fe52011-07-18 04:24:23 +00002050 llvm::FunctionType *fnType
John McCall31168b02011-06-15 23:02:42 +00002051 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2052 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2053 }
2054
John McCall882987f2013-02-28 19:01:20 +00002055 llvm::Value *args[] = {
2056 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2057 Builder.CreateBitCast(value, Int8PtrTy)
2058 };
2059 EmitNounwindRuntimeCall(fn, args);
John McCall31168b02011-06-15 23:02:42 +00002060
Craig Topper8a13c412014-05-21 05:09:00 +00002061 if (ignored) return nullptr;
John McCall31168b02011-06-15 23:02:42 +00002062 return value;
2063}
2064
2065/// Store into a strong object. Sometimes calls this:
James Dennett14c41ea2012-06-22 05:41:30 +00002066/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002067/// Other times, breaks it down into components.
John McCall55e1fbc2011-06-25 02:11:03 +00002068llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCall31168b02011-06-15 23:02:42 +00002069 llvm::Value *newValue,
2070 bool ignored) {
John McCall55e1fbc2011-06-25 02:11:03 +00002071 QualType type = dst.getType();
John McCall31168b02011-06-15 23:02:42 +00002072 bool isBlock = type->isBlockPointerType();
2073
2074 // Use a store barrier at -O0 unless this is a block type or the
2075 // lvalue is inadequately aligned.
2076 if (shouldUseFusedARCCalls() &&
2077 !isBlock &&
Eli Friedmana0544d62011-12-03 04:14:32 +00002078 (dst.getAlignment().isZero() ||
2079 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCall31168b02011-06-15 23:02:42 +00002080 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2081 }
2082
2083 // Otherwise, split it out.
2084
2085 // Retain the new value.
2086 newValue = EmitARCRetain(type, newValue);
2087
2088 // Read the old value.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002089 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCall31168b02011-06-15 23:02:42 +00002090
2091 // Store. We do this before the release so that any deallocs won't
2092 // see the old value.
John McCall55e1fbc2011-06-25 02:11:03 +00002093 EmitStoreOfScalar(newValue, dst);
John McCall31168b02011-06-15 23:02:42 +00002094
2095 // Finally, release the old value.
John McCallcdda29c2013-03-13 03:10:54 +00002096 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002097
2098 return newValue;
2099}
2100
2101/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002102/// call i8* \@objc_autorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002103llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2104 return emitARCValueOperation(*this, value,
2105 CGM.getARCEntrypoints().objc_autorelease,
2106 "objc_autorelease");
2107}
2108
2109/// Autorelease the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002110/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002111llvm::Value *
2112CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2113 return emitARCValueOperation(*this, value,
2114 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002115 "objc_autoreleaseReturnValue",
2116 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002117}
2118
2119/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002120/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002121llvm::Value *
2122CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2123 return emitARCValueOperation(*this, value,
2124 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosier13799b32012-12-12 17:52:21 +00002125 "objc_retainAutoreleaseReturnValue",
2126 /*isTailCall*/ true);
John McCall31168b02011-06-15 23:02:42 +00002127}
2128
2129/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002130/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002131/// or
James Dennett14c41ea2012-06-22 05:41:30 +00002132/// %retain = call i8* \@objc_retainBlock(i8* %value)
2133/// call i8* \@objc_autorelease(i8* %retain)
John McCall31168b02011-06-15 23:02:42 +00002134llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2135 llvm::Value *value) {
2136 if (!type->isBlockPointerType())
2137 return EmitARCRetainAutoreleaseNonBlock(value);
2138
2139 if (isa<llvm::ConstantPointerNull>(value)) return value;
2140
Chris Lattner2192fe52011-07-18 04:24:23 +00002141 llvm::Type *origType = value->getType();
John McCall31168b02011-06-15 23:02:42 +00002142 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCallff613032011-10-04 06:23:45 +00002143 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCall31168b02011-06-15 23:02:42 +00002144 value = EmitARCAutorelease(value);
2145 return Builder.CreateBitCast(value, origType);
2146}
2147
2148/// Do a fused retain/autorelease of the given object.
James Dennett14c41ea2012-06-22 05:41:30 +00002149/// call i8* \@objc_retainAutorelease(i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002150llvm::Value *
2151CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2152 return emitARCValueOperation(*this, value,
2153 CGM.getARCEntrypoints().objc_retainAutorelease,
2154 "objc_retainAutorelease");
2155}
2156
James Dennett14c41ea2012-06-22 05:41:30 +00002157/// i8* \@objc_loadWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002158/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2159llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2160 return emitARCLoadOperation(*this, addr,
2161 CGM.getARCEntrypoints().objc_loadWeak,
2162 "objc_loadWeak");
2163}
2164
James Dennett14c41ea2012-06-22 05:41:30 +00002165/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002166llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2167 return emitARCLoadOperation(*this, addr,
2168 CGM.getARCEntrypoints().objc_loadWeakRetained,
2169 "objc_loadWeakRetained");
2170}
2171
James Dennett14c41ea2012-06-22 05:41:30 +00002172/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002173/// Returns %value.
2174llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2175 llvm::Value *value,
2176 bool ignored) {
2177 return emitARCStoreOperation(*this, addr, value,
2178 CGM.getARCEntrypoints().objc_storeWeak,
2179 "objc_storeWeak", ignored);
2180}
2181
James Dennett14c41ea2012-06-22 05:41:30 +00002182/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCall31168b02011-06-15 23:02:42 +00002183/// Returns %value. %addr is known to not have a current weak entry.
2184/// Essentially equivalent to:
2185/// *addr = nil; objc_storeWeak(addr, value);
2186void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2187 // If we're initializing to null, just write null to memory; no need
2188 // to get the runtime involved. But don't do this if optimization
2189 // is enabled, because accounting for this would make the optimizer
2190 // much more complicated.
2191 if (isa<llvm::ConstantPointerNull>(value) &&
2192 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2193 Builder.CreateStore(value, addr);
2194 return;
2195 }
2196
2197 emitARCStoreOperation(*this, addr, value,
2198 CGM.getARCEntrypoints().objc_initWeak,
2199 "objc_initWeak", /*ignored*/ true);
2200}
2201
James Dennett14c41ea2012-06-22 05:41:30 +00002202/// void \@objc_destroyWeak(i8** %addr)
John McCall31168b02011-06-15 23:02:42 +00002203/// Essentially objc_storeWeak(addr, nil).
2204void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2205 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2206 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002207 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002208 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002209 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2210 }
2211
2212 // Cast the argument to 'id*'.
2213 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2214
John McCall882987f2013-02-28 19:01:20 +00002215 EmitNounwindRuntimeCall(fn, addr);
John McCall31168b02011-06-15 23:02:42 +00002216}
2217
James Dennett14c41ea2012-06-22 05:41:30 +00002218/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002219/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2220/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2221void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2222 emitARCCopyOperation(*this, dst, src,
2223 CGM.getARCEntrypoints().objc_moveWeak,
2224 "objc_moveWeak");
2225}
2226
James Dennett14c41ea2012-06-22 05:41:30 +00002227/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCall31168b02011-06-15 23:02:42 +00002228/// Disregards the current value in %dest. Essentially
2229/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2230void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2231 emitARCCopyOperation(*this, dst, src,
2232 CGM.getARCEntrypoints().objc_copyWeak,
2233 "objc_copyWeak");
2234}
2235
2236/// Produce the code to do a objc_autoreleasepool_push.
James Dennett14c41ea2012-06-22 05:41:30 +00002237/// call i8* \@objc_autoreleasePoolPush(void)
John McCall31168b02011-06-15 23:02:42 +00002238llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2239 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2240 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002241 llvm::FunctionType *fnType =
John McCall31168b02011-06-15 23:02:42 +00002242 llvm::FunctionType::get(Int8PtrTy, false);
2243 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2244 }
2245
John McCall882987f2013-02-28 19:01:20 +00002246 return EmitNounwindRuntimeCall(fn);
John McCall31168b02011-06-15 23:02:42 +00002247}
2248
2249/// Produce the code to do a primitive release.
James Dennett14c41ea2012-06-22 05:41:30 +00002250/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCall31168b02011-06-15 23:02:42 +00002251void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2252 assert(value->getType() == Int8PtrTy);
2253
2254 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2255 if (!fn) {
Chris Lattner2192fe52011-07-18 04:24:23 +00002256 llvm::FunctionType *fnType =
Benjamin Kramer95e19362013-03-07 21:18:31 +00002257 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCall31168b02011-06-15 23:02:42 +00002258
2259 // We don't want to use a weak import here; instead we should not
2260 // fall into this path.
2261 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2262 }
2263
John McCallb7ff6db2013-04-16 21:29:40 +00002264 // objc_autoreleasePoolPop can throw.
2265 EmitRuntimeCallOrInvoke(fn, value);
John McCall31168b02011-06-15 23:02:42 +00002266}
2267
2268/// Produce the code to do an MRR version objc_autoreleasepool_push.
2269/// Which is: [[NSAutoreleasePool alloc] init];
2270/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2271/// init is declared as: - (id) init; in its NSObject super class.
2272///
2273llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2274 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCall882987f2013-02-28 19:01:20 +00002275 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCall31168b02011-06-15 23:02:42 +00002276 // [NSAutoreleasePool alloc]
2277 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2278 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2279 CallArgList Args;
2280 RValue AllocRV =
2281 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2282 getContext().getObjCIdType(),
2283 AllocSel, Receiver, Args);
2284
2285 // [Receiver init]
2286 Receiver = AllocRV.getScalarVal();
2287 II = &CGM.getContext().Idents.get("init");
2288 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2289 RValue InitRV =
2290 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2291 getContext().getObjCIdType(),
2292 InitSel, Receiver, Args);
2293 return InitRV.getScalarVal();
2294}
2295
2296/// Produce the code to do a primitive release.
2297/// [tmp drain];
2298void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2299 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2300 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2301 CallArgList Args;
2302 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2303 getContext().VoidTy, DrainSel, Arg, Args);
2304}
2305
John McCall82fe67b2011-07-09 01:37:26 +00002306void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2307 llvm::Value *addr,
2308 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002309 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002310}
2311
2312void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2313 llvm::Value *addr,
2314 QualType type) {
John McCallcdda29c2013-03-13 03:10:54 +00002315 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCall82fe67b2011-07-09 01:37:26 +00002316}
2317
2318void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2319 llvm::Value *addr,
2320 QualType type) {
2321 CGF.EmitARCDestroyWeak(addr);
2322}
2323
John McCall31168b02011-06-15 23:02:42 +00002324namespace {
John McCall31168b02011-06-15 23:02:42 +00002325 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2326 llvm::Value *Token;
2327
2328 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2329
Craig Topper4f12f102014-03-12 06:41:41 +00002330 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002331 CGF.EmitObjCAutoreleasePoolPop(Token);
2332 }
2333 };
2334 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2335 llvm::Value *Token;
2336
2337 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2338
Craig Topper4f12f102014-03-12 06:41:41 +00002339 void Emit(CodeGenFunction &CGF, Flags flags) override {
John McCall31168b02011-06-15 23:02:42 +00002340 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2341 }
2342 };
2343}
2344
2345void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002346 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCall31168b02011-06-15 23:02:42 +00002347 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2348 else
2349 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2350}
2351
John McCall31168b02011-06-15 23:02:42 +00002352static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2353 LValue lvalue,
2354 QualType type) {
2355 switch (type.getObjCLifetime()) {
2356 case Qualifiers::OCL_None:
2357 case Qualifiers::OCL_ExplicitNone:
2358 case Qualifiers::OCL_Strong:
2359 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky2d84e842013-10-02 02:29:49 +00002360 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2361 SourceLocation()).getScalarVal(),
John McCall31168b02011-06-15 23:02:42 +00002362 false);
2363
2364 case Qualifiers::OCL_Weak:
2365 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2366 true);
2367 }
2368
2369 llvm_unreachable("impossible lifetime!");
John McCall31168b02011-06-15 23:02:42 +00002370}
2371
2372static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2373 const Expr *e) {
2374 e = e->IgnoreParens();
2375 QualType type = e->getType();
2376
John McCall154a2fd2011-08-30 00:57:29 +00002377 // If we're loading retained from a __strong xvalue, we can avoid
2378 // an extra retain/release pair by zeroing out the source of this
2379 // "move" operation.
2380 if (e->isXValue() &&
2381 !type.isConstQualified() &&
2382 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2383 // Emit the lvalue.
2384 LValue lv = CGF.EmitLValue(e);
2385
2386 // Load the object pointer.
Nick Lewycky2d84e842013-10-02 02:29:49 +00002387 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2388 SourceLocation()).getScalarVal();
John McCall154a2fd2011-08-30 00:57:29 +00002389
2390 // Set the source pointer to NULL.
2391 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2392
2393 return TryEmitResult(result, true);
2394 }
2395
John McCall31168b02011-06-15 23:02:42 +00002396 // As a very special optimization, in ARC++, if the l-value is the
2397 // result of a non-volatile assignment, do a simple retain of the
2398 // result of the call to objc_storeWeak instead of reloading.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002399 if (CGF.getLangOpts().CPlusPlus &&
John McCall31168b02011-06-15 23:02:42 +00002400 !type.isVolatileQualified() &&
2401 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2402 isa<BinaryOperator>(e) &&
2403 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2404 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2405
2406 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2407}
2408
2409static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2410 llvm::Value *value);
2411
2412/// Given that the given expression is some sort of call (which does
2413/// not return retained), emit a retain following it.
2414static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2415 llvm::Value *value = CGF.EmitScalarExpr(e);
2416 return emitARCRetainAfterCall(CGF, value);
2417}
2418
2419static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2420 llvm::Value *value) {
2421 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2422 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2423
2424 // Place the retain immediately following the call.
2425 CGF.Builder.SetInsertPoint(call->getParent(),
2426 ++llvm::BasicBlock::iterator(call));
2427 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2428
2429 CGF.Builder.restoreIP(ip);
2430 return value;
2431 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2432 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2433
2434 // Place the retain at the beginning of the normal destination block.
2435 llvm::BasicBlock *BB = invoke->getNormalDest();
2436 CGF.Builder.SetInsertPoint(BB, BB->begin());
2437 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2438
2439 CGF.Builder.restoreIP(ip);
2440 return value;
2441
2442 // Bitcasts can arise because of related-result returns. Rewrite
2443 // the operand.
2444 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2445 llvm::Value *operand = bitcast->getOperand(0);
2446 operand = emitARCRetainAfterCall(CGF, operand);
2447 bitcast->setOperand(0, operand);
2448 return bitcast;
2449
2450 // Generic fall-back case.
2451 } else {
2452 // Retain using the non-block variant: we never need to do a copy
2453 // of a block that's been returned to us.
2454 return CGF.EmitARCRetainNonBlock(value);
2455 }
2456}
2457
John McCallcd78e802011-09-10 01:16:55 +00002458/// Determine whether it might be important to emit a separate
2459/// objc_retain_block on the result of the given expression, or
2460/// whether it's okay to just emit it in a +1 context.
2461static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2462 assert(e->getType()->isBlockPointerType());
2463 e = e->IgnoreParens();
2464
2465 // For future goodness, emit block expressions directly in +1
2466 // contexts if we can.
2467 if (isa<BlockExpr>(e))
2468 return false;
2469
2470 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2471 switch (cast->getCastKind()) {
2472 // Emitting these operations in +1 contexts is goodness.
2473 case CK_LValueToRValue:
John McCall2d637d22011-09-10 06:18:15 +00002474 case CK_ARCReclaimReturnedObject:
2475 case CK_ARCConsumeObject:
2476 case CK_ARCProduceObject:
John McCallcd78e802011-09-10 01:16:55 +00002477 return false;
2478
2479 // These operations preserve a block type.
2480 case CK_NoOp:
2481 case CK_BitCast:
2482 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2483
2484 // These operations are known to be bad (or haven't been considered).
2485 case CK_AnyPointerToBlockPointerCast:
2486 default:
2487 return true;
2488 }
2489 }
2490
2491 return true;
2492}
2493
John McCallfe96e0b2011-11-06 09:01:30 +00002494/// Try to emit a PseudoObjectExpr at +1.
2495///
2496/// This massively duplicates emitPseudoObjectRValue.
2497static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2498 const PseudoObjectExpr *E) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002499 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCallfe96e0b2011-11-06 09:01:30 +00002500
2501 // Find the result expression.
2502 const Expr *resultExpr = E->getResultExpr();
2503 assert(resultExpr);
2504 TryEmitResult result;
2505
2506 for (PseudoObjectExpr::const_semantics_iterator
2507 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2508 const Expr *semantic = *i;
2509
2510 // If this semantic expression is an opaque value, bind it
2511 // to the result of its source expression.
2512 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2513 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2514 OVMA opaqueData;
2515
2516 // If this semantic is the result of the pseudo-object
2517 // expression, try to evaluate the source as +1.
2518 if (ov == resultExpr) {
2519 assert(!OVMA::shouldBindAsLValue(ov));
2520 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2521 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2522
2523 // Otherwise, just bind it.
2524 } else {
2525 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2526 }
2527 opaques.push_back(opaqueData);
2528
2529 // Otherwise, if the expression is the result, evaluate it
2530 // and remember the result.
2531 } else if (semantic == resultExpr) {
2532 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2533
2534 // Otherwise, evaluate the expression in an ignored context.
2535 } else {
2536 CGF.EmitIgnoredExpr(semantic);
2537 }
2538 }
2539
2540 // Unbind all the opaques now.
2541 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2542 opaques[i].unbind(CGF);
2543
2544 return result;
2545}
2546
John McCall31168b02011-06-15 23:02:42 +00002547static TryEmitResult
2548tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002549 // We should *never* see a nested full-expression here, because if
2550 // we fail to emit at +1, our caller must not retain after we close
2551 // out the full-expression.
2552 assert(!isa<ExprWithCleanups>(e));
John McCall53848232011-07-27 01:07:15 +00002553
John McCall31168b02011-06-15 23:02:42 +00002554 // The desired result type, if it differs from the type of the
2555 // ultimate opaque expression.
Craig Topper8a13c412014-05-21 05:09:00 +00002556 llvm::Type *resultType = nullptr;
John McCall31168b02011-06-15 23:02:42 +00002557
2558 while (true) {
2559 e = e->IgnoreParens();
2560
2561 // There's a break at the end of this if-chain; anything
2562 // that wants to keep looping has to explicitly continue.
2563 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2564 switch (ce->getCastKind()) {
2565 // No-op casts don't change the type, so we just ignore them.
2566 case CK_NoOp:
2567 e = ce->getSubExpr();
2568 continue;
2569
2570 case CK_LValueToRValue: {
2571 TryEmitResult loadResult
2572 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2573 if (resultType) {
2574 llvm::Value *value = loadResult.getPointer();
2575 value = CGF.Builder.CreateBitCast(value, resultType);
2576 loadResult.setPointer(value);
2577 }
2578 return loadResult;
2579 }
2580
2581 // These casts can change the type, so remember that and
2582 // soldier on. We only need to remember the outermost such
2583 // cast, though.
John McCall9320b872011-09-09 05:25:32 +00002584 case CK_CPointerToObjCPointerCast:
2585 case CK_BlockPointerToObjCPointerCast:
John McCall31168b02011-06-15 23:02:42 +00002586 case CK_AnyPointerToBlockPointerCast:
2587 case CK_BitCast:
2588 if (!resultType)
2589 resultType = CGF.ConvertType(ce->getType());
2590 e = ce->getSubExpr();
2591 assert(e->getType()->hasPointerRepresentation());
2592 continue;
2593
2594 // For consumptions, just emit the subexpression and thus elide
2595 // the retain/release pair.
John McCall2d637d22011-09-10 06:18:15 +00002596 case CK_ARCConsumeObject: {
John McCall31168b02011-06-15 23:02:42 +00002597 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2598 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2599 return TryEmitResult(result, true);
2600 }
2601
John McCallcd78e802011-09-10 01:16:55 +00002602 // Block extends are net +0. Naively, we could just recurse on
2603 // the subexpression, but actually we need to ensure that the
2604 // value is copied as a block, so there's a little filter here.
John McCall2d637d22011-09-10 06:18:15 +00002605 case CK_ARCExtendBlockObject: {
John McCallcd78e802011-09-10 01:16:55 +00002606 llvm::Value *result; // will be a +0 value
2607
2608 // If we can't safely assume the sub-expression will produce a
2609 // block-copied value, emit the sub-expression at +0.
2610 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2611 result = CGF.EmitScalarExpr(ce->getSubExpr());
2612
2613 // Otherwise, try to emit the sub-expression at +1 recursively.
2614 } else {
2615 TryEmitResult subresult
2616 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2617 result = subresult.getPointer();
2618
2619 // If that produced a retained value, just use that,
2620 // possibly casting down.
2621 if (subresult.getInt()) {
2622 if (resultType)
2623 result = CGF.Builder.CreateBitCast(result, resultType);
2624 return TryEmitResult(result, true);
2625 }
2626
2627 // Otherwise it's +0.
2628 }
2629
2630 // Retain the object as a block, then cast down.
John McCallff613032011-10-04 06:23:45 +00002631 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCallcd78e802011-09-10 01:16:55 +00002632 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2633 return TryEmitResult(result, true);
2634 }
2635
John McCall4db5c3c2011-07-07 06:58:02 +00002636 // For reclaims, emit the subexpression as a retained call and
2637 // skip the consumption.
John McCall2d637d22011-09-10 06:18:15 +00002638 case CK_ARCReclaimReturnedObject: {
John McCall4db5c3c2011-07-07 06:58:02 +00002639 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2640 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2641 return TryEmitResult(result, true);
2642 }
2643
John McCall31168b02011-06-15 23:02:42 +00002644 default:
2645 break;
2646 }
2647
2648 // Skip __extension__.
2649 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2650 if (op->getOpcode() == UO_Extension) {
2651 e = op->getSubExpr();
2652 continue;
2653 }
2654
2655 // For calls and message sends, use the retained-call logic.
2656 // Delegate inits are a special case in that they're the only
2657 // returns-retained expression that *isn't* surrounded by
2658 // a consume.
2659 } else if (isa<CallExpr>(e) ||
2660 (isa<ObjCMessageExpr>(e) &&
2661 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2662 llvm::Value *result = emitARCRetainCall(CGF, e);
2663 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2664 return TryEmitResult(result, true);
John McCallfe96e0b2011-11-06 09:01:30 +00002665
2666 // Look through pseudo-object expressions.
2667 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2668 TryEmitResult result
2669 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2670 if (resultType) {
2671 llvm::Value *value = result.getPointer();
2672 value = CGF.Builder.CreateBitCast(value, resultType);
2673 result.setPointer(value);
2674 }
2675 return result;
John McCall31168b02011-06-15 23:02:42 +00002676 }
2677
2678 // Conservatively halt the search at any other expression kind.
2679 break;
2680 }
2681
2682 // We didn't find an obvious production, so emit what we've got and
2683 // tell the caller that we didn't manage to retain.
2684 llvm::Value *result = CGF.EmitScalarExpr(e);
2685 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2686 return TryEmitResult(result, false);
2687}
2688
2689static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2690 LValue lvalue,
2691 QualType type) {
2692 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2693 llvm::Value *value = result.getPointer();
2694 if (!result.getInt())
2695 value = CGF.EmitARCRetain(type, value);
2696 return value;
2697}
2698
2699/// EmitARCRetainScalarExpr - Semantically equivalent to
2700/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2701/// best-effort attempt to peephole expressions that naturally produce
2702/// retained objects.
2703llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002704 // The retain needs to happen within the full-expression.
2705 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2706 enterFullExpression(cleanups);
2707 RunCleanupsScope scope(*this);
2708 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2709 }
2710
John McCall31168b02011-06-15 23:02:42 +00002711 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2712 llvm::Value *value = result.getPointer();
2713 if (!result.getInt())
2714 value = EmitARCRetain(e->getType(), value);
2715 return value;
2716}
2717
2718llvm::Value *
2719CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCalld21cdd42013-02-12 00:25:08 +00002720 // The retain needs to happen within the full-expression.
2721 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2722 enterFullExpression(cleanups);
2723 RunCleanupsScope scope(*this);
2724 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2725 }
2726
John McCall31168b02011-06-15 23:02:42 +00002727 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2728 llvm::Value *value = result.getPointer();
2729 if (result.getInt())
2730 value = EmitARCAutorelease(value);
2731 else
2732 value = EmitARCRetainAutorelease(e->getType(), value);
2733 return value;
2734}
2735
John McCallff613032011-10-04 06:23:45 +00002736llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2737 llvm::Value *result;
2738 bool doRetain;
2739
2740 if (shouldEmitSeparateBlockRetain(e)) {
2741 result = EmitScalarExpr(e);
2742 doRetain = true;
2743 } else {
2744 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2745 result = subresult.getPointer();
2746 doRetain = !subresult.getInt();
2747 }
2748
2749 if (doRetain)
2750 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2751 return EmitObjCConsumeObject(e->getType(), result);
2752}
2753
John McCall248512a2011-10-01 10:32:24 +00002754llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2755 // In ARC, retain and autorelease the expression.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002756 if (getLangOpts().ObjCAutoRefCount) {
John McCall248512a2011-10-01 10:32:24 +00002757 // Do so before running any cleanups for the full-expression.
John McCalld21cdd42013-02-12 00:25:08 +00002758 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall248512a2011-10-01 10:32:24 +00002759 return EmitARCRetainAutoreleaseScalarExpr(expr);
2760 }
2761
2762 // Otherwise, use the normal scalar-expression emission. The
2763 // exception machinery doesn't do anything special with the
2764 // exception like retaining it, so there's no safety associated with
2765 // only running cleanups after the throw has started, and when it
2766 // matters it tends to be substantially inferior code.
2767 return EmitScalarExpr(expr);
2768}
2769
John McCall31168b02011-06-15 23:02:42 +00002770std::pair<LValue,llvm::Value*>
2771CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2772 bool ignored) {
2773 // Evaluate the RHS first.
2774 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2775 llvm::Value *value = result.getPointer();
2776
John McCallb726a552011-07-28 07:23:35 +00002777 bool hasImmediateRetain = result.getInt();
2778
2779 // If we didn't emit a retained object, and the l-value is of block
2780 // type, then we need to emit the block-retain immediately in case
2781 // it invalidates the l-value.
2782 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCallff613032011-10-04 06:23:45 +00002783 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallb726a552011-07-28 07:23:35 +00002784 hasImmediateRetain = true;
2785 }
2786
John McCall31168b02011-06-15 23:02:42 +00002787 LValue lvalue = EmitLValue(e->getLHS());
2788
2789 // If the RHS was emitted retained, expand this.
John McCallb726a552011-07-28 07:23:35 +00002790 if (hasImmediateRetain) {
Nick Lewyckyce550072013-10-02 02:33:11 +00002791 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedmana0544d62011-12-03 04:14:32 +00002792 EmitStoreOfScalar(value, lvalue);
John McCallcdda29c2013-03-13 03:10:54 +00002793 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCall31168b02011-06-15 23:02:42 +00002794 } else {
John McCall55e1fbc2011-06-25 02:11:03 +00002795 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCall31168b02011-06-15 23:02:42 +00002796 }
2797
2798 return std::pair<LValue,llvm::Value*>(lvalue, value);
2799}
2800
2801std::pair<LValue,llvm::Value*>
2802CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2803 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2804 LValue lvalue = EmitLValue(e->getLHS());
2805
Eli Friedmana0544d62011-12-03 04:14:32 +00002806 EmitStoreOfScalar(value, lvalue);
John McCall31168b02011-06-15 23:02:42 +00002807
2808 return std::pair<LValue,llvm::Value*>(lvalue, value);
2809}
2810
2811void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002812 const ObjCAutoreleasePoolStmt &ARPS) {
John McCall31168b02011-06-15 23:02:42 +00002813 const Stmt *subStmt = ARPS.getSubStmt();
2814 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2815
2816 CGDebugInfo *DI = getDebugInfo();
Eric Christopher7cdf9482011-10-13 21:45:18 +00002817 if (DI)
2818 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002819
2820 // Keep track of the current cleanup stack depth.
2821 RunCleanupsScope Scope(*this);
John McCall3deb1ad2012-08-21 02:47:43 +00002822 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCall31168b02011-06-15 23:02:42 +00002823 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2824 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2825 } else {
2826 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2827 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2828 }
2829
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00002830 for (const auto *I : S.body())
2831 EmitStmt(I);
John McCall31168b02011-06-15 23:02:42 +00002832
Eric Christopher7cdf9482011-10-13 21:45:18 +00002833 if (DI)
2834 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCall31168b02011-06-15 23:02:42 +00002835}
John McCall1bd25562011-06-24 23:21:27 +00002836
2837/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2838/// make sure it survives garbage collection until this point.
2839void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2840 // We just use an inline assembly.
John McCall1bd25562011-06-24 23:21:27 +00002841 llvm::FunctionType *extenderType
John McCalla729c622012-02-17 03:33:10 +00002842 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall1bd25562011-06-24 23:21:27 +00002843 llvm::Value *extender
2844 = llvm::InlineAsm::get(extenderType,
2845 /* assembly */ "",
2846 /* constraints */ "r",
2847 /* side effects */ true);
2848
2849 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCall882987f2013-02-28 19:01:20 +00002850 EmitNounwindRuntimeCall(extender, object);
John McCall1bd25562011-06-24 23:21:27 +00002851}
2852
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002853/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002854/// non-trivial copy assignment function, produce following helper function.
2855/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2856///
2857llvm::Constant *
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002858CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2859 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002860 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002861 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002862 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002863 QualType Ty = PID->getPropertyIvarDecl()->getType();
2864 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002865 return nullptr;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002866 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002867 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002868 return nullptr;
2869 llvm::Constant *HelperFn = nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002870 if (hasTrivialSetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002871 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002872 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2873 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2874 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002875
2876 ASTContext &C = getContext();
2877 IdentifierInfo *II
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002878 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002879 FunctionDecl *FD = FunctionDecl::Create(C,
2880 C.getTranslationUnitDecl(),
2881 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002882 SourceLocation(), II, C.VoidTy,
2883 nullptr, SC_Static,
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002884 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002885 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002886
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002887 QualType DestTy = C.getPointerType(Ty);
2888 QualType SrcTy = Ty;
2889 SrcTy.addConst();
2890 SrcTy = C.getPointerType(SrcTy);
2891
2892 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002893 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002894 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002895 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002896 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002897
2898 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2899 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2900
John McCalla729c622012-02-17 03:33:10 +00002901 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002902
2903 llvm::Function *Fn =
2904 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher5d2b8d92012-03-29 17:31:31 +00002905 "__assign_helper_atomic_property_",
2906 &CGM.getModule());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002907
Adrian Prantl22e66b42014-04-11 01:13:04 +00002908 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002909
John McCall113bee02012-03-10 09:33:50 +00002910 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2911 VK_RValue, SourceLocation());
2912 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2913 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002914
John McCall113bee02012-03-10 09:33:50 +00002915 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2916 VK_RValue, SourceLocation());
2917 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2918 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002919
John McCall113bee02012-03-10 09:33:50 +00002920 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002921 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCall113bee02012-03-10 09:33:50 +00002922 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00002923 Args, DestTy->getPointeeType(),
Lang Hames5de91cc2012-10-02 04:45:10 +00002924 VK_LValue, SourceLocation(), false);
John McCall113bee02012-03-10 09:33:50 +00002925
2926 EmitStmt(&TheCall);
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00002927
2928 FinishFunction();
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002929 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002930 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahanian7ff610b2012-01-06 22:33:54 +00002931 return HelperFn;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002932}
2933
2934llvm::Constant *
2935CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2936 const ObjCPropertyImplDecl *PID) {
John McCall5fb5df92012-06-20 06:18:46 +00002937 if (!getLangOpts().CPlusPlus ||
Rafael Espindolad727d3d2012-12-18 04:29:34 +00002938 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Craig Topper8a13c412014-05-21 05:09:00 +00002939 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002940 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2941 QualType Ty = PD->getType();
2942 if (!Ty->isRecordType())
Craig Topper8a13c412014-05-21 05:09:00 +00002943 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002944 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Craig Topper8a13c412014-05-21 05:09:00 +00002945 return nullptr;
2946 llvm::Constant *HelperFn = nullptr;
2947
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002948 if (hasTrivialGetExpr(PID))
Craig Topper8a13c412014-05-21 05:09:00 +00002949 return nullptr;
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002950 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2951 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2952 return HelperFn;
2953
2954
2955 ASTContext &C = getContext();
2956 IdentifierInfo *II
2957 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2958 FunctionDecl *FD = FunctionDecl::Create(C,
2959 C.getTranslationUnitDecl(),
2960 SourceLocation(),
Craig Topper8a13c412014-05-21 05:09:00 +00002961 SourceLocation(), II, C.VoidTy,
2962 nullptr, SC_Static,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002963 false,
Eric Christopher0b1aef22012-04-12 02:16:49 +00002964 false);
Craig Topper8a13c412014-05-21 05:09:00 +00002965
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002966 QualType DestTy = C.getPointerType(Ty);
2967 QualType SrcTy = Ty;
2968 SrcTy.addConst();
2969 SrcTy = C.getPointerType(SrcTy);
2970
2971 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +00002972 ImplicitParamDecl dstDecl(getContext(), FD, SourceLocation(), nullptr,DestTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002973 args.push_back(&dstDecl);
Craig Topper8a13c412014-05-21 05:09:00 +00002974 ImplicitParamDecl srcDecl(getContext(), FD, SourceLocation(), nullptr, SrcTy);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002975 args.push_back(&srcDecl);
Reid Kleckner4982b822014-01-31 22:54:50 +00002976
2977 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
2978 C.VoidTy, args, FunctionType::ExtInfo(), RequiredArgs::All);
2979
John McCalla729c622012-02-17 03:33:10 +00002980 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002981
2982 llvm::Function *Fn =
2983 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2984 "__copy_helper_atomic_property_", &CGM.getModule());
2985
Adrian Prantl22e66b42014-04-11 01:13:04 +00002986 StartFunction(FD, C.VoidTy, Fn, FI, args);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002987
John McCall113bee02012-03-10 09:33:50 +00002988 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002989 VK_RValue, SourceLocation());
2990
John McCall113bee02012-03-10 09:33:50 +00002991 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2992 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002993
2994 CXXConstructExpr *CXXConstExpr =
2995 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2996
2997 SmallVector<Expr*, 4> ConstructorArgs;
John McCall113bee02012-03-10 09:33:50 +00002998 ConstructorArgs.push_back(&SRC);
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00002999 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3000 ++A;
3001
3002 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3003 A != AEnd; ++A)
3004 ConstructorArgs.push_back(*A);
3005
3006 CXXConstructExpr *TheCXXConstructExpr =
3007 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3008 CXXConstExpr->getConstructor(),
3009 CXXConstExpr->isElidable(),
Benjamin Kramerc215e762012-08-24 11:54:20 +00003010 ConstructorArgs,
Sebastian Redla9351792012-02-11 23:51:47 +00003011 CXXConstExpr->hadMultipleCandidates(),
3012 CXXConstExpr->isListInitialization(),
Richard Smithf8adcdc2014-07-17 05:12:35 +00003013 CXXConstExpr->isStdInitListInitialization(),
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003014 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003015 CXXConstExpr->getConstructionKind(),
3016 SourceRange());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003017
John McCall113bee02012-03-10 09:33:50 +00003018 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3019 VK_RValue, SourceLocation());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003020
John McCall113bee02012-03-10 09:33:50 +00003021 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher5d2b8d92012-03-29 17:31:31 +00003022 CharUnits Alignment
3023 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003024 EmitAggExpr(TheCXXConstructExpr,
3025 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3026 AggValueSlot::IsDestructed,
3027 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier615ed1a2012-03-29 17:37:10 +00003028 AggValueSlot::IsNotAliased));
Fariborz Jahaniana08a7472012-01-10 00:37:01 +00003029
3030 FinishFunction();
3031 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3032 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3033 return HelperFn;
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003034}
3035
Eli Friedmanec75fec2012-02-28 01:08:45 +00003036llvm::Value *
3037CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3038 // Get selectors for retain/autorelease.
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003039 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3040 Selector CopySelector =
3041 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003042 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3043 Selector AutoreleaseSelector =
3044 getContext().Selectors.getNullarySelector(AutoreleaseID);
3045
3046 // Emit calls to retain/autorelease.
3047 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3048 llvm::Value *Val = Block;
3049 RValue Result;
3050 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedmanc4e5d0c2012-03-01 22:52:28 +00003051 Ty, CopySelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003052 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003053 Val = Result.getScalarVal();
3054 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3055 Ty, AutoreleaseSelector,
Craig Topper8a13c412014-05-21 05:09:00 +00003056 Val, CallArgList(), nullptr, nullptr);
Eli Friedmanec75fec2012-02-28 01:08:45 +00003057 Val = Result.getScalarVal();
3058 return Val;
3059}
3060
Fariborz Jahanian17eaf402012-01-06 00:29:35 +00003061
Ted Kremenek43e06332008-04-09 15:51:31 +00003062CGObjCRuntime::~CGObjCRuntime() {}