blob: a0c67cdaf8db1e029efeb0bd6ca8c7486b497a06 [file] [log] [blame]
Anders Carlsson55085182007-08-21 17:43:55 +00001//===---- CGBuiltin.cpp - Emit LLVM Code for builtins ---------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Carlsson55085182007-08-21 17:43:55 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This contains code to emit Objective-C code as LLVM code.
11//
12//===----------------------------------------------------------------------===//
13
Devang Patelbcbd03a2011-01-19 01:36:36 +000014#include "CGDebugInfo.h"
Ted Kremenek2979ec72008-04-09 15:51:31 +000015#include "CGObjCRuntime.h"
Anders Carlsson55085182007-08-21 17:43:55 +000016#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
John McCallf85e1932011-06-15 23:02:42 +000018#include "TargetInfo.h"
Daniel Dunbar85c59ed2008-08-29 08:11:39 +000019#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000020#include "clang/AST/DeclObjC.h"
Chris Lattner16f00492009-04-26 01:32:48 +000021#include "clang/AST/StmtObjC.h"
Daniel Dunbare66f4e32008-09-03 00:27:26 +000022#include "clang/Basic/Diagnostic.h"
Anders Carlsson3d8400d2008-08-30 19:51:14 +000023#include "llvm/ADT/STLExtras.h"
John McCallb57f6b32013-04-16 21:29:40 +000024#include "llvm/Support/CallSite.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000025#include "llvm/IR/DataLayout.h"
26#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000027using namespace clang;
28using namespace CodeGen;
29
John McCallf85e1932011-06-15 23:02:42 +000030typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
31static TryEmitResult
32tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000033static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000034 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000035 const ObjCMethodDecl *Method,
36 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000037
38/// Given the address of a variable of pointer type, find the correct
39/// null to store into it.
40static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000041 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000042 cast<llvm::PointerType>(addr->getType())->getElementType();
43 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
44}
45
Chris Lattner8fdf3282008-06-24 17:04:18 +000046/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000047llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000048{
David Chisnall0d13f6f2010-01-23 02:40:42 +000049 llvm::Constant *C =
50 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000051 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000052 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000053}
54
Patrick Beardeb382ec2012-04-19 00:25:12 +000055/// EmitObjCBoxedExpr - This routine generates code to call
56/// the appropriate expression boxing method. This will either be
57/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000058///
Eric Christopher16098f32012-03-29 17:31:31 +000059llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000060CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000061 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000062 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000063 // Get the method.
Patrick Beardeb382ec2012-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 Kremenekebcb57a2012-03-06 20:05:56 +000068
69 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-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 Kremenekebcb57a2012-03-06 20:05:56 +000072 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000073 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000074 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beardeb382ec2012-04-19 00:25:12 +000075
76 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000077 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000078 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000079 CallArgList Args;
80 Args.add(RV, ArgQT);
Patrick Beardeb382ec2012-04-19 00:25:12 +000081
Ted Kremenekebcb57a2012-03-06 20:05:56 +000082 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beardeb382ec2012-04-19 00:25:12 +000083 BoxingMethod->getResultType(), Sel, Receiver, Args,
84 ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000085 return Builder.CreateBitCast(result.getScalarVal(),
86 ConvertType(E->getType()));
87}
88
89llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
90 const ObjCMethodDecl *MethodWithObjects) {
91 ASTContext &Context = CGM.getContext();
92 const ObjCDictionaryLiteral *DLE = 0;
93 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
94 if (!ALE)
95 DLE = cast<ObjCDictionaryLiteral>(E);
96
97 // Compute the type of the array we're initializing.
98 uint64_t NumElements =
99 ALE ? ALE->getNumElements() : DLE->getNumElements();
100 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
101 NumElements);
102 QualType ElementType = Context.getObjCIdType().withConst();
103 QualType ElementArrayType
104 = Context.getConstantArrayType(ElementType, APNumElements,
105 ArrayType::Normal, /*IndexTypeQuals=*/0);
106
107 // Allocate the temporary array(s).
108 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
109 llvm::Value *Keys = 0;
110 if (DLE)
111 Keys = CreateMemTemp(ElementArrayType, "keys");
112
John McCall527842f2013-04-04 00:20:38 +0000113 // In ARC, we may need to do extra work to keep all the keys and
114 // values alive until after the call.
115 SmallVector<llvm::Value *, 16> NeededObjects;
116 bool TrackNeededObjects =
117 (getLangOpts().ObjCAutoRefCount &&
118 CGM.getCodeGenOpts().OptimizationLevel != 0);
119
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000120 // Perform the actual initialialization of the array(s).
121 for (uint64_t i = 0; i < NumElements; i++) {
122 if (ALE) {
John McCall527842f2013-04-04 00:20:38 +0000123 // Emit the element and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000124 const Expr *Rhs = ALE->getElement(i);
125 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
126 ElementType,
127 Context.getTypeAlignInChars(Rhs->getType()),
128 Context);
John McCall527842f2013-04-04 00:20:38 +0000129
130 llvm::Value *value = EmitScalarExpr(Rhs);
131 EmitStoreThroughLValue(RValue::get(value), LV, true);
132 if (TrackNeededObjects) {
133 NeededObjects.push_back(value);
134 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000135 } else {
John McCall527842f2013-04-04 00:20:38 +0000136 // Emit the key and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000137 const Expr *Key = DLE->getKeyValueElement(i).Key;
138 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
139 ElementType,
140 Context.getTypeAlignInChars(Key->getType()),
141 Context);
John McCall527842f2013-04-04 00:20:38 +0000142 llvm::Value *keyValue = EmitScalarExpr(Key);
143 EmitStoreThroughLValue(RValue::get(keyValue), KeyLV, /*isInit=*/true);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000144
John McCall527842f2013-04-04 00:20:38 +0000145 // Emit the value and store it to the appropriate array slot.
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000146 const Expr *Value = DLE->getKeyValueElement(i).Value;
147 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
148 ElementType,
149 Context.getTypeAlignInChars(Value->getType()),
150 Context);
John McCall527842f2013-04-04 00:20:38 +0000151 llvm::Value *valueValue = EmitScalarExpr(Value);
152 EmitStoreThroughLValue(RValue::get(valueValue), ValueLV, /*isInit=*/true);
153 if (TrackNeededObjects) {
154 NeededObjects.push_back(keyValue);
155 NeededObjects.push_back(valueValue);
156 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000157 }
158 }
159
160 // Generate the argument list.
161 CallArgList Args;
162 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
163 const ParmVarDecl *argDecl = *PI++;
164 QualType ArgQT = argDecl->getType().getUnqualifiedType();
165 Args.add(RValue::get(Objects), ArgQT);
166 if (DLE) {
167 argDecl = *PI++;
168 ArgQT = argDecl->getType().getUnqualifiedType();
169 Args.add(RValue::get(Keys), ArgQT);
170 }
171 argDecl = *PI;
172 ArgQT = argDecl->getType().getUnqualifiedType();
173 llvm::Value *Count =
174 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
175 Args.add(RValue::get(Count), ArgQT);
176
177 // Generate a reference to the class pointer, which will be the receiver.
178 Selector Sel = MethodWithObjects->getSelector();
179 QualType ResultType = E->getType();
180 const ObjCObjectPointerType *InterfacePointerType
181 = ResultType->getAsObjCInterfacePointerType();
182 ObjCInterfaceDecl *Class
183 = InterfacePointerType->getObjectType()->getInterface();
184 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +0000185 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000186
187 // Generate the message send.
Eric Christopher16098f32012-03-29 17:31:31 +0000188 RValue result
189 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
190 MethodWithObjects->getResultType(),
191 Sel,
192 Receiver, Args, Class,
193 MethodWithObjects);
John McCall527842f2013-04-04 00:20:38 +0000194
195 // The above message send needs these objects, but in ARC they are
196 // passed in a buffer that is essentially __unsafe_unretained.
197 // Therefore we must prevent the optimizer from releasing them until
198 // after the call.
199 if (TrackNeededObjects) {
200 EmitARCIntrinsicUse(NeededObjects);
201 }
202
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000203 return Builder.CreateBitCast(result.getScalarVal(),
204 ConvertType(E->getType()));
205}
206
207llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
208 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
209}
210
211llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
212 const ObjCDictionaryLiteral *E) {
213 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
214}
215
Chris Lattner8fdf3282008-06-24 17:04:18 +0000216/// Emit a selector.
217llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
218 // Untyped selector.
219 // Note that this implementation allows for non-constant strings to be passed
220 // as arguments to @selector(). Currently, the only thing preventing this
221 // behaviour is the type checking in the front end.
John McCallbd7370a2013-02-28 19:01:20 +0000222 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000223}
224
Daniel Dunbared7c6182008-08-20 00:28:19 +0000225llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
226 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000227 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000228}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000229
Douglas Gregor926df6c2011-06-11 01:09:30 +0000230/// \brief Adjust the type of the result of an Objective-C message send
231/// expression when the method has a related result type.
232static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000233 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000234 const ObjCMethodDecl *Method,
235 RValue Result) {
236 if (!Method)
237 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000238
Douglas Gregor926df6c2011-06-11 01:09:30 +0000239 if (!Method->hasRelatedResultType() ||
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000240 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000241 !Result.isScalar())
242 return Result;
243
244 // We have applied a related result type. Cast the rvalue appropriately.
245 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000246 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000247}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000248
John McCalldc7c5ad2011-07-22 08:53:00 +0000249/// Decide whether to extend the lifetime of the receiver of a
250/// returns-inner-pointer message.
251static bool
252shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
253 switch (message->getReceiverKind()) {
254
255 // For a normal instance message, we should extend unless the
256 // receiver is loaded from a variable with precise lifetime.
257 case ObjCMessageExpr::Instance: {
258 const Expr *receiver = message->getInstanceReceiver();
259 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
260 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
261 receiver = ice->getSubExpr()->IgnoreParens();
262
263 // Only __strong variables.
264 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
265 return true;
266
267 // All ivars and fields have precise lifetime.
268 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
269 return false;
270
271 // Otherwise, check for variables.
272 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
273 if (!declRef) return true;
274 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
275 if (!var) return true;
276
277 // All variables have precise lifetime except local variables with
278 // automatic storage duration that aren't specially marked.
279 return (var->hasLocalStorage() &&
280 !var->hasAttr<ObjCPreciseLifetimeAttr>());
281 }
282
283 case ObjCMessageExpr::Class:
284 case ObjCMessageExpr::SuperClass:
285 // It's never necessary for class objects.
286 return false;
287
288 case ObjCMessageExpr::SuperInstance:
289 // We generally assume that 'self' lives throughout a method call.
290 return false;
291 }
292
293 llvm_unreachable("invalid receiver kind");
294}
295
John McCallef072fd2010-05-22 01:48:05 +0000296RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
297 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000298 // Only the lookup mechanism and first two arguments of the method
299 // implementation vary between runtimes. We can get the receiver and
300 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000301
John McCallf85e1932011-06-15 23:02:42 +0000302 bool isDelegateInit = E->isDelegateInitCall();
303
John McCalldc7c5ad2011-07-22 08:53:00 +0000304 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000305
John McCallf85e1932011-06-15 23:02:42 +0000306 // We don't retain the receiver in delegate init calls, and this is
307 // safe because the receiver value is always loaded from 'self',
308 // which we zero out. We don't want to Block_copy block receivers,
309 // though.
310 bool retainSelf =
311 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000312 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000313 method &&
314 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000315
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000316 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000317 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000318 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000319 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000320 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000321 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000322 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000323 switch (E->getReceiverKind()) {
324 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000325 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000326 if (retainSelf) {
327 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
328 E->getInstanceReceiver());
329 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000330 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000331 } else
332 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000333 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000334
Douglas Gregor04badcf2010-04-21 00:45:42 +0000335 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000336 ReceiverType = E->getClassReceiver();
337 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000338 assert(ObjTy && "Invalid Objective-C class message send");
339 OID = ObjTy->getInterface();
340 assert(OID && "Invalid Objective-C class message send");
John McCallbd7370a2013-02-28 19:01:20 +0000341 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000342 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000343 break;
344 }
345
346 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000347 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000348 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000349 isSuperMessage = true;
350 break;
351
352 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000353 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000354 Receiver = LoadObjCSelf();
355 isSuperMessage = true;
356 isClassMessage = true;
357 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000358 }
359
John McCalldc7c5ad2011-07-22 08:53:00 +0000360 if (retainSelf)
361 Receiver = EmitARCRetainNonBlock(Receiver);
362
363 // In ARC, we sometimes want to "extend the lifetime"
364 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
365 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000366 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000367 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
368 shouldExtendReceiverForInnerPointerMessage(E))
369 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
370
John McCallf85e1932011-06-15 23:02:42 +0000371 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000372 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000373
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000374 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000375 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000376
John McCallf85e1932011-06-15 23:02:42 +0000377 // For delegate init calls in ARC, do an unsafe store of null into
378 // self. This represents the call taking direct ownership of that
379 // value. We have to do this after emitting the other call
380 // arguments because they might also reference self, but we don't
381 // have to worry about any of them modifying self because that would
382 // be an undefined read and write of an object in unordered
383 // expressions.
384 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000385 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000386 "delegate init calls should only be marked in ARC");
387
388 // Do an unsafe store of null into self.
389 llvm::Value *selfAddr =
390 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
391 assert(selfAddr && "no self entry for a delegate init call?");
392
393 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
394 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000395
Douglas Gregor926df6c2011-06-11 01:09:30 +0000396 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000397 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000398 // super is only valid in an Objective-C method
399 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000400 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000401 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
402 E->getSelector(),
403 OMD->getClassInterface(),
404 isCategoryImpl,
405 Receiver,
406 isClassMessage,
407 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000408 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000409 } else {
410 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
411 E->getSelector(),
412 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000413 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000414 }
John McCallf85e1932011-06-15 23:02:42 +0000415
416 // For delegate init calls in ARC, implicitly store the result of
417 // the call back into self. This takes ownership of the value.
418 if (isDelegateInit) {
419 llvm::Value *selfAddr =
420 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
421 llvm::Value *newSelf = result.getScalarVal();
422
423 // The delegate return type isn't necessarily a matching type; in
424 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000425 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000426 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
427 newSelf = Builder.CreateBitCast(newSelf, selfTy);
428
429 Builder.CreateStore(newSelf, selfAddr);
430 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000431
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000432 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000433}
434
John McCallf85e1932011-06-15 23:02:42 +0000435namespace {
436struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000437 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000438 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000439
440 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000441 const ObjCInterfaceDecl *iface = impl->getClassInterface();
442 if (!iface->getSuperClass()) return;
443
John McCall799d34e2011-07-13 18:26:47 +0000444 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
445
John McCallf85e1932011-06-15 23:02:42 +0000446 // Call [super dealloc] if we have a superclass.
447 llvm::Value *self = CGF.LoadObjCSelf();
448
449 CallArgList args;
450 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
451 CGF.getContext().VoidTy,
452 method->getSelector(),
453 iface,
John McCall799d34e2011-07-13 18:26:47 +0000454 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000455 self,
456 /*is class msg*/ false,
457 args,
458 method);
459 }
460};
461}
462
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000463/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
464/// the LLVM function and sets the other context used by
465/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000466void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000467 const ObjCContainerDecl *CD,
468 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000469 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000470 // Check if we should generate debug info for this method.
David Blaikiec3030bc2013-08-26 20:33:21 +0000471 if (OMD->hasAttr<NoDebugAttr>())
472 DebugInfo = NULL; // disable debug info indefinitely for this function
Devang Patel4800ea62010-04-05 21:09:15 +0000473
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000474 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000475
John McCallde5d3c72012-02-17 03:33:10 +0000476 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000477 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000478
John McCalld26bc762011-03-09 04:27:21 +0000479 args.push_back(OMD->getSelfDecl());
480 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000481
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000482 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher16098f32012-03-29 17:31:31 +0000483 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000484 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000485
Peter Collingbourne14110472011-01-13 18:57:25 +0000486 CurGD = OMD;
487
Devang Patel8d3f8972011-05-19 23:37:41 +0000488 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000489
490 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000491 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000492 OMD->isInstanceMethod() &&
493 OMD->getSelector().isUnarySelector()) {
494 const IdentifierInfo *ident =
495 OMD->getSelector().getIdentifierInfoForSlot(0);
496 if (ident->isStr("dealloc"))
497 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
498 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000499}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000500
John McCallf85e1932011-06-15 23:02:42 +0000501static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
502 LValue lvalue, QualType type);
503
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000504/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000505/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000506void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000507 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000508 EmitStmt(OMD->getBody());
509 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000510}
511
John McCall41bdde92011-09-12 23:06:44 +0000512/// emitStructGetterCall - Call the runtime function to load a property
513/// into the return value slot.
514static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
515 bool isAtomic, bool hasStrong) {
516 ASTContext &Context = CGF.getContext();
517
518 llvm::Value *src =
519 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
520 ivar, 0).getAddress();
521
522 // objc_copyStruct (ReturnValue, &structIvar,
523 // sizeof (Type of Ivar), isAtomic, false);
524 CallArgList args;
525
526 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
527 args.add(RValue::get(dest), Context.VoidPtrTy);
528
529 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
530 args.add(RValue::get(src), Context.VoidPtrTy);
531
532 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
533 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
534 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
535 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
536
537 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000538 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
539 FunctionType::ExtInfo(),
540 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000541 fn, ReturnValueSlot(), args);
542}
543
John McCall1e1f4872011-09-13 03:34:09 +0000544/// Determine whether the given architecture supports unaligned atomic
545/// accesses. They don't have to be fast, just faster than a function
546/// call and a mutex.
547static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000548 // FIXME: Allow unaligned atomic load/store on x86. (It is not
549 // currently supported by the backend.)
550 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000551}
552
553/// Return the maximum size that permits atomic accesses for the given
554/// architecture.
555static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
556 llvm::Triple::ArchType arch) {
557 // ARM has 8-byte atomic accesses, but it's not clear whether we
558 // want to rely on them here.
559
560 // In the default case, just assume that any size up to a pointer is
561 // fine given adequate alignment.
562 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
563}
564
565namespace {
566 class PropertyImplStrategy {
567 public:
568 enum StrategyKind {
569 /// The 'native' strategy is to use the architecture's provided
570 /// reads and writes.
571 Native,
572
573 /// Use objc_setProperty and objc_getProperty.
574 GetSetProperty,
575
576 /// Use objc_setProperty for the setter, but use expression
577 /// evaluation for the getter.
578 SetPropertyAndExpressionGet,
579
580 /// Use objc_copyStruct.
581 CopyStruct,
582
583 /// The 'expression' strategy is to emit normal assignment or
584 /// lvalue-to-rvalue expressions.
585 Expression
586 };
587
588 StrategyKind getKind() const { return StrategyKind(Kind); }
589
590 bool hasStrongMember() const { return HasStrong; }
591 bool isAtomic() const { return IsAtomic; }
592 bool isCopy() const { return IsCopy; }
593
594 CharUnits getIvarSize() const { return IvarSize; }
595 CharUnits getIvarAlignment() const { return IvarAlignment; }
596
597 PropertyImplStrategy(CodeGenModule &CGM,
598 const ObjCPropertyImplDecl *propImpl);
599
600 private:
601 unsigned Kind : 8;
602 unsigned IsAtomic : 1;
603 unsigned IsCopy : 1;
604 unsigned HasStrong : 1;
605
606 CharUnits IvarSize;
607 CharUnits IvarAlignment;
608 };
609}
610
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000611/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000612PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
613 const ObjCPropertyImplDecl *propImpl) {
614 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000615 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000616
John McCall265941b2011-09-13 18:31:23 +0000617 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
618 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000619 HasStrong = false; // doesn't matter here.
620
621 // Evaluate the ivar's size and alignment.
622 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
623 QualType ivarType = ivar->getType();
624 llvm::tie(IvarSize, IvarAlignment)
625 = CGM.getContext().getTypeInfoInChars(ivarType);
626
627 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000628 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000629 if (IsCopy) {
630 Kind = GetSetProperty;
631 return;
632 }
633
John McCall265941b2011-09-13 18:31:23 +0000634 // Handle retain.
635 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000636 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000637 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000638 // fallthrough
639
640 // In ARC, if the property is non-atomic, use expression emission,
641 // which translates to objc_storeStrong. This isn't required, but
642 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000643 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000644 // Using standard expression emission for the setter is only
645 // acceptable if the ivar is __strong, which won't be true if
646 // the property is annotated with __attribute__((NSObject)).
647 // TODO: falling all the way back to objc_setProperty here is
648 // just laziness, though; we could still use objc_storeStrong
649 // if we hacked it right.
650 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
651 Kind = Expression;
652 else
653 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000654 return;
655
656 // Otherwise, we need to at least use setProperty. However, if
657 // the property isn't atomic, we can use normal expression
658 // emission for the getter.
659 } else if (!IsAtomic) {
660 Kind = SetPropertyAndExpressionGet;
661 return;
662
663 // Otherwise, we have to use both setProperty and getProperty.
664 } else {
665 Kind = GetSetProperty;
666 return;
667 }
668 }
669
670 // If we're not atomic, just use expression accesses.
671 if (!IsAtomic) {
672 Kind = Expression;
673 return;
674 }
675
John McCall5889c602011-09-13 05:36:29 +0000676 // Properties on bitfield ivars need to be emitted using expression
677 // accesses even if they're nominally atomic.
678 if (ivar->isBitField()) {
679 Kind = Expression;
680 return;
681 }
682
John McCall1e1f4872011-09-13 03:34:09 +0000683 // GC-qualified or ARC-qualified ivars need to be emitted as
684 // expressions. This actually works out to being atomic anyway,
685 // except for ARC __strong, but that should trigger the above code.
686 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000687 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000688 CGM.getContext().getObjCGCAttrKind(ivarType))) {
689 Kind = Expression;
690 return;
691 }
692
693 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000694 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000695 if (const RecordType *recordType = ivarType->getAs<RecordType>())
696 HasStrong = recordType->getDecl()->hasObjectMember();
697
698 // We can never access structs with object members with a native
699 // access, because we need to use write barriers. This is what
700 // objc_copyStruct is for.
701 if (HasStrong) {
702 Kind = CopyStruct;
703 return;
704 }
705
706 // Otherwise, this is target-dependent and based on the size and
707 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000708
709 // If the size of the ivar is not a power of two, give up. We don't
710 // want to get into the business of doing compare-and-swaps.
711 if (!IvarSize.isPowerOfTwo()) {
712 Kind = CopyStruct;
713 return;
714 }
715
John McCall1e1f4872011-09-13 03:34:09 +0000716 llvm::Triple::ArchType arch =
John McCall64aa4b32013-04-16 22:48:15 +0000717 CGM.getTarget().getTriple().getArch();
John McCall1e1f4872011-09-13 03:34:09 +0000718
719 // Most architectures require memory to fit within a single cache
720 // line, so the alignment has to be at least the size of the access.
721 // Otherwise we have to grab a lock.
722 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
723 Kind = CopyStruct;
724 return;
725 }
726
727 // If the ivar's size exceeds the architecture's maximum atomic
728 // access size, we have to use CopyStruct.
729 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
730 Kind = CopyStruct;
731 return;
732 }
733
734 // Otherwise, we can use native loads and stores.
735 Kind = Native;
736}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000737
James Dennett2ee5ba32012-06-15 22:10:14 +0000738/// \brief Generate an Objective-C property getter function.
739///
740/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000741/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000742void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
743 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000744 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000745 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000746 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
747 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
748 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000749 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000750
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000751 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000752
753 FinishFunction();
754}
755
John McCall6c11f0b2011-09-13 06:00:03 +0000756static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
757 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000758 if (!getter) return true;
759
760 // Sema only makes only of these when the ivar has a C++ class type,
761 // so the form is pretty constrained.
762
John McCall6c11f0b2011-09-13 06:00:03 +0000763 // If the property has a reference type, we might just be binding a
764 // reference, in which case the result will be a gl-value. We should
765 // treat this as a non-trivial operation.
766 if (getter->isGLValue())
767 return false;
768
John McCall1e1f4872011-09-13 03:34:09 +0000769 // If we selected a trivial copy-constructor, we're okay.
770 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
771 return (construct->getConstructor()->isTrivial());
772
773 // The constructor might require cleanups (in which case it's never
774 // trivial).
775 assert(isa<ExprWithCleanups>(getter));
776 return false;
777}
778
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000779/// emitCPPObjectAtomicGetterCall - Call the runtime function to
780/// copy the ivar into the resturn slot.
781static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
782 llvm::Value *returnAddr,
783 ObjCIvarDecl *ivar,
784 llvm::Constant *AtomicHelperFn) {
785 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
786 // AtomicHelperFn);
787 CallArgList args;
788
789 // The 1st argument is the return Slot.
790 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
791
792 // The 2nd argument is the address of the ivar.
793 llvm::Value *ivarAddr =
794 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
795 CGF.LoadObjCSelf(), ivar, 0).getAddress();
796 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
797 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
798
799 // Third argument is the helper function.
800 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
801
802 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000803 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000804 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
805 args,
806 FunctionType::ExtInfo(),
807 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000808 copyCppAtomicObjectFn, ReturnValueSlot(), args);
809}
810
John McCall1e1f4872011-09-13 03:34:09 +0000811void
812CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000813 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000814 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000815 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000816 // If there's a non-trivial 'get' expression, we just have to emit that.
817 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000818 if (!AtomicHelperFn) {
819 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
820 /*nrvo*/ 0);
821 EmitReturnStmt(ret);
822 }
823 else {
824 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
825 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
826 ivar, AtomicHelperFn);
827 }
John McCall1e1f4872011-09-13 03:34:09 +0000828 return;
829 }
830
831 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
832 QualType propType = prop->getType();
833 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
834
835 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
836
837 // Pick an implementation strategy.
838 PropertyImplStrategy strategy(CGM, propImpl);
839 switch (strategy.getKind()) {
840 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000841 // We don't need to do anything for a zero-size struct.
842 if (strategy.getIvarSize().isZero())
843 return;
844
John McCall1e1f4872011-09-13 03:34:09 +0000845 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
846
847 // Currently, all atomic accesses have to be through integer
848 // types, so there's no point in trying to pick a prettier type.
849 llvm::Type *bitcastType =
850 llvm::Type::getIntNTy(getLLVMContext(),
851 getContext().toBits(strategy.getIvarSize()));
852 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
853
854 // Perform an atomic load. This does not impose ordering constraints.
855 llvm::Value *ivarAddr = LV.getAddress();
856 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
857 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
858 load->setAlignment(strategy.getIvarAlignment().getQuantity());
859 load->setAtomic(llvm::Unordered);
860
861 // Store that value into the return address. Doing this with a
862 // bitcast is likely to produce some pretty ugly IR, but it's not
863 // the *most* terrible thing in the world.
864 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
865
866 // Make sure we don't do an autorelease.
867 AutoreleaseResult = false;
868 return;
869 }
870
871 case PropertyImplStrategy::GetSetProperty: {
872 llvm::Value *getPropertyFn =
873 CGM.getObjCRuntime().GetPropertyGetFunction();
874 if (!getPropertyFn) {
875 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000876 return;
877 }
878
879 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
880 // FIXME: Can't this be simpler? This might even be worse than the
881 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000882 llvm::Value *cmd =
883 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
884 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
885 llvm::Value *ivarOffset =
886 EmitIvarOffset(classImpl->getClassInterface(), ivar);
887
888 CallArgList args;
889 args.add(RValue::get(self), getContext().getObjCIdType());
890 args.add(RValue::get(cmd), getContext().getObjCSelType());
891 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000892 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
893 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000894
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000895 // FIXME: We shouldn't need to get the function info here, the
896 // runtime already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +0000897 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
898 FunctionType::ExtInfo(),
899 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000900 getPropertyFn, ReturnValueSlot(), args);
901
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000902 // We need to fix the type here. Ivars with copy & retain are
903 // always objects so we don't need to worry about complex or
904 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000905 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000906 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000907
908 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000909
910 // objc_getProperty does an autorelease, so we should suppress ours.
911 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000912
John McCall1e1f4872011-09-13 03:34:09 +0000913 return;
914 }
915
916 case PropertyImplStrategy::CopyStruct:
917 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
918 strategy.hasStrongMember());
919 return;
920
921 case PropertyImplStrategy::Expression:
922 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
923 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
924
925 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +0000926 switch (getEvaluationKind(ivarType)) {
927 case TEK_Complex: {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000928 ComplexPairTy pair = EmitLoadOfComplex(LV, SourceLocation());
John McCall9d232c82013-03-07 21:37:08 +0000929 EmitStoreOfComplex(pair,
930 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
931 /*init*/ true);
932 return;
933 }
934 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +0000935 // The return value slot is guaranteed to not be aliased, but
936 // that's not necessarily the same as "on the stack", so
937 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000938 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +0000939 return;
940 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +0000941 llvm::Value *value;
942 if (propType->isReferenceType()) {
943 value = LV.getAddress();
944 } else {
945 // We want to load and autoreleaseReturnValue ARC __weak ivars.
946 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000947 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000948
949 // Otherwise we want to do a simple load, suppressing the
950 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000951 } else {
Nick Lewycky4ee7dc22013-10-02 02:29:49 +0000952 value = EmitLoadOfLValue(LV, SourceLocation()).getScalarVal();
John McCallba3dd902011-07-22 05:23:13 +0000953 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000954 }
John McCallf85e1932011-06-15 23:02:42 +0000955
John McCallba3dd902011-07-22 05:23:13 +0000956 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000957 value = Builder.CreateBitCast(value,
958 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000959 }
960
961 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +0000962 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000963 }
John McCall9d232c82013-03-07 21:37:08 +0000964 }
965 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000966 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000967
John McCall1e1f4872011-09-13 03:34:09 +0000968 }
969 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000970}
971
John McCall41bdde92011-09-12 23:06:44 +0000972/// emitStructSetterCall - Call the runtime function to store the value
973/// from the first formal parameter into the given ivar.
974static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
975 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000976 // objc_copyStruct (&structIvar, &Arg,
977 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000978 CallArgList args;
979
980 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000981 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
982 CGF.LoadObjCSelf(), ivar, 0)
983 .getAddress();
984 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
985 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000986
987 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000988 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000989 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000990 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000991 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
992 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
993 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000994
995 // The third argument is the sizeof the type.
996 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000997 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
998 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000999
John McCall41bdde92011-09-12 23:06:44 +00001000 // The fourth argument is the 'isAtomic' flag.
1001 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +00001002
John McCall41bdde92011-09-12 23:06:44 +00001003 // The fifth argument is the 'hasStrong' flag.
1004 // FIXME: should this really always be false?
1005 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
1006
1007 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001008 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1009 args,
1010 FunctionType::ExtInfo(),
1011 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +00001012 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +00001013}
1014
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001015/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
1016/// the value from the first formal parameter into the given ivar, using
1017/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
1018static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
1019 ObjCMethodDecl *OMD,
1020 ObjCIvarDecl *ivar,
1021 llvm::Constant *AtomicHelperFn) {
1022 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
1023 // AtomicHelperFn);
1024 CallArgList args;
1025
1026 // The first argument is the address of the ivar.
1027 llvm::Value *ivarAddr =
1028 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1029 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1030 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1031 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1032
1033 // The second argument is the address of the parameter variable.
1034 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001035 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001036 VK_LValue, SourceLocation());
1037 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1038 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1039 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1040
1041 // Third argument is the helper function.
1042 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1043
1044 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001045 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001046 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1047 args,
1048 FunctionType::ExtInfo(),
1049 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001050 copyCppAtomicObjectFn, ReturnValueSlot(), args);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001051}
1052
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001053
John McCall1e1f4872011-09-13 03:34:09 +00001054static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1055 Expr *setter = PID->getSetterCXXAssignment();
1056 if (!setter) return true;
1057
1058 // Sema only makes only of these when the ivar has a C++ class type,
1059 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001060
1061 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001062 // This also implies that there's nothing non-trivial going on with
1063 // the arguments, because operator= can only be trivial if it's a
1064 // synthesized assignment operator and therefore both parameters are
1065 // references.
1066 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001067 if (const FunctionDecl *callee
1068 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1069 if (callee->isTrivial())
1070 return true;
1071 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001072 }
John McCall71c758d2011-09-10 09:17:20 +00001073
John McCall1e1f4872011-09-13 03:34:09 +00001074 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001075 return false;
1076}
1077
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001078static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001079 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001080 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001081 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001082}
1083
John McCall71c758d2011-09-10 09:17:20 +00001084void
1085CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001086 const ObjCPropertyImplDecl *propImpl,
1087 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001088 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001089 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001090 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001091
1092 // Just use the setter expression if Sema gave us one and it's
1093 // non-trivial.
1094 if (!hasTrivialSetExpr(propImpl)) {
1095 if (!AtomicHelperFn)
1096 // If non-atomic, assignment is called directly.
1097 EmitStmt(propImpl->getSetterCXXAssignment());
1098 else
1099 // If atomic, assignment is called via a locking api.
1100 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1101 AtomicHelperFn);
1102 return;
1103 }
John McCall71c758d2011-09-10 09:17:20 +00001104
John McCall1e1f4872011-09-13 03:34:09 +00001105 PropertyImplStrategy strategy(CGM, propImpl);
1106 switch (strategy.getKind()) {
1107 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001108 // We don't need to do anything for a zero-size struct.
1109 if (strategy.getIvarSize().isZero())
1110 return;
1111
John McCall1e1f4872011-09-13 03:34:09 +00001112 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001113
John McCall1e1f4872011-09-13 03:34:09 +00001114 LValue ivarLValue =
1115 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1116 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001117
John McCall1e1f4872011-09-13 03:34:09 +00001118 // Currently, all atomic accesses have to be through integer
1119 // types, so there's no point in trying to pick a prettier type.
1120 llvm::Type *bitcastType =
1121 llvm::Type::getIntNTy(getLLVMContext(),
1122 getContext().toBits(strategy.getIvarSize()));
1123 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1124
1125 // Cast both arguments to the chosen operation type.
1126 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1127 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1128
1129 // This bitcast load is likely to cause some nasty IR.
1130 llvm::Value *load = Builder.CreateLoad(argAddr);
1131
1132 // Perform an atomic store. There are no memory ordering requirements.
1133 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1134 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1135 store->setAtomic(llvm::Unordered);
1136 return;
1137 }
1138
1139 case PropertyImplStrategy::GetSetProperty:
1140 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001141
1142 llvm::Value *setOptimizedPropertyFn = 0;
1143 llvm::Value *setPropertyFn = 0;
1144 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001145 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001146 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001147 CGM.getObjCRuntime()
1148 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1149 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001150 if (!setOptimizedPropertyFn) {
1151 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1152 return;
1153 }
John McCall71c758d2011-09-10 09:17:20 +00001154 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001155 else {
1156 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1157 if (!setPropertyFn) {
1158 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1159 return;
1160 }
1161 }
1162
John McCall71c758d2011-09-10 09:17:20 +00001163 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1164 // <is-atomic>, <is-copy>).
1165 llvm::Value *cmd =
1166 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1167 llvm::Value *self =
1168 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1169 llvm::Value *ivarOffset =
1170 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1171 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1172 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1173
1174 CallArgList args;
1175 args.add(RValue::get(self), getContext().getObjCIdType());
1176 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001177 if (setOptimizedPropertyFn) {
1178 args.add(RValue::get(arg), getContext().getObjCIdType());
1179 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001180 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1181 FunctionType::ExtInfo(),
1182 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001183 setOptimizedPropertyFn, ReturnValueSlot(), args);
1184 } else {
1185 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1186 args.add(RValue::get(arg), getContext().getObjCIdType());
1187 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1188 getContext().BoolTy);
1189 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1190 getContext().BoolTy);
1191 // FIXME: We shouldn't need to get the function info here, the runtime
1192 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001193 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1194 FunctionType::ExtInfo(),
1195 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001196 setPropertyFn, ReturnValueSlot(), args);
1197 }
1198
John McCall71c758d2011-09-10 09:17:20 +00001199 return;
1200 }
1201
John McCall1e1f4872011-09-13 03:34:09 +00001202 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001203 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001204 return;
John McCall1e1f4872011-09-13 03:34:09 +00001205
1206 case PropertyImplStrategy::Expression:
1207 break;
John McCall71c758d2011-09-10 09:17:20 +00001208 }
1209
1210 // Otherwise, fake up some ASTs and emit a normal assignment.
1211 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001212 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1213 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001214 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1215 selfDecl->getType(), CK_LValueToRValue, &self,
1216 VK_RValue);
1217 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001218 SourceLocation(), SourceLocation(),
1219 &selfLoad, true, true);
John McCall71c758d2011-09-10 09:17:20 +00001220
1221 ParmVarDecl *argDecl = *setterMethod->param_begin();
1222 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001223 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001224 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1225 argType.getUnqualifiedType(), CK_LValueToRValue,
1226 &arg, VK_RValue);
1227
1228 // The property type can differ from the ivar type in some situations with
1229 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1230 // The following absurdity is just to ensure well-formed IR.
1231 CastKind argCK = CK_NoOp;
1232 if (ivarRef.getType()->isObjCObjectPointerType()) {
1233 if (argLoad.getType()->isObjCObjectPointerType())
1234 argCK = CK_BitCast;
1235 else if (argLoad.getType()->isBlockPointerType())
1236 argCK = CK_BlockPointerToObjCPointerCast;
1237 else
1238 argCK = CK_CPointerToObjCPointerCast;
1239 } else if (ivarRef.getType()->isBlockPointerType()) {
1240 if (argLoad.getType()->isBlockPointerType())
1241 argCK = CK_BitCast;
1242 else
1243 argCK = CK_AnyPointerToBlockPointerCast;
1244 } else if (ivarRef.getType()->isPointerType()) {
1245 argCK = CK_BitCast;
1246 }
1247 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1248 ivarRef.getType(), argCK, &argLoad,
1249 VK_RValue);
1250 Expr *finalArg = &argLoad;
1251 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1252 argLoad.getType()))
1253 finalArg = &argCast;
1254
1255
1256 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1257 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001258 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001259 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001260}
1261
James Dennett2ee5ba32012-06-15 22:10:14 +00001262/// \brief Generate an Objective-C property setter function.
1263///
1264/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001265/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001266void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1267 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001268 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001269 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001270 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1271 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1272 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001273 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001274
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001275 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001276
1277 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001278}
1279
John McCalle81ac692011-03-22 07:05:39 +00001280namespace {
John McCall9928c482011-07-12 16:41:08 +00001281 struct DestroyIvar : EHScopeStack::Cleanup {
1282 private:
1283 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001284 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001285 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001286 bool useEHCleanupForArray;
1287 public:
1288 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1289 CodeGenFunction::Destroyer *destroyer,
1290 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001291 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001292 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001293
John McCallad346f42011-07-12 20:27:29 +00001294 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001295 LValue lvalue
1296 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1297 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001298 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001299 }
1300 };
1301}
1302
John McCall9928c482011-07-12 16:41:08 +00001303/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1304static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1305 llvm::Value *addr,
1306 QualType type) {
1307 llvm::Value *null = getNullForVariable(addr);
1308 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1309}
John McCallf85e1932011-06-15 23:02:42 +00001310
John McCalle81ac692011-03-22 07:05:39 +00001311static void emitCXXDestructMethod(CodeGenFunction &CGF,
1312 ObjCImplementationDecl *impl) {
1313 CodeGenFunction::RunCleanupsScope scope(CGF);
1314
1315 llvm::Value *self = CGF.LoadObjCSelf();
1316
Jordy Rosedb8264e2011-07-22 02:08:32 +00001317 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1318 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001319 ivar; ivar = ivar->getNextIvar()) {
1320 QualType type = ivar->getType();
1321
John McCalle81ac692011-03-22 07:05:39 +00001322 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001323 QualType::DestructionKind dtorKind = type.isDestructedType();
1324 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001325
John McCall9928c482011-07-12 16:41:08 +00001326 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001327
John McCall9928c482011-07-12 16:41:08 +00001328 // Use a call to objc_storeStrong to destroy strong ivars, for the
1329 // general benefit of the tools.
1330 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001331 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001332
John McCall9928c482011-07-12 16:41:08 +00001333 // Otherwise use the default for the destruction kind.
1334 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001335 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001336 }
John McCall9928c482011-07-12 16:41:08 +00001337
1338 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1339
1340 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1341 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001342 }
1343
1344 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1345}
1346
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001347void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1348 ObjCMethodDecl *MD,
1349 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001350 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001351 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001352
1353 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001354 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001355 // Suppress the final autorelease in ARC.
1356 AutoreleaseResult = false;
1357
Chris Lattner5f9e2722011-07-23 10:55:15 +00001358 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001359 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1360 E = IMP->init_end(); B != E; ++B) {
1361 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001362 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001363 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001364 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1365 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001366 EmitAggExpr(IvarInit->getInit(),
1367 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001368 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001369 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001370 }
1371 // constructor returns 'self'.
1372 CodeGenTypes &Types = CGM.getTypes();
1373 QualType IdTy(CGM.getContext().getObjCIdType());
1374 llvm::Value *SelfAsId =
1375 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1376 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001377
1378 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001379 } else {
John McCalle81ac692011-03-22 07:05:39 +00001380 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001381 }
1382 FinishFunction();
1383}
1384
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001385bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1386 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1387 it++; it++;
1388 const ABIArgInfo &AI = it->info;
1389 // FIXME. Is this sufficient check?
1390 return (AI.getKind() == ABIArgInfo::Indirect);
1391}
1392
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001393bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001394 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001395 return false;
1396 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1397 return FDTTy->getDecl()->hasObjectMember();
1398 return false;
1399}
1400
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001401llvm::Value *CodeGenFunction::LoadObjCSelf() {
John McCallf5ebf9b2013-05-03 07:33:41 +00001402 VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
1403 DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
1404 Self->getType(), VK_LValue, SourceLocation());
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00001405 return EmitLoadOfScalar(EmitDeclRefLValue(&DRE), SourceLocation());
Chris Lattner41110242008-06-17 18:05:57 +00001406}
1407
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001408QualType CodeGenFunction::TypeOfSelfObject() {
1409 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1410 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001411 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1412 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001413 return PTy->getPointeeType();
1414}
1415
Chris Lattner74391b42009-03-22 21:03:39 +00001416void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001417 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001418 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001419
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001420 if (!EnumerationMutationFn) {
1421 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1422 return;
1423 }
1424
Devang Patelbcbd03a2011-01-19 01:36:36 +00001425 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001426 if (DI)
1427 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001428
Devang Patel9d99f2d2011-06-13 23:15:32 +00001429 // The local variable comes into scope immediately.
1430 AutoVarEmission variable = AutoVarEmission::invalid();
1431 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1432 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1433
John McCalld88687f2011-01-07 01:49:06 +00001434 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001435
Anders Carlssonf484c312008-08-31 02:33:12 +00001436 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001437 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001438 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001439 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001440
Anders Carlssonf484c312008-08-31 02:33:12 +00001441 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001442 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001443
John McCalld88687f2011-01-07 01:49:06 +00001444 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001445 IdentifierInfo *II[] = {
1446 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1447 &CGM.getContext().Idents.get("objects"),
1448 &CGM.getContext().Idents.get("count")
1449 };
1450 Selector FastEnumSel =
1451 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001452
1453 QualType ItemsTy =
1454 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001455 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001456 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001457 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001458
John McCall990567c2011-07-27 01:07:15 +00001459 // Emit the collection pointer. In ARC, we do a retain.
1460 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001461 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001462 Collection = EmitARCRetainScalarExpr(S.getCollection());
1463
1464 // Enter a cleanup to do the release.
1465 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1466 } else {
1467 Collection = EmitScalarExpr(S.getCollection());
1468 }
Mike Stump1eb44332009-09-09 15:08:12 +00001469
John McCall4b302d32011-08-05 00:14:38 +00001470 // The 'continue' label needs to appear within the cleanup for the
1471 // collection object.
1472 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1473
John McCalld88687f2011-01-07 01:49:06 +00001474 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001475 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001476
1477 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001478 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001479
John McCalld88687f2011-01-07 01:49:06 +00001480 // The second argument is a temporary array with space for NumItems
1481 // pointers. We'll actually be loading elements from the array
1482 // pointer written into the control state; this buffer is so that
1483 // collections that *aren't* backed by arrays can still queue up
1484 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001485 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001486
John McCalld88687f2011-01-07 01:49:06 +00001487 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001488 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001489 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001490 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
John McCalld88687f2011-01-07 01:49:06 +00001492 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001493 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001494 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001495 getContext().UnsignedLongTy,
1496 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001497 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001498
John McCalld88687f2011-01-07 01:49:06 +00001499 // The initial number of objects that were returned in the buffer.
1500 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001501
John McCalld88687f2011-01-07 01:49:06 +00001502 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1503 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001504
John McCalld88687f2011-01-07 01:49:06 +00001505 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001506
John McCalld88687f2011-01-07 01:49:06 +00001507 // If the limit pointer was zero to begin with, the collection is
1508 // empty; skip all this.
1509 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1510 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001511
John McCalld88687f2011-01-07 01:49:06 +00001512 // Otherwise, initialize the loop.
1513 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
John McCalld88687f2011-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:.
Mike Stump1eb44332009-09-09 15:08:12 +00001518 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001519 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001520 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001521 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001522
John McCalld88687f2011-01-07 01:49:06 +00001523 llvm::Value *initialMutations =
1524 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001525
John McCalld88687f2011-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 Stump1eb44332009-09-09 15:08:12 +00001530
John McCalld88687f2011-01-07 01:49:06 +00001531 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001532 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001533 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001534
John McCalld88687f2011-01-07 01:49:06 +00001535 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001536 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001537 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001538
John McCalld88687f2011-01-07 01:49:06 +00001539 // Check whether the mutations value has changed from where it was
1540 // at start. StateMutationsPtr should actually be invariant between
1541 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001542 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001543 llvm::Value *currentMutations
1544 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001545
John McCalld88687f2011-01-07 01:49:06 +00001546 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001547 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001548
John McCalld88687f2011-01-07 01:49:06 +00001549 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1550 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001551
John McCalld88687f2011-01-07 01:49:06 +00001552 // If so, call the enumeration-mutation function.
1553 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001554 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001555 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001556 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001557 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001558 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001559 // FIXME: We shouldn't need to get the function info here, the runtime already
1560 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001561 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1562 FunctionType::ExtInfo(),
1563 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001564 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001565
John McCalld88687f2011-01-07 01:49:06 +00001566 // Otherwise, or if the mutation function returns, just continue.
1567 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001568
John McCalld88687f2011-01-07 01:49:06 +00001569 // Initialize the element variable.
1570 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001571 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001572 LValue elementLValue;
1573 QualType elementType;
1574 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001575 // Initialize the variable, in case it's a __block variable or something.
1576 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001577
John McCall57b3b6a2011-02-22 07:16:58 +00001578 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001579 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001580 VK_LValue, SourceLocation());
1581 elementLValue = EmitLValue(&tempDRE);
1582 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001583 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001584
1585 if (D->isARCPseudoStrong())
1586 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001587 } else {
1588 elementLValue = LValue(); // suppress warning
1589 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001590 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001591 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001592 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001593
1594 // Fetch the buffer out of the enumeration state.
1595 // TODO: this pointer should actually be invariant between
1596 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001597 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001598 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001599 llvm::Value *EnumStateItems =
1600 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001601
John McCalld88687f2011-01-07 01:49:06 +00001602 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001603 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001604 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1605 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001606
John McCalld88687f2011-01-07 01:49:06 +00001607 // Cast that value to the right type.
1608 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1609 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001610
John McCalld88687f2011-01-07 01:49:06 +00001611 // Make sure we have an l-value. Yes, this gets evaluated every
1612 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001613 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001614 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001615 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001616 } else {
1617 EmitScalarInit(CurrentItem, elementLValue);
1618 }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
John McCall57b3b6a2011-02-22 07:16:58 +00001620 // If we do have an element variable, this assignment is the end of
1621 // its initialization.
1622 if (elementIsVariable)
1623 EmitAutoVarCleanups(variable);
1624
John McCalld88687f2011-01-07 01:49:06 +00001625 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001626 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001627 {
1628 RunCleanupsScope Scope(*this);
1629 EmitStmt(S.getBody());
1630 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001631 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001632
John McCalld88687f2011-01-07 01:49:06 +00001633 // Destroy the element variable now.
1634 elementVariableScope.ForceCleanup();
1635
1636 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001637 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001638
John McCalld88687f2011-01-07 01:49:06 +00001639 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001640
John McCalld88687f2011-01-07 01:49:06 +00001641 // First we check in the local buffer.
1642 llvm::Value *indexPlusOne
1643 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001644
John McCalld88687f2011-01-07 01:49:06 +00001645 // If we haven't overrun the buffer yet, we can continue.
1646 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1647 LoopBodyBB, FetchMoreBB);
1648
1649 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1650 count->addIncoming(count, AfterBody.getBlock());
1651
1652 // Otherwise, we have to fetch more elements.
1653 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001654
1655 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001656 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001657 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001658 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001659 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001660
John McCalld88687f2011-01-07 01:49:06 +00001661 // If we got a zero count, we're done.
1662 llvm::Value *refetchCount = CountRV.getScalarVal();
1663
1664 // (note that the message send might split FetchMoreBB)
1665 index->addIncoming(zero, Builder.GetInsertBlock());
1666 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1667
1668 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1669 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001670
Anders Carlssonf484c312008-08-31 02:33:12 +00001671 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001672 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001673
John McCall57b3b6a2011-02-22 07:16:58 +00001674 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001675 // If the element was not a declaration, set it to be null.
1676
John McCalld88687f2011-01-07 01:49:06 +00001677 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1678 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001679 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001680 }
1681
Eric Christopher73fb3502011-10-13 21:45:18 +00001682 if (DI)
1683 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001684
John McCall990567c2011-07-27 01:07:15 +00001685 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001686 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001687 PopCleanupBlock();
1688
John McCallff8e1152010-07-23 21:56:41 +00001689 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001690}
1691
Mike Stump1eb44332009-09-09 15:08:12 +00001692void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001693 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001694}
1695
Mike Stump1eb44332009-09-09 15:08:12 +00001696void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001697 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1698}
1699
Chris Lattner10cac6f2008-11-15 21:26:17 +00001700void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001701 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001702 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001703}
1704
John McCall33e56f32011-09-10 06:18:15 +00001705/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001706/// primitive retain.
1707llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1708 llvm::Value *value) {
1709 return EmitARCRetain(type, value);
1710}
1711
1712namespace {
1713 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001714 CallObjCRelease(llvm::Value *object) : object(object) {}
1715 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001716
John McCallad346f42011-07-12 20:27:29 +00001717 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall5b07e802013-03-13 03:10:54 +00001718 // Releases at the end of the full-expression are imprecise.
1719 CGF.EmitARCRelease(object, ARCImpreciseLifetime);
John McCallf85e1932011-06-15 23:02:42 +00001720 }
1721 };
1722}
1723
John McCall33e56f32011-09-10 06:18:15 +00001724/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001725/// release at the end of the full-expression.
1726llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1727 llvm::Value *object) {
1728 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001729 // conditional.
1730 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001731 return object;
1732}
1733
1734llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1735 llvm::Value *value) {
1736 return EmitARCRetainAutorelease(type, value);
1737}
1738
John McCallb6a60792013-03-23 02:35:54 +00001739/// Given a number of pointers, inform the optimizer that they're
1740/// being intrinsically used up until this point in the program.
1741void CodeGenFunction::EmitARCIntrinsicUse(ArrayRef<llvm::Value*> values) {
1742 llvm::Constant *&fn = CGM.getARCEntrypoints().clang_arc_use;
1743 if (!fn) {
1744 llvm::FunctionType *fnType =
1745 llvm::FunctionType::get(CGM.VoidTy, ArrayRef<llvm::Type*>(), true);
1746 fn = CGM.CreateRuntimeFunction(fnType, "clang.arc.use");
1747 }
1748
1749 // This isn't really a "runtime" function, but as an intrinsic it
1750 // doesn't really matter as long as we align things up.
1751 EmitNounwindRuntimeCall(fn, values);
1752}
1753
John McCallf85e1932011-06-15 23:02:42 +00001754
1755static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001756 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001757 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001758 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1759
Michael Gottesman554b07d2013-02-02 00:57:44 +00001760 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001761 // If the target runtime doesn't naturally support ARC, emit weak
1762 // references to the runtime support library. We don't really
1763 // permit this to fail, but we need a particular relocation style.
Michael Gottesman554b07d2013-02-02 00:57:44 +00001764 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00001765 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001766 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1767 // If we have Native ARC, set nonlazybind attribute for these APIs for
1768 // performance.
Bill Wendling72390b32012-12-20 19:27:06 +00001769 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001770 }
Michael Gottesman554b07d2013-02-02 00:57:44 +00001771 }
John McCallf85e1932011-06-15 23:02:42 +00001772
1773 return fn;
1774}
1775
1776/// Perform an operation having the signature
1777/// i8* (i8*)
1778/// where a null input causes a no-op and returns null.
1779static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1780 llvm::Value *value,
1781 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001782 StringRef fnName,
1783 bool isTailCall = false) {
John McCallf85e1932011-06-15 23:02:42 +00001784 if (isa<llvm::ConstantPointerNull>(value)) return value;
1785
1786 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001787 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001788 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001789 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1790 }
1791
1792 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001793 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001794 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1795
1796 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001797 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001798 if (isTailCall)
1799 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001800
1801 // Cast the result back to the original type.
1802 return CGF.Builder.CreateBitCast(call, origType);
1803}
1804
1805/// Perform an operation having the following signature:
1806/// i8* (i8**)
1807static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1808 llvm::Value *addr,
1809 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001810 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001811 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001812 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001813 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001814 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1815 }
1816
1817 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001818 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001819 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1820
1821 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001822 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00001823
1824 // Cast the result back to a dereference of the original type.
John McCallf85e1932011-06-15 23:02:42 +00001825 if (origType != CGF.Int8PtrPtrTy)
1826 result = CGF.Builder.CreateBitCast(result,
1827 cast<llvm::PointerType>(origType)->getElementType());
1828
1829 return result;
1830}
1831
1832/// Perform an operation having the following signature:
1833/// i8* (i8**, i8*)
1834static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1835 llvm::Value *addr,
1836 llvm::Value *value,
1837 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001838 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001839 bool ignored) {
1840 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1841 == value->getType());
1842
1843 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001844 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001845
Chris Lattner2acc6e32011-07-18 04:24:23 +00001846 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001847 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1848 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1849 }
1850
Chris Lattner2acc6e32011-07-18 04:24:23 +00001851 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001852
John McCallbd7370a2013-02-28 19:01:20 +00001853 llvm::Value *args[] = {
1854 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1855 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1856 };
1857 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001858
1859 if (ignored) return 0;
1860
1861 return CGF.Builder.CreateBitCast(result, origType);
1862}
1863
1864/// Perform an operation having the following signature:
1865/// void (i8**, i8**)
1866static void emitARCCopyOperation(CodeGenFunction &CGF,
1867 llvm::Value *dst,
1868 llvm::Value *src,
1869 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001870 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001871 assert(dst->getType() == src->getType());
1872
1873 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001874 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1875
Chris Lattner2acc6e32011-07-18 04:24:23 +00001876 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001877 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1878 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1879 }
1880
John McCallbd7370a2013-02-28 19:01:20 +00001881 llvm::Value *args[] = {
1882 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1883 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1884 };
1885 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001886}
1887
1888/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001889/// call i8* \@objc_retain(i8* %value)
1890/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001891llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1892 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001893 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001894 else
1895 return EmitARCRetainNonBlock(value);
1896}
1897
1898/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001899/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001900llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1901 return emitARCValueOperation(*this, value,
1902 CGM.getARCEntrypoints().objc_retain,
1903 "objc_retain");
1904}
1905
1906/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001907/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001908///
1909/// \param mandatory - If false, emit the call with metadata
1910/// indicating that it's okay for the optimizer to eliminate this call
1911/// if it can prove that the block never escapes except down the stack.
1912llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1913 bool mandatory) {
1914 llvm::Value *result
1915 = emitARCValueOperation(*this, value,
1916 CGM.getARCEntrypoints().objc_retainBlock,
1917 "objc_retainBlock");
1918
1919 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1920 // tell the optimizer that it doesn't need to do this copy if the
1921 // block doesn't escape, where being passed as an argument doesn't
1922 // count as escaping.
1923 if (!mandatory && isa<llvm::Instruction>(result)) {
1924 llvm::CallInst *call
1925 = cast<llvm::CallInst>(result->stripPointerCasts());
1926 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1927
1928 SmallVector<llvm::Value*,1> args;
1929 call->setMetadata("clang.arc.copy_on_escape",
1930 llvm::MDNode::get(Builder.getContext(), args));
1931 }
1932
1933 return result;
John McCallf85e1932011-06-15 23:02:42 +00001934}
1935
1936/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001937/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001938///
1939/// Yes, this function name is one character away from a different
1940/// call with completely different semantics.
1941llvm::Value *
1942CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1943 // Fetch the void(void) inline asm which marks that we're going to
1944 // retain the autoreleased return value.
1945 llvm::InlineAsm *&marker
1946 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1947 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001948 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001949 = CGM.getTargetCodeGenInfo()
1950 .getARCRetainAutoreleasedReturnValueMarker();
1951
1952 // If we have an empty assembly string, there's nothing to do.
1953 if (assembly.empty()) {
1954
1955 // Otherwise, at -O0, build an inline asm that we're going to call
1956 // in a moment.
1957 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1958 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001959 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001960
1961 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1962
1963 // If we're at -O1 and above, we don't want to litter the code
1964 // with this marker yet, so leave a breadcrumb for the ARC
1965 // optimizer to pick up.
1966 } else {
1967 llvm::NamedMDNode *metadata =
1968 CGM.getModule().getOrInsertNamedMetadata(
1969 "clang.arc.retainAutoreleasedReturnValueMarker");
1970 assert(metadata->getNumOperands() <= 1);
1971 if (metadata->getNumOperands() == 0) {
1972 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001973 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001974 }
1975 }
1976 }
1977
1978 // Call the marker asm if we made one, which we do only at -O0.
1979 if (marker) Builder.CreateCall(marker);
1980
1981 return emitARCValueOperation(*this, value,
1982 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1983 "objc_retainAutoreleasedReturnValue");
1984}
1985
1986/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001987/// call void \@objc_release(i8* %value)
John McCall5b07e802013-03-13 03:10:54 +00001988void CodeGenFunction::EmitARCRelease(llvm::Value *value,
1989 ARCPreciseLifetime_t precise) {
John McCallf85e1932011-06-15 23:02:42 +00001990 if (isa<llvm::ConstantPointerNull>(value)) return;
1991
1992 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1993 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001994 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001995 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001996 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1997 }
1998
1999 // Cast the argument to 'id'.
2000 value = Builder.CreateBitCast(value, Int8PtrTy);
2001
2002 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00002003 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002004
John McCall5b07e802013-03-13 03:10:54 +00002005 if (precise == ARCImpreciseLifetime) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002006 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00002007 call->setMetadata("clang.imprecise_release",
2008 llvm::MDNode::get(Builder.getContext(), args));
2009 }
2010}
2011
John McCall015f33b2012-10-17 02:28:37 +00002012/// Destroy a __strong variable.
2013///
2014/// At -O0, emit a call to store 'null' into the address;
2015/// instrumenting tools prefer this because the address is exposed,
2016/// but it's relatively cumbersome to optimize.
2017///
2018/// At -O1 and above, just load and call objc_release.
2019///
2020/// call void \@objc_storeStrong(i8** %addr, i8* null)
John McCall5b07e802013-03-13 03:10:54 +00002021void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr,
2022 ARCPreciseLifetime_t precise) {
John McCall015f33b2012-10-17 02:28:37 +00002023 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
2024 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
2025 llvm::Value *null = llvm::ConstantPointerNull::get(
2026 cast<llvm::PointerType>(addrTy->getElementType()));
2027 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
2028 return;
2029 }
2030
2031 llvm::Value *value = Builder.CreateLoad(addr);
2032 EmitARCRelease(value, precise);
2033}
2034
John McCallf85e1932011-06-15 23:02:42 +00002035/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002036/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002037llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
2038 llvm::Value *value,
2039 bool ignored) {
2040 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
2041 == value->getType());
2042
2043 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
2044 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00002045 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00002046 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002047 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2048 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2049 }
2050
John McCallbd7370a2013-02-28 19:01:20 +00002051 llvm::Value *args[] = {
2052 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2053 Builder.CreateBitCast(value, Int8PtrTy)
2054 };
2055 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002056
2057 if (ignored) return 0;
2058 return value;
2059}
2060
2061/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002062/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002063/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002064llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002065 llvm::Value *newValue,
2066 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002067 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002068 bool isBlock = type->isBlockPointerType();
2069
2070 // Use a store barrier at -O0 unless this is a block type or the
2071 // lvalue is inadequately aligned.
2072 if (shouldUseFusedARCCalls() &&
2073 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002074 (dst.getAlignment().isZero() ||
2075 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002076 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2077 }
2078
2079 // Otherwise, split it out.
2080
2081 // Retain the new value.
2082 newValue = EmitARCRetain(type, newValue);
2083
2084 // Read the old value.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002085 llvm::Value *oldValue = EmitLoadOfScalar(dst, SourceLocation());
John McCallf85e1932011-06-15 23:02:42 +00002086
2087 // Store. We do this before the release so that any deallocs won't
2088 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002089 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002090
2091 // Finally, release the old value.
John McCall5b07e802013-03-13 03:10:54 +00002092 EmitARCRelease(oldValue, dst.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002093
2094 return newValue;
2095}
2096
2097/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002098/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002099llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2100 return emitARCValueOperation(*this, value,
2101 CGM.getARCEntrypoints().objc_autorelease,
2102 "objc_autorelease");
2103}
2104
2105/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002106/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002107llvm::Value *
2108CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2109 return emitARCValueOperation(*this, value,
2110 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002111 "objc_autoreleaseReturnValue",
2112 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002113}
2114
2115/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002116/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002117llvm::Value *
2118CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2119 return emitARCValueOperation(*this, value,
2120 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002121 "objc_retainAutoreleaseReturnValue",
2122 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002123}
2124
2125/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002126/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002127/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002128/// %retain = call i8* \@objc_retainBlock(i8* %value)
2129/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002130llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2131 llvm::Value *value) {
2132 if (!type->isBlockPointerType())
2133 return EmitARCRetainAutoreleaseNonBlock(value);
2134
2135 if (isa<llvm::ConstantPointerNull>(value)) return value;
2136
Chris Lattner2acc6e32011-07-18 04:24:23 +00002137 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002138 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002139 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002140 value = EmitARCAutorelease(value);
2141 return Builder.CreateBitCast(value, origType);
2142}
2143
2144/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002145/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002146llvm::Value *
2147CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2148 return emitARCValueOperation(*this, value,
2149 CGM.getARCEntrypoints().objc_retainAutorelease,
2150 "objc_retainAutorelease");
2151}
2152
James Dennett9d96e9c2012-06-22 05:41:30 +00002153/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002154/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2155llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2156 return emitARCLoadOperation(*this, addr,
2157 CGM.getARCEntrypoints().objc_loadWeak,
2158 "objc_loadWeak");
2159}
2160
James Dennett9d96e9c2012-06-22 05:41:30 +00002161/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002162llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2163 return emitARCLoadOperation(*this, addr,
2164 CGM.getARCEntrypoints().objc_loadWeakRetained,
2165 "objc_loadWeakRetained");
2166}
2167
James Dennett9d96e9c2012-06-22 05:41:30 +00002168/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002169/// Returns %value.
2170llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2171 llvm::Value *value,
2172 bool ignored) {
2173 return emitARCStoreOperation(*this, addr, value,
2174 CGM.getARCEntrypoints().objc_storeWeak,
2175 "objc_storeWeak", ignored);
2176}
2177
James Dennett9d96e9c2012-06-22 05:41:30 +00002178/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002179/// Returns %value. %addr is known to not have a current weak entry.
2180/// Essentially equivalent to:
2181/// *addr = nil; objc_storeWeak(addr, value);
2182void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2183 // If we're initializing to null, just write null to memory; no need
2184 // to get the runtime involved. But don't do this if optimization
2185 // is enabled, because accounting for this would make the optimizer
2186 // much more complicated.
2187 if (isa<llvm::ConstantPointerNull>(value) &&
2188 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2189 Builder.CreateStore(value, addr);
2190 return;
2191 }
2192
2193 emitARCStoreOperation(*this, addr, value,
2194 CGM.getARCEntrypoints().objc_initWeak,
2195 "objc_initWeak", /*ignored*/ true);
2196}
2197
James Dennett9d96e9c2012-06-22 05:41:30 +00002198/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002199/// Essentially objc_storeWeak(addr, nil).
2200void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2201 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2202 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002203 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002204 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002205 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2206 }
2207
2208 // Cast the argument to 'id*'.
2209 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2210
John McCallbd7370a2013-02-28 19:01:20 +00002211 EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00002212}
2213
James Dennett9d96e9c2012-06-22 05:41:30 +00002214/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002215/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2216/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2217void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2218 emitARCCopyOperation(*this, dst, src,
2219 CGM.getARCEntrypoints().objc_moveWeak,
2220 "objc_moveWeak");
2221}
2222
James Dennett9d96e9c2012-06-22 05:41:30 +00002223/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002224/// Disregards the current value in %dest. Essentially
2225/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2226void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2227 emitARCCopyOperation(*this, dst, src,
2228 CGM.getARCEntrypoints().objc_copyWeak,
2229 "objc_copyWeak");
2230}
2231
2232/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002233/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002234llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2235 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2236 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002237 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002238 llvm::FunctionType::get(Int8PtrTy, false);
2239 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2240 }
2241
John McCallbd7370a2013-02-28 19:01:20 +00002242 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002243}
2244
2245/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002246/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002247void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2248 assert(value->getType() == Int8PtrTy);
2249
2250 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2251 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002252 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002253 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002254
2255 // We don't want to use a weak import here; instead we should not
2256 // fall into this path.
2257 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2258 }
2259
John McCallb57f6b32013-04-16 21:29:40 +00002260 // objc_autoreleasePoolPop can throw.
2261 EmitRuntimeCallOrInvoke(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002262}
2263
2264/// Produce the code to do an MRR version objc_autoreleasepool_push.
2265/// Which is: [[NSAutoreleasePool alloc] init];
2266/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2267/// init is declared as: - (id) init; in its NSObject super class.
2268///
2269llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2270 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002271 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002272 // [NSAutoreleasePool alloc]
2273 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2274 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2275 CallArgList Args;
2276 RValue AllocRV =
2277 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2278 getContext().getObjCIdType(),
2279 AllocSel, Receiver, Args);
2280
2281 // [Receiver init]
2282 Receiver = AllocRV.getScalarVal();
2283 II = &CGM.getContext().Idents.get("init");
2284 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2285 RValue InitRV =
2286 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2287 getContext().getObjCIdType(),
2288 InitSel, Receiver, Args);
2289 return InitRV.getScalarVal();
2290}
2291
2292/// Produce the code to do a primitive release.
2293/// [tmp drain];
2294void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2295 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2296 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2297 CallArgList Args;
2298 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2299 getContext().VoidTy, DrainSel, Arg, Args);
2300}
2301
John McCallbdc4d802011-07-09 01:37:26 +00002302void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2303 llvm::Value *addr,
2304 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002305 CGF.EmitARCDestroyStrong(addr, ARCPreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002306}
2307
2308void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2309 llvm::Value *addr,
2310 QualType type) {
John McCall5b07e802013-03-13 03:10:54 +00002311 CGF.EmitARCDestroyStrong(addr, ARCImpreciseLifetime);
John McCallbdc4d802011-07-09 01:37:26 +00002312}
2313
2314void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2315 llvm::Value *addr,
2316 QualType type) {
2317 CGF.EmitARCDestroyWeak(addr);
2318}
2319
John McCallf85e1932011-06-15 23:02:42 +00002320namespace {
John McCallf85e1932011-06-15 23:02:42 +00002321 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2322 llvm::Value *Token;
2323
2324 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2325
John McCallad346f42011-07-12 20:27:29 +00002326 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002327 CGF.EmitObjCAutoreleasePoolPop(Token);
2328 }
2329 };
2330 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2331 llvm::Value *Token;
2332
2333 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2334
John McCallad346f42011-07-12 20:27:29 +00002335 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002336 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2337 }
2338 };
2339}
2340
2341void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002342 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002343 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2344 else
2345 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2346}
2347
John McCallf85e1932011-06-15 23:02:42 +00002348static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2349 LValue lvalue,
2350 QualType type) {
2351 switch (type.getObjCLifetime()) {
2352 case Qualifiers::OCL_None:
2353 case Qualifiers::OCL_ExplicitNone:
2354 case Qualifiers::OCL_Strong:
2355 case Qualifiers::OCL_Autoreleasing:
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002356 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue,
2357 SourceLocation()).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002358 false);
2359
2360 case Qualifiers::OCL_Weak:
2361 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2362 true);
2363 }
2364
2365 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002366}
2367
2368static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2369 const Expr *e) {
2370 e = e->IgnoreParens();
2371 QualType type = e->getType();
2372
John McCall21480112011-08-30 00:57:29 +00002373 // If we're loading retained from a __strong xvalue, we can avoid
2374 // an extra retain/release pair by zeroing out the source of this
2375 // "move" operation.
2376 if (e->isXValue() &&
2377 !type.isConstQualified() &&
2378 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2379 // Emit the lvalue.
2380 LValue lv = CGF.EmitLValue(e);
2381
2382 // Load the object pointer.
Nick Lewycky4ee7dc22013-10-02 02:29:49 +00002383 llvm::Value *result = CGF.EmitLoadOfLValue(lv,
2384 SourceLocation()).getScalarVal();
John McCall21480112011-08-30 00:57:29 +00002385
2386 // Set the source pointer to NULL.
2387 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2388
2389 return TryEmitResult(result, true);
2390 }
2391
John McCallf85e1932011-06-15 23:02:42 +00002392 // As a very special optimization, in ARC++, if the l-value is the
2393 // result of a non-volatile assignment, do a simple retain of the
2394 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002395 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002396 !type.isVolatileQualified() &&
2397 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2398 isa<BinaryOperator>(e) &&
2399 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2400 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2401
2402 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2403}
2404
2405static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2406 llvm::Value *value);
2407
2408/// Given that the given expression is some sort of call (which does
2409/// not return retained), emit a retain following it.
2410static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2411 llvm::Value *value = CGF.EmitScalarExpr(e);
2412 return emitARCRetainAfterCall(CGF, value);
2413}
2414
2415static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2416 llvm::Value *value) {
2417 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2418 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2419
2420 // Place the retain immediately following the call.
2421 CGF.Builder.SetInsertPoint(call->getParent(),
2422 ++llvm::BasicBlock::iterator(call));
2423 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2424
2425 CGF.Builder.restoreIP(ip);
2426 return value;
2427 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2428 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2429
2430 // Place the retain at the beginning of the normal destination block.
2431 llvm::BasicBlock *BB = invoke->getNormalDest();
2432 CGF.Builder.SetInsertPoint(BB, BB->begin());
2433 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2434
2435 CGF.Builder.restoreIP(ip);
2436 return value;
2437
2438 // Bitcasts can arise because of related-result returns. Rewrite
2439 // the operand.
2440 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2441 llvm::Value *operand = bitcast->getOperand(0);
2442 operand = emitARCRetainAfterCall(CGF, operand);
2443 bitcast->setOperand(0, operand);
2444 return bitcast;
2445
2446 // Generic fall-back case.
2447 } else {
2448 // Retain using the non-block variant: we never need to do a copy
2449 // of a block that's been returned to us.
2450 return CGF.EmitARCRetainNonBlock(value);
2451 }
2452}
2453
John McCalldc05b112011-09-10 01:16:55 +00002454/// Determine whether it might be important to emit a separate
2455/// objc_retain_block on the result of the given expression, or
2456/// whether it's okay to just emit it in a +1 context.
2457static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2458 assert(e->getType()->isBlockPointerType());
2459 e = e->IgnoreParens();
2460
2461 // For future goodness, emit block expressions directly in +1
2462 // contexts if we can.
2463 if (isa<BlockExpr>(e))
2464 return false;
2465
2466 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2467 switch (cast->getCastKind()) {
2468 // Emitting these operations in +1 contexts is goodness.
2469 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002470 case CK_ARCReclaimReturnedObject:
2471 case CK_ARCConsumeObject:
2472 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002473 return false;
2474
2475 // These operations preserve a block type.
2476 case CK_NoOp:
2477 case CK_BitCast:
2478 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2479
2480 // These operations are known to be bad (or haven't been considered).
2481 case CK_AnyPointerToBlockPointerCast:
2482 default:
2483 return true;
2484 }
2485 }
2486
2487 return true;
2488}
2489
John McCall4b9c2d22011-11-06 09:01:30 +00002490/// Try to emit a PseudoObjectExpr at +1.
2491///
2492/// This massively duplicates emitPseudoObjectRValue.
2493static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2494 const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002495 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002496
2497 // Find the result expression.
2498 const Expr *resultExpr = E->getResultExpr();
2499 assert(resultExpr);
2500 TryEmitResult result;
2501
2502 for (PseudoObjectExpr::const_semantics_iterator
2503 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2504 const Expr *semantic = *i;
2505
2506 // If this semantic expression is an opaque value, bind it
2507 // to the result of its source expression.
2508 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2509 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2510 OVMA opaqueData;
2511
2512 // If this semantic is the result of the pseudo-object
2513 // expression, try to evaluate the source as +1.
2514 if (ov == resultExpr) {
2515 assert(!OVMA::shouldBindAsLValue(ov));
2516 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2517 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2518
2519 // Otherwise, just bind it.
2520 } else {
2521 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2522 }
2523 opaques.push_back(opaqueData);
2524
2525 // Otherwise, if the expression is the result, evaluate it
2526 // and remember the result.
2527 } else if (semantic == resultExpr) {
2528 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2529
2530 // Otherwise, evaluate the expression in an ignored context.
2531 } else {
2532 CGF.EmitIgnoredExpr(semantic);
2533 }
2534 }
2535
2536 // Unbind all the opaques now.
2537 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2538 opaques[i].unbind(CGF);
2539
2540 return result;
2541}
2542
John McCallf85e1932011-06-15 23:02:42 +00002543static TryEmitResult
2544tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002545 // We should *never* see a nested full-expression here, because if
2546 // we fail to emit at +1, our caller must not retain after we close
2547 // out the full-expression.
2548 assert(!isa<ExprWithCleanups>(e));
John McCall990567c2011-07-27 01:07:15 +00002549
John McCallf85e1932011-06-15 23:02:42 +00002550 // The desired result type, if it differs from the type of the
2551 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002552 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002553
2554 while (true) {
2555 e = e->IgnoreParens();
2556
2557 // There's a break at the end of this if-chain; anything
2558 // that wants to keep looping has to explicitly continue.
2559 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2560 switch (ce->getCastKind()) {
2561 // No-op casts don't change the type, so we just ignore them.
2562 case CK_NoOp:
2563 e = ce->getSubExpr();
2564 continue;
2565
2566 case CK_LValueToRValue: {
2567 TryEmitResult loadResult
2568 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2569 if (resultType) {
2570 llvm::Value *value = loadResult.getPointer();
2571 value = CGF.Builder.CreateBitCast(value, resultType);
2572 loadResult.setPointer(value);
2573 }
2574 return loadResult;
2575 }
2576
2577 // These casts can change the type, so remember that and
2578 // soldier on. We only need to remember the outermost such
2579 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002580 case CK_CPointerToObjCPointerCast:
2581 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002582 case CK_AnyPointerToBlockPointerCast:
2583 case CK_BitCast:
2584 if (!resultType)
2585 resultType = CGF.ConvertType(ce->getType());
2586 e = ce->getSubExpr();
2587 assert(e->getType()->hasPointerRepresentation());
2588 continue;
2589
2590 // For consumptions, just emit the subexpression and thus elide
2591 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002592 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002593 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2594 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2595 return TryEmitResult(result, true);
2596 }
2597
John McCalldc05b112011-09-10 01:16:55 +00002598 // Block extends are net +0. Naively, we could just recurse on
2599 // the subexpression, but actually we need to ensure that the
2600 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002601 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002602 llvm::Value *result; // will be a +0 value
2603
2604 // If we can't safely assume the sub-expression will produce a
2605 // block-copied value, emit the sub-expression at +0.
2606 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2607 result = CGF.EmitScalarExpr(ce->getSubExpr());
2608
2609 // Otherwise, try to emit the sub-expression at +1 recursively.
2610 } else {
2611 TryEmitResult subresult
2612 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2613 result = subresult.getPointer();
2614
2615 // If that produced a retained value, just use that,
2616 // possibly casting down.
2617 if (subresult.getInt()) {
2618 if (resultType)
2619 result = CGF.Builder.CreateBitCast(result, resultType);
2620 return TryEmitResult(result, true);
2621 }
2622
2623 // Otherwise it's +0.
2624 }
2625
2626 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002627 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002628 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2629 return TryEmitResult(result, true);
2630 }
2631
John McCall7e5e5f42011-07-07 06:58:02 +00002632 // For reclaims, emit the subexpression as a retained call and
2633 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002634 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002635 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2636 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2637 return TryEmitResult(result, true);
2638 }
2639
John McCallf85e1932011-06-15 23:02:42 +00002640 default:
2641 break;
2642 }
2643
2644 // Skip __extension__.
2645 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2646 if (op->getOpcode() == UO_Extension) {
2647 e = op->getSubExpr();
2648 continue;
2649 }
2650
2651 // For calls and message sends, use the retained-call logic.
2652 // Delegate inits are a special case in that they're the only
2653 // returns-retained expression that *isn't* surrounded by
2654 // a consume.
2655 } else if (isa<CallExpr>(e) ||
2656 (isa<ObjCMessageExpr>(e) &&
2657 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2658 llvm::Value *result = emitARCRetainCall(CGF, e);
2659 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2660 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002661
2662 // Look through pseudo-object expressions.
2663 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2664 TryEmitResult result
2665 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2666 if (resultType) {
2667 llvm::Value *value = result.getPointer();
2668 value = CGF.Builder.CreateBitCast(value, resultType);
2669 result.setPointer(value);
2670 }
2671 return result;
John McCallf85e1932011-06-15 23:02:42 +00002672 }
2673
2674 // Conservatively halt the search at any other expression kind.
2675 break;
2676 }
2677
2678 // We didn't find an obvious production, so emit what we've got and
2679 // tell the caller that we didn't manage to retain.
2680 llvm::Value *result = CGF.EmitScalarExpr(e);
2681 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2682 return TryEmitResult(result, false);
2683}
2684
2685static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2686 LValue lvalue,
2687 QualType type) {
2688 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2689 llvm::Value *value = result.getPointer();
2690 if (!result.getInt())
2691 value = CGF.EmitARCRetain(type, value);
2692 return value;
2693}
2694
2695/// EmitARCRetainScalarExpr - Semantically equivalent to
2696/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2697/// best-effort attempt to peephole expressions that naturally produce
2698/// retained objects.
2699llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002700 // The retain needs to happen within the full-expression.
2701 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2702 enterFullExpression(cleanups);
2703 RunCleanupsScope scope(*this);
2704 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2705 }
2706
John McCallf85e1932011-06-15 23:02:42 +00002707 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2708 llvm::Value *value = result.getPointer();
2709 if (!result.getInt())
2710 value = EmitARCRetain(e->getType(), value);
2711 return value;
2712}
2713
2714llvm::Value *
2715CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002716 // The retain needs to happen within the full-expression.
2717 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2718 enterFullExpression(cleanups);
2719 RunCleanupsScope scope(*this);
2720 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2721 }
2722
John McCallf85e1932011-06-15 23:02:42 +00002723 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2724 llvm::Value *value = result.getPointer();
2725 if (result.getInt())
2726 value = EmitARCAutorelease(value);
2727 else
2728 value = EmitARCRetainAutorelease(e->getType(), value);
2729 return value;
2730}
2731
John McCall348f16f2011-10-04 06:23:45 +00002732llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2733 llvm::Value *result;
2734 bool doRetain;
2735
2736 if (shouldEmitSeparateBlockRetain(e)) {
2737 result = EmitScalarExpr(e);
2738 doRetain = true;
2739 } else {
2740 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2741 result = subresult.getPointer();
2742 doRetain = !subresult.getInt();
2743 }
2744
2745 if (doRetain)
2746 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2747 return EmitObjCConsumeObject(e->getType(), result);
2748}
2749
John McCall2b014d62011-10-01 10:32:24 +00002750llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2751 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002752 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002753 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00002754 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00002755 return EmitARCRetainAutoreleaseScalarExpr(expr);
2756 }
2757
2758 // Otherwise, use the normal scalar-expression emission. The
2759 // exception machinery doesn't do anything special with the
2760 // exception like retaining it, so there's no safety associated with
2761 // only running cleanups after the throw has started, and when it
2762 // matters it tends to be substantially inferior code.
2763 return EmitScalarExpr(expr);
2764}
2765
John McCallf85e1932011-06-15 23:02:42 +00002766std::pair<LValue,llvm::Value*>
2767CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2768 bool ignored) {
2769 // Evaluate the RHS first.
2770 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2771 llvm::Value *value = result.getPointer();
2772
John McCallfb720812011-07-28 07:23:35 +00002773 bool hasImmediateRetain = result.getInt();
2774
2775 // If we didn't emit a retained object, and the l-value is of block
2776 // type, then we need to emit the block-retain immediately in case
2777 // it invalidates the l-value.
2778 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002779 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002780 hasImmediateRetain = true;
2781 }
2782
John McCallf85e1932011-06-15 23:02:42 +00002783 LValue lvalue = EmitLValue(e->getLHS());
2784
2785 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002786 if (hasImmediateRetain) {
Nick Lewyckyc53143c2013-10-02 02:33:11 +00002787 llvm::Value *oldValue = EmitLoadOfScalar(lvalue, SourceLocation());
Eli Friedman6da2c712011-12-03 04:14:32 +00002788 EmitStoreOfScalar(value, lvalue);
John McCall5b07e802013-03-13 03:10:54 +00002789 EmitARCRelease(oldValue, lvalue.isARCPreciseLifetime());
John McCallf85e1932011-06-15 23:02:42 +00002790 } else {
John McCall545d9962011-06-25 02:11:03 +00002791 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002792 }
2793
2794 return std::pair<LValue,llvm::Value*>(lvalue, value);
2795}
2796
2797std::pair<LValue,llvm::Value*>
2798CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2799 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2800 LValue lvalue = EmitLValue(e->getLHS());
2801
Eli Friedman6da2c712011-12-03 04:14:32 +00002802 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002803
2804 return std::pair<LValue,llvm::Value*>(lvalue, value);
2805}
2806
2807void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002808 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002809 const Stmt *subStmt = ARPS.getSubStmt();
2810 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2811
2812 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002813 if (DI)
2814 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002815
2816 // Keep track of the current cleanup stack depth.
2817 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002818 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002819 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2820 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2821 } else {
2822 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2823 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2824 }
2825
2826 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2827 E = S.body_end(); I != E; ++I)
2828 EmitStmt(*I);
2829
Eric Christopher73fb3502011-10-13 21:45:18 +00002830 if (DI)
2831 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002832}
John McCall0c24c802011-06-24 23:21:27 +00002833
2834/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2835/// make sure it survives garbage collection until this point.
2836void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2837 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002838 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002839 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002840 llvm::Value *extender
2841 = llvm::InlineAsm::get(extenderType,
2842 /* assembly */ "",
2843 /* constraints */ "r",
2844 /* side effects */ true);
2845
2846 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00002847 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00002848}
2849
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002850/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002851/// non-trivial copy assignment function, produce following helper function.
2852/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2853///
2854llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002855CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2856 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002857 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002858 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002859 return 0;
2860 QualType Ty = PID->getPropertyIvarDecl()->getType();
2861 if (!Ty->isRecordType())
2862 return 0;
2863 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002864 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002865 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002866 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002867 if (hasTrivialSetExpr(PID))
2868 return 0;
2869 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2870 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2871 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002872
2873 ASTContext &C = getContext();
2874 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002875 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002876 FunctionDecl *FD = FunctionDecl::Create(C,
2877 C.getTranslationUnitDecl(),
2878 SourceLocation(),
2879 SourceLocation(), II, C.VoidTy, 0,
2880 SC_Static,
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002881 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002882 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002883
2884 QualType DestTy = C.getPointerType(Ty);
2885 QualType SrcTy = Ty;
2886 SrcTy.addConst();
2887 SrcTy = C.getPointerType(SrcTy);
2888
2889 FunctionArgList args;
2890 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2891 args.push_back(&dstDecl);
2892 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2893 args.push_back(&srcDecl);
2894
2895 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002896 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2897 FunctionType::ExtInfo(),
2898 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002899
John McCallde5d3c72012-02-17 03:33:10 +00002900 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002901
2902 llvm::Function *Fn =
2903 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002904 "__assign_helper_atomic_property_",
2905 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002906
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002907 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2908
John McCallf4b88a42012-03-10 09:33:50 +00002909 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2910 VK_RValue, SourceLocation());
2911 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2912 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002913
John McCallf4b88a42012-03-10 09:33:50 +00002914 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2915 VK_RValue, SourceLocation());
2916 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2917 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002918
John McCallf4b88a42012-03-10 09:33:50 +00002919 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002920 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002921 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002922 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002923 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002924
2925 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002926
2927 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002928 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002929 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002930 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002931}
2932
2933llvm::Constant *
2934CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2935 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002936 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002937 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002938 return 0;
2939 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2940 QualType Ty = PD->getType();
2941 if (!Ty->isRecordType())
2942 return 0;
2943 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2944 return 0;
2945 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002946
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002947 if (hasTrivialGetExpr(PID))
2948 return 0;
2949 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2950 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2951 return HelperFn;
2952
2953
2954 ASTContext &C = getContext();
2955 IdentifierInfo *II
2956 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2957 FunctionDecl *FD = FunctionDecl::Create(C,
2958 C.getTranslationUnitDecl(),
2959 SourceLocation(),
2960 SourceLocation(), II, C.VoidTy, 0,
2961 SC_Static,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002962 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002963 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002964
2965 QualType DestTy = C.getPointerType(Ty);
2966 QualType SrcTy = Ty;
2967 SrcTy.addConst();
2968 SrcTy = C.getPointerType(SrcTy);
2969
2970 FunctionArgList args;
2971 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2972 args.push_back(&dstDecl);
2973 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2974 args.push_back(&srcDecl);
2975
2976 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002977 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2978 FunctionType::ExtInfo(),
2979 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002980
John McCallde5d3c72012-02-17 03:33:10 +00002981 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002982
2983 llvm::Function *Fn =
2984 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2985 "__copy_helper_atomic_property_", &CGM.getModule());
2986
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002987 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2988
John McCallf4b88a42012-03-10 09:33:50 +00002989 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002990 VK_RValue, SourceLocation());
2991
John McCallf4b88a42012-03-10 09:33:50 +00002992 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2993 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002994
2995 CXXConstructExpr *CXXConstExpr =
2996 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2997
2998 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002999 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003000 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
3001 ++A;
3002
3003 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
3004 A != AEnd; ++A)
3005 ConstructorArgs.push_back(*A);
3006
3007 CXXConstructExpr *TheCXXConstructExpr =
3008 CXXConstructExpr::Create(C, Ty, SourceLocation(),
3009 CXXConstExpr->getConstructor(),
3010 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003011 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00003012 CXXConstExpr->hadMultipleCandidates(),
3013 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003014 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00003015 CXXConstExpr->getConstructionKind(),
3016 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003017
John McCallf4b88a42012-03-10 09:33:50 +00003018 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
3019 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003020
John McCallf4b88a42012-03-10 09:33:50 +00003021 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00003022 CharUnits Alignment
3023 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003024 EmitAggExpr(TheCXXConstructExpr,
3025 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
3026 AggValueSlot::IsDestructed,
3027 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00003028 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00003029
3030 FinishFunction();
3031 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
3032 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
3033 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003034}
3035
Eli Friedmancae40c42012-02-28 01:08:45 +00003036llvm::Value *
3037CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
3038 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003039 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
3040 Selector CopySelector =
3041 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-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 Friedman8c72a7d2012-03-01 22:52:28 +00003051 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00003052 Val, CallArgList(), 0, 0);
3053 Val = Result.getScalarVal();
3054 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3055 Ty, AutoreleaseSelector,
3056 Val, CallArgList(), 0, 0);
3057 Val = Result.getScalarVal();
3058 return Val;
3059}
3060
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003061
Ted Kremenek2979ec72008-04-09 15:51:31 +00003062CGObjCRuntime::~CGObjCRuntime() {}