blob: ad7d62951ae342e5f37dc787fcfc98bc36926881 [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"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000024#include "llvm/IR/DataLayout.h"
25#include "llvm/IR/InlineAsm.h"
Anders Carlsson55085182007-08-21 17:43:55 +000026using namespace clang;
27using namespace CodeGen;
28
John McCallf85e1932011-06-15 23:02:42 +000029typedef llvm::PointerIntPair<llvm::Value*,1,bool> TryEmitResult;
30static TryEmitResult
31tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000032static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +000033 QualType ET,
Ted Kremenekebcb57a2012-03-06 20:05:56 +000034 const ObjCMethodDecl *Method,
35 RValue Result);
John McCallf85e1932011-06-15 23:02:42 +000036
37/// Given the address of a variable of pointer type, find the correct
38/// null to store into it.
39static llvm::Constant *getNullForVariable(llvm::Value *addr) {
Chris Lattner2acc6e32011-07-18 04:24:23 +000040 llvm::Type *type =
John McCallf85e1932011-06-15 23:02:42 +000041 cast<llvm::PointerType>(addr->getType())->getElementType();
42 return llvm::ConstantPointerNull::get(cast<llvm::PointerType>(type));
43}
44
Chris Lattner8fdf3282008-06-24 17:04:18 +000045/// Emits an instance of NSConstantString representing the object.
Mike Stump1eb44332009-09-09 15:08:12 +000046llvm::Value *CodeGenFunction::EmitObjCStringLiteral(const ObjCStringLiteral *E)
Daniel Dunbar71fcec92008-11-25 21:53:21 +000047{
David Chisnall0d13f6f2010-01-23 02:40:42 +000048 llvm::Constant *C =
49 CGM.getObjCRuntime().GenerateConstantString(E->getString());
Daniel Dunbared7c6182008-08-20 00:28:19 +000050 // FIXME: This bitcast should just be made an invariant on the Runtime.
Owen Anderson3c4972d2009-07-29 18:54:39 +000051 return llvm::ConstantExpr::getBitCast(C, ConvertType(E->getType()));
Chris Lattner8fdf3282008-06-24 17:04:18 +000052}
53
Patrick Beardeb382ec2012-04-19 00:25:12 +000054/// EmitObjCBoxedExpr - This routine generates code to call
55/// the appropriate expression boxing method. This will either be
56/// one of +[NSNumber numberWith<Type>:], or +[NSString stringWithUTF8String:].
Ted Kremenekebcb57a2012-03-06 20:05:56 +000057///
Eric Christopher16098f32012-03-29 17:31:31 +000058llvm::Value *
Patrick Beardeb382ec2012-04-19 00:25:12 +000059CodeGenFunction::EmitObjCBoxedExpr(const ObjCBoxedExpr *E) {
Ted Kremenekebcb57a2012-03-06 20:05:56 +000060 // Generate the correct selector for this literal's concrete type.
Patrick Beardeb382ec2012-04-19 00:25:12 +000061 const Expr *SubExpr = E->getSubExpr();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000062 // Get the method.
Patrick Beardeb382ec2012-04-19 00:25:12 +000063 const ObjCMethodDecl *BoxingMethod = E->getBoxingMethod();
64 assert(BoxingMethod && "BoxingMethod is null");
65 assert(BoxingMethod->isClassMethod() && "BoxingMethod must be a class method");
66 Selector Sel = BoxingMethod->getSelector();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000067
68 // Generate a reference to the class pointer, which will be the receiver.
Patrick Beardeb382ec2012-04-19 00:25:12 +000069 // Assumes that the method was introduced in the class that should be
70 // messaged (avoids pulling it out of the result type).
Ted Kremenekebcb57a2012-03-06 20:05:56 +000071 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Patrick Beardeb382ec2012-04-19 00:25:12 +000072 const ObjCInterfaceDecl *ClassDecl = BoxingMethod->getClassInterface();
John McCallbd7370a2013-02-28 19:01:20 +000073 llvm::Value *Receiver = Runtime.GetClass(*this, ClassDecl);
Patrick Beardeb382ec2012-04-19 00:25:12 +000074
75 const ParmVarDecl *argDecl = *BoxingMethod->param_begin();
Ted Kremenekebcb57a2012-03-06 20:05:56 +000076 QualType ArgQT = argDecl->getType().getUnqualifiedType();
Patrick Beardeb382ec2012-04-19 00:25:12 +000077 RValue RV = EmitAnyExpr(SubExpr);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000078 CallArgList Args;
79 Args.add(RV, ArgQT);
Patrick Beardeb382ec2012-04-19 00:25:12 +000080
Ted Kremenekebcb57a2012-03-06 20:05:56 +000081 RValue result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Patrick Beardeb382ec2012-04-19 00:25:12 +000082 BoxingMethod->getResultType(), Sel, Receiver, Args,
83 ClassDecl, BoxingMethod);
Ted Kremenekebcb57a2012-03-06 20:05:56 +000084 return Builder.CreateBitCast(result.getScalarVal(),
85 ConvertType(E->getType()));
86}
87
88llvm::Value *CodeGenFunction::EmitObjCCollectionLiteral(const Expr *E,
89 const ObjCMethodDecl *MethodWithObjects) {
90 ASTContext &Context = CGM.getContext();
91 const ObjCDictionaryLiteral *DLE = 0;
92 const ObjCArrayLiteral *ALE = dyn_cast<ObjCArrayLiteral>(E);
93 if (!ALE)
94 DLE = cast<ObjCDictionaryLiteral>(E);
95
96 // Compute the type of the array we're initializing.
97 uint64_t NumElements =
98 ALE ? ALE->getNumElements() : DLE->getNumElements();
99 llvm::APInt APNumElements(Context.getTypeSize(Context.getSizeType()),
100 NumElements);
101 QualType ElementType = Context.getObjCIdType().withConst();
102 QualType ElementArrayType
103 = Context.getConstantArrayType(ElementType, APNumElements,
104 ArrayType::Normal, /*IndexTypeQuals=*/0);
105
106 // Allocate the temporary array(s).
107 llvm::Value *Objects = CreateMemTemp(ElementArrayType, "objects");
108 llvm::Value *Keys = 0;
109 if (DLE)
110 Keys = CreateMemTemp(ElementArrayType, "keys");
111
112 // Perform the actual initialialization of the array(s).
113 for (uint64_t i = 0; i < NumElements; i++) {
114 if (ALE) {
115 // Emit the initializer.
116 const Expr *Rhs = ALE->getElement(i);
117 LValue LV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
118 ElementType,
119 Context.getTypeAlignInChars(Rhs->getType()),
120 Context);
121 EmitScalarInit(Rhs, /*D=*/0, LV, /*capturedByInit=*/false);
122 } else {
123 // Emit the key initializer.
124 const Expr *Key = DLE->getKeyValueElement(i).Key;
125 LValue KeyLV = LValue::MakeAddr(Builder.CreateStructGEP(Keys, i),
126 ElementType,
127 Context.getTypeAlignInChars(Key->getType()),
128 Context);
129 EmitScalarInit(Key, /*D=*/0, KeyLV, /*capturedByInit=*/false);
130
131 // Emit the value initializer.
132 const Expr *Value = DLE->getKeyValueElement(i).Value;
133 LValue ValueLV = LValue::MakeAddr(Builder.CreateStructGEP(Objects, i),
134 ElementType,
135 Context.getTypeAlignInChars(Value->getType()),
136 Context);
137 EmitScalarInit(Value, /*D=*/0, ValueLV, /*capturedByInit=*/false);
138 }
139 }
140
141 // Generate the argument list.
142 CallArgList Args;
143 ObjCMethodDecl::param_const_iterator PI = MethodWithObjects->param_begin();
144 const ParmVarDecl *argDecl = *PI++;
145 QualType ArgQT = argDecl->getType().getUnqualifiedType();
146 Args.add(RValue::get(Objects), ArgQT);
147 if (DLE) {
148 argDecl = *PI++;
149 ArgQT = argDecl->getType().getUnqualifiedType();
150 Args.add(RValue::get(Keys), ArgQT);
151 }
152 argDecl = *PI;
153 ArgQT = argDecl->getType().getUnqualifiedType();
154 llvm::Value *Count =
155 llvm::ConstantInt::get(CGM.getTypes().ConvertType(ArgQT), NumElements);
156 Args.add(RValue::get(Count), ArgQT);
157
158 // Generate a reference to the class pointer, which will be the receiver.
159 Selector Sel = MethodWithObjects->getSelector();
160 QualType ResultType = E->getType();
161 const ObjCObjectPointerType *InterfacePointerType
162 = ResultType->getAsObjCInterfacePointerType();
163 ObjCInterfaceDecl *Class
164 = InterfacePointerType->getObjectType()->getInterface();
165 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +0000166 llvm::Value *Receiver = Runtime.GetClass(*this, Class);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000167
168 // Generate the message send.
Eric Christopher16098f32012-03-29 17:31:31 +0000169 RValue result
170 = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
171 MethodWithObjects->getResultType(),
172 Sel,
173 Receiver, Args, Class,
174 MethodWithObjects);
Ted Kremenekebcb57a2012-03-06 20:05:56 +0000175 return Builder.CreateBitCast(result.getScalarVal(),
176 ConvertType(E->getType()));
177}
178
179llvm::Value *CodeGenFunction::EmitObjCArrayLiteral(const ObjCArrayLiteral *E) {
180 return EmitObjCCollectionLiteral(E, E->getArrayWithObjectsMethod());
181}
182
183llvm::Value *CodeGenFunction::EmitObjCDictionaryLiteral(
184 const ObjCDictionaryLiteral *E) {
185 return EmitObjCCollectionLiteral(E, E->getDictWithObjectsMethod());
186}
187
Chris Lattner8fdf3282008-06-24 17:04:18 +0000188/// Emit a selector.
189llvm::Value *CodeGenFunction::EmitObjCSelectorExpr(const ObjCSelectorExpr *E) {
190 // Untyped selector.
191 // Note that this implementation allows for non-constant strings to be passed
192 // as arguments to @selector(). Currently, the only thing preventing this
193 // behaviour is the type checking in the front end.
John McCallbd7370a2013-02-28 19:01:20 +0000194 return CGM.getObjCRuntime().GetSelector(*this, E->getSelector());
Chris Lattner8fdf3282008-06-24 17:04:18 +0000195}
196
Daniel Dunbared7c6182008-08-20 00:28:19 +0000197llvm::Value *CodeGenFunction::EmitObjCProtocolExpr(const ObjCProtocolExpr *E) {
198 // FIXME: This should pass the Decl not the name.
John McCallbd7370a2013-02-28 19:01:20 +0000199 return CGM.getObjCRuntime().GenerateProtocolRef(*this, E->getProtocol());
Daniel Dunbared7c6182008-08-20 00:28:19 +0000200}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000201
Douglas Gregor926df6c2011-06-11 01:09:30 +0000202/// \brief Adjust the type of the result of an Objective-C message send
203/// expression when the method has a related result type.
204static RValue AdjustRelatedResultType(CodeGenFunction &CGF,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000205 QualType ExpT,
Douglas Gregor926df6c2011-06-11 01:09:30 +0000206 const ObjCMethodDecl *Method,
207 RValue Result) {
208 if (!Method)
209 return Result;
John McCallf85e1932011-06-15 23:02:42 +0000210
Douglas Gregor926df6c2011-06-11 01:09:30 +0000211 if (!Method->hasRelatedResultType() ||
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000212 CGF.getContext().hasSameType(ExpT, Method->getResultType()) ||
Douglas Gregor926df6c2011-06-11 01:09:30 +0000213 !Result.isScalar())
214 return Result;
215
216 // We have applied a related result type. Cast the rvalue appropriately.
217 return RValue::get(CGF.Builder.CreateBitCast(Result.getScalarVal(),
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000218 CGF.ConvertType(ExpT)));
Douglas Gregor926df6c2011-06-11 01:09:30 +0000219}
Chris Lattner8fdf3282008-06-24 17:04:18 +0000220
John McCalldc7c5ad2011-07-22 08:53:00 +0000221/// Decide whether to extend the lifetime of the receiver of a
222/// returns-inner-pointer message.
223static bool
224shouldExtendReceiverForInnerPointerMessage(const ObjCMessageExpr *message) {
225 switch (message->getReceiverKind()) {
226
227 // For a normal instance message, we should extend unless the
228 // receiver is loaded from a variable with precise lifetime.
229 case ObjCMessageExpr::Instance: {
230 const Expr *receiver = message->getInstanceReceiver();
231 const ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(receiver);
232 if (!ice || ice->getCastKind() != CK_LValueToRValue) return true;
233 receiver = ice->getSubExpr()->IgnoreParens();
234
235 // Only __strong variables.
236 if (receiver->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
237 return true;
238
239 // All ivars and fields have precise lifetime.
240 if (isa<MemberExpr>(receiver) || isa<ObjCIvarRefExpr>(receiver))
241 return false;
242
243 // Otherwise, check for variables.
244 const DeclRefExpr *declRef = dyn_cast<DeclRefExpr>(ice->getSubExpr());
245 if (!declRef) return true;
246 const VarDecl *var = dyn_cast<VarDecl>(declRef->getDecl());
247 if (!var) return true;
248
249 // All variables have precise lifetime except local variables with
250 // automatic storage duration that aren't specially marked.
251 return (var->hasLocalStorage() &&
252 !var->hasAttr<ObjCPreciseLifetimeAttr>());
253 }
254
255 case ObjCMessageExpr::Class:
256 case ObjCMessageExpr::SuperClass:
257 // It's never necessary for class objects.
258 return false;
259
260 case ObjCMessageExpr::SuperInstance:
261 // We generally assume that 'self' lives throughout a method call.
262 return false;
263 }
264
265 llvm_unreachable("invalid receiver kind");
266}
267
John McCallef072fd2010-05-22 01:48:05 +0000268RValue CodeGenFunction::EmitObjCMessageExpr(const ObjCMessageExpr *E,
269 ReturnValueSlot Return) {
Chris Lattner8fdf3282008-06-24 17:04:18 +0000270 // Only the lookup mechanism and first two arguments of the method
271 // implementation vary between runtimes. We can get the receiver and
272 // arguments in generic code.
Mike Stump1eb44332009-09-09 15:08:12 +0000273
John McCallf85e1932011-06-15 23:02:42 +0000274 bool isDelegateInit = E->isDelegateInitCall();
275
John McCalldc7c5ad2011-07-22 08:53:00 +0000276 const ObjCMethodDecl *method = E->getMethodDecl();
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000277
John McCallf85e1932011-06-15 23:02:42 +0000278 // We don't retain the receiver in delegate init calls, and this is
279 // safe because the receiver value is always loaded from 'self',
280 // which we zero out. We don't want to Block_copy block receivers,
281 // though.
282 bool retainSelf =
283 (!isDelegateInit &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000284 CGM.getLangOpts().ObjCAutoRefCount &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000285 method &&
286 method->hasAttr<NSConsumesSelfAttr>());
John McCallf85e1932011-06-15 23:02:42 +0000287
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000288 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000289 bool isSuperMessage = false;
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000290 bool isClassMessage = false;
David Chisnallc6cd5fd2010-04-28 19:33:36 +0000291 ObjCInterfaceDecl *OID = 0;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000292 // Find the receiver
Douglas Gregor926df6c2011-06-11 01:09:30 +0000293 QualType ReceiverType;
Daniel Dunbar0b647a62010-04-22 03:17:06 +0000294 llvm::Value *Receiver = 0;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000295 switch (E->getReceiverKind()) {
296 case ObjCMessageExpr::Instance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000297 ReceiverType = E->getInstanceReceiver()->getType();
John McCallf85e1932011-06-15 23:02:42 +0000298 if (retainSelf) {
299 TryEmitResult ter = tryEmitARCRetainScalarExpr(*this,
300 E->getInstanceReceiver());
301 Receiver = ter.getPointer();
John McCalldc7c5ad2011-07-22 08:53:00 +0000302 if (ter.getInt()) retainSelf = false;
John McCallf85e1932011-06-15 23:02:42 +0000303 } else
304 Receiver = EmitScalarExpr(E->getInstanceReceiver());
Douglas Gregor04badcf2010-04-21 00:45:42 +0000305 break;
Daniel Dunbarddb2a3d2008-08-16 00:25:02 +0000306
Douglas Gregor04badcf2010-04-21 00:45:42 +0000307 case ObjCMessageExpr::Class: {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000308 ReceiverType = E->getClassReceiver();
309 const ObjCObjectType *ObjTy = ReceiverType->getAs<ObjCObjectType>();
John McCall3031c632010-05-17 20:12:43 +0000310 assert(ObjTy && "Invalid Objective-C class message send");
311 OID = ObjTy->getInterface();
312 assert(OID && "Invalid Objective-C class message send");
John McCallbd7370a2013-02-28 19:01:20 +0000313 Receiver = Runtime.GetClass(*this, OID);
Daniel Dunbarf56f1912008-08-25 08:19:24 +0000314 isClassMessage = true;
Douglas Gregor04badcf2010-04-21 00:45:42 +0000315 break;
316 }
317
318 case ObjCMessageExpr::SuperInstance:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000319 ReceiverType = E->getSuperType();
Chris Lattner8fdf3282008-06-24 17:04:18 +0000320 Receiver = LoadObjCSelf();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000321 isSuperMessage = true;
322 break;
323
324 case ObjCMessageExpr::SuperClass:
Douglas Gregor926df6c2011-06-11 01:09:30 +0000325 ReceiverType = E->getSuperType();
Douglas Gregor04badcf2010-04-21 00:45:42 +0000326 Receiver = LoadObjCSelf();
327 isSuperMessage = true;
328 isClassMessage = true;
329 break;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000330 }
331
John McCalldc7c5ad2011-07-22 08:53:00 +0000332 if (retainSelf)
333 Receiver = EmitARCRetainNonBlock(Receiver);
334
335 // In ARC, we sometimes want to "extend the lifetime"
336 // (i.e. retain+autorelease) of receivers of returns-inner-pointer
337 // messages.
David Blaikie4e4d0842012-03-11 07:00:24 +0000338 if (getLangOpts().ObjCAutoRefCount && method &&
John McCalldc7c5ad2011-07-22 08:53:00 +0000339 method->hasAttr<ObjCReturnsInnerPointerAttr>() &&
340 shouldExtendReceiverForInnerPointerMessage(E))
341 Receiver = EmitARCRetainAutorelease(ReceiverType, Receiver);
342
John McCallf85e1932011-06-15 23:02:42 +0000343 QualType ResultType =
John McCalldc7c5ad2011-07-22 08:53:00 +0000344 method ? method->getResultType() : E->getType();
John McCallf85e1932011-06-15 23:02:42 +0000345
Daniel Dunbar19cd87e2008-08-30 03:02:31 +0000346 CallArgList Args;
John McCalldc7c5ad2011-07-22 08:53:00 +0000347 EmitCallArgs(Args, method, E->arg_begin(), E->arg_end());
Mike Stump1eb44332009-09-09 15:08:12 +0000348
John McCallf85e1932011-06-15 23:02:42 +0000349 // For delegate init calls in ARC, do an unsafe store of null into
350 // self. This represents the call taking direct ownership of that
351 // value. We have to do this after emitting the other call
352 // arguments because they might also reference self, but we don't
353 // have to worry about any of them modifying self because that would
354 // be an undefined read and write of an object in unordered
355 // expressions.
356 if (isDelegateInit) {
David Blaikie4e4d0842012-03-11 07:00:24 +0000357 assert(getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000358 "delegate init calls should only be marked in ARC");
359
360 // Do an unsafe store of null into self.
361 llvm::Value *selfAddr =
362 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
363 assert(selfAddr && "no self entry for a delegate init call?");
364
365 Builder.CreateStore(getNullForVariable(selfAddr), selfAddr);
366 }
Anders Carlsson7e70fb22010-06-21 20:59:55 +0000367
Douglas Gregor926df6c2011-06-11 01:09:30 +0000368 RValue result;
Chris Lattner8fdf3282008-06-24 17:04:18 +0000369 if (isSuperMessage) {
Chris Lattner9384c762008-06-26 04:42:20 +0000370 // super is only valid in an Objective-C method
371 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
Fariborz Jahanian7ce77922009-02-28 20:07:56 +0000372 bool isCategoryImpl = isa<ObjCCategoryImplDecl>(OMD->getDeclContext());
Douglas Gregor926df6c2011-06-11 01:09:30 +0000373 result = Runtime.GenerateMessageSendSuper(*this, Return, ResultType,
374 E->getSelector(),
375 OMD->getClassInterface(),
376 isCategoryImpl,
377 Receiver,
378 isClassMessage,
379 Args,
John McCalldc7c5ad2011-07-22 08:53:00 +0000380 method);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000381 } else {
382 result = Runtime.GenerateMessageSend(*this, Return, ResultType,
383 E->getSelector(),
384 Receiver, Args, OID,
John McCalldc7c5ad2011-07-22 08:53:00 +0000385 method);
Chris Lattner8fdf3282008-06-24 17:04:18 +0000386 }
John McCallf85e1932011-06-15 23:02:42 +0000387
388 // For delegate init calls in ARC, implicitly store the result of
389 // the call back into self. This takes ownership of the value.
390 if (isDelegateInit) {
391 llvm::Value *selfAddr =
392 LocalDeclMap[cast<ObjCMethodDecl>(CurCodeDecl)->getSelfDecl()];
393 llvm::Value *newSelf = result.getScalarVal();
394
395 // The delegate return type isn't necessarily a matching type; in
396 // fact, it's quite likely to be 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +0000397 llvm::Type *selfTy =
John McCallf85e1932011-06-15 23:02:42 +0000398 cast<llvm::PointerType>(selfAddr->getType())->getElementType();
399 newSelf = Builder.CreateBitCast(newSelf, selfTy);
400
401 Builder.CreateStore(newSelf, selfAddr);
402 }
Fariborz Jahanian4e1524b2012-01-29 20:27:13 +0000403
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000404 return AdjustRelatedResultType(*this, E->getType(), method, result);
Anders Carlsson55085182007-08-21 17:43:55 +0000405}
406
John McCallf85e1932011-06-15 23:02:42 +0000407namespace {
408struct FinishARCDealloc : EHScopeStack::Cleanup {
John McCallad346f42011-07-12 20:27:29 +0000409 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +0000410 const ObjCMethodDecl *method = cast<ObjCMethodDecl>(CGF.CurCodeDecl);
John McCall799d34e2011-07-13 18:26:47 +0000411
412 const ObjCImplDecl *impl = cast<ObjCImplDecl>(method->getDeclContext());
John McCallf85e1932011-06-15 23:02:42 +0000413 const ObjCInterfaceDecl *iface = impl->getClassInterface();
414 if (!iface->getSuperClass()) return;
415
John McCall799d34e2011-07-13 18:26:47 +0000416 bool isCategory = isa<ObjCCategoryImplDecl>(impl);
417
John McCallf85e1932011-06-15 23:02:42 +0000418 // Call [super dealloc] if we have a superclass.
419 llvm::Value *self = CGF.LoadObjCSelf();
420
421 CallArgList args;
422 CGF.CGM.getObjCRuntime().GenerateMessageSendSuper(CGF, ReturnValueSlot(),
423 CGF.getContext().VoidTy,
424 method->getSelector(),
425 iface,
John McCall799d34e2011-07-13 18:26:47 +0000426 isCategory,
John McCallf85e1932011-06-15 23:02:42 +0000427 self,
428 /*is class msg*/ false,
429 args,
430 method);
431 }
432};
433}
434
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000435/// StartObjCMethod - Begin emission of an ObjCMethod. This generates
436/// the LLVM function and sets the other context used by
437/// CodeGenFunction.
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000438void CodeGenFunction::StartObjCMethod(const ObjCMethodDecl *OMD,
Devang Patel8d3f8972011-05-19 23:37:41 +0000439 const ObjCContainerDecl *CD,
440 SourceLocation StartLoc) {
John McCalld26bc762011-03-09 04:27:21 +0000441 FunctionArgList args;
Devang Patel4800ea62010-04-05 21:09:15 +0000442 // Check if we should generate debug info for this method.
Alexey Samsonova240df22012-10-16 07:22:28 +0000443 if (!OMD->hasAttr<NoDebugAttr>())
444 maybeInitializeDebugInfo();
Devang Patel4800ea62010-04-05 21:09:15 +0000445
Fariborz Jahanian679a5022009-01-10 21:06:09 +0000446 llvm::Function *Fn = CGM.getObjCRuntime().GenerateMethod(OMD, CD);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000447
John McCallde5d3c72012-02-17 03:33:10 +0000448 const CGFunctionInfo &FI = CGM.getTypes().arrangeObjCMethodDeclaration(OMD);
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000449 CGM.SetInternalFunctionAttributes(OMD, Fn, FI);
Chris Lattner41110242008-06-17 18:05:57 +0000450
John McCalld26bc762011-03-09 04:27:21 +0000451 args.push_back(OMD->getSelfDecl());
452 args.push_back(OMD->getCmdDecl());
Chris Lattner41110242008-06-17 18:05:57 +0000453
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000454 for (ObjCMethodDecl::param_const_iterator PI = OMD->param_begin(),
Eric Christopher16098f32012-03-29 17:31:31 +0000455 E = OMD->param_end(); PI != E; ++PI)
John McCalld26bc762011-03-09 04:27:21 +0000456 args.push_back(*PI);
Chris Lattner41110242008-06-17 18:05:57 +0000457
Peter Collingbourne14110472011-01-13 18:57:25 +0000458 CurGD = OMD;
459
Devang Patel8d3f8972011-05-19 23:37:41 +0000460 StartFunction(OMD, OMD->getResultType(), Fn, FI, args, StartLoc);
John McCallf85e1932011-06-15 23:02:42 +0000461
462 // In ARC, certain methods get an extra cleanup.
David Blaikie4e4d0842012-03-11 07:00:24 +0000463 if (CGM.getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +0000464 OMD->isInstanceMethod() &&
465 OMD->getSelector().isUnarySelector()) {
466 const IdentifierInfo *ident =
467 OMD->getSelector().getIdentifierInfoForSlot(0);
468 if (ident->isStr("dealloc"))
469 EHStack.pushCleanup<FinishARCDealloc>(getARCCleanupKind());
470 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000471}
Daniel Dunbarb7ec2462008-08-16 03:19:19 +0000472
John McCallf85e1932011-06-15 23:02:42 +0000473static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
474 LValue lvalue, QualType type);
475
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000476/// Generate an Objective-C method. An Objective-C method is a C function with
Mike Stump1eb44332009-09-09 15:08:12 +0000477/// its pointer, name, and types registered in the class struture.
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000478void CodeGenFunction::GenerateObjCMethod(const ObjCMethodDecl *OMD) {
Devang Patel8d3f8972011-05-19 23:37:41 +0000479 StartObjCMethod(OMD, OMD->getClassInterface(), OMD->getLocStart());
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +0000480 EmitStmt(OMD->getBody());
481 FinishFunction(OMD->getBodyRBrace());
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000482}
483
John McCall41bdde92011-09-12 23:06:44 +0000484/// emitStructGetterCall - Call the runtime function to load a property
485/// into the return value slot.
486static void emitStructGetterCall(CodeGenFunction &CGF, ObjCIvarDecl *ivar,
487 bool isAtomic, bool hasStrong) {
488 ASTContext &Context = CGF.getContext();
489
490 llvm::Value *src =
491 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), CGF.LoadObjCSelf(),
492 ivar, 0).getAddress();
493
494 // objc_copyStruct (ReturnValue, &structIvar,
495 // sizeof (Type of Ivar), isAtomic, false);
496 CallArgList args;
497
498 llvm::Value *dest = CGF.Builder.CreateBitCast(CGF.ReturnValue, CGF.VoidPtrTy);
499 args.add(RValue::get(dest), Context.VoidPtrTy);
500
501 src = CGF.Builder.CreateBitCast(src, CGF.VoidPtrTy);
502 args.add(RValue::get(src), Context.VoidPtrTy);
503
504 CharUnits size = CGF.getContext().getTypeSizeInChars(ivar->getType());
505 args.add(RValue::get(CGF.CGM.getSize(size)), Context.getSizeType());
506 args.add(RValue::get(CGF.Builder.getInt1(isAtomic)), Context.BoolTy);
507 args.add(RValue::get(CGF.Builder.getInt1(hasStrong)), Context.BoolTy);
508
509 llvm::Value *fn = CGF.CGM.getObjCRuntime().GetGetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000510 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(Context.VoidTy, args,
511 FunctionType::ExtInfo(),
512 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000513 fn, ReturnValueSlot(), args);
514}
515
John McCall1e1f4872011-09-13 03:34:09 +0000516/// Determine whether the given architecture supports unaligned atomic
517/// accesses. They don't have to be fast, just faster than a function
518/// call and a mutex.
519static bool hasUnalignedAtomics(llvm::Triple::ArchType arch) {
Eli Friedmande24d442011-09-13 20:48:30 +0000520 // FIXME: Allow unaligned atomic load/store on x86. (It is not
521 // currently supported by the backend.)
522 return 0;
John McCall1e1f4872011-09-13 03:34:09 +0000523}
524
525/// Return the maximum size that permits atomic accesses for the given
526/// architecture.
527static CharUnits getMaxAtomicAccessSize(CodeGenModule &CGM,
528 llvm::Triple::ArchType arch) {
529 // ARM has 8-byte atomic accesses, but it's not clear whether we
530 // want to rely on them here.
531
532 // In the default case, just assume that any size up to a pointer is
533 // fine given adequate alignment.
534 return CharUnits::fromQuantity(CGM.PointerSizeInBytes);
535}
536
537namespace {
538 class PropertyImplStrategy {
539 public:
540 enum StrategyKind {
541 /// The 'native' strategy is to use the architecture's provided
542 /// reads and writes.
543 Native,
544
545 /// Use objc_setProperty and objc_getProperty.
546 GetSetProperty,
547
548 /// Use objc_setProperty for the setter, but use expression
549 /// evaluation for the getter.
550 SetPropertyAndExpressionGet,
551
552 /// Use objc_copyStruct.
553 CopyStruct,
554
555 /// The 'expression' strategy is to emit normal assignment or
556 /// lvalue-to-rvalue expressions.
557 Expression
558 };
559
560 StrategyKind getKind() const { return StrategyKind(Kind); }
561
562 bool hasStrongMember() const { return HasStrong; }
563 bool isAtomic() const { return IsAtomic; }
564 bool isCopy() const { return IsCopy; }
565
566 CharUnits getIvarSize() const { return IvarSize; }
567 CharUnits getIvarAlignment() const { return IvarAlignment; }
568
569 PropertyImplStrategy(CodeGenModule &CGM,
570 const ObjCPropertyImplDecl *propImpl);
571
572 private:
573 unsigned Kind : 8;
574 unsigned IsAtomic : 1;
575 unsigned IsCopy : 1;
576 unsigned HasStrong : 1;
577
578 CharUnits IvarSize;
579 CharUnits IvarAlignment;
580 };
581}
582
Sylvestre Ledrubed28ac2012-07-23 08:59:39 +0000583/// Pick an implementation strategy for the given property synthesis.
John McCall1e1f4872011-09-13 03:34:09 +0000584PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
585 const ObjCPropertyImplDecl *propImpl) {
586 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
John McCall265941b2011-09-13 18:31:23 +0000587 ObjCPropertyDecl::SetterKind setterKind = prop->getSetterKind();
John McCall1e1f4872011-09-13 03:34:09 +0000588
John McCall265941b2011-09-13 18:31:23 +0000589 IsCopy = (setterKind == ObjCPropertyDecl::Copy);
590 IsAtomic = prop->isAtomic();
John McCall1e1f4872011-09-13 03:34:09 +0000591 HasStrong = false; // doesn't matter here.
592
593 // Evaluate the ivar's size and alignment.
594 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
595 QualType ivarType = ivar->getType();
596 llvm::tie(IvarSize, IvarAlignment)
597 = CGM.getContext().getTypeInfoInChars(ivarType);
598
599 // If we have a copy property, we always have to use getProperty/setProperty.
John McCall265941b2011-09-13 18:31:23 +0000600 // TODO: we could actually use setProperty and an expression for non-atomics.
John McCall1e1f4872011-09-13 03:34:09 +0000601 if (IsCopy) {
602 Kind = GetSetProperty;
603 return;
604 }
605
John McCall265941b2011-09-13 18:31:23 +0000606 // Handle retain.
607 if (setterKind == ObjCPropertyDecl::Retain) {
John McCall1e1f4872011-09-13 03:34:09 +0000608 // In GC-only, there's nothing special that needs to be done.
David Blaikie4e4d0842012-03-11 07:00:24 +0000609 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
John McCall1e1f4872011-09-13 03:34:09 +0000610 // fallthrough
611
612 // In ARC, if the property is non-atomic, use expression emission,
613 // which translates to objc_storeStrong. This isn't required, but
614 // it's slightly nicer.
David Blaikie4e4d0842012-03-11 07:00:24 +0000615 } else if (CGM.getLangOpts().ObjCAutoRefCount && !IsAtomic) {
John McCalld64c2eb2012-08-20 23:36:59 +0000616 // Using standard expression emission for the setter is only
617 // acceptable if the ivar is __strong, which won't be true if
618 // the property is annotated with __attribute__((NSObject)).
619 // TODO: falling all the way back to objc_setProperty here is
620 // just laziness, though; we could still use objc_storeStrong
621 // if we hacked it right.
622 if (ivarType.getObjCLifetime() == Qualifiers::OCL_Strong)
623 Kind = Expression;
624 else
625 Kind = SetPropertyAndExpressionGet;
John McCall1e1f4872011-09-13 03:34:09 +0000626 return;
627
628 // Otherwise, we need to at least use setProperty. However, if
629 // the property isn't atomic, we can use normal expression
630 // emission for the getter.
631 } else if (!IsAtomic) {
632 Kind = SetPropertyAndExpressionGet;
633 return;
634
635 // Otherwise, we have to use both setProperty and getProperty.
636 } else {
637 Kind = GetSetProperty;
638 return;
639 }
640 }
641
642 // If we're not atomic, just use expression accesses.
643 if (!IsAtomic) {
644 Kind = Expression;
645 return;
646 }
647
John McCall5889c602011-09-13 05:36:29 +0000648 // Properties on bitfield ivars need to be emitted using expression
649 // accesses even if they're nominally atomic.
650 if (ivar->isBitField()) {
651 Kind = Expression;
652 return;
653 }
654
John McCall1e1f4872011-09-13 03:34:09 +0000655 // GC-qualified or ARC-qualified ivars need to be emitted as
656 // expressions. This actually works out to being atomic anyway,
657 // except for ARC __strong, but that should trigger the above code.
658 if (ivarType.hasNonTrivialObjCLifetime() ||
David Blaikie4e4d0842012-03-11 07:00:24 +0000659 (CGM.getLangOpts().getGC() &&
John McCall1e1f4872011-09-13 03:34:09 +0000660 CGM.getContext().getObjCGCAttrKind(ivarType))) {
661 Kind = Expression;
662 return;
663 }
664
665 // Compute whether the ivar has strong members.
David Blaikie4e4d0842012-03-11 07:00:24 +0000666 if (CGM.getLangOpts().getGC())
John McCall1e1f4872011-09-13 03:34:09 +0000667 if (const RecordType *recordType = ivarType->getAs<RecordType>())
668 HasStrong = recordType->getDecl()->hasObjectMember();
669
670 // We can never access structs with object members with a native
671 // access, because we need to use write barriers. This is what
672 // objc_copyStruct is for.
673 if (HasStrong) {
674 Kind = CopyStruct;
675 return;
676 }
677
678 // Otherwise, this is target-dependent and based on the size and
679 // alignment of the ivar.
John McCallc5d9a902011-09-13 07:33:34 +0000680
681 // If the size of the ivar is not a power of two, give up. We don't
682 // want to get into the business of doing compare-and-swaps.
683 if (!IvarSize.isPowerOfTwo()) {
684 Kind = CopyStruct;
685 return;
686 }
687
John McCall1e1f4872011-09-13 03:34:09 +0000688 llvm::Triple::ArchType arch =
689 CGM.getContext().getTargetInfo().getTriple().getArch();
690
691 // Most architectures require memory to fit within a single cache
692 // line, so the alignment has to be at least the size of the access.
693 // Otherwise we have to grab a lock.
694 if (IvarAlignment < IvarSize && !hasUnalignedAtomics(arch)) {
695 Kind = CopyStruct;
696 return;
697 }
698
699 // If the ivar's size exceeds the architecture's maximum atomic
700 // access size, we have to use CopyStruct.
701 if (IvarSize > getMaxAtomicAccessSize(CGM, arch)) {
702 Kind = CopyStruct;
703 return;
704 }
705
706 // Otherwise, we can use native loads and stores.
707 Kind = Native;
708}
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000709
James Dennett2ee5ba32012-06-15 22:10:14 +0000710/// \brief Generate an Objective-C property getter function.
711///
712/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +0000713/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000714void CodeGenFunction::GenerateObjCGetter(ObjCImplementationDecl *IMP,
715 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000716 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000717 GenerateObjCAtomicGetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000718 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
719 ObjCMethodDecl *OMD = PD->getGetterMethodDecl();
720 assert(OMD && "Invalid call to generate getter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +0000721 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +0000722
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000723 generateObjCGetterBody(IMP, PID, OMD, AtomicHelperFn);
John McCall1e1f4872011-09-13 03:34:09 +0000724
725 FinishFunction();
726}
727
John McCall6c11f0b2011-09-13 06:00:03 +0000728static bool hasTrivialGetExpr(const ObjCPropertyImplDecl *propImpl) {
729 const Expr *getter = propImpl->getGetterCXXConstructor();
John McCall1e1f4872011-09-13 03:34:09 +0000730 if (!getter) return true;
731
732 // Sema only makes only of these when the ivar has a C++ class type,
733 // so the form is pretty constrained.
734
John McCall6c11f0b2011-09-13 06:00:03 +0000735 // If the property has a reference type, we might just be binding a
736 // reference, in which case the result will be a gl-value. We should
737 // treat this as a non-trivial operation.
738 if (getter->isGLValue())
739 return false;
740
John McCall1e1f4872011-09-13 03:34:09 +0000741 // If we selected a trivial copy-constructor, we're okay.
742 if (const CXXConstructExpr *construct = dyn_cast<CXXConstructExpr>(getter))
743 return (construct->getConstructor()->isTrivial());
744
745 // The constructor might require cleanups (in which case it's never
746 // trivial).
747 assert(isa<ExprWithCleanups>(getter));
748 return false;
749}
750
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000751/// emitCPPObjectAtomicGetterCall - Call the runtime function to
752/// copy the ivar into the resturn slot.
753static void emitCPPObjectAtomicGetterCall(CodeGenFunction &CGF,
754 llvm::Value *returnAddr,
755 ObjCIvarDecl *ivar,
756 llvm::Constant *AtomicHelperFn) {
757 // objc_copyCppObjectAtomic (&returnSlot, &CppObjectIvar,
758 // AtomicHelperFn);
759 CallArgList args;
760
761 // The 1st argument is the return Slot.
762 args.add(RValue::get(returnAddr), CGF.getContext().VoidPtrTy);
763
764 // The 2nd argument is the address of the ivar.
765 llvm::Value *ivarAddr =
766 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
767 CGF.LoadObjCSelf(), ivar, 0).getAddress();
768 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
769 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
770
771 // Third argument is the helper function.
772 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
773
774 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +0000775 CGF.CGM.getObjCRuntime().GetCppAtomicObjectGetFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000776 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
777 args,
778 FunctionType::ExtInfo(),
779 RequiredArgs::All),
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000780 copyCppAtomicObjectFn, ReturnValueSlot(), args);
781}
782
John McCall1e1f4872011-09-13 03:34:09 +0000783void
784CodeGenFunction::generateObjCGetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000785 const ObjCPropertyImplDecl *propImpl,
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000786 const ObjCMethodDecl *GetterMethodDecl,
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +0000787 llvm::Constant *AtomicHelperFn) {
John McCall1e1f4872011-09-13 03:34:09 +0000788 // If there's a non-trivial 'get' expression, we just have to emit that.
789 if (!hasTrivialGetExpr(propImpl)) {
Fariborz Jahanian20abee62012-01-10 00:37:01 +0000790 if (!AtomicHelperFn) {
791 ReturnStmt ret(SourceLocation(), propImpl->getGetterCXXConstructor(),
792 /*nrvo*/ 0);
793 EmitReturnStmt(ret);
794 }
795 else {
796 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
797 emitCPPObjectAtomicGetterCall(*this, ReturnValue,
798 ivar, AtomicHelperFn);
799 }
John McCall1e1f4872011-09-13 03:34:09 +0000800 return;
801 }
802
803 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
804 QualType propType = prop->getType();
805 ObjCMethodDecl *getterMethod = prop->getGetterMethodDecl();
806
807 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
808
809 // Pick an implementation strategy.
810 PropertyImplStrategy strategy(CGM, propImpl);
811 switch (strategy.getKind()) {
812 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +0000813 // We don't need to do anything for a zero-size struct.
814 if (strategy.getIvarSize().isZero())
815 return;
816
John McCall1e1f4872011-09-13 03:34:09 +0000817 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
818
819 // Currently, all atomic accesses have to be through integer
820 // types, so there's no point in trying to pick a prettier type.
821 llvm::Type *bitcastType =
822 llvm::Type::getIntNTy(getLLVMContext(),
823 getContext().toBits(strategy.getIvarSize()));
824 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
825
826 // Perform an atomic load. This does not impose ordering constraints.
827 llvm::Value *ivarAddr = LV.getAddress();
828 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
829 llvm::LoadInst *load = Builder.CreateLoad(ivarAddr, "load");
830 load->setAlignment(strategy.getIvarAlignment().getQuantity());
831 load->setAtomic(llvm::Unordered);
832
833 // Store that value into the return address. Doing this with a
834 // bitcast is likely to produce some pretty ugly IR, but it's not
835 // the *most* terrible thing in the world.
836 Builder.CreateStore(load, Builder.CreateBitCast(ReturnValue, bitcastType));
837
838 // Make sure we don't do an autorelease.
839 AutoreleaseResult = false;
840 return;
841 }
842
843 case PropertyImplStrategy::GetSetProperty: {
844 llvm::Value *getPropertyFn =
845 CGM.getObjCRuntime().GetPropertyGetFunction();
846 if (!getPropertyFn) {
847 CGM.ErrorUnsupported(propImpl, "Obj-C getter requiring atomic copy");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000848 return;
849 }
850
851 // Return (ivar-type) objc_getProperty((id) self, _cmd, offset, true).
852 // FIXME: Can't this be simpler? This might even be worse than the
853 // corresponding gcc code.
John McCall1e1f4872011-09-13 03:34:09 +0000854 llvm::Value *cmd =
855 Builder.CreateLoad(LocalDeclMap[getterMethod->getCmdDecl()], "cmd");
856 llvm::Value *self = Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
857 llvm::Value *ivarOffset =
858 EmitIvarOffset(classImpl->getClassInterface(), ivar);
859
860 CallArgList args;
861 args.add(RValue::get(self), getContext().getObjCIdType());
862 args.add(RValue::get(cmd), getContext().getObjCSelType());
863 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall265941b2011-09-13 18:31:23 +0000864 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
865 getContext().BoolTy);
John McCall1e1f4872011-09-13 03:34:09 +0000866
Daniel Dunbare4be5a62009-02-03 23:43:59 +0000867 // FIXME: We shouldn't need to get the function info here, the
868 // runtime already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +0000869 RValue RV = EmitCall(getTypes().arrangeFreeFunctionCall(propType, args,
870 FunctionType::ExtInfo(),
871 RequiredArgs::All),
John McCall1e1f4872011-09-13 03:34:09 +0000872 getPropertyFn, ReturnValueSlot(), args);
873
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000874 // We need to fix the type here. Ivars with copy & retain are
875 // always objects so we don't need to worry about complex or
876 // aggregates.
Mike Stump1eb44332009-09-09 15:08:12 +0000877 RV = RValue::get(Builder.CreateBitCast(RV.getScalarVal(),
Fariborz Jahanian52c18b02012-04-26 21:33:14 +0000878 getTypes().ConvertType(getterMethod->getResultType())));
John McCall1e1f4872011-09-13 03:34:09 +0000879
880 EmitReturnOfRValue(RV, propType);
John McCallf85e1932011-06-15 23:02:42 +0000881
882 // objc_getProperty does an autorelease, so we should suppress ours.
883 AutoreleaseResult = false;
John McCallf85e1932011-06-15 23:02:42 +0000884
John McCall1e1f4872011-09-13 03:34:09 +0000885 return;
886 }
887
888 case PropertyImplStrategy::CopyStruct:
889 emitStructGetterCall(*this, ivar, strategy.isAtomic(),
890 strategy.hasStrongMember());
891 return;
892
893 case PropertyImplStrategy::Expression:
894 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
895 LValue LV = EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, 0);
896
897 QualType ivarType = ivar->getType();
John McCall9d232c82013-03-07 21:37:08 +0000898 switch (getEvaluationKind(ivarType)) {
899 case TEK_Complex: {
900 ComplexPairTy pair = EmitLoadOfComplex(LV);
901 EmitStoreOfComplex(pair,
902 MakeNaturalAlignAddrLValue(ReturnValue, ivarType),
903 /*init*/ true);
904 return;
905 }
906 case TEK_Aggregate:
John McCall1e1f4872011-09-13 03:34:09 +0000907 // The return value slot is guaranteed to not be aliased, but
908 // that's not necessarily the same as "on the stack", so
909 // we still potentially need objc_memmove_collectable.
Chad Rosier649b4a12012-03-29 17:37:10 +0000910 EmitAggregateCopy(ReturnValue, LV.getAddress(), ivarType);
John McCall9d232c82013-03-07 21:37:08 +0000911 return;
912 case TEK_Scalar: {
John McCallba3dd902011-07-22 05:23:13 +0000913 llvm::Value *value;
914 if (propType->isReferenceType()) {
915 value = LV.getAddress();
916 } else {
917 // We want to load and autoreleaseReturnValue ARC __weak ivars.
918 if (LV.getQuals().getObjCLifetime() == Qualifiers::OCL_Weak) {
John McCall1e1f4872011-09-13 03:34:09 +0000919 value = emitARCRetainLoadOfScalar(*this, LV, ivarType);
John McCallba3dd902011-07-22 05:23:13 +0000920
921 // Otherwise we want to do a simple load, suppressing the
922 // final autorelease.
John McCallf85e1932011-06-15 23:02:42 +0000923 } else {
John McCallba3dd902011-07-22 05:23:13 +0000924 value = EmitLoadOfLValue(LV).getScalarVal();
925 AutoreleaseResult = false;
Fariborz Jahanian14086762011-03-28 23:47:18 +0000926 }
John McCallf85e1932011-06-15 23:02:42 +0000927
John McCallba3dd902011-07-22 05:23:13 +0000928 value = Builder.CreateBitCast(value, ConvertType(propType));
Fariborz Jahanian490a52b2012-05-29 19:56:01 +0000929 value = Builder.CreateBitCast(value,
930 ConvertType(GetterMethodDecl->getResultType()));
John McCallba3dd902011-07-22 05:23:13 +0000931 }
932
933 EmitReturnOfRValue(RValue::get(value), propType);
John McCall9d232c82013-03-07 21:37:08 +0000934 return;
Fariborz Jahanianed1d29d2009-03-03 18:49:40 +0000935 }
John McCall9d232c82013-03-07 21:37:08 +0000936 }
937 llvm_unreachable("bad evaluation kind");
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +0000938 }
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000939
John McCall1e1f4872011-09-13 03:34:09 +0000940 }
941 llvm_unreachable("bad @property implementation strategy!");
Daniel Dunbaraf05bb92008-08-26 08:29:31 +0000942}
943
John McCall41bdde92011-09-12 23:06:44 +0000944/// emitStructSetterCall - Call the runtime function to store the value
945/// from the first formal parameter into the given ivar.
946static void emitStructSetterCall(CodeGenFunction &CGF, ObjCMethodDecl *OMD,
947 ObjCIvarDecl *ivar) {
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000948 // objc_copyStruct (&structIvar, &Arg,
949 // sizeof (struct something), true, false);
John McCallbbb253c2011-09-10 09:30:49 +0000950 CallArgList args;
951
952 // The first argument is the address of the ivar.
John McCall41bdde92011-09-12 23:06:44 +0000953 llvm::Value *ivarAddr = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
954 CGF.LoadObjCSelf(), ivar, 0)
955 .getAddress();
956 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
957 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000958
959 // The second argument is the address of the parameter variable.
John McCall41bdde92011-09-12 23:06:44 +0000960 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +0000961 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahanianc3953aa2012-01-05 00:10:16 +0000962 VK_LValue, SourceLocation());
John McCall41bdde92011-09-12 23:06:44 +0000963 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
964 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
965 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
John McCallbbb253c2011-09-10 09:30:49 +0000966
967 // The third argument is the sizeof the type.
968 llvm::Value *size =
John McCall41bdde92011-09-12 23:06:44 +0000969 CGF.CGM.getSize(CGF.getContext().getTypeSizeInChars(ivar->getType()));
970 args.add(RValue::get(size), CGF.getContext().getSizeType());
John McCallbbb253c2011-09-10 09:30:49 +0000971
John McCall41bdde92011-09-12 23:06:44 +0000972 // The fourth argument is the 'isAtomic' flag.
973 args.add(RValue::get(CGF.Builder.getTrue()), CGF.getContext().BoolTy);
John McCallbbb253c2011-09-10 09:30:49 +0000974
John McCall41bdde92011-09-12 23:06:44 +0000975 // The fifth argument is the 'hasStrong' flag.
976 // FIXME: should this really always be false?
977 args.add(RValue::get(CGF.Builder.getFalse()), CGF.getContext().BoolTy);
978
979 llvm::Value *copyStructFn = CGF.CGM.getObjCRuntime().GetSetStructFunction();
John McCall0f3d0972012-07-07 06:41:13 +0000980 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
981 args,
982 FunctionType::ExtInfo(),
983 RequiredArgs::All),
John McCall41bdde92011-09-12 23:06:44 +0000984 copyStructFn, ReturnValueSlot(), args);
Fariborz Jahanian2846b972011-02-18 19:15:13 +0000985}
986
Fariborz Jahaniancd93b962012-01-06 22:33:54 +0000987/// emitCPPObjectAtomicSetterCall - Call the runtime function to store
988/// the value from the first formal parameter into the given ivar, using
989/// the Cpp API for atomic Cpp objects with non-trivial copy assignment.
990static void emitCPPObjectAtomicSetterCall(CodeGenFunction &CGF,
991 ObjCMethodDecl *OMD,
992 ObjCIvarDecl *ivar,
993 llvm::Constant *AtomicHelperFn) {
994 // objc_copyCppObjectAtomic (&CppObjectIvar, &Arg,
995 // AtomicHelperFn);
996 CallArgList args;
997
998 // The first argument is the address of the ivar.
999 llvm::Value *ivarAddr =
1000 CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(),
1001 CGF.LoadObjCSelf(), ivar, 0).getAddress();
1002 ivarAddr = CGF.Builder.CreateBitCast(ivarAddr, CGF.Int8PtrTy);
1003 args.add(RValue::get(ivarAddr), CGF.getContext().VoidPtrTy);
1004
1005 // The second argument is the address of the parameter variable.
1006 ParmVarDecl *argVar = *OMD->param_begin();
John McCallf4b88a42012-03-10 09:33:50 +00001007 DeclRefExpr argRef(argVar, false, argVar->getType().getNonReferenceType(),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001008 VK_LValue, SourceLocation());
1009 llvm::Value *argAddr = CGF.EmitLValue(&argRef).getAddress();
1010 argAddr = CGF.Builder.CreateBitCast(argAddr, CGF.Int8PtrTy);
1011 args.add(RValue::get(argAddr), CGF.getContext().VoidPtrTy);
1012
1013 // Third argument is the helper function.
1014 args.add(RValue::get(AtomicHelperFn), CGF.getContext().VoidPtrTy);
1015
1016 llvm::Value *copyCppAtomicObjectFn =
David Chisnalld397cfe2012-12-17 18:54:24 +00001017 CGF.CGM.getObjCRuntime().GetCppAtomicObjectSetFunction();
John McCall0f3d0972012-07-07 06:41:13 +00001018 CGF.EmitCall(CGF.getTypes().arrangeFreeFunctionCall(CGF.getContext().VoidTy,
1019 args,
1020 FunctionType::ExtInfo(),
1021 RequiredArgs::All),
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001022 copyCppAtomicObjectFn, ReturnValueSlot(), args);
1023
1024
1025}
1026
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001027
John McCall1e1f4872011-09-13 03:34:09 +00001028static bool hasTrivialSetExpr(const ObjCPropertyImplDecl *PID) {
1029 Expr *setter = PID->getSetterCXXAssignment();
1030 if (!setter) return true;
1031
1032 // Sema only makes only of these when the ivar has a C++ class type,
1033 // so the form is pretty constrained.
John McCall71c758d2011-09-10 09:17:20 +00001034
1035 // An operator call is trivial if the function it calls is trivial.
John McCall1e1f4872011-09-13 03:34:09 +00001036 // This also implies that there's nothing non-trivial going on with
1037 // the arguments, because operator= can only be trivial if it's a
1038 // synthesized assignment operator and therefore both parameters are
1039 // references.
1040 if (CallExpr *call = dyn_cast<CallExpr>(setter)) {
John McCall71c758d2011-09-10 09:17:20 +00001041 if (const FunctionDecl *callee
1042 = dyn_cast_or_null<FunctionDecl>(call->getCalleeDecl()))
1043 if (callee->isTrivial())
1044 return true;
1045 return false;
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001046 }
John McCall71c758d2011-09-10 09:17:20 +00001047
John McCall1e1f4872011-09-13 03:34:09 +00001048 assert(isa<ExprWithCleanups>(setter));
John McCall71c758d2011-09-10 09:17:20 +00001049 return false;
1050}
1051
Benjamin Kramer4e494cf2012-03-10 20:38:56 +00001052static bool UseOptimizedSetter(CodeGenModule &CGM) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001053 if (CGM.getLangOpts().getGC() != LangOptions::NonGC)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001054 return false;
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001055 return CGM.getLangOpts().ObjCRuntime.hasOptimizedSetter();
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001056}
1057
John McCall71c758d2011-09-10 09:17:20 +00001058void
1059CodeGenFunction::generateObjCSetterBody(const ObjCImplementationDecl *classImpl,
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001060 const ObjCPropertyImplDecl *propImpl,
1061 llvm::Constant *AtomicHelperFn) {
John McCall71c758d2011-09-10 09:17:20 +00001062 const ObjCPropertyDecl *prop = propImpl->getPropertyDecl();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00001063 ObjCIvarDecl *ivar = propImpl->getPropertyIvarDecl();
John McCall71c758d2011-09-10 09:17:20 +00001064 ObjCMethodDecl *setterMethod = prop->getSetterMethodDecl();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001065
1066 // Just use the setter expression if Sema gave us one and it's
1067 // non-trivial.
1068 if (!hasTrivialSetExpr(propImpl)) {
1069 if (!AtomicHelperFn)
1070 // If non-atomic, assignment is called directly.
1071 EmitStmt(propImpl->getSetterCXXAssignment());
1072 else
1073 // If atomic, assignment is called via a locking api.
1074 emitCPPObjectAtomicSetterCall(*this, setterMethod, ivar,
1075 AtomicHelperFn);
1076 return;
1077 }
John McCall71c758d2011-09-10 09:17:20 +00001078
John McCall1e1f4872011-09-13 03:34:09 +00001079 PropertyImplStrategy strategy(CGM, propImpl);
1080 switch (strategy.getKind()) {
1081 case PropertyImplStrategy::Native: {
Eli Friedmanaa014662012-10-26 22:38:05 +00001082 // We don't need to do anything for a zero-size struct.
1083 if (strategy.getIvarSize().isZero())
1084 return;
1085
John McCall1e1f4872011-09-13 03:34:09 +00001086 llvm::Value *argAddr = LocalDeclMap[*setterMethod->param_begin()];
John McCall71c758d2011-09-10 09:17:20 +00001087
John McCall1e1f4872011-09-13 03:34:09 +00001088 LValue ivarLValue =
1089 EmitLValueForIvar(TypeOfSelfObject(), LoadObjCSelf(), ivar, /*quals*/ 0);
1090 llvm::Value *ivarAddr = ivarLValue.getAddress();
John McCall71c758d2011-09-10 09:17:20 +00001091
John McCall1e1f4872011-09-13 03:34:09 +00001092 // Currently, all atomic accesses have to be through integer
1093 // types, so there's no point in trying to pick a prettier type.
1094 llvm::Type *bitcastType =
1095 llvm::Type::getIntNTy(getLLVMContext(),
1096 getContext().toBits(strategy.getIvarSize()));
1097 bitcastType = bitcastType->getPointerTo(); // addrspace 0 okay
1098
1099 // Cast both arguments to the chosen operation type.
1100 argAddr = Builder.CreateBitCast(argAddr, bitcastType);
1101 ivarAddr = Builder.CreateBitCast(ivarAddr, bitcastType);
1102
1103 // This bitcast load is likely to cause some nasty IR.
1104 llvm::Value *load = Builder.CreateLoad(argAddr);
1105
1106 // Perform an atomic store. There are no memory ordering requirements.
1107 llvm::StoreInst *store = Builder.CreateStore(load, ivarAddr);
1108 store->setAlignment(strategy.getIvarAlignment().getQuantity());
1109 store->setAtomic(llvm::Unordered);
1110 return;
1111 }
1112
1113 case PropertyImplStrategy::GetSetProperty:
1114 case PropertyImplStrategy::SetPropertyAndExpressionGet: {
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001115
1116 llvm::Value *setOptimizedPropertyFn = 0;
1117 llvm::Value *setPropertyFn = 0;
1118 if (UseOptimizedSetter(CGM)) {
Daniel Dunbar7a0c0642012-10-15 22:23:53 +00001119 // 10.8 and iOS 6.0 code and GC is off
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001120 setOptimizedPropertyFn =
Eric Christopher16098f32012-03-29 17:31:31 +00001121 CGM.getObjCRuntime()
1122 .GetOptimizedPropertySetFunction(strategy.isAtomic(),
1123 strategy.isCopy());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001124 if (!setOptimizedPropertyFn) {
1125 CGM.ErrorUnsupported(propImpl, "Obj-C optimized setter - NYI");
1126 return;
1127 }
John McCall71c758d2011-09-10 09:17:20 +00001128 }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001129 else {
1130 setPropertyFn = CGM.getObjCRuntime().GetPropertySetFunction();
1131 if (!setPropertyFn) {
1132 CGM.ErrorUnsupported(propImpl, "Obj-C setter requiring atomic copy");
1133 return;
1134 }
1135 }
1136
John McCall71c758d2011-09-10 09:17:20 +00001137 // Emit objc_setProperty((id) self, _cmd, offset, arg,
1138 // <is-atomic>, <is-copy>).
1139 llvm::Value *cmd =
1140 Builder.CreateLoad(LocalDeclMap[setterMethod->getCmdDecl()]);
1141 llvm::Value *self =
1142 Builder.CreateBitCast(LoadObjCSelf(), VoidPtrTy);
1143 llvm::Value *ivarOffset =
1144 EmitIvarOffset(classImpl->getClassInterface(), ivar);
1145 llvm::Value *arg = LocalDeclMap[*setterMethod->param_begin()];
1146 arg = Builder.CreateBitCast(Builder.CreateLoad(arg, "arg"), VoidPtrTy);
1147
1148 CallArgList args;
1149 args.add(RValue::get(self), getContext().getObjCIdType());
1150 args.add(RValue::get(cmd), getContext().getObjCSelType());
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001151 if (setOptimizedPropertyFn) {
1152 args.add(RValue::get(arg), getContext().getObjCIdType());
1153 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
John McCall0f3d0972012-07-07 06:41:13 +00001154 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1155 FunctionType::ExtInfo(),
1156 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001157 setOptimizedPropertyFn, ReturnValueSlot(), args);
1158 } else {
1159 args.add(RValue::get(ivarOffset), getContext().getPointerDiffType());
1160 args.add(RValue::get(arg), getContext().getObjCIdType());
1161 args.add(RValue::get(Builder.getInt1(strategy.isAtomic())),
1162 getContext().BoolTy);
1163 args.add(RValue::get(Builder.getInt1(strategy.isCopy())),
1164 getContext().BoolTy);
1165 // FIXME: We shouldn't need to get the function info here, the runtime
1166 // already should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001167 EmitCall(getTypes().arrangeFreeFunctionCall(getContext().VoidTy, args,
1168 FunctionType::ExtInfo(),
1169 RequiredArgs::All),
Ted Kremenekebcb57a2012-03-06 20:05:56 +00001170 setPropertyFn, ReturnValueSlot(), args);
1171 }
1172
John McCall71c758d2011-09-10 09:17:20 +00001173 return;
1174 }
1175
John McCall1e1f4872011-09-13 03:34:09 +00001176 case PropertyImplStrategy::CopyStruct:
John McCall41bdde92011-09-12 23:06:44 +00001177 emitStructSetterCall(*this, setterMethod, ivar);
John McCall71c758d2011-09-10 09:17:20 +00001178 return;
John McCall1e1f4872011-09-13 03:34:09 +00001179
1180 case PropertyImplStrategy::Expression:
1181 break;
John McCall71c758d2011-09-10 09:17:20 +00001182 }
1183
1184 // Otherwise, fake up some ASTs and emit a normal assignment.
1185 ValueDecl *selfDecl = setterMethod->getSelfDecl();
John McCallf4b88a42012-03-10 09:33:50 +00001186 DeclRefExpr self(selfDecl, false, selfDecl->getType(),
1187 VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001188 ImplicitCastExpr selfLoad(ImplicitCastExpr::OnStack,
1189 selfDecl->getType(), CK_LValueToRValue, &self,
1190 VK_RValue);
1191 ObjCIvarRefExpr ivarRef(ivar, ivar->getType().getNonReferenceType(),
1192 SourceLocation(), &selfLoad, true, true);
1193
1194 ParmVarDecl *argDecl = *setterMethod->param_begin();
1195 QualType argType = argDecl->getType().getNonReferenceType();
John McCallf4b88a42012-03-10 09:33:50 +00001196 DeclRefExpr arg(argDecl, false, argType, VK_LValue, SourceLocation());
John McCall71c758d2011-09-10 09:17:20 +00001197 ImplicitCastExpr argLoad(ImplicitCastExpr::OnStack,
1198 argType.getUnqualifiedType(), CK_LValueToRValue,
1199 &arg, VK_RValue);
1200
1201 // The property type can differ from the ivar type in some situations with
1202 // Objective-C pointer types, we can always bit cast the RHS in these cases.
1203 // The following absurdity is just to ensure well-formed IR.
1204 CastKind argCK = CK_NoOp;
1205 if (ivarRef.getType()->isObjCObjectPointerType()) {
1206 if (argLoad.getType()->isObjCObjectPointerType())
1207 argCK = CK_BitCast;
1208 else if (argLoad.getType()->isBlockPointerType())
1209 argCK = CK_BlockPointerToObjCPointerCast;
1210 else
1211 argCK = CK_CPointerToObjCPointerCast;
1212 } else if (ivarRef.getType()->isBlockPointerType()) {
1213 if (argLoad.getType()->isBlockPointerType())
1214 argCK = CK_BitCast;
1215 else
1216 argCK = CK_AnyPointerToBlockPointerCast;
1217 } else if (ivarRef.getType()->isPointerType()) {
1218 argCK = CK_BitCast;
1219 }
1220 ImplicitCastExpr argCast(ImplicitCastExpr::OnStack,
1221 ivarRef.getType(), argCK, &argLoad,
1222 VK_RValue);
1223 Expr *finalArg = &argLoad;
1224 if (!getContext().hasSameUnqualifiedType(ivarRef.getType(),
1225 argLoad.getType()))
1226 finalArg = &argCast;
1227
1228
1229 BinaryOperator assign(&ivarRef, finalArg, BO_Assign,
1230 ivarRef.getType(), VK_RValue, OK_Ordinary,
Lang Hamesbe9af122012-10-02 04:45:10 +00001231 SourceLocation(), false);
John McCall71c758d2011-09-10 09:17:20 +00001232 EmitStmt(&assign);
Fariborz Jahanian01cb3072011-04-06 16:05:26 +00001233}
1234
James Dennett2ee5ba32012-06-15 22:10:14 +00001235/// \brief Generate an Objective-C property setter function.
1236///
1237/// The given Decl must be an ObjCImplementationDecl. \@synthesize
Steve Naroff489034c2009-01-10 22:55:25 +00001238/// is illegal within a category.
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00001239void CodeGenFunction::GenerateObjCSetter(ObjCImplementationDecl *IMP,
1240 const ObjCPropertyImplDecl *PID) {
Fariborz Jahanianb6e5fe32012-01-07 18:56:22 +00001241 llvm::Constant *AtomicHelperFn =
Fariborz Jahanian20abee62012-01-10 00:37:01 +00001242 GenerateObjCAtomicSetterCopyHelperFunction(PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001243 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1244 ObjCMethodDecl *OMD = PD->getSetterMethodDecl();
1245 assert(OMD && "Invalid call to generate setter (empty method)");
Eric Christopherea320472012-04-03 00:44:15 +00001246 StartObjCMethod(OMD, IMP->getClassInterface(), OMD->getLocStart());
Daniel Dunbar86957eb2008-09-24 06:32:09 +00001247
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00001248 generateObjCSetterBody(IMP, PID, AtomicHelperFn);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00001249
1250 FinishFunction();
Chris Lattner41110242008-06-17 18:05:57 +00001251}
1252
John McCalle81ac692011-03-22 07:05:39 +00001253namespace {
John McCall9928c482011-07-12 16:41:08 +00001254 struct DestroyIvar : EHScopeStack::Cleanup {
1255 private:
1256 llvm::Value *addr;
John McCalle81ac692011-03-22 07:05:39 +00001257 const ObjCIvarDecl *ivar;
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001258 CodeGenFunction::Destroyer *destroyer;
John McCall9928c482011-07-12 16:41:08 +00001259 bool useEHCleanupForArray;
1260 public:
1261 DestroyIvar(llvm::Value *addr, const ObjCIvarDecl *ivar,
1262 CodeGenFunction::Destroyer *destroyer,
1263 bool useEHCleanupForArray)
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001264 : addr(addr), ivar(ivar), destroyer(destroyer),
John McCall9928c482011-07-12 16:41:08 +00001265 useEHCleanupForArray(useEHCleanupForArray) {}
John McCalle81ac692011-03-22 07:05:39 +00001266
John McCallad346f42011-07-12 20:27:29 +00001267 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCall9928c482011-07-12 16:41:08 +00001268 LValue lvalue
1269 = CGF.EmitLValueForIvar(CGF.TypeOfSelfObject(), addr, ivar, /*CVR*/ 0);
1270 CGF.emitDestroy(lvalue.getAddress(), ivar->getType(), destroyer,
John McCallad346f42011-07-12 20:27:29 +00001271 flags.isForNormalCleanup() && useEHCleanupForArray);
John McCalle81ac692011-03-22 07:05:39 +00001272 }
1273 };
1274}
1275
John McCall9928c482011-07-12 16:41:08 +00001276/// Like CodeGenFunction::destroyARCStrong, but do it with a call.
1277static void destroyARCStrongWithStore(CodeGenFunction &CGF,
1278 llvm::Value *addr,
1279 QualType type) {
1280 llvm::Value *null = getNullForVariable(addr);
1281 CGF.EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1282}
John McCallf85e1932011-06-15 23:02:42 +00001283
John McCalle81ac692011-03-22 07:05:39 +00001284static void emitCXXDestructMethod(CodeGenFunction &CGF,
1285 ObjCImplementationDecl *impl) {
1286 CodeGenFunction::RunCleanupsScope scope(CGF);
1287
1288 llvm::Value *self = CGF.LoadObjCSelf();
1289
Jordy Rosedb8264e2011-07-22 02:08:32 +00001290 const ObjCInterfaceDecl *iface = impl->getClassInterface();
1291 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00001292 ivar; ivar = ivar->getNextIvar()) {
1293 QualType type = ivar->getType();
1294
John McCalle81ac692011-03-22 07:05:39 +00001295 // Check whether the ivar is a destructible type.
John McCall9928c482011-07-12 16:41:08 +00001296 QualType::DestructionKind dtorKind = type.isDestructedType();
1297 if (!dtorKind) continue;
John McCalle81ac692011-03-22 07:05:39 +00001298
John McCall9928c482011-07-12 16:41:08 +00001299 CodeGenFunction::Destroyer *destroyer = 0;
John McCalle81ac692011-03-22 07:05:39 +00001300
John McCall9928c482011-07-12 16:41:08 +00001301 // Use a call to objc_storeStrong to destroy strong ivars, for the
1302 // general benefit of the tools.
1303 if (dtorKind == QualType::DK_objc_strong_lifetime) {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001304 destroyer = destroyARCStrongWithStore;
John McCallf85e1932011-06-15 23:02:42 +00001305
John McCall9928c482011-07-12 16:41:08 +00001306 // Otherwise use the default for the destruction kind.
1307 } else {
Peter Collingbourne516bbd42012-01-26 03:33:36 +00001308 destroyer = CGF.getDestroyer(dtorKind);
John McCalle81ac692011-03-22 07:05:39 +00001309 }
John McCall9928c482011-07-12 16:41:08 +00001310
1311 CleanupKind cleanupKind = CGF.getCleanupKind(dtorKind);
1312
1313 CGF.EHStack.pushCleanup<DestroyIvar>(cleanupKind, self, ivar, destroyer,
1314 cleanupKind & EHCleanup);
John McCalle81ac692011-03-22 07:05:39 +00001315 }
1316
1317 assert(scope.requiresCleanups() && "nothing to do in .cxx_destruct?");
1318}
1319
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001320void CodeGenFunction::GenerateObjCCtorDtorMethod(ObjCImplementationDecl *IMP,
1321 ObjCMethodDecl *MD,
1322 bool ctor) {
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001323 MD->createImplicitParams(CGM.getContext(), IMP->getClassInterface());
Devang Patel8d3f8972011-05-19 23:37:41 +00001324 StartObjCMethod(MD, IMP->getClassInterface(), MD->getLocStart());
John McCalle81ac692011-03-22 07:05:39 +00001325
1326 // Emit .cxx_construct.
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001327 if (ctor) {
John McCallf85e1932011-06-15 23:02:42 +00001328 // Suppress the final autorelease in ARC.
1329 AutoreleaseResult = false;
1330
Chris Lattner5f9e2722011-07-23 10:55:15 +00001331 SmallVector<CXXCtorInitializer *, 8> IvarInitializers;
John McCalle81ac692011-03-22 07:05:39 +00001332 for (ObjCImplementationDecl::init_const_iterator B = IMP->init_begin(),
1333 E = IMP->init_end(); B != E; ++B) {
1334 CXXCtorInitializer *IvarInit = (*B);
Francois Pichet00eb3f92010-12-04 09:14:42 +00001335 FieldDecl *Field = IvarInit->getAnyMember();
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001336 ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(Field);
Fariborz Jahanian9b4d4fc2010-04-28 22:30:33 +00001337 LValue LV = EmitLValueForIvar(TypeOfSelfObject(),
1338 LoadObjCSelf(), Ivar, 0);
John McCall7c2349b2011-08-25 20:40:09 +00001339 EmitAggExpr(IvarInit->getInit(),
1340 AggValueSlot::forLValue(LV, AggValueSlot::IsDestructed,
John McCall410ffb22011-08-25 23:04:34 +00001341 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00001342 AggValueSlot::IsNotAliased));
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001343 }
1344 // constructor returns 'self'.
1345 CodeGenTypes &Types = CGM.getTypes();
1346 QualType IdTy(CGM.getContext().getObjCIdType());
1347 llvm::Value *SelfAsId =
1348 Builder.CreateBitCast(LoadObjCSelf(), Types.ConvertType(IdTy));
1349 EmitReturnOfRValue(RValue::get(SelfAsId), IdTy);
John McCalle81ac692011-03-22 07:05:39 +00001350
1351 // Emit .cxx_destruct.
Chandler Carruthbc397cf2010-05-06 00:20:39 +00001352 } else {
John McCalle81ac692011-03-22 07:05:39 +00001353 emitCXXDestructMethod(*this, IMP);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00001354 }
1355 FinishFunction();
1356}
1357
Fariborz Jahanian0b2bd472010-04-13 00:38:05 +00001358bool CodeGenFunction::IndirectObjCSetterArg(const CGFunctionInfo &FI) {
1359 CGFunctionInfo::const_arg_iterator it = FI.arg_begin();
1360 it++; it++;
1361 const ABIArgInfo &AI = it->info;
1362 // FIXME. Is this sufficient check?
1363 return (AI.getKind() == ABIArgInfo::Indirect);
1364}
1365
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001366bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001367 if (CGM.getLangOpts().getGC() == LangOptions::NonGC)
Fariborz Jahanian15bd5882010-04-13 18:32:24 +00001368 return false;
1369 if (const RecordType *FDTTy = Ty.getTypePtr()->getAs<RecordType>())
1370 return FDTTy->getDecl()->hasObjectMember();
1371 return false;
1372}
1373
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001374llvm::Value *CodeGenFunction::LoadObjCSelf() {
Daniel Dunbarb7ec2462008-08-16 03:19:19 +00001375 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1376 return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
Chris Lattner41110242008-06-17 18:05:57 +00001377}
1378
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001379QualType CodeGenFunction::TypeOfSelfObject() {
1380 const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
1381 ImplicitParamDecl *selfDecl = OMD->getSelfDecl();
Steve Naroff14108da2009-07-10 23:34:53 +00001382 const ObjCObjectPointerType *PTy = cast<ObjCObjectPointerType>(
1383 getContext().getCanonicalType(selfDecl->getType()));
Fariborz Jahanian45012a72009-02-03 00:09:52 +00001384 return PTy->getPointeeType();
1385}
1386
Chris Lattner74391b42009-03-22 21:03:39 +00001387void CodeGenFunction::EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S){
Mike Stump1eb44332009-09-09 15:08:12 +00001388 llvm::Constant *EnumerationMutationFn =
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001389 CGM.getObjCRuntime().EnumerationMutationFunction();
Mike Stump1eb44332009-09-09 15:08:12 +00001390
Daniel Dunbarc1cf4a52008-09-24 04:04:31 +00001391 if (!EnumerationMutationFn) {
1392 CGM.ErrorUnsupported(&S, "Obj-C fast enumeration for this runtime");
1393 return;
1394 }
1395
Devang Patelbcbd03a2011-01-19 01:36:36 +00001396 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00001397 if (DI)
1398 DI->EmitLexicalBlockStart(Builder, S.getSourceRange().getBegin());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001399
Devang Patel9d99f2d2011-06-13 23:15:32 +00001400 // The local variable comes into scope immediately.
1401 AutoVarEmission variable = AutoVarEmission::invalid();
1402 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement()))
1403 variable = EmitAutoVarAlloca(*cast<VarDecl>(SD->getSingleDecl()));
1404
John McCalld88687f2011-01-07 01:49:06 +00001405 JumpDest LoopEnd = getJumpDestInCurrentScope("forcoll.end");
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Anders Carlssonf484c312008-08-31 02:33:12 +00001407 // Fast enumeration state.
Douglas Gregor0815b572011-08-09 17:23:49 +00001408 QualType StateTy = CGM.getObjCFastEnumerationStateType();
Daniel Dunbar195337d2010-02-09 02:48:28 +00001409 llvm::Value *StatePtr = CreateMemTemp(StateTy, "state.ptr");
Anders Carlsson1884eb02010-05-22 17:35:42 +00001410 EmitNullInitialization(StatePtr, StateTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001411
Anders Carlssonf484c312008-08-31 02:33:12 +00001412 // Number of elements in the items array.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001413 static const unsigned NumItems = 16;
Mike Stump1eb44332009-09-09 15:08:12 +00001414
John McCalld88687f2011-01-07 01:49:06 +00001415 // Fetch the countByEnumeratingWithState:objects:count: selector.
Benjamin Kramerad468862010-03-30 11:36:44 +00001416 IdentifierInfo *II[] = {
1417 &CGM.getContext().Idents.get("countByEnumeratingWithState"),
1418 &CGM.getContext().Idents.get("objects"),
1419 &CGM.getContext().Idents.get("count")
1420 };
1421 Selector FastEnumSel =
1422 CGM.getContext().Selectors.getSelector(llvm::array_lengthof(II), &II[0]);
Anders Carlssonf484c312008-08-31 02:33:12 +00001423
1424 QualType ItemsTy =
1425 getContext().getConstantArrayType(getContext().getObjCIdType(),
Mike Stump1eb44332009-09-09 15:08:12 +00001426 llvm::APInt(32, NumItems),
Anders Carlssonf484c312008-08-31 02:33:12 +00001427 ArrayType::Normal, 0);
Daniel Dunbar195337d2010-02-09 02:48:28 +00001428 llvm::Value *ItemsPtr = CreateMemTemp(ItemsTy, "items.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001429
John McCall990567c2011-07-27 01:07:15 +00001430 // Emit the collection pointer. In ARC, we do a retain.
1431 llvm::Value *Collection;
David Blaikie4e4d0842012-03-11 07:00:24 +00001432 if (getLangOpts().ObjCAutoRefCount) {
John McCall990567c2011-07-27 01:07:15 +00001433 Collection = EmitARCRetainScalarExpr(S.getCollection());
1434
1435 // Enter a cleanup to do the release.
1436 EmitObjCConsumeObject(S.getCollection()->getType(), Collection);
1437 } else {
1438 Collection = EmitScalarExpr(S.getCollection());
1439 }
Mike Stump1eb44332009-09-09 15:08:12 +00001440
John McCall4b302d32011-08-05 00:14:38 +00001441 // The 'continue' label needs to appear within the cleanup for the
1442 // collection object.
1443 JumpDest AfterBody = getJumpDestInCurrentScope("forcoll.next");
1444
John McCalld88687f2011-01-07 01:49:06 +00001445 // Send it our message:
Anders Carlssonf484c312008-08-31 02:33:12 +00001446 CallArgList Args;
John McCalld88687f2011-01-07 01:49:06 +00001447
1448 // The first argument is a temporary of the enumeration-state type.
Eli Friedman04c9a492011-05-02 17:57:46 +00001449 Args.add(RValue::get(StatePtr), getContext().getPointerType(StateTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001450
John McCalld88687f2011-01-07 01:49:06 +00001451 // The second argument is a temporary array with space for NumItems
1452 // pointers. We'll actually be loading elements from the array
1453 // pointer written into the control state; this buffer is so that
1454 // collections that *aren't* backed by arrays can still queue up
1455 // batches of elements.
Eli Friedman04c9a492011-05-02 17:57:46 +00001456 Args.add(RValue::get(ItemsPtr), getContext().getPointerType(ItemsTy));
Mike Stump1eb44332009-09-09 15:08:12 +00001457
John McCalld88687f2011-01-07 01:49:06 +00001458 // The third argument is the capacity of that temporary array.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001459 llvm::Type *UnsignedLongLTy = ConvertType(getContext().UnsignedLongTy);
Owen Anderson4a28d5d2009-07-24 23:12:58 +00001460 llvm::Constant *Count = llvm::ConstantInt::get(UnsignedLongLTy, NumItems);
Eli Friedman04c9a492011-05-02 17:57:46 +00001461 Args.add(RValue::get(Count), getContext().UnsignedLongTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001462
John McCalld88687f2011-01-07 01:49:06 +00001463 // Start the enumeration.
Mike Stump1eb44332009-09-09 15:08:12 +00001464 RValue CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001465 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001466 getContext().UnsignedLongTy,
1467 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001468 Collection, Args);
Anders Carlssonf484c312008-08-31 02:33:12 +00001469
John McCalld88687f2011-01-07 01:49:06 +00001470 // The initial number of objects that were returned in the buffer.
1471 llvm::Value *initialBufferLimit = CountRV.getScalarVal();
Mike Stump1eb44332009-09-09 15:08:12 +00001472
John McCalld88687f2011-01-07 01:49:06 +00001473 llvm::BasicBlock *EmptyBB = createBasicBlock("forcoll.empty");
1474 llvm::BasicBlock *LoopInitBB = createBasicBlock("forcoll.loopinit");
Mike Stump1eb44332009-09-09 15:08:12 +00001475
John McCalld88687f2011-01-07 01:49:06 +00001476 llvm::Value *zero = llvm::Constant::getNullValue(UnsignedLongLTy);
Anders Carlssonf484c312008-08-31 02:33:12 +00001477
John McCalld88687f2011-01-07 01:49:06 +00001478 // If the limit pointer was zero to begin with, the collection is
1479 // empty; skip all this.
1480 Builder.CreateCondBr(Builder.CreateICmpEQ(initialBufferLimit, zero, "iszero"),
1481 EmptyBB, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001482
John McCalld88687f2011-01-07 01:49:06 +00001483 // Otherwise, initialize the loop.
1484 EmitBlock(LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001485
John McCalld88687f2011-01-07 01:49:06 +00001486 // Save the initial mutations value. This is the value at an
1487 // address that was written into the state object by
1488 // countByEnumeratingWithState:objects:count:.
Mike Stump1eb44332009-09-09 15:08:12 +00001489 llvm::Value *StateMutationsPtrPtr =
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001490 Builder.CreateStructGEP(StatePtr, 2, "mutationsptr.ptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001491 llvm::Value *StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr,
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001492 "mutationsptr");
Mike Stump1eb44332009-09-09 15:08:12 +00001493
John McCalld88687f2011-01-07 01:49:06 +00001494 llvm::Value *initialMutations =
1495 Builder.CreateLoad(StateMutationsPtr, "forcoll.initial-mutations");
Mike Stump1eb44332009-09-09 15:08:12 +00001496
John McCalld88687f2011-01-07 01:49:06 +00001497 // Start looping. This is the point we return to whenever we have a
1498 // fresh, non-empty batch of objects.
1499 llvm::BasicBlock *LoopBodyBB = createBasicBlock("forcoll.loopbody");
1500 EmitBlock(LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001501
John McCalld88687f2011-01-07 01:49:06 +00001502 // The current index into the buffer.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001503 llvm::PHINode *index = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.index");
John McCalld88687f2011-01-07 01:49:06 +00001504 index->addIncoming(zero, LoopInitBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001505
John McCalld88687f2011-01-07 01:49:06 +00001506 // The current buffer size.
Jay Foadbbf3bac2011-03-30 11:28:58 +00001507 llvm::PHINode *count = Builder.CreatePHI(UnsignedLongLTy, 3, "forcoll.count");
John McCalld88687f2011-01-07 01:49:06 +00001508 count->addIncoming(initialBufferLimit, LoopInitBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001509
John McCalld88687f2011-01-07 01:49:06 +00001510 // Check whether the mutations value has changed from where it was
1511 // at start. StateMutationsPtr should actually be invariant between
1512 // refreshes.
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001513 StateMutationsPtr = Builder.CreateLoad(StateMutationsPtrPtr, "mutationsptr");
John McCalld88687f2011-01-07 01:49:06 +00001514 llvm::Value *currentMutations
1515 = Builder.CreateLoad(StateMutationsPtr, "statemutations");
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001516
John McCalld88687f2011-01-07 01:49:06 +00001517 llvm::BasicBlock *WasMutatedBB = createBasicBlock("forcoll.mutated");
Dan Gohman361cf982011-03-02 22:39:34 +00001518 llvm::BasicBlock *WasNotMutatedBB = createBasicBlock("forcoll.notmutated");
Mike Stump1eb44332009-09-09 15:08:12 +00001519
John McCalld88687f2011-01-07 01:49:06 +00001520 Builder.CreateCondBr(Builder.CreateICmpEQ(currentMutations, initialMutations),
1521 WasNotMutatedBB, WasMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001522
John McCalld88687f2011-01-07 01:49:06 +00001523 // If so, call the enumeration-mutation function.
1524 EmitBlock(WasMutatedBB);
Anders Carlsson2abd89c2008-08-31 04:05:03 +00001525 llvm::Value *V =
Mike Stump1eb44332009-09-09 15:08:12 +00001526 Builder.CreateBitCast(Collection,
Benjamin Kramer578faa82011-09-27 21:06:10 +00001527 ConvertType(getContext().getObjCIdType()));
Daniel Dunbar2b2105e2009-02-03 23:55:40 +00001528 CallArgList Args2;
Eli Friedman04c9a492011-05-02 17:57:46 +00001529 Args2.add(RValue::get(V), getContext().getObjCIdType());
Mike Stumpf5408fe2009-05-16 07:57:57 +00001530 // FIXME: We shouldn't need to get the function info here, the runtime already
1531 // should have computed it to build the function.
John McCall0f3d0972012-07-07 06:41:13 +00001532 EmitCall(CGM.getTypes().arrangeFreeFunctionCall(getContext().VoidTy, Args2,
1533 FunctionType::ExtInfo(),
1534 RequiredArgs::All),
Anders Carlssonf3c47c92009-12-24 19:25:24 +00001535 EnumerationMutationFn, ReturnValueSlot(), Args2);
Mike Stump1eb44332009-09-09 15:08:12 +00001536
John McCalld88687f2011-01-07 01:49:06 +00001537 // Otherwise, or if the mutation function returns, just continue.
1538 EmitBlock(WasNotMutatedBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001539
John McCalld88687f2011-01-07 01:49:06 +00001540 // Initialize the element variable.
1541 RunCleanupsScope elementVariableScope(*this);
John McCall57b3b6a2011-02-22 07:16:58 +00001542 bool elementIsVariable;
John McCalld88687f2011-01-07 01:49:06 +00001543 LValue elementLValue;
1544 QualType elementType;
1545 if (const DeclStmt *SD = dyn_cast<DeclStmt>(S.getElement())) {
John McCall57b3b6a2011-02-22 07:16:58 +00001546 // Initialize the variable, in case it's a __block variable or something.
1547 EmitAutoVarInit(variable);
John McCalld88687f2011-01-07 01:49:06 +00001548
John McCall57b3b6a2011-02-22 07:16:58 +00001549 const VarDecl* D = cast<VarDecl>(SD->getSingleDecl());
John McCallf4b88a42012-03-10 09:33:50 +00001550 DeclRefExpr tempDRE(const_cast<VarDecl*>(D), false, D->getType(),
John McCalld88687f2011-01-07 01:49:06 +00001551 VK_LValue, SourceLocation());
1552 elementLValue = EmitLValue(&tempDRE);
1553 elementType = D->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001554 elementIsVariable = true;
John McCall7acddac2011-06-17 06:42:21 +00001555
1556 if (D->isARCPseudoStrong())
1557 elementLValue.getQuals().setObjCLifetime(Qualifiers::OCL_ExplicitNone);
John McCalld88687f2011-01-07 01:49:06 +00001558 } else {
1559 elementLValue = LValue(); // suppress warning
1560 elementType = cast<Expr>(S.getElement())->getType();
John McCall57b3b6a2011-02-22 07:16:58 +00001561 elementIsVariable = false;
John McCalld88687f2011-01-07 01:49:06 +00001562 }
Chris Lattner2acc6e32011-07-18 04:24:23 +00001563 llvm::Type *convertedElementType = ConvertType(elementType);
John McCalld88687f2011-01-07 01:49:06 +00001564
1565 // Fetch the buffer out of the enumeration state.
1566 // TODO: this pointer should actually be invariant between
1567 // refreshes, which would help us do certain loop optimizations.
Mike Stump1eb44332009-09-09 15:08:12 +00001568 llvm::Value *StateItemsPtr =
Anders Carlssonf484c312008-08-31 02:33:12 +00001569 Builder.CreateStructGEP(StatePtr, 1, "stateitems.ptr");
John McCalld88687f2011-01-07 01:49:06 +00001570 llvm::Value *EnumStateItems =
1571 Builder.CreateLoad(StateItemsPtr, "stateitems");
Anders Carlssonf484c312008-08-31 02:33:12 +00001572
John McCalld88687f2011-01-07 01:49:06 +00001573 // Fetch the value at the current index from the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00001574 llvm::Value *CurrentItemPtr =
John McCalld88687f2011-01-07 01:49:06 +00001575 Builder.CreateGEP(EnumStateItems, index, "currentitem.ptr");
1576 llvm::Value *CurrentItem = Builder.CreateLoad(CurrentItemPtr);
Mike Stump1eb44332009-09-09 15:08:12 +00001577
John McCalld88687f2011-01-07 01:49:06 +00001578 // Cast that value to the right type.
1579 CurrentItem = Builder.CreateBitCast(CurrentItem, convertedElementType,
1580 "currentitem");
Mike Stump1eb44332009-09-09 15:08:12 +00001581
John McCalld88687f2011-01-07 01:49:06 +00001582 // Make sure we have an l-value. Yes, this gets evaluated every
1583 // time through the loop.
John McCall7acddac2011-06-17 06:42:21 +00001584 if (!elementIsVariable) {
John McCalld88687f2011-01-07 01:49:06 +00001585 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001586 EmitStoreThroughLValue(RValue::get(CurrentItem), elementLValue);
John McCall7acddac2011-06-17 06:42:21 +00001587 } else {
1588 EmitScalarInit(CurrentItem, elementLValue);
1589 }
Mike Stump1eb44332009-09-09 15:08:12 +00001590
John McCall57b3b6a2011-02-22 07:16:58 +00001591 // If we do have an element variable, this assignment is the end of
1592 // its initialization.
1593 if (elementIsVariable)
1594 EmitAutoVarCleanups(variable);
1595
John McCalld88687f2011-01-07 01:49:06 +00001596 // Perform the loop body, setting up break and continue labels.
Anders Carlssone4b6d342009-02-10 05:52:02 +00001597 BreakContinueStack.push_back(BreakContinue(LoopEnd, AfterBody));
John McCalld88687f2011-01-07 01:49:06 +00001598 {
1599 RunCleanupsScope Scope(*this);
1600 EmitStmt(S.getBody());
1601 }
Anders Carlssonf484c312008-08-31 02:33:12 +00001602 BreakContinueStack.pop_back();
Mike Stump1eb44332009-09-09 15:08:12 +00001603
John McCalld88687f2011-01-07 01:49:06 +00001604 // Destroy the element variable now.
1605 elementVariableScope.ForceCleanup();
1606
1607 // Check whether there are more elements.
John McCallff8e1152010-07-23 21:56:41 +00001608 EmitBlock(AfterBody.getBlock());
Mike Stump1eb44332009-09-09 15:08:12 +00001609
John McCalld88687f2011-01-07 01:49:06 +00001610 llvm::BasicBlock *FetchMoreBB = createBasicBlock("forcoll.refetch");
Fariborz Jahanianf0906c42009-01-06 18:56:31 +00001611
John McCalld88687f2011-01-07 01:49:06 +00001612 // First we check in the local buffer.
1613 llvm::Value *indexPlusOne
1614 = Builder.CreateAdd(index, llvm::ConstantInt::get(UnsignedLongLTy, 1));
Anders Carlssonf484c312008-08-31 02:33:12 +00001615
John McCalld88687f2011-01-07 01:49:06 +00001616 // If we haven't overrun the buffer yet, we can continue.
1617 Builder.CreateCondBr(Builder.CreateICmpULT(indexPlusOne, count),
1618 LoopBodyBB, FetchMoreBB);
1619
1620 index->addIncoming(indexPlusOne, AfterBody.getBlock());
1621 count->addIncoming(count, AfterBody.getBlock());
1622
1623 // Otherwise, we have to fetch more elements.
1624 EmitBlock(FetchMoreBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001625
1626 CountRV =
John McCallef072fd2010-05-22 01:48:05 +00001627 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
Anders Carlssonf484c312008-08-31 02:33:12 +00001628 getContext().UnsignedLongTy,
Mike Stump1eb44332009-09-09 15:08:12 +00001629 FastEnumSel,
David Chisnallc6cd5fd2010-04-28 19:33:36 +00001630 Collection, Args);
Mike Stump1eb44332009-09-09 15:08:12 +00001631
John McCalld88687f2011-01-07 01:49:06 +00001632 // If we got a zero count, we're done.
1633 llvm::Value *refetchCount = CountRV.getScalarVal();
1634
1635 // (note that the message send might split FetchMoreBB)
1636 index->addIncoming(zero, Builder.GetInsertBlock());
1637 count->addIncoming(refetchCount, Builder.GetInsertBlock());
1638
1639 Builder.CreateCondBr(Builder.CreateICmpEQ(refetchCount, zero),
1640 EmptyBB, LoopBodyBB);
Mike Stump1eb44332009-09-09 15:08:12 +00001641
Anders Carlssonf484c312008-08-31 02:33:12 +00001642 // No more elements.
John McCalld88687f2011-01-07 01:49:06 +00001643 EmitBlock(EmptyBB);
Anders Carlssonf484c312008-08-31 02:33:12 +00001644
John McCall57b3b6a2011-02-22 07:16:58 +00001645 if (!elementIsVariable) {
Anders Carlssonf484c312008-08-31 02:33:12 +00001646 // If the element was not a declaration, set it to be null.
1647
John McCalld88687f2011-01-07 01:49:06 +00001648 llvm::Value *null = llvm::Constant::getNullValue(convertedElementType);
1649 elementLValue = EmitLValue(cast<Expr>(S.getElement()));
John McCall545d9962011-06-25 02:11:03 +00001650 EmitStoreThroughLValue(RValue::get(null), elementLValue);
Anders Carlssonf484c312008-08-31 02:33:12 +00001651 }
1652
Eric Christopher73fb3502011-10-13 21:45:18 +00001653 if (DI)
1654 DI->EmitLexicalBlockEnd(Builder, S.getSourceRange().getEnd());
Devang Patelbcbd03a2011-01-19 01:36:36 +00001655
John McCall990567c2011-07-27 01:07:15 +00001656 // Leave the cleanup we entered in ARC.
David Blaikie4e4d0842012-03-11 07:00:24 +00001657 if (getLangOpts().ObjCAutoRefCount)
John McCall990567c2011-07-27 01:07:15 +00001658 PopCleanupBlock();
1659
John McCallff8e1152010-07-23 21:56:41 +00001660 EmitBlock(LoopEnd.getBlock());
Anders Carlsson3d8400d2008-08-30 19:51:14 +00001661}
1662
Mike Stump1eb44332009-09-09 15:08:12 +00001663void CodeGenFunction::EmitObjCAtTryStmt(const ObjCAtTryStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001664 CGM.getObjCRuntime().EmitTryStmt(*this, S);
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001665}
1666
Mike Stump1eb44332009-09-09 15:08:12 +00001667void CodeGenFunction::EmitObjCAtThrowStmt(const ObjCAtThrowStmt &S) {
Anders Carlsson64d5d6c2008-09-09 10:04:29 +00001668 CGM.getObjCRuntime().EmitThrowStmt(*this, S);
1669}
1670
Chris Lattner10cac6f2008-11-15 21:26:17 +00001671void CodeGenFunction::EmitObjCAtSynchronizedStmt(
Mike Stump1eb44332009-09-09 15:08:12 +00001672 const ObjCAtSynchronizedStmt &S) {
John McCallf1549f62010-07-06 01:34:17 +00001673 CGM.getObjCRuntime().EmitSynchronizedStmt(*this, S);
Chris Lattner10cac6f2008-11-15 21:26:17 +00001674}
1675
John McCall33e56f32011-09-10 06:18:15 +00001676/// Produce the code for a CK_ARCProduceObject. Just does a
John McCallf85e1932011-06-15 23:02:42 +00001677/// primitive retain.
1678llvm::Value *CodeGenFunction::EmitObjCProduceObject(QualType type,
1679 llvm::Value *value) {
1680 return EmitARCRetain(type, value);
1681}
1682
1683namespace {
1684 struct CallObjCRelease : EHScopeStack::Cleanup {
John McCallbddfd872011-08-03 22:24:24 +00001685 CallObjCRelease(llvm::Value *object) : object(object) {}
1686 llvm::Value *object;
John McCallf85e1932011-06-15 23:02:42 +00001687
John McCallad346f42011-07-12 20:27:29 +00001688 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00001689 CGF.EmitARCRelease(object, /*precise*/ true);
John McCallf85e1932011-06-15 23:02:42 +00001690 }
1691 };
1692}
1693
John McCall33e56f32011-09-10 06:18:15 +00001694/// Produce the code for a CK_ARCConsumeObject. Does a primitive
John McCallf85e1932011-06-15 23:02:42 +00001695/// release at the end of the full-expression.
1696llvm::Value *CodeGenFunction::EmitObjCConsumeObject(QualType type,
1697 llvm::Value *object) {
1698 // If we're in a conditional branch, we need to make the cleanup
John McCallbddfd872011-08-03 22:24:24 +00001699 // conditional.
1700 pushFullExprCleanup<CallObjCRelease>(getARCCleanupKind(), object);
John McCallf85e1932011-06-15 23:02:42 +00001701 return object;
1702}
1703
1704llvm::Value *CodeGenFunction::EmitObjCExtendObjectLifetime(QualType type,
1705 llvm::Value *value) {
1706 return EmitARCRetainAutorelease(type, value);
1707}
1708
1709
1710static llvm::Constant *createARCRuntimeFunction(CodeGenModule &CGM,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001711 llvm::FunctionType *type,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001712 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001713 llvm::Constant *fn = CGM.CreateRuntimeFunction(type, fnName);
1714
Michael Gottesman554b07d2013-02-02 00:57:44 +00001715 if (llvm::Function *f = dyn_cast<llvm::Function>(fn)) {
Michael Gottesmancfe18a12013-02-02 01:05:06 +00001716 // If the target runtime doesn't naturally support ARC, emit weak
1717 // references to the runtime support library. We don't really
1718 // permit this to fail, but we need a particular relocation style.
Michael Gottesman554b07d2013-02-02 00:57:44 +00001719 if (!CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00001720 f->setLinkage(llvm::Function::ExternalWeakLinkage);
Michael Gottesman554b07d2013-02-02 00:57:44 +00001721 } else if (fnName == "objc_retain" || fnName == "objc_release") {
1722 // If we have Native ARC, set nonlazybind attribute for these APIs for
1723 // performance.
Bill Wendling72390b32012-12-20 19:27:06 +00001724 f->addFnAttr(llvm::Attribute::NonLazyBind);
Michael Gottesmandb99e8b2013-02-02 01:03:01 +00001725 }
Michael Gottesman554b07d2013-02-02 00:57:44 +00001726 }
John McCallf85e1932011-06-15 23:02:42 +00001727
1728 return fn;
1729}
1730
1731/// Perform an operation having the signature
1732/// i8* (i8*)
1733/// where a null input causes a no-op and returns null.
1734static llvm::Value *emitARCValueOperation(CodeGenFunction &CGF,
1735 llvm::Value *value,
1736 llvm::Constant *&fn,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001737 StringRef fnName,
1738 bool isTailCall = false) {
John McCallf85e1932011-06-15 23:02:42 +00001739 if (isa<llvm::ConstantPointerNull>(value)) return value;
1740
1741 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001742 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001743 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001744 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1745 }
1746
1747 // Cast the argument to 'id'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001748 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001749 value = CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy);
1750
1751 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001752 llvm::CallInst *call = CGF.EmitNounwindRuntimeCall(fn, value);
Chad Rosierdf76f1e2012-12-12 17:52:21 +00001753 if (isTailCall)
1754 call->setTailCall();
John McCallf85e1932011-06-15 23:02:42 +00001755
1756 // Cast the result back to the original type.
1757 return CGF.Builder.CreateBitCast(call, origType);
1758}
1759
1760/// Perform an operation having the following signature:
1761/// i8* (i8**)
1762static llvm::Value *emitARCLoadOperation(CodeGenFunction &CGF,
1763 llvm::Value *addr,
1764 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001765 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001766 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001767 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001768 llvm::FunctionType::get(CGF.Int8PtrTy, CGF.Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001769 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1770 }
1771
1772 // Cast the argument to 'id*'.
Chris Lattner2acc6e32011-07-18 04:24:23 +00001773 llvm::Type *origType = addr->getType();
John McCallf85e1932011-06-15 23:02:42 +00001774 addr = CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy);
1775
1776 // Call the function.
John McCallbd7370a2013-02-28 19:01:20 +00001777 llvm::Value *result = CGF.EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00001778
1779 // Cast the result back to a dereference of the original type.
John McCallf85e1932011-06-15 23:02:42 +00001780 if (origType != CGF.Int8PtrPtrTy)
1781 result = CGF.Builder.CreateBitCast(result,
1782 cast<llvm::PointerType>(origType)->getElementType());
1783
1784 return result;
1785}
1786
1787/// Perform an operation having the following signature:
1788/// i8* (i8**, i8*)
1789static llvm::Value *emitARCStoreOperation(CodeGenFunction &CGF,
1790 llvm::Value *addr,
1791 llvm::Value *value,
1792 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001793 StringRef fnName,
John McCallf85e1932011-06-15 23:02:42 +00001794 bool ignored) {
1795 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1796 == value->getType());
1797
1798 if (!fn) {
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00001799 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrTy };
John McCallf85e1932011-06-15 23:02:42 +00001800
Chris Lattner2acc6e32011-07-18 04:24:23 +00001801 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001802 = llvm::FunctionType::get(CGF.Int8PtrTy, argTypes, false);
1803 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1804 }
1805
Chris Lattner2acc6e32011-07-18 04:24:23 +00001806 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00001807
John McCallbd7370a2013-02-28 19:01:20 +00001808 llvm::Value *args[] = {
1809 CGF.Builder.CreateBitCast(addr, CGF.Int8PtrPtrTy),
1810 CGF.Builder.CreateBitCast(value, CGF.Int8PtrTy)
1811 };
1812 llvm::CallInst *result = CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001813
1814 if (ignored) return 0;
1815
1816 return CGF.Builder.CreateBitCast(result, origType);
1817}
1818
1819/// Perform an operation having the following signature:
1820/// void (i8**, i8**)
1821static void emitARCCopyOperation(CodeGenFunction &CGF,
1822 llvm::Value *dst,
1823 llvm::Value *src,
1824 llvm::Constant *&fn,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001825 StringRef fnName) {
John McCallf85e1932011-06-15 23:02:42 +00001826 assert(dst->getType() == src->getType());
1827
1828 if (!fn) {
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001829 llvm::Type *argTypes[] = { CGF.Int8PtrPtrTy, CGF.Int8PtrPtrTy };
1830
Chris Lattner2acc6e32011-07-18 04:24:23 +00001831 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00001832 = llvm::FunctionType::get(CGF.Builder.getVoidTy(), argTypes, false);
1833 fn = createARCRuntimeFunction(CGF.CGM, fnType, fnName);
1834 }
1835
John McCallbd7370a2013-02-28 19:01:20 +00001836 llvm::Value *args[] = {
1837 CGF.Builder.CreateBitCast(dst, CGF.Int8PtrPtrTy),
1838 CGF.Builder.CreateBitCast(src, CGF.Int8PtrPtrTy)
1839 };
1840 CGF.EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00001841}
1842
1843/// Produce the code to do a retain. Based on the type, calls one of:
James Dennett9d96e9c2012-06-22 05:41:30 +00001844/// call i8* \@objc_retain(i8* %value)
1845/// call i8* \@objc_retainBlock(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001846llvm::Value *CodeGenFunction::EmitARCRetain(QualType type, llvm::Value *value) {
1847 if (type->isBlockPointerType())
John McCall348f16f2011-10-04 06:23:45 +00001848 return EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallf85e1932011-06-15 23:02:42 +00001849 else
1850 return EmitARCRetainNonBlock(value);
1851}
1852
1853/// Retain the given object, with normal retain semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001854/// call i8* \@objc_retain(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001855llvm::Value *CodeGenFunction::EmitARCRetainNonBlock(llvm::Value *value) {
1856 return emitARCValueOperation(*this, value,
1857 CGM.getARCEntrypoints().objc_retain,
1858 "objc_retain");
1859}
1860
1861/// Retain the given block, with _Block_copy semantics.
James Dennett9d96e9c2012-06-22 05:41:30 +00001862/// call i8* \@objc_retainBlock(i8* %value)
John McCall348f16f2011-10-04 06:23:45 +00001863///
1864/// \param mandatory - If false, emit the call with metadata
1865/// indicating that it's okay for the optimizer to eliminate this call
1866/// if it can prove that the block never escapes except down the stack.
1867llvm::Value *CodeGenFunction::EmitARCRetainBlock(llvm::Value *value,
1868 bool mandatory) {
1869 llvm::Value *result
1870 = emitARCValueOperation(*this, value,
1871 CGM.getARCEntrypoints().objc_retainBlock,
1872 "objc_retainBlock");
1873
1874 // If the copy isn't mandatory, add !clang.arc.copy_on_escape to
1875 // tell the optimizer that it doesn't need to do this copy if the
1876 // block doesn't escape, where being passed as an argument doesn't
1877 // count as escaping.
1878 if (!mandatory && isa<llvm::Instruction>(result)) {
1879 llvm::CallInst *call
1880 = cast<llvm::CallInst>(result->stripPointerCasts());
1881 assert(call->getCalledValue() == CGM.getARCEntrypoints().objc_retainBlock);
1882
1883 SmallVector<llvm::Value*,1> args;
1884 call->setMetadata("clang.arc.copy_on_escape",
1885 llvm::MDNode::get(Builder.getContext(), args));
1886 }
1887
1888 return result;
John McCallf85e1932011-06-15 23:02:42 +00001889}
1890
1891/// Retain the given object which is the result of a function call.
James Dennett9d96e9c2012-06-22 05:41:30 +00001892/// call i8* \@objc_retainAutoreleasedReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001893///
1894/// Yes, this function name is one character away from a different
1895/// call with completely different semantics.
1896llvm::Value *
1897CodeGenFunction::EmitARCRetainAutoreleasedReturnValue(llvm::Value *value) {
1898 // Fetch the void(void) inline asm which marks that we're going to
1899 // retain the autoreleased return value.
1900 llvm::InlineAsm *&marker
1901 = CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker;
1902 if (!marker) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001903 StringRef assembly
John McCallf85e1932011-06-15 23:02:42 +00001904 = CGM.getTargetCodeGenInfo()
1905 .getARCRetainAutoreleasedReturnValueMarker();
1906
1907 // If we have an empty assembly string, there's nothing to do.
1908 if (assembly.empty()) {
1909
1910 // Otherwise, at -O0, build an inline asm that we're going to call
1911 // in a moment.
1912 } else if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1913 llvm::FunctionType *type =
Chris Lattner8b418682012-02-07 00:39:47 +00001914 llvm::FunctionType::get(VoidTy, /*variadic*/false);
John McCallf85e1932011-06-15 23:02:42 +00001915
1916 marker = llvm::InlineAsm::get(type, assembly, "", /*sideeffects*/ true);
1917
1918 // If we're at -O1 and above, we don't want to litter the code
1919 // with this marker yet, so leave a breadcrumb for the ARC
1920 // optimizer to pick up.
1921 } else {
1922 llvm::NamedMDNode *metadata =
1923 CGM.getModule().getOrInsertNamedMetadata(
1924 "clang.arc.retainAutoreleasedReturnValueMarker");
1925 assert(metadata->getNumOperands() <= 1);
1926 if (metadata->getNumOperands() == 0) {
1927 llvm::Value *string = llvm::MDString::get(getLLVMContext(), assembly);
Jay Foadda549e82011-07-29 13:56:53 +00001928 metadata->addOperand(llvm::MDNode::get(getLLVMContext(), string));
John McCallf85e1932011-06-15 23:02:42 +00001929 }
1930 }
1931 }
1932
1933 // Call the marker asm if we made one, which we do only at -O0.
1934 if (marker) Builder.CreateCall(marker);
1935
1936 return emitARCValueOperation(*this, value,
1937 CGM.getARCEntrypoints().objc_retainAutoreleasedReturnValue,
1938 "objc_retainAutoreleasedReturnValue");
1939}
1940
1941/// Release the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00001942/// call void \@objc_release(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001943void CodeGenFunction::EmitARCRelease(llvm::Value *value, bool precise) {
1944 if (isa<llvm::ConstantPointerNull>(value)) return;
1945
1946 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_release;
1947 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00001948 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00001949 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00001950 fn = createARCRuntimeFunction(CGM, fnType, "objc_release");
1951 }
1952
1953 // Cast the argument to 'id'.
1954 value = Builder.CreateBitCast(value, Int8PtrTy);
1955
1956 // Call objc_release.
John McCallbd7370a2013-02-28 19:01:20 +00001957 llvm::CallInst *call = EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00001958
1959 if (!precise) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00001960 SmallVector<llvm::Value*,1> args;
John McCallf85e1932011-06-15 23:02:42 +00001961 call->setMetadata("clang.imprecise_release",
1962 llvm::MDNode::get(Builder.getContext(), args));
1963 }
1964}
1965
John McCall015f33b2012-10-17 02:28:37 +00001966/// Destroy a __strong variable.
1967///
1968/// At -O0, emit a call to store 'null' into the address;
1969/// instrumenting tools prefer this because the address is exposed,
1970/// but it's relatively cumbersome to optimize.
1971///
1972/// At -O1 and above, just load and call objc_release.
1973///
1974/// call void \@objc_storeStrong(i8** %addr, i8* null)
1975void CodeGenFunction::EmitARCDestroyStrong(llvm::Value *addr, bool precise) {
1976 if (CGM.getCodeGenOpts().OptimizationLevel == 0) {
1977 llvm::PointerType *addrTy = cast<llvm::PointerType>(addr->getType());
1978 llvm::Value *null = llvm::ConstantPointerNull::get(
1979 cast<llvm::PointerType>(addrTy->getElementType()));
1980 EmitARCStoreStrongCall(addr, null, /*ignored*/ true);
1981 return;
1982 }
1983
1984 llvm::Value *value = Builder.CreateLoad(addr);
1985 EmitARCRelease(value, precise);
1986}
1987
John McCallf85e1932011-06-15 23:02:42 +00001988/// Store into a strong object. Always calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00001989/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00001990llvm::Value *CodeGenFunction::EmitARCStoreStrongCall(llvm::Value *addr,
1991 llvm::Value *value,
1992 bool ignored) {
1993 assert(cast<llvm::PointerType>(addr->getType())->getElementType()
1994 == value->getType());
1995
1996 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_storeStrong;
1997 if (!fn) {
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001998 llvm::Type *argTypes[] = { Int8PtrPtrTy, Int8PtrTy };
Chris Lattner2acc6e32011-07-18 04:24:23 +00001999 llvm::FunctionType *fnType
John McCallf85e1932011-06-15 23:02:42 +00002000 = llvm::FunctionType::get(Builder.getVoidTy(), argTypes, false);
2001 fn = createARCRuntimeFunction(CGM, fnType, "objc_storeStrong");
2002 }
2003
John McCallbd7370a2013-02-28 19:01:20 +00002004 llvm::Value *args[] = {
2005 Builder.CreateBitCast(addr, Int8PtrPtrTy),
2006 Builder.CreateBitCast(value, Int8PtrTy)
2007 };
2008 EmitNounwindRuntimeCall(fn, args);
John McCallf85e1932011-06-15 23:02:42 +00002009
2010 if (ignored) return 0;
2011 return value;
2012}
2013
2014/// Store into a strong object. Sometimes calls this:
James Dennett9d96e9c2012-06-22 05:41:30 +00002015/// call void \@objc_storeStrong(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002016/// Other times, breaks it down into components.
John McCall545d9962011-06-25 02:11:03 +00002017llvm::Value *CodeGenFunction::EmitARCStoreStrong(LValue dst,
John McCallf85e1932011-06-15 23:02:42 +00002018 llvm::Value *newValue,
2019 bool ignored) {
John McCall545d9962011-06-25 02:11:03 +00002020 QualType type = dst.getType();
John McCallf85e1932011-06-15 23:02:42 +00002021 bool isBlock = type->isBlockPointerType();
2022
2023 // Use a store barrier at -O0 unless this is a block type or the
2024 // lvalue is inadequately aligned.
2025 if (shouldUseFusedARCCalls() &&
2026 !isBlock &&
Eli Friedman6da2c712011-12-03 04:14:32 +00002027 (dst.getAlignment().isZero() ||
2028 dst.getAlignment() >= CharUnits::fromQuantity(PointerAlignInBytes))) {
John McCallf85e1932011-06-15 23:02:42 +00002029 return EmitARCStoreStrongCall(dst.getAddress(), newValue, ignored);
2030 }
2031
2032 // Otherwise, split it out.
2033
2034 // Retain the new value.
2035 newValue = EmitARCRetain(type, newValue);
2036
2037 // Read the old value.
John McCall545d9962011-06-25 02:11:03 +00002038 llvm::Value *oldValue = EmitLoadOfScalar(dst);
John McCallf85e1932011-06-15 23:02:42 +00002039
2040 // Store. We do this before the release so that any deallocs won't
2041 // see the old value.
John McCall545d9962011-06-25 02:11:03 +00002042 EmitStoreOfScalar(newValue, dst);
John McCallf85e1932011-06-15 23:02:42 +00002043
2044 // Finally, release the old value.
2045 EmitARCRelease(oldValue, /*precise*/ false);
2046
2047 return newValue;
2048}
2049
2050/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002051/// call i8* \@objc_autorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002052llvm::Value *CodeGenFunction::EmitARCAutorelease(llvm::Value *value) {
2053 return emitARCValueOperation(*this, value,
2054 CGM.getARCEntrypoints().objc_autorelease,
2055 "objc_autorelease");
2056}
2057
2058/// Autorelease the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002059/// call i8* \@objc_autoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002060llvm::Value *
2061CodeGenFunction::EmitARCAutoreleaseReturnValue(llvm::Value *value) {
2062 return emitARCValueOperation(*this, value,
2063 CGM.getARCEntrypoints().objc_autoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002064 "objc_autoreleaseReturnValue",
2065 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002066}
2067
2068/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002069/// call i8* \@objc_retainAutoreleaseReturnValue(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002070llvm::Value *
2071CodeGenFunction::EmitARCRetainAutoreleaseReturnValue(llvm::Value *value) {
2072 return emitARCValueOperation(*this, value,
2073 CGM.getARCEntrypoints().objc_retainAutoreleaseReturnValue,
Chad Rosierdf76f1e2012-12-12 17:52:21 +00002074 "objc_retainAutoreleaseReturnValue",
2075 /*isTailCall*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002076}
2077
2078/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002079/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002080/// or
James Dennett9d96e9c2012-06-22 05:41:30 +00002081/// %retain = call i8* \@objc_retainBlock(i8* %value)
2082/// call i8* \@objc_autorelease(i8* %retain)
John McCallf85e1932011-06-15 23:02:42 +00002083llvm::Value *CodeGenFunction::EmitARCRetainAutorelease(QualType type,
2084 llvm::Value *value) {
2085 if (!type->isBlockPointerType())
2086 return EmitARCRetainAutoreleaseNonBlock(value);
2087
2088 if (isa<llvm::ConstantPointerNull>(value)) return value;
2089
Chris Lattner2acc6e32011-07-18 04:24:23 +00002090 llvm::Type *origType = value->getType();
John McCallf85e1932011-06-15 23:02:42 +00002091 value = Builder.CreateBitCast(value, Int8PtrTy);
John McCall348f16f2011-10-04 06:23:45 +00002092 value = EmitARCRetainBlock(value, /*mandatory*/ true);
John McCallf85e1932011-06-15 23:02:42 +00002093 value = EmitARCAutorelease(value);
2094 return Builder.CreateBitCast(value, origType);
2095}
2096
2097/// Do a fused retain/autorelease of the given object.
James Dennett9d96e9c2012-06-22 05:41:30 +00002098/// call i8* \@objc_retainAutorelease(i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002099llvm::Value *
2100CodeGenFunction::EmitARCRetainAutoreleaseNonBlock(llvm::Value *value) {
2101 return emitARCValueOperation(*this, value,
2102 CGM.getARCEntrypoints().objc_retainAutorelease,
2103 "objc_retainAutorelease");
2104}
2105
James Dennett9d96e9c2012-06-22 05:41:30 +00002106/// i8* \@objc_loadWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002107/// Essentially objc_autorelease(objc_loadWeakRetained(addr)).
2108llvm::Value *CodeGenFunction::EmitARCLoadWeak(llvm::Value *addr) {
2109 return emitARCLoadOperation(*this, addr,
2110 CGM.getARCEntrypoints().objc_loadWeak,
2111 "objc_loadWeak");
2112}
2113
James Dennett9d96e9c2012-06-22 05:41:30 +00002114/// i8* \@objc_loadWeakRetained(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002115llvm::Value *CodeGenFunction::EmitARCLoadWeakRetained(llvm::Value *addr) {
2116 return emitARCLoadOperation(*this, addr,
2117 CGM.getARCEntrypoints().objc_loadWeakRetained,
2118 "objc_loadWeakRetained");
2119}
2120
James Dennett9d96e9c2012-06-22 05:41:30 +00002121/// i8* \@objc_storeWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002122/// Returns %value.
2123llvm::Value *CodeGenFunction::EmitARCStoreWeak(llvm::Value *addr,
2124 llvm::Value *value,
2125 bool ignored) {
2126 return emitARCStoreOperation(*this, addr, value,
2127 CGM.getARCEntrypoints().objc_storeWeak,
2128 "objc_storeWeak", ignored);
2129}
2130
James Dennett9d96e9c2012-06-22 05:41:30 +00002131/// i8* \@objc_initWeak(i8** %addr, i8* %value)
John McCallf85e1932011-06-15 23:02:42 +00002132/// Returns %value. %addr is known to not have a current weak entry.
2133/// Essentially equivalent to:
2134/// *addr = nil; objc_storeWeak(addr, value);
2135void CodeGenFunction::EmitARCInitWeak(llvm::Value *addr, llvm::Value *value) {
2136 // If we're initializing to null, just write null to memory; no need
2137 // to get the runtime involved. But don't do this if optimization
2138 // is enabled, because accounting for this would make the optimizer
2139 // much more complicated.
2140 if (isa<llvm::ConstantPointerNull>(value) &&
2141 CGM.getCodeGenOpts().OptimizationLevel == 0) {
2142 Builder.CreateStore(value, addr);
2143 return;
2144 }
2145
2146 emitARCStoreOperation(*this, addr, value,
2147 CGM.getARCEntrypoints().objc_initWeak,
2148 "objc_initWeak", /*ignored*/ true);
2149}
2150
James Dennett9d96e9c2012-06-22 05:41:30 +00002151/// void \@objc_destroyWeak(i8** %addr)
John McCallf85e1932011-06-15 23:02:42 +00002152/// Essentially objc_storeWeak(addr, nil).
2153void CodeGenFunction::EmitARCDestroyWeak(llvm::Value *addr) {
2154 llvm::Constant *&fn = CGM.getARCEntrypoints().objc_destroyWeak;
2155 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002156 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002157 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrPtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002158 fn = createARCRuntimeFunction(CGM, fnType, "objc_destroyWeak");
2159 }
2160
2161 // Cast the argument to 'id*'.
2162 addr = Builder.CreateBitCast(addr, Int8PtrPtrTy);
2163
John McCallbd7370a2013-02-28 19:01:20 +00002164 EmitNounwindRuntimeCall(fn, addr);
John McCallf85e1932011-06-15 23:02:42 +00002165}
2166
James Dennett9d96e9c2012-06-22 05:41:30 +00002167/// void \@objc_moveWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002168/// Disregards the current value in %dest. Leaves %src pointing to nothing.
2169/// Essentially (objc_copyWeak(dest, src), objc_destroyWeak(src)).
2170void CodeGenFunction::EmitARCMoveWeak(llvm::Value *dst, llvm::Value *src) {
2171 emitARCCopyOperation(*this, dst, src,
2172 CGM.getARCEntrypoints().objc_moveWeak,
2173 "objc_moveWeak");
2174}
2175
James Dennett9d96e9c2012-06-22 05:41:30 +00002176/// void \@objc_copyWeak(i8** %dest, i8** %src)
John McCallf85e1932011-06-15 23:02:42 +00002177/// Disregards the current value in %dest. Essentially
2178/// objc_release(objc_initWeak(dest, objc_readWeakRetained(src)))
2179void CodeGenFunction::EmitARCCopyWeak(llvm::Value *dst, llvm::Value *src) {
2180 emitARCCopyOperation(*this, dst, src,
2181 CGM.getARCEntrypoints().objc_copyWeak,
2182 "objc_copyWeak");
2183}
2184
2185/// Produce the code to do a objc_autoreleasepool_push.
James Dennett9d96e9c2012-06-22 05:41:30 +00002186/// call i8* \@objc_autoreleasePoolPush(void)
John McCallf85e1932011-06-15 23:02:42 +00002187llvm::Value *CodeGenFunction::EmitObjCAutoreleasePoolPush() {
2188 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPush;
2189 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002190 llvm::FunctionType *fnType =
John McCallf85e1932011-06-15 23:02:42 +00002191 llvm::FunctionType::get(Int8PtrTy, false);
2192 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPush");
2193 }
2194
John McCallbd7370a2013-02-28 19:01:20 +00002195 return EmitNounwindRuntimeCall(fn);
John McCallf85e1932011-06-15 23:02:42 +00002196}
2197
2198/// Produce the code to do a primitive release.
James Dennett9d96e9c2012-06-22 05:41:30 +00002199/// call void \@objc_autoreleasePoolPop(i8* %ptr)
John McCallf85e1932011-06-15 23:02:42 +00002200void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
2201 assert(value->getType() == Int8PtrTy);
2202
2203 llvm::Constant *&fn = CGM.getRREntrypoints().objc_autoreleasePoolPop;
2204 if (!fn) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002205 llvm::FunctionType *fnType =
Benjamin Kramer76ecdfc2013-03-07 21:18:31 +00002206 llvm::FunctionType::get(Builder.getVoidTy(), Int8PtrTy, false);
John McCallf85e1932011-06-15 23:02:42 +00002207
2208 // We don't want to use a weak import here; instead we should not
2209 // fall into this path.
2210 fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
2211 }
2212
John McCallbd7370a2013-02-28 19:01:20 +00002213 EmitNounwindRuntimeCall(fn, value);
John McCallf85e1932011-06-15 23:02:42 +00002214}
2215
2216/// Produce the code to do an MRR version objc_autoreleasepool_push.
2217/// Which is: [[NSAutoreleasePool alloc] init];
2218/// Where alloc is declared as: + (id) alloc; in NSAutoreleasePool class.
2219/// init is declared as: - (id) init; in its NSObject super class.
2220///
2221llvm::Value *CodeGenFunction::EmitObjCMRRAutoreleasePoolPush() {
2222 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
John McCallbd7370a2013-02-28 19:01:20 +00002223 llvm::Value *Receiver = Runtime.EmitNSAutoreleasePoolClassRef(*this);
John McCallf85e1932011-06-15 23:02:42 +00002224 // [NSAutoreleasePool alloc]
2225 IdentifierInfo *II = &CGM.getContext().Idents.get("alloc");
2226 Selector AllocSel = getContext().Selectors.getSelector(0, &II);
2227 CallArgList Args;
2228 RValue AllocRV =
2229 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2230 getContext().getObjCIdType(),
2231 AllocSel, Receiver, Args);
2232
2233 // [Receiver init]
2234 Receiver = AllocRV.getScalarVal();
2235 II = &CGM.getContext().Idents.get("init");
2236 Selector InitSel = getContext().Selectors.getSelector(0, &II);
2237 RValue InitRV =
2238 Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
2239 getContext().getObjCIdType(),
2240 InitSel, Receiver, Args);
2241 return InitRV.getScalarVal();
2242}
2243
2244/// Produce the code to do a primitive release.
2245/// [tmp drain];
2246void CodeGenFunction::EmitObjCMRRAutoreleasePoolPop(llvm::Value *Arg) {
2247 IdentifierInfo *II = &CGM.getContext().Idents.get("drain");
2248 Selector DrainSel = getContext().Selectors.getSelector(0, &II);
2249 CallArgList Args;
2250 CGM.getObjCRuntime().GenerateMessageSend(*this, ReturnValueSlot(),
2251 getContext().VoidTy, DrainSel, Arg, Args);
2252}
2253
John McCallbdc4d802011-07-09 01:37:26 +00002254void CodeGenFunction::destroyARCStrongPrecise(CodeGenFunction &CGF,
2255 llvm::Value *addr,
2256 QualType type) {
John McCall015f33b2012-10-17 02:28:37 +00002257 CGF.EmitARCDestroyStrong(addr, /*precise*/ true);
John McCallbdc4d802011-07-09 01:37:26 +00002258}
2259
2260void CodeGenFunction::destroyARCStrongImprecise(CodeGenFunction &CGF,
2261 llvm::Value *addr,
2262 QualType type) {
John McCall015f33b2012-10-17 02:28:37 +00002263 CGF.EmitARCDestroyStrong(addr, /*precise*/ false);
John McCallbdc4d802011-07-09 01:37:26 +00002264}
2265
2266void CodeGenFunction::destroyARCWeak(CodeGenFunction &CGF,
2267 llvm::Value *addr,
2268 QualType type) {
2269 CGF.EmitARCDestroyWeak(addr);
2270}
2271
John McCallf85e1932011-06-15 23:02:42 +00002272namespace {
John McCallf85e1932011-06-15 23:02:42 +00002273 struct CallObjCAutoreleasePoolObject : EHScopeStack::Cleanup {
2274 llvm::Value *Token;
2275
2276 CallObjCAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2277
John McCallad346f42011-07-12 20:27:29 +00002278 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002279 CGF.EmitObjCAutoreleasePoolPop(Token);
2280 }
2281 };
2282 struct CallObjCMRRAutoreleasePoolObject : EHScopeStack::Cleanup {
2283 llvm::Value *Token;
2284
2285 CallObjCMRRAutoreleasePoolObject(llvm::Value *token) : Token(token) {}
2286
John McCallad346f42011-07-12 20:27:29 +00002287 void Emit(CodeGenFunction &CGF, Flags flags) {
John McCallf85e1932011-06-15 23:02:42 +00002288 CGF.EmitObjCMRRAutoreleasePoolPop(Token);
2289 }
2290 };
2291}
2292
2293void CodeGenFunction::EmitObjCAutoreleasePoolCleanup(llvm::Value *Ptr) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002294 if (CGM.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +00002295 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, Ptr);
2296 else
2297 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, Ptr);
2298}
2299
John McCallf85e1932011-06-15 23:02:42 +00002300static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2301 LValue lvalue,
2302 QualType type) {
2303 switch (type.getObjCLifetime()) {
2304 case Qualifiers::OCL_None:
2305 case Qualifiers::OCL_ExplicitNone:
2306 case Qualifiers::OCL_Strong:
2307 case Qualifiers::OCL_Autoreleasing:
John McCall545d9962011-06-25 02:11:03 +00002308 return TryEmitResult(CGF.EmitLoadOfLValue(lvalue).getScalarVal(),
John McCallf85e1932011-06-15 23:02:42 +00002309 false);
2310
2311 case Qualifiers::OCL_Weak:
2312 return TryEmitResult(CGF.EmitARCLoadWeakRetained(lvalue.getAddress()),
2313 true);
2314 }
2315
2316 llvm_unreachable("impossible lifetime!");
John McCallf85e1932011-06-15 23:02:42 +00002317}
2318
2319static TryEmitResult tryEmitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2320 const Expr *e) {
2321 e = e->IgnoreParens();
2322 QualType type = e->getType();
2323
John McCall21480112011-08-30 00:57:29 +00002324 // If we're loading retained from a __strong xvalue, we can avoid
2325 // an extra retain/release pair by zeroing out the source of this
2326 // "move" operation.
2327 if (e->isXValue() &&
2328 !type.isConstQualified() &&
2329 type.getObjCLifetime() == Qualifiers::OCL_Strong) {
2330 // Emit the lvalue.
2331 LValue lv = CGF.EmitLValue(e);
2332
2333 // Load the object pointer.
2334 llvm::Value *result = CGF.EmitLoadOfLValue(lv).getScalarVal();
2335
2336 // Set the source pointer to NULL.
2337 CGF.EmitStoreOfScalar(getNullForVariable(lv.getAddress()), lv);
2338
2339 return TryEmitResult(result, true);
2340 }
2341
John McCallf85e1932011-06-15 23:02:42 +00002342 // As a very special optimization, in ARC++, if the l-value is the
2343 // result of a non-volatile assignment, do a simple retain of the
2344 // result of the call to objc_storeWeak instead of reloading.
David Blaikie4e4d0842012-03-11 07:00:24 +00002345 if (CGF.getLangOpts().CPlusPlus &&
John McCallf85e1932011-06-15 23:02:42 +00002346 !type.isVolatileQualified() &&
2347 type.getObjCLifetime() == Qualifiers::OCL_Weak &&
2348 isa<BinaryOperator>(e) &&
2349 cast<BinaryOperator>(e)->getOpcode() == BO_Assign)
2350 return TryEmitResult(CGF.EmitScalarExpr(e), false);
2351
2352 return tryEmitARCRetainLoadOfScalar(CGF, CGF.EmitLValue(e), type);
2353}
2354
2355static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2356 llvm::Value *value);
2357
2358/// Given that the given expression is some sort of call (which does
2359/// not return retained), emit a retain following it.
2360static llvm::Value *emitARCRetainCall(CodeGenFunction &CGF, const Expr *e) {
2361 llvm::Value *value = CGF.EmitScalarExpr(e);
2362 return emitARCRetainAfterCall(CGF, value);
2363}
2364
2365static llvm::Value *emitARCRetainAfterCall(CodeGenFunction &CGF,
2366 llvm::Value *value) {
2367 if (llvm::CallInst *call = dyn_cast<llvm::CallInst>(value)) {
2368 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2369
2370 // Place the retain immediately following the call.
2371 CGF.Builder.SetInsertPoint(call->getParent(),
2372 ++llvm::BasicBlock::iterator(call));
2373 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2374
2375 CGF.Builder.restoreIP(ip);
2376 return value;
2377 } else if (llvm::InvokeInst *invoke = dyn_cast<llvm::InvokeInst>(value)) {
2378 CGBuilderTy::InsertPoint ip = CGF.Builder.saveIP();
2379
2380 // Place the retain at the beginning of the normal destination block.
2381 llvm::BasicBlock *BB = invoke->getNormalDest();
2382 CGF.Builder.SetInsertPoint(BB, BB->begin());
2383 value = CGF.EmitARCRetainAutoreleasedReturnValue(value);
2384
2385 CGF.Builder.restoreIP(ip);
2386 return value;
2387
2388 // Bitcasts can arise because of related-result returns. Rewrite
2389 // the operand.
2390 } else if (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(value)) {
2391 llvm::Value *operand = bitcast->getOperand(0);
2392 operand = emitARCRetainAfterCall(CGF, operand);
2393 bitcast->setOperand(0, operand);
2394 return bitcast;
2395
2396 // Generic fall-back case.
2397 } else {
2398 // Retain using the non-block variant: we never need to do a copy
2399 // of a block that's been returned to us.
2400 return CGF.EmitARCRetainNonBlock(value);
2401 }
2402}
2403
John McCalldc05b112011-09-10 01:16:55 +00002404/// Determine whether it might be important to emit a separate
2405/// objc_retain_block on the result of the given expression, or
2406/// whether it's okay to just emit it in a +1 context.
2407static bool shouldEmitSeparateBlockRetain(const Expr *e) {
2408 assert(e->getType()->isBlockPointerType());
2409 e = e->IgnoreParens();
2410
2411 // For future goodness, emit block expressions directly in +1
2412 // contexts if we can.
2413 if (isa<BlockExpr>(e))
2414 return false;
2415
2416 if (const CastExpr *cast = dyn_cast<CastExpr>(e)) {
2417 switch (cast->getCastKind()) {
2418 // Emitting these operations in +1 contexts is goodness.
2419 case CK_LValueToRValue:
John McCall33e56f32011-09-10 06:18:15 +00002420 case CK_ARCReclaimReturnedObject:
2421 case CK_ARCConsumeObject:
2422 case CK_ARCProduceObject:
John McCalldc05b112011-09-10 01:16:55 +00002423 return false;
2424
2425 // These operations preserve a block type.
2426 case CK_NoOp:
2427 case CK_BitCast:
2428 return shouldEmitSeparateBlockRetain(cast->getSubExpr());
2429
2430 // These operations are known to be bad (or haven't been considered).
2431 case CK_AnyPointerToBlockPointerCast:
2432 default:
2433 return true;
2434 }
2435 }
2436
2437 return true;
2438}
2439
John McCall4b9c2d22011-11-06 09:01:30 +00002440/// Try to emit a PseudoObjectExpr at +1.
2441///
2442/// This massively duplicates emitPseudoObjectRValue.
2443static TryEmitResult tryEmitARCRetainPseudoObject(CodeGenFunction &CGF,
2444 const PseudoObjectExpr *E) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002445 SmallVector<CodeGenFunction::OpaqueValueMappingData, 4> opaques;
John McCall4b9c2d22011-11-06 09:01:30 +00002446
2447 // Find the result expression.
2448 const Expr *resultExpr = E->getResultExpr();
2449 assert(resultExpr);
2450 TryEmitResult result;
2451
2452 for (PseudoObjectExpr::const_semantics_iterator
2453 i = E->semantics_begin(), e = E->semantics_end(); i != e; ++i) {
2454 const Expr *semantic = *i;
2455
2456 // If this semantic expression is an opaque value, bind it
2457 // to the result of its source expression.
2458 if (const OpaqueValueExpr *ov = dyn_cast<OpaqueValueExpr>(semantic)) {
2459 typedef CodeGenFunction::OpaqueValueMappingData OVMA;
2460 OVMA opaqueData;
2461
2462 // If this semantic is the result of the pseudo-object
2463 // expression, try to evaluate the source as +1.
2464 if (ov == resultExpr) {
2465 assert(!OVMA::shouldBindAsLValue(ov));
2466 result = tryEmitARCRetainScalarExpr(CGF, ov->getSourceExpr());
2467 opaqueData = OVMA::bind(CGF, ov, RValue::get(result.getPointer()));
2468
2469 // Otherwise, just bind it.
2470 } else {
2471 opaqueData = OVMA::bind(CGF, ov, ov->getSourceExpr());
2472 }
2473 opaques.push_back(opaqueData);
2474
2475 // Otherwise, if the expression is the result, evaluate it
2476 // and remember the result.
2477 } else if (semantic == resultExpr) {
2478 result = tryEmitARCRetainScalarExpr(CGF, semantic);
2479
2480 // Otherwise, evaluate the expression in an ignored context.
2481 } else {
2482 CGF.EmitIgnoredExpr(semantic);
2483 }
2484 }
2485
2486 // Unbind all the opaques now.
2487 for (unsigned i = 0, e = opaques.size(); i != e; ++i)
2488 opaques[i].unbind(CGF);
2489
2490 return result;
2491}
2492
John McCallf85e1932011-06-15 23:02:42 +00002493static TryEmitResult
2494tryEmitARCRetainScalarExpr(CodeGenFunction &CGF, const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002495 // We should *never* see a nested full-expression here, because if
2496 // we fail to emit at +1, our caller must not retain after we close
2497 // out the full-expression.
2498 assert(!isa<ExprWithCleanups>(e));
John McCall990567c2011-07-27 01:07:15 +00002499
John McCallf85e1932011-06-15 23:02:42 +00002500 // The desired result type, if it differs from the type of the
2501 // ultimate opaque expression.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002502 llvm::Type *resultType = 0;
John McCallf85e1932011-06-15 23:02:42 +00002503
2504 while (true) {
2505 e = e->IgnoreParens();
2506
2507 // There's a break at the end of this if-chain; anything
2508 // that wants to keep looping has to explicitly continue.
2509 if (const CastExpr *ce = dyn_cast<CastExpr>(e)) {
2510 switch (ce->getCastKind()) {
2511 // No-op casts don't change the type, so we just ignore them.
2512 case CK_NoOp:
2513 e = ce->getSubExpr();
2514 continue;
2515
2516 case CK_LValueToRValue: {
2517 TryEmitResult loadResult
2518 = tryEmitARCRetainLoadOfScalar(CGF, ce->getSubExpr());
2519 if (resultType) {
2520 llvm::Value *value = loadResult.getPointer();
2521 value = CGF.Builder.CreateBitCast(value, resultType);
2522 loadResult.setPointer(value);
2523 }
2524 return loadResult;
2525 }
2526
2527 // These casts can change the type, so remember that and
2528 // soldier on. We only need to remember the outermost such
2529 // cast, though.
John McCall1d9b3b22011-09-09 05:25:32 +00002530 case CK_CPointerToObjCPointerCast:
2531 case CK_BlockPointerToObjCPointerCast:
John McCallf85e1932011-06-15 23:02:42 +00002532 case CK_AnyPointerToBlockPointerCast:
2533 case CK_BitCast:
2534 if (!resultType)
2535 resultType = CGF.ConvertType(ce->getType());
2536 e = ce->getSubExpr();
2537 assert(e->getType()->hasPointerRepresentation());
2538 continue;
2539
2540 // For consumptions, just emit the subexpression and thus elide
2541 // the retain/release pair.
John McCall33e56f32011-09-10 06:18:15 +00002542 case CK_ARCConsumeObject: {
John McCallf85e1932011-06-15 23:02:42 +00002543 llvm::Value *result = CGF.EmitScalarExpr(ce->getSubExpr());
2544 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2545 return TryEmitResult(result, true);
2546 }
2547
John McCalldc05b112011-09-10 01:16:55 +00002548 // Block extends are net +0. Naively, we could just recurse on
2549 // the subexpression, but actually we need to ensure that the
2550 // value is copied as a block, so there's a little filter here.
John McCall33e56f32011-09-10 06:18:15 +00002551 case CK_ARCExtendBlockObject: {
John McCalldc05b112011-09-10 01:16:55 +00002552 llvm::Value *result; // will be a +0 value
2553
2554 // If we can't safely assume the sub-expression will produce a
2555 // block-copied value, emit the sub-expression at +0.
2556 if (shouldEmitSeparateBlockRetain(ce->getSubExpr())) {
2557 result = CGF.EmitScalarExpr(ce->getSubExpr());
2558
2559 // Otherwise, try to emit the sub-expression at +1 recursively.
2560 } else {
2561 TryEmitResult subresult
2562 = tryEmitARCRetainScalarExpr(CGF, ce->getSubExpr());
2563 result = subresult.getPointer();
2564
2565 // If that produced a retained value, just use that,
2566 // possibly casting down.
2567 if (subresult.getInt()) {
2568 if (resultType)
2569 result = CGF.Builder.CreateBitCast(result, resultType);
2570 return TryEmitResult(result, true);
2571 }
2572
2573 // Otherwise it's +0.
2574 }
2575
2576 // Retain the object as a block, then cast down.
John McCall348f16f2011-10-04 06:23:45 +00002577 result = CGF.EmitARCRetainBlock(result, /*mandatory*/ true);
John McCalldc05b112011-09-10 01:16:55 +00002578 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2579 return TryEmitResult(result, true);
2580 }
2581
John McCall7e5e5f42011-07-07 06:58:02 +00002582 // For reclaims, emit the subexpression as a retained call and
2583 // skip the consumption.
John McCall33e56f32011-09-10 06:18:15 +00002584 case CK_ARCReclaimReturnedObject: {
John McCall7e5e5f42011-07-07 06:58:02 +00002585 llvm::Value *result = emitARCRetainCall(CGF, ce->getSubExpr());
2586 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2587 return TryEmitResult(result, true);
2588 }
2589
John McCallf85e1932011-06-15 23:02:42 +00002590 default:
2591 break;
2592 }
2593
2594 // Skip __extension__.
2595 } else if (const UnaryOperator *op = dyn_cast<UnaryOperator>(e)) {
2596 if (op->getOpcode() == UO_Extension) {
2597 e = op->getSubExpr();
2598 continue;
2599 }
2600
2601 // For calls and message sends, use the retained-call logic.
2602 // Delegate inits are a special case in that they're the only
2603 // returns-retained expression that *isn't* surrounded by
2604 // a consume.
2605 } else if (isa<CallExpr>(e) ||
2606 (isa<ObjCMessageExpr>(e) &&
2607 !cast<ObjCMessageExpr>(e)->isDelegateInitCall())) {
2608 llvm::Value *result = emitARCRetainCall(CGF, e);
2609 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2610 return TryEmitResult(result, true);
John McCall4b9c2d22011-11-06 09:01:30 +00002611
2612 // Look through pseudo-object expressions.
2613 } else if (const PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
2614 TryEmitResult result
2615 = tryEmitARCRetainPseudoObject(CGF, pseudo);
2616 if (resultType) {
2617 llvm::Value *value = result.getPointer();
2618 value = CGF.Builder.CreateBitCast(value, resultType);
2619 result.setPointer(value);
2620 }
2621 return result;
John McCallf85e1932011-06-15 23:02:42 +00002622 }
2623
2624 // Conservatively halt the search at any other expression kind.
2625 break;
2626 }
2627
2628 // We didn't find an obvious production, so emit what we've got and
2629 // tell the caller that we didn't manage to retain.
2630 llvm::Value *result = CGF.EmitScalarExpr(e);
2631 if (resultType) result = CGF.Builder.CreateBitCast(result, resultType);
2632 return TryEmitResult(result, false);
2633}
2634
2635static llvm::Value *emitARCRetainLoadOfScalar(CodeGenFunction &CGF,
2636 LValue lvalue,
2637 QualType type) {
2638 TryEmitResult result = tryEmitARCRetainLoadOfScalar(CGF, lvalue, type);
2639 llvm::Value *value = result.getPointer();
2640 if (!result.getInt())
2641 value = CGF.EmitARCRetain(type, value);
2642 return value;
2643}
2644
2645/// EmitARCRetainScalarExpr - Semantically equivalent to
2646/// EmitARCRetainObject(e->getType(), EmitScalarExpr(e)), but making a
2647/// best-effort attempt to peephole expressions that naturally produce
2648/// retained objects.
2649llvm::Value *CodeGenFunction::EmitARCRetainScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002650 // The retain needs to happen within the full-expression.
2651 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2652 enterFullExpression(cleanups);
2653 RunCleanupsScope scope(*this);
2654 return EmitARCRetainScalarExpr(cleanups->getSubExpr());
2655 }
2656
John McCallf85e1932011-06-15 23:02:42 +00002657 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2658 llvm::Value *value = result.getPointer();
2659 if (!result.getInt())
2660 value = EmitARCRetain(e->getType(), value);
2661 return value;
2662}
2663
2664llvm::Value *
2665CodeGenFunction::EmitARCRetainAutoreleaseScalarExpr(const Expr *e) {
John McCall72dcecc2013-02-12 00:25:08 +00002666 // The retain needs to happen within the full-expression.
2667 if (const ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(e)) {
2668 enterFullExpression(cleanups);
2669 RunCleanupsScope scope(*this);
2670 return EmitARCRetainAutoreleaseScalarExpr(cleanups->getSubExpr());
2671 }
2672
John McCallf85e1932011-06-15 23:02:42 +00002673 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e);
2674 llvm::Value *value = result.getPointer();
2675 if (result.getInt())
2676 value = EmitARCAutorelease(value);
2677 else
2678 value = EmitARCRetainAutorelease(e->getType(), value);
2679 return value;
2680}
2681
John McCall348f16f2011-10-04 06:23:45 +00002682llvm::Value *CodeGenFunction::EmitARCExtendBlockObject(const Expr *e) {
2683 llvm::Value *result;
2684 bool doRetain;
2685
2686 if (shouldEmitSeparateBlockRetain(e)) {
2687 result = EmitScalarExpr(e);
2688 doRetain = true;
2689 } else {
2690 TryEmitResult subresult = tryEmitARCRetainScalarExpr(*this, e);
2691 result = subresult.getPointer();
2692 doRetain = !subresult.getInt();
2693 }
2694
2695 if (doRetain)
2696 result = EmitARCRetainBlock(result, /*mandatory*/ true);
2697 return EmitObjCConsumeObject(e->getType(), result);
2698}
2699
John McCall2b014d62011-10-01 10:32:24 +00002700llvm::Value *CodeGenFunction::EmitObjCThrowOperand(const Expr *expr) {
2701 // In ARC, retain and autorelease the expression.
David Blaikie4e4d0842012-03-11 07:00:24 +00002702 if (getLangOpts().ObjCAutoRefCount) {
John McCall2b014d62011-10-01 10:32:24 +00002703 // Do so before running any cleanups for the full-expression.
John McCall72dcecc2013-02-12 00:25:08 +00002704 // EmitARCRetainAutoreleaseScalarExpr does this for us.
John McCall2b014d62011-10-01 10:32:24 +00002705 return EmitARCRetainAutoreleaseScalarExpr(expr);
2706 }
2707
2708 // Otherwise, use the normal scalar-expression emission. The
2709 // exception machinery doesn't do anything special with the
2710 // exception like retaining it, so there's no safety associated with
2711 // only running cleanups after the throw has started, and when it
2712 // matters it tends to be substantially inferior code.
2713 return EmitScalarExpr(expr);
2714}
2715
John McCallf85e1932011-06-15 23:02:42 +00002716std::pair<LValue,llvm::Value*>
2717CodeGenFunction::EmitARCStoreStrong(const BinaryOperator *e,
2718 bool ignored) {
2719 // Evaluate the RHS first.
2720 TryEmitResult result = tryEmitARCRetainScalarExpr(*this, e->getRHS());
2721 llvm::Value *value = result.getPointer();
2722
John McCallfb720812011-07-28 07:23:35 +00002723 bool hasImmediateRetain = result.getInt();
2724
2725 // If we didn't emit a retained object, and the l-value is of block
2726 // type, then we need to emit the block-retain immediately in case
2727 // it invalidates the l-value.
2728 if (!hasImmediateRetain && e->getType()->isBlockPointerType()) {
John McCall348f16f2011-10-04 06:23:45 +00002729 value = EmitARCRetainBlock(value, /*mandatory*/ false);
John McCallfb720812011-07-28 07:23:35 +00002730 hasImmediateRetain = true;
2731 }
2732
John McCallf85e1932011-06-15 23:02:42 +00002733 LValue lvalue = EmitLValue(e->getLHS());
2734
2735 // If the RHS was emitted retained, expand this.
John McCallfb720812011-07-28 07:23:35 +00002736 if (hasImmediateRetain) {
John McCallf85e1932011-06-15 23:02:42 +00002737 llvm::Value *oldValue =
Eli Friedman6da2c712011-12-03 04:14:32 +00002738 EmitLoadOfScalar(lvalue);
2739 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002740 EmitARCRelease(oldValue, /*precise*/ false);
2741 } else {
John McCall545d9962011-06-25 02:11:03 +00002742 value = EmitARCStoreStrong(lvalue, value, ignored);
John McCallf85e1932011-06-15 23:02:42 +00002743 }
2744
2745 return std::pair<LValue,llvm::Value*>(lvalue, value);
2746}
2747
2748std::pair<LValue,llvm::Value*>
2749CodeGenFunction::EmitARCStoreAutoreleasing(const BinaryOperator *e) {
2750 llvm::Value *value = EmitARCRetainAutoreleaseScalarExpr(e->getRHS());
2751 LValue lvalue = EmitLValue(e->getLHS());
2752
Eli Friedman6da2c712011-12-03 04:14:32 +00002753 EmitStoreOfScalar(value, lvalue);
John McCallf85e1932011-06-15 23:02:42 +00002754
2755 return std::pair<LValue,llvm::Value*>(lvalue, value);
2756}
2757
2758void CodeGenFunction::EmitObjCAutoreleasePoolStmt(
Eric Christopher16098f32012-03-29 17:31:31 +00002759 const ObjCAutoreleasePoolStmt &ARPS) {
John McCallf85e1932011-06-15 23:02:42 +00002760 const Stmt *subStmt = ARPS.getSubStmt();
2761 const CompoundStmt &S = cast<CompoundStmt>(*subStmt);
2762
2763 CGDebugInfo *DI = getDebugInfo();
Eric Christopher73fb3502011-10-13 21:45:18 +00002764 if (DI)
2765 DI->EmitLexicalBlockStart(Builder, S.getLBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002766
2767 // Keep track of the current cleanup stack depth.
2768 RunCleanupsScope Scope(*this);
John McCall0a7dd782012-08-21 02:47:43 +00002769 if (CGM.getLangOpts().ObjCRuntime.hasNativeARC()) {
John McCallf85e1932011-06-15 23:02:42 +00002770 llvm::Value *token = EmitObjCAutoreleasePoolPush();
2771 EHStack.pushCleanup<CallObjCAutoreleasePoolObject>(NormalCleanup, token);
2772 } else {
2773 llvm::Value *token = EmitObjCMRRAutoreleasePoolPush();
2774 EHStack.pushCleanup<CallObjCMRRAutoreleasePoolObject>(NormalCleanup, token);
2775 }
2776
2777 for (CompoundStmt::const_body_iterator I = S.body_begin(),
2778 E = S.body_end(); I != E; ++I)
2779 EmitStmt(*I);
2780
Eric Christopher73fb3502011-10-13 21:45:18 +00002781 if (DI)
2782 DI->EmitLexicalBlockEnd(Builder, S.getRBracLoc());
John McCallf85e1932011-06-15 23:02:42 +00002783}
John McCall0c24c802011-06-24 23:21:27 +00002784
2785/// EmitExtendGCLifetime - Given a pointer to an Objective-C object,
2786/// make sure it survives garbage collection until this point.
2787void CodeGenFunction::EmitExtendGCLifetime(llvm::Value *object) {
2788 // We just use an inline assembly.
John McCall0c24c802011-06-24 23:21:27 +00002789 llvm::FunctionType *extenderType
John McCallde5d3c72012-02-17 03:33:10 +00002790 = llvm::FunctionType::get(VoidTy, VoidPtrTy, RequiredArgs::All);
John McCall0c24c802011-06-24 23:21:27 +00002791 llvm::Value *extender
2792 = llvm::InlineAsm::get(extenderType,
2793 /* assembly */ "",
2794 /* constraints */ "r",
2795 /* side effects */ true);
2796
2797 object = Builder.CreateBitCast(object, VoidPtrTy);
John McCallbd7370a2013-02-28 19:01:20 +00002798 EmitNounwindRuntimeCall(extender, object);
John McCall0c24c802011-06-24 23:21:27 +00002799}
2800
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002801/// GenerateObjCAtomicSetterCopyHelperFunction - Given a c++ object type with
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002802/// non-trivial copy assignment function, produce following helper function.
2803/// static void copyHelper(Ty *dest, const Ty *source) { *dest = *source; }
2804///
2805llvm::Constant *
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002806CodeGenFunction::GenerateObjCAtomicSetterCopyHelperFunction(
2807 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002808 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002809 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002810 return 0;
2811 QualType Ty = PID->getPropertyIvarDecl()->getType();
2812 if (!Ty->isRecordType())
2813 return 0;
2814 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002815 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002816 return 0;
Fariborz Jahanianb08cfb32012-01-08 19:13:23 +00002817 llvm::Constant * HelperFn = 0;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002818 if (hasTrivialSetExpr(PID))
2819 return 0;
2820 assert(PID->getSetterCXXAssignment() && "SetterCXXAssignment - null");
2821 if ((HelperFn = CGM.getAtomicSetterHelperFnMap(Ty)))
2822 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002823
2824 ASTContext &C = getContext();
2825 IdentifierInfo *II
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002826 = &CGM.getContext().Idents.get("__assign_helper_atomic_property_");
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002827 FunctionDecl *FD = FunctionDecl::Create(C,
2828 C.getTranslationUnitDecl(),
2829 SourceLocation(),
2830 SourceLocation(), II, C.VoidTy, 0,
2831 SC_Static,
2832 SC_None,
2833 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002834 false);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002835
2836 QualType DestTy = C.getPointerType(Ty);
2837 QualType SrcTy = Ty;
2838 SrcTy.addConst();
2839 SrcTy = C.getPointerType(SrcTy);
2840
2841 FunctionArgList args;
2842 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2843 args.push_back(&dstDecl);
2844 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2845 args.push_back(&srcDecl);
2846
2847 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002848 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2849 FunctionType::ExtInfo(),
2850 RequiredArgs::All);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002851
John McCallde5d3c72012-02-17 03:33:10 +00002852 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002853
2854 llvm::Function *Fn =
2855 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
Eric Christopher16098f32012-03-29 17:31:31 +00002856 "__assign_helper_atomic_property_",
2857 &CGM.getModule());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002858
Alexey Samsonova240df22012-10-16 07:22:28 +00002859 // Initialize debug info if needed.
2860 maybeInitializeDebugInfo();
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002861
2862 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2863
John McCallf4b88a42012-03-10 09:33:50 +00002864 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2865 VK_RValue, SourceLocation());
2866 UnaryOperator DST(&DstExpr, UO_Deref, DestTy->getPointeeType(),
2867 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002868
John McCallf4b88a42012-03-10 09:33:50 +00002869 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
2870 VK_RValue, SourceLocation());
2871 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2872 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002873
John McCallf4b88a42012-03-10 09:33:50 +00002874 Expr *Args[2] = { &DST, &SRC };
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002875 CallExpr *CalleeExp = cast<CallExpr>(PID->getSetterCXXAssignment());
John McCallf4b88a42012-03-10 09:33:50 +00002876 CXXOperatorCallExpr TheCall(C, OO_Equal, CalleeExp->getCallee(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002877 Args, DestTy->getPointeeType(),
Lang Hamesbe9af122012-10-02 04:45:10 +00002878 VK_LValue, SourceLocation(), false);
John McCallf4b88a42012-03-10 09:33:50 +00002879
2880 EmitStmt(&TheCall);
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002881
2882 FinishFunction();
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002883 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002884 CGM.setAtomicSetterHelperFnMap(Ty, HelperFn);
Fariborz Jahaniancd93b962012-01-06 22:33:54 +00002885 return HelperFn;
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002886}
2887
2888llvm::Constant *
2889CodeGenFunction::GenerateObjCAtomicGetterCopyHelperFunction(
2890 const ObjCPropertyImplDecl *PID) {
John McCall260611a2012-06-20 06:18:46 +00002891 if (!getLangOpts().CPlusPlus ||
Rafael Espindola90f69262012-12-18 04:29:34 +00002892 !getLangOpts().ObjCRuntime.hasAtomicCopyHelper())
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002893 return 0;
2894 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
2895 QualType Ty = PD->getType();
2896 if (!Ty->isRecordType())
2897 return 0;
2898 if ((!(PD->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_atomic)))
2899 return 0;
2900 llvm::Constant * HelperFn = 0;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002901
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002902 if (hasTrivialGetExpr(PID))
2903 return 0;
2904 assert(PID->getGetterCXXConstructor() && "getGetterCXXConstructor - null");
2905 if ((HelperFn = CGM.getAtomicGetterHelperFnMap(Ty)))
2906 return HelperFn;
2907
2908
2909 ASTContext &C = getContext();
2910 IdentifierInfo *II
2911 = &CGM.getContext().Idents.get("__copy_helper_atomic_property_");
2912 FunctionDecl *FD = FunctionDecl::Create(C,
2913 C.getTranslationUnitDecl(),
2914 SourceLocation(),
2915 SourceLocation(), II, C.VoidTy, 0,
2916 SC_Static,
2917 SC_None,
2918 false,
Eric Christopherb92bd4b2012-04-12 02:16:49 +00002919 false);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002920
2921 QualType DestTy = C.getPointerType(Ty);
2922 QualType SrcTy = Ty;
2923 SrcTy.addConst();
2924 SrcTy = C.getPointerType(SrcTy);
2925
2926 FunctionArgList args;
2927 ImplicitParamDecl dstDecl(FD, SourceLocation(), 0, DestTy);
2928 args.push_back(&dstDecl);
2929 ImplicitParamDecl srcDecl(FD, SourceLocation(), 0, SrcTy);
2930 args.push_back(&srcDecl);
2931
2932 const CGFunctionInfo &FI =
John McCallde5d3c72012-02-17 03:33:10 +00002933 CGM.getTypes().arrangeFunctionDeclaration(C.VoidTy, args,
2934 FunctionType::ExtInfo(),
2935 RequiredArgs::All);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002936
John McCallde5d3c72012-02-17 03:33:10 +00002937 llvm::FunctionType *LTy = CGM.getTypes().GetFunctionType(FI);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002938
2939 llvm::Function *Fn =
2940 llvm::Function::Create(LTy, llvm::GlobalValue::InternalLinkage,
2941 "__copy_helper_atomic_property_", &CGM.getModule());
2942
Alexey Samsonova240df22012-10-16 07:22:28 +00002943 // Initialize debug info if needed.
2944 maybeInitializeDebugInfo();
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002945
2946 StartFunction(FD, C.VoidTy, Fn, FI, args, SourceLocation());
2947
John McCallf4b88a42012-03-10 09:33:50 +00002948 DeclRefExpr SrcExpr(&srcDecl, false, SrcTy,
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002949 VK_RValue, SourceLocation());
2950
John McCallf4b88a42012-03-10 09:33:50 +00002951 UnaryOperator SRC(&SrcExpr, UO_Deref, SrcTy->getPointeeType(),
2952 VK_LValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002953
2954 CXXConstructExpr *CXXConstExpr =
2955 cast<CXXConstructExpr>(PID->getGetterCXXConstructor());
2956
2957 SmallVector<Expr*, 4> ConstructorArgs;
John McCallf4b88a42012-03-10 09:33:50 +00002958 ConstructorArgs.push_back(&SRC);
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002959 CXXConstructExpr::arg_iterator A = CXXConstExpr->arg_begin();
2960 ++A;
2961
2962 for (CXXConstructExpr::arg_iterator AEnd = CXXConstExpr->arg_end();
2963 A != AEnd; ++A)
2964 ConstructorArgs.push_back(*A);
2965
2966 CXXConstructExpr *TheCXXConstructExpr =
2967 CXXConstructExpr::Create(C, Ty, SourceLocation(),
2968 CXXConstExpr->getConstructor(),
2969 CXXConstExpr->isElidable(),
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002970 ConstructorArgs,
Sebastian Redl5b9cc5d2012-02-11 23:51:47 +00002971 CXXConstExpr->hadMultipleCandidates(),
2972 CXXConstExpr->isListInitialization(),
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002973 CXXConstExpr->requiresZeroInitialization(),
Eric Christopher16098f32012-03-29 17:31:31 +00002974 CXXConstExpr->getConstructionKind(),
2975 SourceRange());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002976
John McCallf4b88a42012-03-10 09:33:50 +00002977 DeclRefExpr DstExpr(&dstDecl, false, DestTy,
2978 VK_RValue, SourceLocation());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002979
John McCallf4b88a42012-03-10 09:33:50 +00002980 RValue DV = EmitAnyExpr(&DstExpr);
Eric Christopher16098f32012-03-29 17:31:31 +00002981 CharUnits Alignment
2982 = getContext().getTypeAlignInChars(TheCXXConstructExpr->getType());
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002983 EmitAggExpr(TheCXXConstructExpr,
2984 AggValueSlot::forAddr(DV.getScalarVal(), Alignment, Qualifiers(),
2985 AggValueSlot::IsDestructed,
2986 AggValueSlot::DoesNotNeedGCBarriers,
Chad Rosier649b4a12012-03-29 17:37:10 +00002987 AggValueSlot::IsNotAliased));
Fariborz Jahanian20abee62012-01-10 00:37:01 +00002988
2989 FinishFunction();
2990 HelperFn = llvm::ConstantExpr::getBitCast(Fn, VoidPtrTy);
2991 CGM.setAtomicGetterHelperFnMap(Ty, HelperFn);
2992 return HelperFn;
Fariborz Jahanian84e49862012-01-06 00:29:35 +00002993}
2994
Eli Friedmancae40c42012-02-28 01:08:45 +00002995llvm::Value *
2996CodeGenFunction::EmitBlockCopyAndAutorelease(llvm::Value *Block, QualType Ty) {
2997 // Get selectors for retain/autorelease.
Eli Friedman8c72a7d2012-03-01 22:52:28 +00002998 IdentifierInfo *CopyID = &getContext().Idents.get("copy");
2999 Selector CopySelector =
3000 getContext().Selectors.getNullarySelector(CopyID);
Eli Friedmancae40c42012-02-28 01:08:45 +00003001 IdentifierInfo *AutoreleaseID = &getContext().Idents.get("autorelease");
3002 Selector AutoreleaseSelector =
3003 getContext().Selectors.getNullarySelector(AutoreleaseID);
3004
3005 // Emit calls to retain/autorelease.
3006 CGObjCRuntime &Runtime = CGM.getObjCRuntime();
3007 llvm::Value *Val = Block;
3008 RValue Result;
3009 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
Eli Friedman8c72a7d2012-03-01 22:52:28 +00003010 Ty, CopySelector,
Eli Friedmancae40c42012-02-28 01:08:45 +00003011 Val, CallArgList(), 0, 0);
3012 Val = Result.getScalarVal();
3013 Result = Runtime.GenerateMessageSend(*this, ReturnValueSlot(),
3014 Ty, AutoreleaseSelector,
3015 Val, CallArgList(), 0, 0);
3016 Val = Result.getScalarVal();
3017 return Val;
3018}
3019
Fariborz Jahanian84e49862012-01-06 00:29:35 +00003020
Ted Kremenek2979ec72008-04-09 15:51:31 +00003021CGObjCRuntime::~CGObjCRuntime() {}